Merge remote-tracking branch 'upstream/main' into fix/page-check-typed-envelopes

# Conflicts:
#	docs/target-app-parity.md
This commit is contained in:
jmverges committed 2026-11-13 17:22:20 +00:00
commit deabf78747
157 files changed
+7250 -541

No files matched your search

+5 -4
View File
@@ -286,7 +286,9 @@ impl Document {
self.next_id = self.next_id.max(id);
}
/// Ensure `next_id` is above every id in the tree (after deserializing foreign data).
/// Ensure `next_id` is above every id in the tree (after deserializing foreign data), then give
/// the objects outside the layer tree (opacity-mask art, symbols, graph designs and patterns)
/// whose id is missing or already taken a new one, so each stored object has an id of its own.
pub fn fix_next_id(&mut self) {
// Ids from [`MAX_NEXT_ID`] up (a damaged or hand-made file: #1718) are left out, as is a
// counter up there: new ids start under them and never reach them, where counting on from
@@ -297,13 +299,12 @@ impl Document {
max = max.max(id);
}
};
for l in &self.layers {
l.walk(&mut |n| see(n.id.0));
}
self.visit_stored(|n, _| see(n.id.0));
self.slices.iter().for_each(|s| see(s.id.0));
self.assets.iter().for_each(|a| see(a.id));
let counter = Some(self.next_id).filter(|n| *n <= MAX_NEXT_ID).unwrap_or(0);
self.next_id = counter.max(max.saturating_add(1));
self.renumber_stored_duplicates();
}
/// Find a node anywhere in the tree.
+7
View File
@@ -554,6 +554,13 @@ impl Document {
t.cached_baselines.clear();
t.cached_ink = None;
}
// Opacity-mask art is stored art too: the copy's gets ids of its own.
if let Some(art) = n.extras().mask.as_ref().map(|m| Arc::clone(&m.art)) {
let art = Arc::new(self.reid(&art));
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) {
m.art = art;
}
}
let on_path = n.extras().objects_on_path.is_some();
let mut renamed = std::collections::HashMap::new();
if let Some(ch) = n.children_mut() {
+2
View File
@@ -142,6 +142,7 @@ mod graphic_style;
mod guides;
mod limits;
mod records;
mod stored_art;
mod units;
pub use artboard::{ARTBOARD_GAP, Artboard, ArtboardSide, LockedArtboards, RetiredArtboardId, VIDEO_PIXEL_ASPECT_RANGE, VIDEO_SAFE_INSETS};
@@ -154,6 +155,7 @@ pub use guides::{GridPrefs, Guide, RulerMode};
use limits::MAX_NEXT_ID;
pub use limits::{DocError, FORMAT_VERSION, MAX_COORD};
pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, SvgFilter, Symbol, SymbolEdit};
pub use stored_art::{StoredPlace, StoredRoot};
pub use units::{ColorMode, Unit, parse_number};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+376
View File
@@ -0,0 +1,376 @@
//! Every object a document stores, wherever it is kept: in the layers, in opacity-mask art, and in
//! the art of symbols, graph designs and pattern swatches. [`Document::node`] finds objects in the
//! layer tree only; the lookups here find the others by their ids too, which
//! [`Document::fix_next_id`] keeps unique across all of them.
use std::collections::HashSet;
use std::sync::Arc;
use super::limits::MAX_NEXT_ID;
use super::{Document, Node, NodeId};
/// The art a stored object belongs to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StoredRoot {
/// Layer `index` of [`Document::layers`].
Layer(usize),
/// Symbol `index` of [`Document::symbols`].
Symbol(usize),
/// Graph design `index` of [`Document::graph_designs`].
GraphDesign(usize),
/// Object `art` of pattern swatch `pattern` of [`Document::patterns`].
Pattern { pattern: usize, art: usize },
}
/// Where a stored object is: its root and, inside opacity-mask art, the object that mask belongs
/// to (the innermost one when masks hold masks).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct StoredPlace {
pub root: StoredRoot,
pub mask_of: Option<NodeId>,
}
impl StoredPlace {
/// Is the object in the layer tree itself, where [`Document::node`] finds it and the canvas
/// draws it as itself?
pub fn in_layers(self) -> bool {
matches!(self.root, StoredRoot::Layer(_)) && self.mask_of.is_none()
}
}
/// One step down from a node: to its child at an index, or to its opacity-mask art.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Step {
Child(usize),
Mask,
}
/// `n` and everything below it with its place, the opacity-mask art right after the object it
/// masks, then the children.
fn visit<'a>(n: &'a Arc<Node>, place: StoredPlace, f: &mut dyn FnMut(&'a Arc<Node>, StoredPlace)) {
f(n, place);
if let Some(m) = &n.extras().mask {
visit(&m.art, StoredPlace { mask_of: Some(n.id), ..place }, f);
}
for c in n.children().into_iter().flatten() {
visit(c, place, f);
}
}
/// The steps from `n` to the first node in [`visit`] order with id `id`, and the object whose mask
/// holds it last on the way.
fn find(n: &Node, id: NodeId, steps: &mut Vec<Step>, mask_of: &mut Option<NodeId>) -> bool {
if n.id == id {
return true;
}
if let Some(m) = &n.extras().mask {
steps.push(Step::Mask);
let before = *mask_of;
*mask_of = Some(n.id);
if find(&m.art, id, steps, mask_of) {
return true;
}
*mask_of = before;
steps.pop();
}
for (i, c) in n.children().into_iter().flatten().enumerate() {
steps.push(Step::Child(i));
if find(c, id, steps, mask_of) {
return true;
}
steps.pop();
}
false
}
/// The node `steps` below `n`.
fn at<'a>(mut n: &'a Arc<Node>, steps: &[Step]) -> Option<&'a Arc<Node>> {
for s in steps {
n = match s {
Step::Mask => &n.extras().mask.as_ref()?.art,
Step::Child(i) => n.children()?.get(*i)?,
};
}
Some(n)
}
/// The node `steps` below `n` to change, the nodes on the way copied when shared.
fn at_mut<'a>(mut n: &'a mut Arc<Node>, steps: &[Step]) -> Option<&'a mut Node> {
for s in steps {
let node = Arc::make_mut(n);
n = match s {
Step::Mask => &mut node.extras_if_any()?.mask.as_mut()?.art,
Step::Child(i) => node.children_mut()?.get_mut(*i)?,
};
}
Some(Arc::make_mut(n))
}
/// Gives every node from `n` down that `fresh` names a new id from `next`, counting nodes in
/// [`visit`] order from `*count`; only the nodes on the way to one are copied. Each part below is
/// renumbered through a second handle, so a new pointer marks a change.
fn renumber(n: &mut Arc<Node>, fresh: &HashSet<usize>, count: &mut usize, next: &mut u64) {
let own = fresh.contains(count);
*count += 1;
let mask = n.extras().mask.as_ref().and_then(|m| {
let mut art = Arc::clone(&m.art);
renumber(&mut art, fresh, count, next);
(!Arc::ptr_eq(&art, &m.art)).then_some(art)
});
let mut slots = vec![];
// Children's new ids by their old ones, for an Objects on Path group, which names its path and
// members by id. An id another child keeps still names that child.
let mut renamed = std::collections::HashMap::new();
let mut kept = HashSet::new();
for (i, c) in n.children().into_iter().flatten().enumerate() {
let mut new = Arc::clone(c);
renumber(&mut new, fresh, count, next);
if new.id == c.id {
kept.insert(c.id);
} else {
renamed.insert(c.id, new.id);
}
if !Arc::ptr_eq(&new, c) {
slots.push((i, new));
}
}
renamed.retain(|old, _| !kept.contains(old));
if !own && mask.is_none() && slots.is_empty() {
return;
}
let node = Arc::make_mut(n);
if own {
node.id = NodeId(*next);
*next += 1;
}
if let (Some(art), Some(m)) = (mask, node.extras_if_any().and_then(|e| e.mask.as_mut())) {
m.art = art;
}
if let Some(children) = node.children_mut() {
for (i, c) in slots {
if let Some(slot) = children.get_mut(i) {
*slot = c;
}
}
}
if !renamed.is_empty()
&& let Some(on_path) = node.extras_if_any().and_then(|e| e.objects_on_path.as_mut())
{
on_path.rename(&renamed);
}
}
impl Document {
/// The roots of the art kept outside the layers, each with its [`StoredRoot`].
fn definition_roots(&self) -> impl Iterator<Item = (&Arc<Node>, StoredRoot)> {
let symbols = self.symbols.iter().enumerate().map(|(i, s)| (&s.art, StoredRoot::Symbol(i)));
let designs = self.graph_designs.iter().enumerate().map(|(i, g)| (&g.art, StoredRoot::GraphDesign(i)));
let patterns = self
.patterns
.iter()
.enumerate()
.flat_map(|(p, def)| def.art.iter().enumerate().map(move |(a, n)| (n, StoredRoot::Pattern { pattern: p, art: a })));
symbols.chain(designs).chain(patterns)
}
/// Every root of stored art: the layers, then the art of symbols, graph designs and patterns.
fn stored_roots(&self) -> impl Iterator<Item = (&Arc<Node>, StoredRoot)> {
self.layers.iter().enumerate().map(|(i, l)| (l, StoredRoot::Layer(i))).chain(self.definition_roots())
}
/// The root `root` names, to change.
fn stored_root_mut(&mut self, root: StoredRoot) -> Option<&mut Arc<Node>> {
match root {
StoredRoot::Layer(i) => self.layers.get_mut(i),
StoredRoot::Symbol(i) => self.symbols.get_mut(i).map(|s| &mut s.art),
StoredRoot::GraphDesign(i) => self.graph_designs.get_mut(i).map(|g| &mut g.art),
StoredRoot::Pattern { pattern, art } => self.patterns.get_mut(pattern)?.art.get_mut(art),
}
}
/// Visit every stored object with its place: the layer tree with the opacity-mask art of its
/// objects, then the art of symbols, graph designs and pattern swatches (their definitions,
/// once each, never the copies instances and tiles draw).
pub fn visit_stored<'a>(&'a self, mut f: impl FnMut(&'a Node, StoredPlace)) {
self.visit_stored_arcs(|n, place| f(n, place));
}
/// [`Self::visit_stored`] with each object's shared handle, which keeps its identity from one
/// look to the next while the object is unchanged (for caches such as thumbnails).
pub fn visit_stored_arcs<'a>(&'a self, mut f: impl FnMut(&'a Arc<Node>, StoredPlace)) {
for (root, r) in self.stored_roots() {
visit(root, StoredPlace { root: r, mask_of: None }, &mut f);
}
}
/// Where object `id` is stored: the root, and the steps from it.
fn stored_path(&self, id: NodeId) -> Option<(StoredPlace, Vec<Step>)> {
if let Some(path) = self.index_path(id) {
let (first, rest) = path.split_first()?;
return Some((StoredPlace { root: StoredRoot::Layer(*first), mask_of: None }, rest.iter().map(|i| Step::Child(*i)).collect()));
}
// Not in the layer tree: in mask art (in the layers too) or in a definition's art.
for (root, r) in self.stored_roots() {
let (mut steps, mut mask_of) = (vec![], None);
if find(root, id, &mut steps, &mut mask_of) {
return Some((StoredPlace { root: r, mask_of }, steps));
}
}
None
}
/// Stored object `id` (see [`Self::visit_stored`]) with its place: one in the layer tree as
/// [`Self::node`] finds it, else the first in visiting order.
pub fn stored_node(&self, id: NodeId) -> Option<(&Arc<Node>, StoredPlace)> {
let (place, steps) = self.stored_path(id)?;
let root = self.stored_roots().find(|(_, r)| *r == place.root)?.0;
Some((at(root, &steps)?, place))
}
/// [`Self::stored_node`] to change; the nodes on the way are copied when shared.
pub fn stored_node_mut(&mut self, id: NodeId) -> Option<&mut Node> {
let (place, steps) = self.stored_path(id)?;
at_mut(self.stored_root_mut(place.root)?, &steps)
}
/// Gives the objects outside the layer tree (in opacity-mask art and in the art of symbols,
/// graph designs and patterns) whose id is 0, past the id range, or already taken by an object
/// visited before them (the layer tree's own objects first) a new id, so every stored object
/// can be named by its id. Returns how many changed; the id counter then stands above them.
pub(crate) fn renumber_stored_duplicates(&mut self) -> usize {
let mut seen: HashSet<NodeId> = HashSet::new();
for l in &self.layers {
l.walk(&mut |n| {
seen.insert(n.id);
});
}
self.slices.iter().for_each(|s| {
seen.insert(s.id);
});
// Per root, the visiting indices of the nodes that take a new id.
let mut fresh: Vec<(StoredRoot, HashSet<usize>)> = vec![];
for (root, r) in self.stored_roots() {
let (mut i, mut here) = (0, HashSet::new());
visit(root, StoredPlace { root: r, mask_of: None }, &mut |n, place| {
if !place.in_layers() && (n.id.0 == 0 || n.id.0 >= MAX_NEXT_ID || !seen.insert(n.id)) {
here.insert(i);
}
i += 1;
});
if !here.is_empty() {
fresh.push((r, here));
}
}
let total = fresh.iter().map(|(_, f)| f.len()).sum();
if total == 0 {
return 0;
}
// No id left to give: the objects keep theirs rather than share one given out later.
if self.peek_next_id().saturating_add(total as u64) > MAX_NEXT_ID {
return 0;
}
let mut next = self.peek_next_id();
for (r, f) in fresh {
if let Some(root) = self.stored_root_mut(r) {
renumber(root, &f, &mut 0, &mut next);
}
}
self.raise_next_id(next);
total
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{GraphDesign, OpacityMask, PatternDef, Symbol};
use vectorcraft_geom::Rect;
fn rect(id: u64) -> Node {
Node::path(NodeId(id), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), crate::Appearance::default_art())
}
fn masked(id: u64, art: Node) -> Node {
rect(id).with_mask(Some(Box::new(OpacityMask::new(art, true))))
}
/// A document with object 10 in its layer, mask art 11 on it, and one object in a symbol,
/// a graph design and a pattern (ids `defs`).
fn doc(defs: [u64; 3]) -> Document {
let mut d = Document::new(100.0, 100.0);
let layer = d.layers[0].id;
d.insert(Some(layer), 0, masked(10, rect(11))).unwrap();
d.symbols.push(Symbol { name: "S".into(), art: Arc::new(rect(defs[0])), dynamic: false });
d.graph_designs.push(GraphDesign { name: "G".into(), art: Arc::new(rect(defs[1])) });
d.patterns.push(PatternDef::new("P", vec![Arc::new(rect(defs[2]))]));
d.raise_next_id(20);
d
}
#[test]
fn stored_objects_are_found_in_every_art() {
let d = doc([12, 13, 14]);
let place = |id: u64| d.stored_node(NodeId(id)).map(|(n, p)| (n.id.0, p));
assert!(place(10).unwrap().1.in_layers());
assert_eq!(place(11).unwrap().1, StoredPlace { root: StoredRoot::Layer(0), mask_of: Some(NodeId(10)) });
assert_eq!(place(12).unwrap().1.root, StoredRoot::Symbol(0));
assert_eq!(place(13).unwrap().1.root, StoredRoot::GraphDesign(0));
assert_eq!(place(14).unwrap().1.root, StoredRoot::Pattern { pattern: 0, art: 0 });
assert!(d.node(NodeId(11)).is_none() && d.node(NodeId(12)).is_none(), "the layer lookup stays the layer tree's");
assert!(d.stored_node(NodeId(99)).is_none());
let mut seen = vec![];
d.visit_stored(|n, _| seen.push(n.id.0));
assert_eq!(seen, [d.layers[0].id.0, 10, 11, 12, 13, 14]);
}
#[test]
fn stored_objects_change_by_id() {
let mut d = doc([12, 13, 14]);
let before = d.clone();
d.stored_node_mut(NodeId(13)).unwrap().name = Some("changed".into());
assert_eq!(d.graph_designs[0].art.name.as_deref(), Some("changed"));
assert!(Arc::ptr_eq(&d.symbols[0].art, &before.symbols[0].art), "other art is not copied");
assert_eq!(before.graph_designs[0].art.name, None, "the earlier document is unchanged");
d.stored_node_mut(NodeId(11)).unwrap().name = Some("mask".into());
assert_eq!(d.stored_node(NodeId(11)).unwrap().0.name.as_deref(), Some("mask"));
}
#[test]
fn fix_next_id_gives_nested_duplicates_new_ids() {
// The symbol's object repeats the layer's object, the design's has no id, and the pattern's
// repeats the mask art's.
let mut d = doc([10, 0, 11]);
d.next_id = 1;
d.fix_next_id();
let mut ids = vec![];
d.visit_stored(|n, _| ids.push(n.id.0));
let unique: HashSet<u64> = ids.iter().copied().collect();
assert_eq!(unique.len(), ids.len(), "{ids:?}");
assert!(!ids.contains(&0));
assert_eq!(&ids[..3], &[d.layers[0].id.0, 10, 11], "the layer tree and the first mask art keep theirs");
assert!(ids.iter().all(|id| *id < d.peek_next_id()), "{ids:?} {}", d.peek_next_id());
// Ids already unique are kept, and a second pass changes nothing.
let again = d.clone();
assert_eq!(d.renumber_stored_duplicates(), 0);
assert_eq!(d, again);
}
#[test]
fn renumbered_objects_on_path_keep_their_path_and_members() {
// A symbol's Objects on Path group whose path repeats the layer's object 10 and whose
// member has no id.
let mut d = doc([12, 13, 14]);
let (path, member) = (rect(10), rect(0));
let rec = crate::objects_on_path::ObjectsOnPath::new(path.id, &[&member], crate::objects_on_path::CENTER, 0.0);
let mut g = Node::new(NodeId(15), crate::NodeKind::Group { children: vec![Arc::new(path), Arc::new(member)], clip: false });
g.extras_mut().objects_on_path = Some(Box::new(rec));
d.symbols[0].art = Arc::new(g);
d.fix_next_id();
let art = &d.symbols[0].art;
let kids: Vec<NodeId> = art.children().unwrap().iter().map(|c| c.id).collect();
assert!(kids.iter().all(|id| id.0 != 10 && id.0 != 0), "{kids:?}");
let on_path = art.extras().objects_on_path.as_ref().unwrap();
assert_eq!(on_path.path, kids[0]);
assert_eq!(on_path.members.iter().map(|m| m.id).collect::<Vec<_>>(), [kids[1]]);
}
}
+1 -1
View File
@@ -27,7 +27,7 @@ pub fn is_revolve(id: &str) -> bool {
/// Most bytes the copies of the object's paint in the faces may take together. Each face and the
/// seam stroke around it gets a copy of the paint, so a gradient of many stops times tens of
/// thousands of faces took gigabytes; past this the source path is drawn.
const MAX_PAINT_COPIES: usize = 256 << 20;
pub(crate) const MAX_PAINT_COPIES: usize = 256 << 20;
/// The most face and box tests a group's transparent members' faces take together to rejoin their
/// members' last runs; past them each starts a run of its own.
+583 -54
View File
@@ -5,8 +5,9 @@ use std::sync::Arc;
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, MAX_OBJECT_FACES, Mesh, PlanarFace, View};
use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect, Vec2};
use vectorcraft_pathops::BoolOp;
use vectorcraft_three_d::{Bevel, BevelShape, DepthPlane, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, PlanarFace, View};
#[cfg(test)]
use vectorcraft_doc::color::Color;
@@ -678,7 +679,8 @@ fn built_solids<'a>(
/// What a face of one of the solids [`art_for`] draws in one order was built from: the facet's
/// depth, whether it is a side face and whether it is turned away from the viewer, the bounds of
/// its polygon, the index of its shape, and whether its solid is that shape's fill or one of its
/// strokes that covers the fill's whole edge.
/// strokes that covers the fill's whole edge. A face that [`convex_face`] takes also keeps its
/// polygon and plane, for [`local_order`]; every other face has an empty `outline` and no `plane`.
struct Placed {
depth: f64,
side: bool,
@@ -686,6 +688,8 @@ struct Placed {
bounds: Rect,
member: usize,
paints: Paints,
outline: Vec<Point>,
plane: Option<DepthPlane>,
}
/// The part of its shape a face's solid is built from ([`Placed`]).
@@ -694,13 +698,22 @@ enum Paints {
Fill,
/// A stroke whose solid holds the fill's whole edge and hides it: one with a width, without
/// dashes, a width profile or a brush, painted with a solid color or a gradient without
/// transparent stops, on a shape whose subpaths are all closed.
/// transparent stops, on a shape whose subpaths are all closed, extruded (an inflated fill can
/// rise in front of its stroke).
Stroke,
Other,
}
/// Can a stroke's solid on a shape with outline `path` hold the fill's edge ([`Paints::Stroke`])
/// under the effect `effect`? Only when the subpaths are all closed and the effect extrudes: an
/// inflated fill can rise in front of its stroke.
fn holds_edge(effect: &str, path: &PathData) -> bool {
effect != INFLATE && path.subpaths.iter().all(|p| p.closed)
}
impl Paints {
/// What `item` of a shape is, the shape's subpaths all closed when `closed`.
/// What `item` of a shape is, its stroke's solid able to hold the fill's edge when `closed`
/// ([`holds_edge`]).
fn of(item: &AppearanceItem, closed: bool) -> Self {
match item {
AppearanceItem::Fill(_) => Paints::Fill,
@@ -729,10 +742,446 @@ impl Placed {
fn of(f: &Facet, member: usize, paints: Paints) -> Self {
let mut points = f.contours.iter().flatten();
let bounds = points.next().map_or(Rect::ZERO, |p| points.fold(Rect::from_points(*p, *p), |r, q| r.union_pt(*q)));
Placed { depth: f.depth, side: f.side, away: f.away, bounds, member, paints }
let local = convex_face(f).is_some();
let outline = f.contours.first().filter(|_| local).cloned().unwrap_or_default();
let plane = f.plane.filter(|_| local);
Placed { depth: f.depth, side: f.side, away: f.away, bounds, member, paints, outline, plane }
}
}
/// The most pairs of faces [`local_order`] compares, and the most [`cut_stroke_faces`] compares;
/// the pairs they have not reached by then keep the order of their depths.
const MAX_LOCAL_CHECKS: usize = 4_000_000;
/// The polygon of `f` and the sign of its turns, when `f` is a face turned toward the viewer other
/// than a planar end, with a plane and one convex contour: a face [`local_order`] and
/// [`cut_stroke_faces`] work on.
fn convex_face(f: &Facet) -> Option<(&[Point], f64)> {
if f.away || f.end.is_some() || f.plane.is_none() || f.contours.len() != 1 {
return None;
}
let c = f.contours.first()?;
Some((c, convex(c)?))
}
/// The bounds of polygon `p` (`Rect::ZERO` when it has no points).
fn polygon_bounds(p: &[Point]) -> Rect {
let mut points = p.iter();
points.next().map_or(Rect::ZERO, |q| points.fold(Rect::from_points(*q, *q), |r, q| r.union_pt(*q)))
}
/// Do rectangles `a` and `b` overlap (more than along an edge)?
fn rects_overlap(a: Rect, b: Rect) -> bool {
a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1
}
/// How many faces [`cut_stroke_faces`] may add to solids painted by `items` that hold `faces` faces
/// and whose paint copies take `paint_bytes` so far: as many as keep the faces within
/// [`MAX_OBJECT_FACES`] and the copies within the allowance, each added face counted as six copies
/// of the costliest stroke's paint.
fn cut_room<'a>(items: impl Iterator<Item = &'a AppearanceItem>, faces: usize, paint_bytes: usize) -> usize {
let per_face = items
.filter(|item| matches!(item, AppearanceItem::Stroke(_)))
.map(|item| {
let mut copies = 0usize;
crate::revolve::paint_copies_add(&mut copies, 6, paint_ref(item));
copies
})
.max()
.unwrap_or(0)
.max(1);
let affordable = crate::revolve::MAX_PAINT_COPIES.saturating_sub(paint_bytes) / per_face;
MAX_OBJECT_FACES.saturating_sub(faces).min(affordable)
}
/// In `solids`, each solid's part ([`Paints`]), its shape's index and its faces, cut each face of a
/// stroke that does not cover the fill's edge ([`Paints::Other`]) that passes through the plane of a
/// face of the same shape's fill, or of a face of another of the shape's strokes, where the two
/// overlap on the drawing ([`cut_through`]). Of two such strokes, the later one's faces are cut
/// against the earlier one's; a covering stroke's faces ([`Paints::Stroke`]) are never cut, and an
/// other stroke's faces are cut against them. At most `room` pieces are added, the object's solids
/// together.
fn cut_stroke_faces(solids: &mut [(Paints, usize, &mut Vec<Facet>)], mut room: usize) {
let mut checks = 0usize;
for k in 0..solids.len() {
let Some((Paints::Other, shape)) = solids.get(k).map(|(p, s, _)| (*p, *s)) else { continue };
let walls: Vec<usize> = (0..solids.len())
.filter(|&j| {
solids.get(j).is_some_and(|(p, s, _)| {
*s == shape
&& match p {
Paints::Fill | Paints::Stroke => true,
Paints::Other => j < k,
}
})
})
.collect();
for j in walls {
let (wall, stroke) = if j < k {
let (before, from) = solids.split_at_mut(k);
(&**before[j].2, &mut *from[0].2)
} else {
let (before, from) = solids.split_at_mut(j);
(&**from[0].2, &mut *before[k].2)
};
cut_through(wall, stroke, &mut room, &mut checks);
}
}
}
/// Cut each face of `stroke` that passes through the plane of a face of `solid` (the fill's or
/// another stroke's) where their polygons overlap on the drawing, along the line where their depths
/// meet, so that each piece is wholly in front of or behind that face there ([`local_order`] can
/// then order them). A dash's end, which crosses the edge of the fill it is drawn on, is cut into its
/// part outside the fill, in front of the fill's wall, and its part inside, behind it. A piece keeps
/// the part of the face's curved outline on its side of the cut. The first piece of a face takes its
/// place, the others go at the end. Each cut adds a face out of `room`, and each pair compared counts
/// in `checks` ([`MAX_LOCAL_CHECKS`]); cutting stops when either runs out.
fn cut_through(solid: &[Facet], stroke: &mut Vec<Facet>, room: &mut usize, checks: &mut usize) {
// The faces from left to right: a face is compared with those that start left of its end.
let mut walls: Vec<(&Facet, &[Point], f64, Rect)> =
solid.iter().filter_map(|f| convex_face(f).map(|(c, turn)| (f, c, turn, polygon_bounds(c)))).collect();
if walls.is_empty() {
return;
}
walls.sort_by(|a, b| a.3.x0.total_cmp(&b.3.x0));
let mut k = 0;
while k < stroke.len() {
let mut extent = stroke.get(k).and_then(convex_face).map(|(c, _)| polygon_bounds(c));
for &(wall, outline, turn, bounds) in &walls {
let Some(at) = extent.filter(|e| bounds.x0 < e.x1) else { break };
if *checks >= MAX_LOCAL_CHECKS || *room == 0 {
return;
}
*checks += 1;
if !rects_overlap(at, bounds) {
continue;
}
let Some(s) = stroke.get(k) else { break };
let Some((c, _)) = convex_face(s) else { break };
if let Some((near, far)) = cut(s, c, wall, outline, turn) {
*room -= 1;
extent = convex_face(&near).map(|(c, _)| polygon_bounds(c));
stroke[k] = near;
stroke.push(far);
}
}
k += 1;
}
}
/// Face `s` (polygon `c`) cut where its depth meets that of face `wall` (convex polygon `outline`,
/// turning with sign `turn`): its piece nearer the viewer than the wall's plane and its piece
/// farther. `None` when the two do not overlap on the drawing or `s` is on one side of the wall's
/// plane wherever they do.
fn cut(s: &Facet, c: &[Point], wall: &Facet, outline: &[Point], turn: f64) -> Option<(Facet, Facet)> {
let ahead = |p: Point| Some(s.depth_at(p)? - wall.depth_at(p)?);
let overlap = clip_convex(c, outline, turn);
centroid(&overlap)?;
let tolerance = 1e-6;
let (mut nearer, mut farther) = (false, false);
for p in &overlap {
let d = ahead(*p)?;
nearer |= d > tolerance;
farther |= d < -tolerance;
}
if !(nearer && farther) {
return None;
}
let (a, b) = (s.plane?, wall.plane?);
let values: Vec<f64> = match (a.eye, b.eye) {
(Some(e), Some(f)) if e == f && a.center == b.center => {
// With perspective the depths themselves are not linear on the drawing, but where they
// meet is a line: (dA - aA e)(nzB - aB) = (dB - aB e)(nzA - aA), with aX = (nX · p) / e,
// whose difference is linear. Its sign is that of the depths' difference over the
// product of the two denominators, taken at the middle of the face.
let at = |p: Point| {
let (x, y) = (p.x - a.center.x, p.y - a.center.y);
let (aa, ab) = ((a.normal[0] * x + a.normal[1] * y) / e, (b.normal[0] * x + b.normal[1] * y) / e);
let (da, db) = (a.normal[2] - aa, b.normal[2] - ab);
((a.offset - aa * e) * db - (b.offset - ab * e) * da, da * db)
};
let sign = at(centroid(c)?).1.signum();
c.iter().map(|p| at(*p).0 * sign).collect()
}
_ => c.iter().map(|p| ahead(*p)).collect::<Option<_>>()?,
};
let piece = |sign: f64| {
let points = half(c, &values, sign);
let mid = centroid(&points)?;
let mut f = s.clone();
f.depth = s.depth_at(mid).unwrap_or(s.depth);
f.contours = vec![points];
f.outline = s.outline.as_ref().and_then(|o| clip_to_side(o, c, &values, sign));
Some(f)
};
Some((piece(1.0)?, piece(-1.0)?))
}
/// Curved outline `outline` of a face with polygon `c`, cut along the line where `values` (one per
/// point of `c`, varying linearly along each edge) is 0, keeping the side where `sign` times them is
/// at least 0. `None` when the line does not cross `c` at two points or nothing is left.
fn clip_to_side(outline: &PathData, c: &[Point], values: &[f64], sign: f64) -> Option<PathData> {
let mut crossings = vec![];
for (j, (&a, &va)) in c.iter().zip(values).enumerate() {
let k = (j + 1) % c.len();
let (Some(&b), Some(&vb)) = (c.get(k), values.get(k)) else { continue };
if (va >= 0.0) != (vb >= 0.0) {
crossings.push(a.lerp(b, va / (va - vb)));
}
}
let &[q0, q1] = crossings.as_slice() else { return None };
let along = q1 - q0;
let length = along.hypot();
if length.is_nan() || length <= 1e-9 {
return None;
}
let along = along / length;
let (inside, _) = c.iter().zip(values).find(|(_, v)| **v * sign > 0.0)?;
let mut across = Vec2::new(-along.y, along.x);
if (*inside - q0).dot(across) < 0.0 {
across = -across;
}
let bounds = outline.bounds()?.union(polygon_bounds(c));
let reach = 2.0 * (bounds.width() + bounds.height() + (q0 - bounds.center()).hypot()) + 1.0;
let mut side = BezPath::new();
side.move_to(q0 - along * reach);
side.line_to(q0 + along * reach);
side.line_to(q0 + along * reach + across * reach);
side.line_to(q0 - along * reach + across * reach);
side.close_path();
let kept = vectorcraft_pathops::boolean(outline, FillRule::NonZero, &PathData::from_bezpath(&side), FillRule::NonZero, BoolOp::Intersect);
kept.bounds().is_some().then_some(kept)
}
/// The part of polygon `p` where `sign` times `values` (one per point, varying linearly along each
/// edge) is at least 0.
fn half(p: &[Point], values: &[f64], sign: f64) -> Vec<Point> {
let mut out = vec![];
for (j, (&a, &va)) in p.iter().zip(values).enumerate() {
let k = (j + 1) % p.len();
let (Some(&b), Some(&vb)) = (p.get(k), values.get(k)) else { continue };
let (sa, sb) = (va * sign, vb * sign);
if sa >= 0.0 {
out.push(a);
}
if (sa >= 0.0) != (sb >= 0.0) {
out.push(a.lerp(b, sa / (sa - sb)));
}
}
out
}
/// `order` (back to front), when it draws a face of one of a shape's strokes and an overlapping face
/// of the same shape's fill or strokes the wrong way round for their depths where they overlap on
/// the drawing, with every pair of overlapping faces that keep a polygon and a plane
/// ([`convex_face`]: turned toward the viewer, not a planar end), of any shape, put in the order of
/// their depths where they overlap: the face nearer the viewer there goes after the other. A fill
/// wall and a face of the same shape's covering stroke ([`Paints::Stroke`]) keep their order. Each
/// face otherwise keeps its place in `order`, so a fill wall in the gap between two dashes stays
/// where its depth puts it. A cycle of such pairs is broken at the face that comes first in `order`.
/// A face drawn last (a planar end turned toward the viewer, at depth `f64::MAX`) keeps its place:
/// no face moves across it. Otherwise `order` as it is.
fn local_order(faces: &[Placed], order: Vec<usize>) -> Vec<usize> {
use std::cmp::Reverse;
// The faces of each shape that take part, from left to right for a sweep along x.
let mut shapes: Vec<Vec<usize>> = vec![];
for (k, f) in faces.iter().enumerate() {
if f.outline.len() < 3 || f.plane.is_none() {
continue;
}
if shapes.len() <= f.member {
shapes.resize_with(f.member + 1, Vec::new);
}
shapes[f.member].push(k);
}
if !shapes.iter().any(|list| list.iter().any(|&k| faces[k].paints != Paints::Fill)) {
return order;
}
for list in &mut shapes {
list.sort_by(|&a, &b| faces[a].bounds.x0.total_cmp(&faces[b].bounds.x0));
}
// A fill wall and a face of the same shape's covering stroke keep the order [`draw_order`] gave
// them: the stroke's solid holds the wall, which never shows.
let covered = |f: &Placed, s: &Placed| f.paints == Paints::Fill && f.side && s.paints == Paints::Stroke && f.member == s.member;
// Is there a face of a shape's strokes and a face of the same shape's fill or strokes that the
// order of their depths draws the wrong way round where they overlap?
let mut position = vec![0usize; faces.len()];
for (at, &k) in order.iter().enumerate() {
position[k] = at;
}
let mut checks = 0usize;
let mut misordered = false;
'shapes: for list in &shapes {
for (i, &f) in list.iter().enumerate() {
let a = &faces[f];
for &s in list.iter().skip(i + 1).take_while(|&&s| faces[s].bounds.x0 < a.bounds.x1) {
if checks >= MAX_LOCAL_CHECKS {
break 'shapes;
}
checks += 1;
let b = &faces[s];
if (a.paints == Paints::Fill && b.paints == Paints::Fill) || covered(a, b) || covered(b, a) || !rects_overlap(a.bounds, b.bounds) {
continue;
}
if nearer_where_overlapping(a, b).is_some_and(|a_nearer| a_nearer != (position[f] > position[s])) {
misordered = true;
break 'shapes;
}
}
}
}
if !misordered {
return order;
}
// Moving those faces must not carry them past any other face they overlap, so every pair of
// faces with a polygon and a plane that overlap goes in the order of their depths there.
let mut sweep: Vec<usize> = (0..faces.len()).filter(|&k| faces[k].outline.len() >= 3 && faces[k].plane.is_some()).collect();
sweep.sort_by(|&a, &b| faces[a].bounds.x0.total_cmp(&faces[b].bounds.x0));
// For each face, the faces drawn after it, and for each, how many go before it.
let mut after: Vec<Vec<usize>> = vec![vec![]; faces.len()];
let mut waits = vec![0usize; faces.len()];
'pairs: for (i, &k) in sweep.iter().enumerate() {
let a = &faces[k];
for &j in sweep.iter().skip(i + 1).take_while(|&&j| faces[j].bounds.x0 < a.bounds.x1) {
if checks >= MAX_LOCAL_CHECKS {
break 'pairs;
}
checks += 1;
let b = &faces[j];
if !rects_overlap(a.bounds, b.bounds) {
continue;
}
let a_later = if covered(a, b) || covered(b, a) {
position[k] > position[j]
} else {
let Some(a_nearer) = nearer_where_overlapping(a, b) else { continue };
a_nearer
};
let (back, front) = if a_later { (j, k) } else { (k, j) };
after[back].push(front);
waits[front] += 1;
}
}
// Each step draws the face that comes first in `order` of those whose faces before are drawn.
let mut ready: std::collections::BinaryHeap<Reverse<(usize, usize)>> =
(0..faces.len()).filter(|&k| waits[k] == 0).map(|k| Reverse((position[k], k))).collect();
// The faces drawn last, in `order`: each goes only after every face before it in `order`.
let last: Vec<usize> = order.iter().copied().filter(|&k| faces[k].depth >= f64::MAX).collect();
let mut next_last = 0usize;
let mut drawn = vec![false; faces.len()];
let mut out = Vec::with_capacity(order.len());
let mut first = 0usize;
while out.len() < order.len() {
while last.get(next_last).is_some_and(|&k| drawn[k]) {
next_last += 1;
}
let limit = last.get(next_last).map_or(usize::MAX, |&k| position[k]);
let k = match ready.peek() {
Some(&Reverse((at, k))) if at < limit => {
ready.pop();
k
}
_ => {
// A cycle, or the faces left to draw before a face drawn last wait for faces after
// it: the first face in `order` not drawn yet goes next.
while order.get(first).is_some_and(|&k| drawn[k]) {
first += 1;
}
let Some(&k) = order.get(first) else { break };
k
}
};
if drawn[k] {
continue;
}
drawn[k] = true;
out.push(k);
for &j in &after[k] {
waits[j] = waits[j].saturating_sub(1);
if waits[j] == 0 && !drawn[j] {
ready.push(Reverse((position[j], j)));
}
}
}
out
}
/// Whether face `a` is nearer the viewer than face `b` where their polygons overlap on the drawing,
/// measured at the middle of the overlap. `None` when they do not overlap, when either polygon is
/// not convex, or when they are at the same depth there.
fn nearer_where_overlapping(a: &Placed, b: &Placed) -> Option<bool> {
let (pa, pb) = (a.plane?, b.plane?);
let turn = convex(&b.outline)?;
convex(&a.outline)?;
let overlap = clip_convex(&a.outline, &b.outline, turn);
let mid = centroid(&overlap)?;
let (da, db) = (pa.depth_at(mid)?, pb.depth_at(mid)?);
let tolerance = 1e-6 * (1.0 + da.abs().max(db.abs()));
((da - db).abs() > tolerance).then_some(da > db)
}
/// The sign of the turns of convex polygon `p` (`None` when it is not convex or has no area).
fn convex(p: &[Point]) -> Option<f64> {
let n = p.len();
let mut sign = 0.0;
for i in 0..n {
let (a, b, c) = (p[i], p[(i + 1) % n], p[(i + 2) % n]);
let cross = (b - a).cross(c - b);
if cross.abs() <= 1e-12 {
continue;
}
if sign == 0.0 {
sign = cross.signum();
} else if cross.signum() != sign {
return None;
}
}
(sign != 0.0).then_some(sign)
}
/// The part of polygon `subject` inside convex polygon `clip`, whose turns have sign `turn`
/// (Sutherland–Hodgman).
fn clip_convex(subject: &[Point], clip: &[Point], turn: f64) -> Vec<Point> {
let mut out = subject.to_vec();
for i in 0..clip.len() {
if out.is_empty() {
break;
}
let (e0, e1) = (clip[i], clip[(i + 1) % clip.len()]);
let side = |p: Point| (e1 - e0).cross(p - e0) * turn;
let input = std::mem::take(&mut out);
for j in 0..input.len() {
let (p, q) = (input[j], input[(j + 1) % input.len()]);
let (sp, sq) = (side(p), side(q));
if sp >= 0.0 {
out.push(p);
}
if (sp >= 0.0) != (sq >= 0.0) {
let t = sp / (sp - sq);
out.push(p.lerp(q, t));
}
}
}
out
}
/// The centroid of polygon `p`, `None` when it has (almost) no area. It is measured from the
/// polygon's first point, so a small polygon far from the origin keeps its area.
fn centroid(p: &[Point]) -> Option<Point> {
let origin = *p.first()?;
let n = p.len();
let (mut area, mut cx, mut cy) = (0.0, 0.0, 0.0);
for i in 0..n {
let (a, b) = (p[i] - origin, p[(i + 1) % n] - origin);
let cross = a.x * b.y - b.x * a.y;
area += cross;
cx += (a.x + b.x) * cross;
cy += (a.y + b.y) * cross;
}
(area.abs() > 1e-9).then(|| origin + Vec2::new(cx / (3.0 * area), cy / (3.0 * area)))
}
/// The most bounds comparisons [`draw_order`] makes; the fill walls it has not reached by then keep
/// their depths.
const MAX_OVERLAP_CHECKS: usize = 4_000_000;
@@ -742,7 +1191,8 @@ const MAX_OVERLAP_CHECKS: usize = 4_000_000;
/// of a shape's fill turned toward the viewer is drawn before each face of the same shape's
/// covering strokes ([`Paints::Stroke`]), turned toward the viewer, whose bounds overlap its own.
/// Such a stroke's closed solid holds the fill's walls, so they never show and can be drawn under
/// any other face.
/// any other face. A shape's fill faces and the faces of its other strokes then go in the order of
/// their depths where they overlap ([`local_order`]).
fn draw_order(faces: &[Placed], sealed: bool) -> Vec<usize> {
// Each face's depth to sort by, and whether it was moved before a stroke face at that depth.
let mut keys: Vec<(f64, bool)> = faces.iter().map(|f| (f.depth, false)).collect();
@@ -781,7 +1231,7 @@ fn draw_order(faces: &[Placed], sealed: bool) -> Vec<usize> {
// A stable sort: faces at the same depth keep the order of the appearance, and a fill's side
// face moved to a stroke face's depth goes before it.
order.sort_by(|&a, &b| keys[a].0.total_cmp(&keys[b].0).then(keys[b].1.cmp(&keys[a].1)));
order
local_order(faces, order)
}
/// `shapes`, the members of group or layer `n`, reshaped by the visible geometry effects `before`
@@ -806,7 +1256,9 @@ type ShadowAndSurfaces = (Vec<Arc<Node>>, Vec<Arc<Node>>);
/// each in its own paint. When every one is opaque with normal blending and no colored light makes
/// a surface one composite, their faces are drawn in one back-to-front order (where depths tie, as
/// for the caps turned toward the viewer, in the order of the appearance, and with caps, a shape's
/// fill walls before the faces of its covering strokes that overlap them: [`draw_order`]), the
/// fill walls before the faces of its covering strokes that overlap them, and its fill's faces and
/// its other strokes' faces, cut where they pass through each other ([`cut_stroke_faces`]), in the
/// order of their depths where they overlap: [`draw_order`]), the
/// faces of a solid in a gradient with transparent stops in runs that carry its opacity mask
/// ([`in_runs`]);
/// otherwise each solid is a surface of its own, in that order. A member's opacity mask and
@@ -995,18 +1447,22 @@ 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)
with_graphics(surfaces.into_iter().map(|(_, s, scopes, _)| (scopes, Arc::new(s))).collect(), 0, 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>)> {
/// `surfaces` (those from index `first`) drawn whole, each with its scopes, and the graphics `arts`
/// ([`placed_graphics`]) of those surfaces 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>)>,
first: usize,
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)| {
out.extend(arts.iter().filter(|(at, ..)| *at == first + k).map(|(.., art)| {
let mut art = art.clone();
if let Some(mask) = &mask {
Arc::make_mut(&mut art).extras_mut().mask = Some(mask.clone());
@@ -1058,7 +1514,7 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
}
}
let arts = placed_graphics(doc, n.id, (ROTATE, &p), b, &filled, masks);
let out = with_graphics(out, &arts);
let out = with_graphics(out, 0, &arts);
return Some(if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() });
}
let (parts, bounds) = solid_parts(shapes, b);
@@ -1085,6 +1541,43 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
let (_, opacity, blend) = paint_of(item, *member);
opacity >= 1.0 && blend == BlendMode::Normal
});
let closed = |shape: usize| shapes.get(shape).is_some_and(|s| holds_edge(&fx.id, &s.path));
// A solid whose surface is one composite of all its facets ([`surface`]: a solid color under
// colored lights with smooth shading) has no faces to order.
let composite = |item: &AppearanceItem, f: &[Facet]| colored && paint_ref(item).color().is_some() && f.iter().any(|f| f.rgb_gradient.is_some());
// The faces are drawn in one order (below) unless a composite draws the surfaces whole. Under
// a member's opacity mask or blending, each member's faces go in one order of their own when its
// fills and strokes are opaque, blend normally, carry no opacity mask and are not composites.
let one_order = opaque && !solids.iter().any(|(item, _, _, f, _)| composite(item, f));
let shape_order: Vec<bool> = (0..shapes.len())
.map(|shape| {
solids.iter().filter(|s| s.4 == shape).all(|(item, member, _, f, _)| {
let (paint, opacity, blend) = paint_of(item, *member);
opacity >= 1.0 && blend == BlendMode::Normal && !masks_surface(&paint, colored) && !composite(item, f)
})
})
.collect();
let ordered = |shape: usize| if masks { shape_order.get(shape).copied().unwrap_or(false) } else { one_order };
if solids.iter().any(|s| ordered(s.4)) {
// A stroke face that passes through a fill wall or another stroke's face is cut where it
// does. The pieces count against the limits as the faces did: cutting stops before the
// faces pass MAX_OBJECT_FACES or their paint copies pass the allowance, so an effect that
// draws uncut still draws.
let counts: Vec<usize> = solids.iter().map(|(.., f, _)| f.len()).collect();
let room = cut_room(solids.iter().map(|(item, ..)| *item), counts.iter().sum(), paint_bytes);
let mut cuts: Vec<(Paints, usize, &mut Vec<Facet>)> = solids
.iter_mut()
.filter(|(.., shape)| ordered(*shape))
.map(|(item, _, _, f, shape)| (Paints::of(item, closed(*shape)), *shape, f))
.collect();
cut_stroke_faces(&mut cuts, room);
for ((item, _, _, f, _), before) in solids.iter().zip(counts) {
let added = f.get(before..).unwrap_or_default();
if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(added, paint_ref(item), colored), paint_ref(item)) {
return None;
}
}
}
let arts = if !graphics_on {
vec![]
} else {
@@ -1100,11 +1593,11 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
.collect();
placed_graphics(doc, n.id, (&fx.id, &p), bounds, &filled, masks)
};
let members: Vec<usize> = solids.iter().map(|s| s.4).collect();
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 paints = Paints::of(item, closed(shape));
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);
@@ -1112,50 +1605,86 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
(depths, art, scopes, ends)
})
.collect();
if masks {
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()));
// 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. 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() {
INFLATE => inflate_options(&p).cap,
CLASSIC_EXTRUDE => classic_extrude_options(&p).cap,
_ => extrude_options(&p).cap,
};
// 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 it draws whole.
let plain = |(depths, s, _, _): &BuiltSurface| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len());
if masks {
// Each member's surfaces, in the scopes of its opacity mask or blending: its faces in one
// order when it is opaque and plain, otherwise each surface whole.
let mut out = vec![];
let mut surfaces = surfaces.into_iter().zip(members).enumerate().peekable();
while let Some((first, (s, member))) = surfaces.next() {
let mut run = vec![s];
while let Some((_, (s, _))) = surfaces.next_if(|(_, (_, m))| *m == member) {
run.push(s);
}
let flat = run.iter().all(|s| plain(s) && s.1.opacity >= 1.0 && s.1.blend == BlendMode::Normal && s.1.extras().mask.is_none());
if ordered(member) && flat {
let scopes = run.first().map_or(&[][..], |s| s.2);
out.push((scopes, Arc::new(Node::group(n.id, in_one_order(n.id, run, first, &arts, sealed)))));
} else {
out.extend(with_graphics(run.into_iter().map(|(_, s, scopes, _)| (scopes, Arc::new(s))).collect(), first, &arts));
}
}
return Some(masked(n.id, out));
}
if !opaque || !surfaces.iter().all(plain) {
return Some(whole_surfaces(surfaces, &arts).into_iter().map(|(_, s)| s).collect());
}
Some(vec![Arc::new(Node::group(n.id, in_one_order(n.id, surfaces, 0, &arts, sealed)))])
}
/// The faces of `surfaces` (plain groups of their faces, [`surfaces_for`]'s from index `first`) in
/// one order ([`draw_order`], `sealed` for solids with caps), each of the graphics `arts` of those
/// surfaces right after the last face it is drawn on, of the surfaces that share it. A surface in a gradient with transparent stops
/// carries an opacity mask: its faces go in runs ([`in_runs`]), each carrying the mask, and each of
/// its graphics carries the mask too ([`with_graphics`]), so a graphic is hidden where its cap is.
fn in_one_order(id: NodeId, surfaces: Vec<BuiltSurface<'_>>, first: usize, arts: &[(usize, PlanarFace, Arc<Node>)], sealed: bool) -> Vec<Arc<Node>> {
let masks: Vec<Option<Box<OpacityMask>>> = surfaces.iter().map(|(_, s, _, _)| s.extras().mask.clone()).collect();
let arts: Vec<&(usize, PlanarFace, Arc<Node>)> = arts.iter().filter(|(at, ..)| (first..first + surfaces.len()).contains(at)).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.into_iter().map(|end| end.map(|end| (surface, end))));
}
}
let order = draw_order(&placed, sealed);
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());
// Each graphic goes right after the last of the faces it is drawn on, among the surfaces that
// share it ([`placed_graphics`]): a masked surface's own, or else the run of surfaces without a
// mask that ends at its surface.
let last: Vec<Option<usize>> = arts
.iter()
.map(|(at, face, _)| {
let at = at - first;
let from = if masks.get(at).is_some_and(Option::is_some) {
at
} else {
masks.get(..at).and_then(|before| before.iter().rposition(Option::is_some)).map_or(0, |k| k + 1)
};
order.iter().rposition(|k| ends.get(*k).copied().flatten().is_some_and(|(surface, end)| end == *face && (from..=at).contains(&surface)))
})
.collect();
let mut drawn: Vec<(usize, Arc<Node>)> = 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()));
drawn.extend(faces.get_mut(k).and_then(Option::take));
drawn.extend(last.iter().zip(&arts).filter(|(l, _)| **l == Some(at)).map(|(_, (surface, .., art))| {
let mut art = art.clone();
if let Some(mask) = masks.get(surface - first).cloned().flatten() {
Arc::make_mut(&mut art).extras_mut().mask = Some(mask);
}
// An index past the surfaces: the graphic goes in a run of its own, with its own mask.
(masks.len(), art)
}));
}
Some(vec![Arc::new(Node::group(n.id, children))])
if masks.iter().any(Option::is_some) { in_runs(id, drawn, &masks) } else { drawn.into_iter().map(|(_, face)| face).collect() }
}
/// `faces` in their back-to-front order, each with the index of its surface, where some surfaces
+467
View File
@@ -253,6 +253,468 @@ fn a_fills_walls_are_drawn_before_the_stroke_faces_over_them() {
}
}
/// The faces of the solids effect `id` with `params` builds for `n`, in the order they are drawn,
/// as [`surfaces_for`] orders them, each with the index of the part ([`solid_parts`]) it was built
/// from and whether it is a stroke's.
fn drawn_parts(n: &Node, id: &str, params: &Value) -> Vec<(Facet, usize, bool)> {
let (path, rule) = profile(n).unwrap();
let shapes = [Profile { path, rule, items: solid_paints(n), opacity: 1.0, scopes: vec![] }];
let p = crate::merged_params(id, params);
let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap());
let mut solids = vec![];
for (part, ((item, _, _, _, _, member), f)) in parts.iter().zip(built_solids(id, &p, &parts, bounds, MAX_OBJECT_FACES)).enumerate() {
let Some(f) = f.unwrap() else { continue };
let closed = holds_edge(id, &shapes[*member].path);
solids.push((Paints::of(item, closed), *member, f, part, matches!(item, AppearanceItem::Stroke(_))));
}
let mut cuts: Vec<(Paints, usize, &mut Vec<Facet>)> = solids.iter_mut().map(|(paints, member, f, _, _)| (*paints, *member, f)).collect();
cut_stroke_faces(&mut cuts, MAX_OBJECT_FACES);
let (mut placed, mut all) = (vec![], vec![]);
for (paints, member, f, part, stroke) in solids {
for facet in f {
placed.push(Placed::of(&facet, member, paints));
all.push((facet, part, stroke));
}
}
let sealed = match id {
INFLATE => inflate_options(&p).cap,
CLASSIC_EXTRUDE => classic_extrude_options(&p).cap,
_ => extrude_options(&p).cap,
};
draw_order(&placed, sealed).into_iter().map(|k| all[k].clone()).collect()
}
/// Is `p` inside the polygon of `f` (nonzero winding)?
fn facet_contains(f: &Facet, p: Point) -> bool {
let mut winding = 0i32;
for c in &f.contours {
for (a, b) in c.iter().zip(c.iter().cycle().skip(1)).take(c.len()) {
let cross = (b.x - a.x) * (p.y - a.y) - (p.x - a.x) * (b.y - a.y);
if a.y <= p.y && b.y > p.y && cross > 0.0 {
winding += 1;
} else if a.y > p.y && b.y <= p.y && cross < 0.0 {
winding -= 1;
}
}
}
winding != 0
}
/// The points of a 1 pt grid over `faces` (drawn in that order, each with whether it is a stroke's)
/// where the face drawn on top is the fill's while a face of the stroke turned toward the viewer is
/// nearer the viewer there by more than 0.5 pt, or the other way round. Points within 0.3 pt of an
/// edge are left out.
fn wrong_on_top(faces: &[(Facet, bool)]) -> Vec<Point> {
let polygons: Vec<&Facet> = faces.iter().map(|(f, _)| f).collect();
let extent =
polygons.iter().flat_map(|f| f.contours.iter().flatten()).fold(Rect::new(f64::MAX, f64::MAX, f64::MIN, f64::MIN), |r, p| r.union_pt(*p));
let mut wrong = vec![];
let mut y = extent.y0.floor() + 0.5;
while y < extent.y1 {
let mut x = extent.x0.floor() + 0.5;
while x < extent.x1 {
let p = Point::new(x, y);
let well_inside = |f: &Facet| {
[(-0.3, -0.3), (0.3, -0.3), (-0.3, 0.3), (0.3, 0.3), (0.0, 0.0)].iter().all(|(dx, dy)| facet_contains(f, Point::new(x + dx, y + dy)))
};
let top = faces.iter().rposition(|(f, _)| facet_contains(f, p));
if let Some((f, stroke)) = top.and_then(|k| faces.get(k)).filter(|(f, _)| !f.away && well_inside(f)) {
let nearest = |of_stroke: bool| {
faces.iter().filter(|(g, s)| *s == of_stroke && !g.away && well_inside(g)).filter_map(|(g, _)| g.depth_at(p)).reduce(f64::max)
};
if let (Some(ds), Some(df)) = (nearest(true), nearest(false))
&& (ds - df).abs() > 0.5
&& (ds > df) != *stroke
&& f.depth_at(p).is_some()
{
wrong.push(p);
}
}
x += 1.0;
}
y += 1.0;
}
wrong
}
/// The points of a 1 pt grid over `faces` (drawn in that order) where the face drawn on top is
/// farther from the viewer than another face turned toward the viewer, of any part, by more than
/// 0.5 pt. Points within 0.3 pt of an edge, and faces without a plane, are left out.
fn misdrawn(faces: &[(Facet, usize, bool)]) -> Vec<Point> {
let extent =
faces.iter().flat_map(|(f, ..)| f.contours.iter().flatten()).fold(Rect::new(f64::MAX, f64::MAX, f64::MIN, f64::MIN), |r, p| r.union_pt(*p));
let mut wrong = vec![];
let mut y = extent.y0.floor() + 0.5;
while y < extent.y1 {
let mut x = extent.x0.floor() + 0.5;
while x < extent.x1 {
let p = Point::new(x, y);
let well_inside = |f: &Facet| {
[(-0.3, -0.3), (0.3, -0.3), (-0.3, 0.3), (0.3, 0.3), (0.0, 0.0)].iter().all(|(dx, dy)| facet_contains(f, Point::new(x + dx, y + dy)))
};
let top = faces.iter().rposition(|(f, ..)| facet_contains(f, p)).and_then(|k| faces.get(k)).filter(|(f, ..)| !f.away && well_inside(f));
if let Some(on_top) = top.and_then(|(f, ..)| f.depth_at(p)) {
let nearest = faces.iter().filter(|(g, ..)| !g.away && well_inside(g)).filter_map(|(g, ..)| g.depth_at(p)).reduce(f64::max);
if nearest.is_some_and(|d| d - on_top > 0.5) {
wrong.push(p);
}
}
x += 1.0;
}
y += 1.0;
}
wrong
}
/// The faces of a shape's fill and strokes are drawn in the order of their depths where they
/// overlap: on a turned C, with or without perspective, under a stroke that does not cover the
/// fill's whole edge (dashed, with a width profile, or with a brush), under a plain stroke and
/// under two strokes whose faces pass through each other, no point shows a face farther from the
/// viewer than another, in Extrude & Bevel and Extrude & Bevel (Classic), and only a few in
/// Inflate, where curved puffs cross.
#[test]
fn fill_walls_and_strokes_that_leave_gaps_draw_in_the_order_of_their_depths_where_they_overlap() {
use vectorcraft_doc::{Dash, WidthProfile};
let views = [
json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0}),
json!({"rotationX": 25, "rotationY": -55, "rotationZ": 10}),
json!({"rotationX": -30, "rotationY": 50, "rotationZ": 5, "perspectiveAngle": 40}),
json!({"rotationX": -30, "rotationY": 20, "rotationZ": 5, "perspectiveAngle": 40}),
];
type Style<'a> = (&'a str, &'a dyn Fn(&mut Node));
let first = |n: &mut Node, set: &dyn Fn(&mut StrokeLayer)| {
if let Some(AppearanceItem::Stroke(s)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) {
set(s);
}
};
let dash = |pattern: Vec<f64>, offset: f64| Some(Dash { pattern, offset, align_corners: false });
let styles: [Style; 6] = [
("plain", &|_| {}),
("dashed", &|n| first(n, &|s| s.dash = dash(vec![12.0, 12.0], 0.0))),
("profiled", &|n| first(n, &|s| s.profile = Some(WidthProfile::lens()))),
("brushed", &|n| first(n, &|s| s.brush = Some("brush".into()))),
("dashed with perspective", &|n| first(n, &|s| s.dash = dash(vec![20.0, 6.0], 3.0))),
("two strokes", &|n| {
first(n, &|s| s.dash = dash(vec![12.0, 12.0], 0.0));
let mut wide = StrokeLayer::new(Paint::solid(RED), 14.0);
wide.profile = Some(WidthProfile::lens());
n.appearance.items.push(AppearanceItem::Stroke(wide));
}),
];
for id in [EXTRUDE, CLASSIC_EXTRUDE, INFLATE] {
for (v, view) in views.iter().enumerate() {
for (style, set) in &styles {
// The last two views, for the plain and the two strokes only.
if v >= 2 && !["plain", "two strokes"].contains(style) {
continue;
}
let mut params = view.clone();
params["depth"] = json!(60);
if style.contains("perspective") {
params["perspectiveAngle"] = json!(40);
}
let mut n = stroked(&letter_c());
set(&mut n);
let parts = drawn_parts(&n, id, &params);
let faces: Vec<(Facet, bool)> = parts.iter().map(|(f, _, s)| (f.clone(), *s)).collect();
assert!(faces.iter().any(|(_, s)| *s) && faces.iter().any(|(_, s)| !*s), "{id} {view} {style}: faces of both");
// Inflate's curved puffs cross each other along curves its flat facets only follow
// roughly: a few points next to those crossings may still show the farther face.
let allowed = if id == INFLATE { 5 } else { 0 };
let wrong = wrong_on_top(&faces);
assert!(wrong.len() <= allowed, "{id} {view} {style}: {} points drawn in the wrong paint, first {:?}", wrong.len(), wrong.first());
let wrong = misdrawn(&parts);
assert!(wrong.len() <= allowed, "{id} {view} {style}: {} points show a farther face, first {:?}", wrong.len(), wrong.first());
}
}
}
}
/// The paths of `art`'s faces in drawing order, leaving out the graphics (clip groups).
fn face_paths(art: &Node) -> Vec<PathData> {
fn walk(n: &Node, out: &mut Vec<PathData>) {
match &n.kind {
NodeKind::Group { clip: true, .. } => {}
NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)),
_ => out.extend(n.path_data().cloned()),
}
}
let mut out = vec![];
walk(art, &mut out);
out
}
/// A member of a 3D group with an opacity mask or a blending mode of its own draws its fill's and
/// its strokes' faces in one order inside that mask, the order the same member draws them in
/// without it, its dashes cut where they pass through the fill's walls. A member whose stroke is
/// translucent still draws each surface whole.
#[test]
fn a_masked_members_fill_and_stroke_faces_go_in_one_order() {
let mut member = stroked(&letter_c());
if let Some(AppearanceItem::Stroke(s)) = member.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) {
s.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false });
}
let solid = |member: Node| {
let mut g = Node::group(NodeId(2), vec![Arc::new(member)]);
g.appearance.effects.push(fx(EXTRUDE, json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0, "depth": 60})));
solid_art(&g).unwrap()
};
let cover = Node::path(
NodeId(900),
vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 400.0, 400.0)),
Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0),
);
let mut masked = member.clone();
masked.extras_mut().mask = Some(Box::new(OpacityMask::new(cover, true)));
let mut multiplied = member.clone();
multiplied.blend = BlendMode::Multiply;
let unmasked = face_paths(&solid(member.clone()));
for (what, scoped) in [("masked", masked.clone()), ("multiplied", multiplied)] {
let art = solid(scoped);
let mut scopes = 0;
art.walk(&mut |n| scopes += usize::from(n.extras().mask.is_some() || n.blend == BlendMode::Multiply));
assert!(scopes > 0, "{what}: drawn in its scope");
assert_eq!(face_paths(&art), unmasked, "{what}: the faces in the member's one order");
}
// A translucent stroke keeps its surface whole: the fill's faces, then the stroke's.
if let Some(AppearanceItem::Stroke(s)) = masked.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) {
s.opacity = 0.5;
}
let art = solid(masked);
let mut groups = vec![];
art.walk(&mut |n| {
if n.opacity == 0.5 {
groups.push(n.children().map_or(0, Vec::len));
}
});
assert_eq!(groups.len(), 1, "the stroke's surface is one translucent group");
}
/// Under a light that is not white, Inflate in gradients, whose faces are drawn one by one, draws the
/// fill's and the dashed stroke's faces in one order, as it does under a white light. A solid color,
/// drawn as one composite of each surface's facets, still draws each surface whole.
#[test]
fn a_colored_inflate_in_gradients_draws_its_faces_in_one_order() {
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
let gradient = |c: Color| {
Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(
GradientKind::Linear,
vec![GradientStop::new(0.0, c), GradientStop::new(1.0, Color::WHITE)],
))))
};
let mut n = stroked(&letter_c());
for item in &mut n.appearance.items {
match item {
AppearanceItem::Fill(f) => f.paint = gradient(RED),
AppearanceItem::Stroke(s) => {
s.paint = gradient(BLUE);
s.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false });
}
}
}
// How many surfaces the art draws, and how many faces the first holds.
let drawn = |n: &Node, lights: Option<Value>| {
let mut n = n.clone();
let mut p = json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0, "depth": 60});
if let Some(lights) = lights {
p["lights"] = lights;
}
n.appearance.effects.push(fx(INFLATE, p));
let art = solid_art(&n).unwrap();
let surfaces = art.children().unwrap();
(surfaces.len(), surfaces[0].children().map_or(0, Vec::len))
};
let colored = json!([{"color": "#ff8080"}]);
let white = drawn(&n, None);
assert_eq!(white.0, 1, "one order");
let cut = drawn_parts(&n, INFLATE, &json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0, "depth": 60})).len();
assert_eq!(white.1, cut, "the white light's faces, cut");
assert_eq!(drawn(&n, Some(colored.clone())).0, 1, "one order under the colored light");
// A solid color under the colored light: a composite for each of the fill and the stroke.
let solid = stroked(&letter_c());
assert_eq!(drawn(&solid, Some(colored)).0, 2);
}
/// A face of a stroke that leaves gaps passing through the plane of its fill's wall where they
/// overlap is cut along the line where their depths meet, into the piece in front of the wall and
/// the piece behind it; a face on one side of the wall, another shape's stroke, a covering stroke
/// and a cut past the room left are left whole.
#[test]
fn a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet() {
let facet = |x: f64, normal: [f64; 3], offset: f64| Facet {
contours: vec![vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)]],
depth: 0.0,
brightness: 1.0,
illumination: [1.0; 3],
normal,
rgb_gradient: None,
outline: None,
side: true,
away: false,
end: None,
plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }),
};
let wall = facet(0.0, [0.0, 0.0, 1.0], 0.0);
// z = x - 8: behind the wall left of x = 8, in front of it right of it.
let r = std::f64::consts::FRAC_1_SQRT_2;
let mut through = facet(5.0, [-r, 0.0, r], -8.0 * r);
// Its curved outline: the top edge bows up to y = -2.
let mut curved = BezPath::new();
curved.move_to((5.0, 0.0));
curved.curve_to((8.0, -8.0 / 3.0), (12.0, -8.0 / 3.0), (15.0, 0.0));
curved.line_to((15.0, 10.0));
curved.line_to((5.0, 10.0));
curved.close_path();
through.outline = Some(PathData::from_bezpath(&curved));
let extent = |f: &Facet| polygon_bounds(&f.contours[0]);
let cut_with = |paints: Paints, member: usize, room: usize| {
let (mut fill, mut stroke) = (vec![wall.clone()], vec![through.clone()]);
let mut solids: Vec<(Paints, usize, &mut Vec<Facet>)> = vec![(Paints::Fill, 0, &mut fill), (paints, member, &mut stroke)];
cut_stroke_faces(&mut solids, room);
stroke
};
let pieces = cut_with(Paints::Other, 0, 10);
assert_eq!(pieces.len(), 2);
let (near, far) = (extent(&pieces[0]), extent(&pieces[1]));
assert!((near.x0 - 8.0).abs() < 1e-9 && near.x1 == 15.0 && far.x0 == 5.0 && (far.x1 - 8.0).abs() < 1e-9, "{near:?} {far:?}");
assert!(pieces[0].depth > 0.0 && pieces[1].depth < 0.0);
// Each piece keeps its side of the curved outline, the bowed edge included.
let curve = |f: &Facet| f.outline.as_ref().and_then(PathData::bounds).unwrap();
let (near, far) = (curve(&pieces[0]), curve(&pieces[1]));
assert!((near.x0 - 8.0).abs() < 1e-6 && (near.x1 - 15.0).abs() < 1e-6 && near.y0 < -1.5, "{near:?}");
assert!((far.x0 - 5.0).abs() < 1e-6 && (far.x1 - 8.0).abs() < 1e-6 && far.y0 < -1.5, "{far:?}");
let whole = std::slice::from_ref(&through);
assert_eq!(cut_with(Paints::Other, 1, 10), whole, "another shape's stroke");
assert_eq!(cut_with(Paints::Stroke, 0, 10), whole, "a covering stroke");
assert_eq!(cut_with(Paints::Other, 0, 0), whole, "no room");
let (mut fill, mut stroke) = (vec![wall.clone()], vec![facet(5.0, [0.0, 0.0, 1.0], 1.0)]);
cut_stroke_faces(&mut [(Paints::Fill, 0, &mut fill), (Paints::Other, 0, &mut stroke)], 10);
assert_eq!(stroke.len(), 1, "in front of the wall wherever they overlap");
// Of two of a shape's strokes whose faces pass through each other, the later stroke's face is
// cut against the earlier one's; a covering stroke's face is never cut, and the other stroke's
// face is cut against it. Two shapes' strokes are left whole.
for (case, (first, second, cut_first)) in
[(Paints::Other, Paints::Other, false), (Paints::Stroke, Paints::Other, false), (Paints::Other, Paints::Stroke, true)].into_iter().enumerate()
{
let (mut a, mut b) = (vec![wall.clone()], vec![through.clone()]);
cut_stroke_faces(&mut [(first, 0, &mut a), (second, 0, &mut b)], 10);
assert_eq!((a.len(), b.len()), if cut_first { (2, 1) } else { (1, 2) }, "case {case}");
}
let (mut a, mut b) = (vec![wall.clone()], vec![through.clone()]);
cut_stroke_faces(&mut [(Paints::Other, 0, &mut a), (Paints::Other, 1, &mut b)], 10);
assert_eq!((a.len(), b.len()), (1, 1), "two shapes");
}
/// A small polygon far from the origin keeps its area and centroid.
#[test]
fn a_small_polygon_far_away_has_a_centroid() {
let far = 100_000_000.0;
let square = [Point::new(far, far), Point::new(far + 1.0, far), Point::new(far + 1.0, far + 1.0), Point::new(far, far + 1.0)];
let c = centroid(&square).unwrap();
assert!((c.x - far - 0.5).abs() < 1e-6 && (c.y - far - 0.5).abs() < 1e-6, "{c:?}");
assert!(centroid(&[]).is_none() && centroid(&square[..2]).is_none());
}
/// Cutting adds no more faces than the object's face limit and the paint-copy allowance leave room
/// for, so an effect that draws with its faces uncut still draws.
#[test]
fn cutting_stays_within_the_face_limit_and_the_paint_allowance() {
let items = stroked(&letter_c()).appearance.items.clone();
let stroke = items.iter().find(|i| matches!(i, AppearanceItem::Stroke(_))).unwrap();
let mut one = 0usize;
crate::revolve::paint_copies_add(&mut one, 6, paint_ref(stroke));
let max = crate::revolve::MAX_PAINT_COPIES;
assert_eq!(cut_room(items.iter(), 10, 0), (MAX_OBJECT_FACES - 10).min(max / one));
assert_eq!(cut_room(items.iter(), MAX_OBJECT_FACES + 5, 0), 0);
assert_eq!(cut_room(items.iter(), 10, max - 3 * one), 3);
assert_eq!(cut_room(items.iter(), 10, max + 1), 0);
}
/// Where a shape's fill wall and a face of its stroke that leaves gaps overlap, the one nearer the
/// viewer there is drawn after the other, whichever their depths put first; a stroke face that
/// overlaps no fill wall keeps its place.
#[test]
fn local_order_puts_overlapping_fill_walls_and_stroke_faces_in_depth_order() {
let square = |x: f64| vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)];
let at = |depth: f64, x: f64, z: f64, paints: Paints| Placed {
depth,
side: true,
away: false,
bounds: Rect::new(x, 0.0, x + 10.0, 10.0),
member: 0,
paints,
outline: square(x),
plane: Some(DepthPlane { normal: [0.0, 0.0, 1.0], offset: z, center: Point::ZERO, eye: None }),
};
// 0 a fill wall at z 0; 1 a stroke face over half of it, nearer, sorted before it; 2 a stroke
// face elsewhere; 3 a stroke face over it, farther, sorted after it.
let faces =
[at(5.0, 0.0, 0.0, Paints::Fill), at(2.0, 5.0, 1.0, Paints::Other), at(1.0, 20.0, 1.0, Paints::Other), at(6.0, 2.0, -1.0, Paints::Other)];
assert_eq!(draw_order(&faces, true), [2, 3, 0, 1]);
assert_eq!(draw_order(&faces, false), [2, 3, 0, 1]);
// A covering stroke's faces keep the wall's own rule.
let covering: Vec<Placed> = faces
.iter()
.map(|f| Placed { paints: if f.paints == Paints::Other { Paints::Stroke } else { f.paints }, outline: vec![], plane: None, ..*f })
.collect();
assert_eq!(draw_order(&covering, false), [2, 1, 0, 3]);
// Another shape's stroke, and a stroke face at the same depth where they overlap, move nothing.
let other_shape: Vec<Placed> =
faces[..3].iter().map(|f| Placed { member: usize::from(f.paints == Paints::Other), outline: f.outline.clone(), ..*f }).collect();
assert_eq!(draw_order(&other_shape, true), [2, 1, 0]);
let level = [at(5.0, 0.0, 0.0, Paints::Fill), at(2.0, 5.0, 0.0, Paints::Other)];
assert_eq!(draw_order(&level, true), [1, 0]);
// A stroke face moved after its fill's wall does not pass a nearer face of another shape that
// it overlaps: 0 a stroke face, 1 another shape's face in front of both, 2 the fill's wall.
let in_front = Placed { member: 1, ..at(2.0, 5.0, 2.0, Paints::Fill) };
let shapes = [at(1.0, 5.0, 1.0, Paints::Other), in_front, at(3.0, 0.0, 0.0, Paints::Fill)];
assert_eq!(draw_order(&shapes, true), [2, 0, 1]);
// A shape with a covering stroke as well keeps its fill wall before the covering stroke's face,
// even where that face is the farther: 0 the fill's wall, 1 the covering stroke's face behind
// it, 2 the other stroke's face in front.
let both = [at(3.0, 0.0, 0.0, Paints::Fill), at(3.0, 0.0, -1.0, Paints::Stroke), at(2.0, 5.0, 1.0, Paints::Other)];
assert_eq!(draw_order(&both, true), [0, 1, 2]);
// Faces of a shape's strokes go in the order of their depths where they overlap too, with no
// fill face among them: 1 is nearer than 0 there, though sorted before it.
for (case, (back, front)) in
[(Paints::Other, Paints::Other), (Paints::Stroke, Paints::Other), (Paints::Stroke, Paints::Stroke)].into_iter().enumerate()
{
let strokes = [at(5.0, 0.0, 0.0, back), at(2.0, 5.0, 1.0, front)];
assert_eq!(draw_order(&strokes, true), [0, 1], "case {case}");
}
}
/// A cycle of overlapping stroke faces is broken at the face that comes first by depth, and a cap
/// drawn last stays after every wall: 0 at x 0 to 10, flat at z 0; 1 at x 4 to 14, z = x - 8; 2 at
/// x 8 to 18, flat at z 1. Where they overlap, 0 is nearer than 1, 1 nearer than 2 and 2 nearer
/// than 0. 3 is the cap.
#[test]
fn a_depth_cycle_keeps_the_cap_last() {
let square = |x: f64| vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)];
let at = |depth: f64, x: f64, normal: [f64; 3], offset: f64| Placed {
depth,
side: true,
away: false,
bounds: Rect::new(x, 0.0, x + 10.0, 10.0),
member: 0,
paints: Paints::Other,
outline: square(x),
plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }),
};
let cap = Placed {
depth: f64::MAX,
side: false,
away: false,
bounds: Rect::new(0.0, 0.0, 18.0, 10.0),
member: 0,
paints: Paints::Other,
outline: vec![],
plane: None,
};
let faces = [at(1.0, 0.0, [0.0, 0.0, 1.0], 0.0), at(2.0, 4.0, [-1.0, 0.0, 1.0], -8.0), at(3.0, 8.0, [0.0, 0.0, 1.0], 1.0), cap];
assert_eq!(draw_order(&faces, true), [0, 2, 1, 3]);
}
/// The order keeps depths except where a shape's fill wall turned toward the viewer overlaps a
/// face of the same shape's stroke drawn before it: the wall then goes just before that face. A
/// cap, a face turned away, another shape's stroke, a stroke face the wall does not overlap and an
@@ -266,6 +728,8 @@ fn the_draw_order_moves_a_fill_wall_before_the_stroke_faces_it_overlaps() {
bounds: Rect::new(x, 0.0, x + 10.0, 10.0),
member,
paints,
outline: vec![],
plane: None,
};
// 0 the fill's wall; 1 the stroke's wall over it; 2 another shape's stroke over it; 3 a stroke
// wall elsewhere; 4 a stroke face turned away; 5 a fill cap; 6 the stroke's cap, nearer; 7 a
@@ -292,6 +756,9 @@ fn the_draw_order_moves_a_fill_wall_before_the_stroke_faces_it_overlaps() {
};
assert!(Paints::of(&stroke(&|_| {}), true) == Paints::Stroke);
assert!(Paints::of(&stroke(&|_| {}), false) == Paints::Other, "an open shape");
let closed = profile(&stroked(&letter_c())).unwrap().0;
assert!(holds_edge(EXTRUDE, &closed) && holds_edge(CLASSIC_EXTRUDE, &closed));
assert!(!holds_edge(INFLATE, &closed), "an inflated fill can rise in front of its stroke");
assert!(Paints::of(&stroke(&|s| s.width = 0.0), true) == Paints::Other, "no width");
let dash = vectorcraft_doc::Dash { pattern: vec![4.0, 4.0], offset: 0.0, align_corners: false };
assert!(Paints::of(&stroke(&|s| s.dash = Some(dash.clone())), true) == Paints::Other, "dashes");
+104
View File
@@ -620,6 +620,110 @@ fn a_solid_in_a_transparent_gradient_keeps_its_graphic() {
assert_eq!(masks(&solid_art_in(Some(&d), &n).unwrap()), vec![true, false]);
}
/// The paths of `art`'s faces in drawing order (a face lit by a colored light is a clip group: its
/// clipping path), leaving out the graphics (clip groups of solid-color paths).
fn face_paths(art: &Node) -> Vec<PathData> {
fn walk(n: &Node, out: &mut Vec<PathData>) {
match &n.kind {
NodeKind::Group { children, clip: true } => {
let graphic = children.get(1).is_some_and(|inner| match &inner.kind {
NodeKind::Group { children: paths, clip: false } => paths.iter().all(|p| {
p.path_data().is_some()
&& p.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.paint.color().is_some()))
}),
_ => false,
});
if !graphic {
out.extend(children.first().and_then(|c| c.path_data()).cloned());
}
}
NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)),
_ => out.extend(n.path_data().cloned()),
}
}
let mut out = vec![];
walk(art, &mut out);
out
}
/// A turned solid in a gradient with transparent stops under a colored light, with a dashed stroke
/// and a graphic, draws its fill's and its stroke's faces in the one order it draws them in without
/// the graphic, and the graphic keeps the cap's mask and goes after the fill's cap, not the stroke's.
#[test]
fn a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order() {
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]));
let solid = |graphics: Value| {
let mut n = object(
EXTRUDE,
json!({"rotationX": -20.0, "rotationY": -40.0, "depth": 60.0, "shade": true, "lights": [{"color": "#ff8080"}], "graphics": graphics}),
);
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.paint = Paint::Gradient(Box::new(gradient.clone()));
}
// A gradient stroke: a solid color under the colored light would be one composite.
let blues = Gradient::new(
GradientKind::Linear,
vec![GradientStop::new(0.0, Color::rgb(0.0, 0.0, 1.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 0.5))],
);
let mut stroke = StrokeLayer::new(Paint::Gradient(Box::new(GradientPaint::new(blues))), 6.0);
stroke.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false });
n.appearance.items.push(AppearanceItem::Stroke(stroke));
solid_art_in(Some(&d), &n).unwrap()
};
let with = solid(json!([{"symbol": "Mark"}]));
let without = solid(json!([]));
assert!(face_paths(&without).len() > 20, "the faces are found");
assert_eq!(face_paths(&with), face_paths(&without), "the faces in one order");
// The graphic is drawn on the fill's cap and on the stroke's (the clip groups holding the
// symbol's red square); the fill's, whose surface carries the mask, carries it too.
let mut masked = vec![];
with.walk(&mut |c| {
if let NodeKind::Group { children, clip: true } = &c.kind
&& let [_, inner] = children.as_slice()
&& let NodeKind::Group { children: paths, clip: false } = &inner.kind
&& paths.iter().any(|p| {
p.appearance.items.iter().any(|i| match i {
AppearanceItem::Fill(f) => f.paint.color().is_some_and(|c| c.to_rgb()[1] < 0.1 && c.to_rgb()[0] > 0.3),
AppearanceItem::Stroke(_) => false,
})
})
{
masked.push(c.extras().mask.is_some());
}
});
masked.sort_unstable();
assert_eq!(masked, [false, true], "the fill's graphic carries the cap's mask");
// The fill's graphic goes right after the fill's cap, so the dashes on the cap's edge, drawn
// after it, cover it. Drawn in order: the fill's graphic (the masked clip group), and each face,
// the fill's or the stroke's by its gradient's first stop (red or blue), with its bounds.
let mut drawn: Vec<(&str, Rect)> = vec![];
with.walk(&mut |c| {
if let NodeKind::Group { children, clip: true } = &c.kind
&& c.extras().mask.is_some()
&& let Some(bounds) = children.first().and_then(|clip| clip.path_data()).and_then(PathData::bounds)
{
drawn.push(("graphic", bounds));
}
let first_stop = c.appearance.items.iter().find_map(|i| match i {
AppearanceItem::Fill(f) => match &f.paint {
Paint::Gradient(g) => g.gradient.stops.first().map(|s| s.color.to_rgb()),
_ => None,
},
AppearanceItem::Stroke(_) => None,
});
if let (Some(rgb), Some(bounds)) = (first_stop, c.path_data().and_then(PathData::bounds)) {
drawn.push((if rgb[0] > rgb[2] { "fill" } else { "stroke" }, bounds));
}
});
let graphic = drawn.iter().position(|(kind, _)| *kind == "graphic").unwrap();
let covering = |(kind, b): &(&str, Rect)| *kind == "stroke" && b.intersect(drawn[graphic].1).area() > 0.0;
assert!(drawn[graphic..].iter().any(covering), "a dash on the cap's edge is drawn over the fill's graphic");
}
#[test]
fn a_cap_with_a_hole_keeps_the_hole_out_of_the_graphic() {
let d = document();
+2
View File
@@ -778,6 +778,8 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap<
pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
pub(crate) use addons::{DecodedImages, refresh_color_masks};
/// Document Info's category titles and the Objects category's count labels.
pub use docinfo::{CATEGORIES, OBJECT_LABELS};
pub use docmenu::guide_indexes;
pub(crate) use edit::{settle_interaction, typing_in_progress};
pub(crate) use object::bounds_rewrite;
+4 -1
View File
@@ -132,8 +132,10 @@ fn export_all_open(s: &mut Session, p: &Value) -> Result<Value> {
let active = s.active;
for i in 0..s.docs.len() {
// Each document in turn is the one Save a Copy writes; switching tabs this way leaves every
// document's tool and interaction alone, and the active one comes back below.
// document's tool and interaction alone, and the active one comes back below. Its colors
// are written through its own profiles.
s.active = Some(i);
s.sync_front_profiles();
let Ok(st) = s.doc() else { continue };
let title = st.doc.title.clone();
let stem = fileio::file_stem(st.path.as_deref().unwrap_or(&title));
@@ -160,6 +162,7 @@ fn export_all_open(s: &mut Session, p: &Value) -> Result<Value> {
}
}
s.active = active;
s.sync_front_profiles();
Ok(json!({ "files": files, "failed": failed, "format": format.id }))
}
+17 -13
View File
@@ -527,8 +527,9 @@ fn color_groups(cmd: &str, d: &mut Document, items: Vec<Arc<Node>>) -> Result<Ve
}
/// What a trace depends on: the object traced (an image, or an Image Trace object traced again),
/// its image, and the settings it is traced with. The tracer makes the same paths of the same
/// inputs, so a trace made away from the command ([`TraceRun`]) stands in for the command's own.
/// its image, the image's encoded bytes, and the settings it is traced with. The tracer makes the
/// same paths of the same inputs, so a trace made away from the command ([`TraceRun`]) stands in
/// for the command's own.
#[derive(Clone, Debug, PartialEq)]
struct TraceInputs {
target: NodeId,
@@ -538,6 +539,9 @@ struct TraceInputs {
/// Document Library: the library's colours, which the JSON leaves out
/// ([`tr::TraceParams::swatches`]).
swatches: Vec<[u8; 3]>,
/// The encoded image the tracer decodes: the blob under the image's key, shared with the
/// document. Two blobs are equal when they are the same allocation or hold the same bytes.
bytes: Arc<Vec<u8>>,
}
/// What `imageTrace.make` and `imageTrace.makeAndExpand` take from the session before they trace.
@@ -549,7 +553,6 @@ struct Prepared {
params_json: Value,
preset_label: String,
library: Vec<([u8; 3], Paint)>,
bytes: Arc<Vec<u8>>,
}
/// What command `c` with params `p` traces, and how, from the session: everything but the trace.
@@ -597,8 +600,8 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result<Prepared> {
let bytes = Arc::clone(&blob.bytes);
let library = trace_library(c, s, &mut params)?;
let traced_with = serde_json::to_value(&params).map_err(|e| EngineError::Other(e.to_string()))?;
let inputs = TraceInputs { target, image, params: traced_with, swatches: params.swatches.clone() };
Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library, bytes })
let inputs = TraceInputs { target, image, params: traced_with, swatches: params.swatches.clone(), bytes };
Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library })
}
/// What a trace made of an image: the size in pixels it was decoded at, and the paths.
@@ -616,11 +619,11 @@ impl Traced {
}
}
/// Decode the image `bytes` and trace it with `params`, telling `steps` how far it has got
/// ([`tr::trace_watched`]); [`EngineError::Cancelled`] once `steps` answers `false`.
fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, bytes: &[u8], steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> {
/// Decode the image bytes of `inputs` and trace them with `params`, telling `steps` how far it has
/// got ([`tr::trace_watched`]); [`EngineError::Cancelled`] once `steps` answers `false`.
fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> {
// An image over the tracer's size is traced scaled down (the paths are scaled back).
let raster = tr::Raster::decode_to_fit(bytes).map_err(|e| EngineError::Other(e.to_string()))?;
let raster = tr::Raster::decode_to_fit(&inputs.bytes).map_err(|e| EngineError::Other(e.to_string()))?;
if !steps(0, 0) {
return Err(EngineError::Cancelled);
}
@@ -682,7 +685,8 @@ impl TraceRun {
(self.prepared.inputs.image.width, self.prepared.inputs.image.height)
}
/// Does it still apply: would the command trace the same object, image and settings now?
/// Does it still apply: would the command trace the same object, image, pixels and settings
/// now?
pub fn current(&self, s: &Session) -> bool {
prepare(s, self.command, &self.params).is_ok_and(|now| now.inputs == self.prepared.inputs)
}
@@ -691,13 +695,13 @@ impl TraceRun {
/// failed or stopped ([`EngineError::Cancelled`] once `steps` answers `false`). It touches no
/// document, so it can run on any thread.
pub fn run(&self, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> {
trace_now(&self.prepared.inputs, &self.prepared.trace, &self.prepared.bytes, steps)
trace_now(&self.prepared.inputs, &self.prepared.trace, steps)
}
}
pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Value> {
let c = if expand { "imageTrace.makeAndExpand" } else { "imageTrace.make" };
let Prepared { inputs, trace, view, params_json, preset_label, library, bytes } = prepare(s, c, p)?;
let Prepared { inputs, trace, view, params_json, preset_label, library } = prepare(s, c, p)?;
let group_by_color = expand && by_color_param(c, p)?;
// A saved preset's settings join the journal entry, so a replay traces as this run did after
// the preset is changed, renamed or deleted.
@@ -709,7 +713,7 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
// A trace handed in for these very inputs ([`TraceRun`]), else one made now.
let Traced { raster, res, .. } = match s.trace_hand_off.take() {
Some(traced) if traced.inputs == inputs => traced,
_ => trace_now(&inputs, &trace, &bytes, &|_, _| true)?,
_ => trace_now(&inputs, &trace, &|_, _| true)?,
};
let TraceInputs { target, image: img, .. } = inputs;
let mut warnings = keep_warnings(&trace, &res);
+6 -4
View File
@@ -5,9 +5,11 @@
//! Colour settings and the proof view are process-wide (`vectorcraft_color::cms::active`,
//! `vectorcraft_render::proof::view`). A document's assigned profiles are stored in
//! `Document::color_profiles` (files before format v3: `Document.unknown["colorProfiles"]`) and
//! take the place of the working spaces in the active settings when assigned, and when the working
//! settings change while the document is in front ([`use_front_profiles`]); the working spaces stay
//! as Edit → Color Settings set them.
//! take the place of the working spaces in the active settings while the document is in front
//! ([`use_front_profiles`]): when they are assigned, when the working settings change, and when the
//! document comes to the front or its assignment comes back (an open, a switch, a close, a revert,
//! an undo or a rollback, [`Session::sync_front_profiles`]); the working spaces stay as Edit → Color
//! Settings set them.
use std::collections::BTreeMap;
use std::sync::Arc;
@@ -181,7 +183,7 @@ fn touch_all(s: &mut Session) {
/// Make the active settings the working settings with the profiles the front document is assigned
/// in place of the working spaces (none, or no document open: the working spaces). The open
/// documents redraw when the active settings change.
fn use_front_profiles(s: &mut Session) {
pub(crate) fn use_front_profiles(s: &mut Session) {
let (rgb, cmyk) = s.active().map(|d| doc_profiles(&d.doc)).unwrap_or_default();
if cms::use_document_profiles(rgb.as_deref(), cmyk.as_deref()) {
touch_all(s);
+1 -1
View File
@@ -52,7 +52,7 @@ pub const CATEGORIES: [(&str, &str); 13] = [
];
/// The object counts of `document.info` and their labels.
const OBJECT_LABELS: [(&str, &str); 19] = [
pub const OBJECT_LABELS: [(&str, &str); 19] = [
("paths", "Paths"),
("compoundPaths", "Compound Paths"),
("groups", "Groups"),
+22 -4
View File
@@ -41,6 +41,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
roll_back(s, start, &stash);
s.notify_text_tool("batch.rollBack");
s.active = active;
s.sync_front_profiles();
(s.paint, s.fill_active, s.draw_mode, s.draw_inside, s.clipboard, s.untitled_counter, s.explicit_undo_group) = saved;
s.pending_paint = None;
return Err(e);
@@ -78,8 +79,11 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
/// `artboard`, as the Artboards panel shows it in the document the step runs in: past that
/// document's last artboard, the last one; a Paste in Place, in Front or in Back step that names
/// `artboards` keeps them, and one that names neither, while the Artboard tool is chosen with
/// several artboards selected, pastes on those. A step that resizes the active artboard
/// ([`crate::FIT_ACTIVE_ARTBOARD`]) and names no `index` gets that artboard as its `index`.
/// several artboards selected, pastes on those. A Fit to Artwork Bounds step that names neither
/// `index` nor `indices`, while the Artboard tool is chosen with several artboards selected when the
/// step runs, gets those as its `indices`, which its journal entry records. Otherwise a step that
/// resizes the active artboard ([`crate::FIT_ACTIVE_ARTBOARD`]) and names no `index` (nor
/// `indices`, for Fit to Artwork Bounds) gets that artboard as its `index`.
/// `grouped` gets each step's undo groups, as [`Session::batch_steps`] keeps them.
fn run_steps(
s: &mut Session,
@@ -110,9 +114,22 @@ fn run_steps(
// Artboard tool is chosen with several artboards selected, pastes on those.
let names_artboards = id.starts_with("edit.pasteIn")
&& (params.get("artboards").is_some() || (params.get("artboard").is_none() && !crate::cmd::edit::artboard_tool_picks(s).is_empty()));
// A Fit to Artwork Bounds step that names neither `index` nor `indices`, while the Artboard
// tool is chosen with several artboards selected, fits those, as the command does on its own.
let fit_picks = if id == "artboard.fitToArt" && params.get("index").is_none() && params.get("indices").is_none() {
crate::cmd::edit::artboard_tool_picks(s)
} else {
Vec::new()
};
if !fit_picks.is_empty()
&& let Some(o) = params.as_object_mut()
{
o.insert("indices".into(), json!(fit_picks));
}
if let Some(a) = artboard
&& let Some(key) = key
&& params.get(key).is_none()
&& !(id == "artboard.fitToArt" && params.get("indices").is_some())
&& !names_artboards
&& let Some(last) = s.active().and_then(|d| d.doc.artboards.len().checked_sub(1))
&& let Some(o) = params.as_object_mut()
@@ -129,8 +146,9 @@ fn run_steps(
}
grouped.push(step_groups(s, start, &held));
// The step's journal entry records what it took from the preferences or the clock (a
// save's date, a new document's), as a command of its own would.
if noted != params
// save's date, a new document's), as a command of its own would, and the artboards a Fit to
// Artwork Bounds step took from the Artboard tool.
if (noted != params || !fit_picks.is_empty())
&& let Some(c) = c.as_object_mut()
{
c.insert("params".into(), noted);
+2 -2
View File
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export Document",
[],
None,
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the visible art), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Line truncated
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the visible art), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditabilit Line truncated
has_doc,
export::export
),
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Batch",
[],
None,
"{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included",
"{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer; an artboard.fitToArt step that names neither index nor indices, while the Artboard tool is chosen with several artboards selected when the step runs, gets those as indices instead, and the journal records them)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included",
has_doc,
batch::batch
),
+7
View File
@@ -629,6 +629,13 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
{
return Ok(Encoded::one_with_notes(bytes, notes));
}
// So does a `.ai` file of the art's bounds (a legacy version 7 `.ai` file has none to leave out).
if use_artboards == Some(false)
&& f.id == "ai"
&& let Some(enc) = super::save::encode_ai_art_page(C, f, doc, p)?
{
return Ok(enc);
}
if use_artboards == Some(false)
&& let Some((art, q)) = art_page(C, doc, p)?
{
+32 -1
View File
@@ -685,6 +685,31 @@ struct AiEditingData {
editing_data: Option<bool>,
}
/// Why a `.ai` file of the art's bounds (`useArtboards: false`) carries no editing data.
pub const AI_EDITING_NEEDS_THE_ARTBOARDS: &str =
"Preserve editing was left out: an .ai file of the art's bounds would replace the document's artboards when reopened";
/// The error for a `.ai` file of the art's bounds without PDF content.
pub const ART_PAGE_NEEDS_PDF: &str = "pdfCompatible: false needs the artboards to keep the editable artwork when useArtboards is false";
/// With `useArtboards: false` in `p`: the PDF-compatible `.ai` file of one page, the bounds of
/// `doc`'s visible art ([`super::encode::art_page`]). It carries neither the native document nor
/// the editing copy for other apps, and its notes end with [`AI_EDITING_NEEDS_THE_ARTBOARDS`].
/// `pdfCompatible: false` is refused. `None` when `p` asks for the artboards or for a legacy
/// version 7 `.ai` file.
pub(super) fn encode_ai_art_page(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result<Option<Encoded>> {
if super::encode::use_artboards(cmd, p)? != Some(false) || super::legacy_ai::wanted(cmd, f, p)? {
return Ok(None);
}
if !bool_or(p, "pdfCompatible", true) {
return Err(bad(cmd, ART_PAGE_NEEDS_PDF));
}
let Some((art, q)) = super::encode::art_page(cmd, doc, p)? else { return Ok(None) };
let mut enc = encode_ai_pages(cmd, f, &art, &q, false)?;
enc.setting_notes.push(AI_EDITING_NEEDS_THE_ARTBOARDS.to_string());
Ok(Some(enc))
}
/// The shared Save and Export encoder for `.ai` files (and `.ait` templates, the same file):
/// PDF-compatible by default, without PDF content (`pdfCompatible: false`), or legacy version 7
/// `.ai` files (`aiVersion: "7"`).
@@ -692,9 +717,15 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res
if super::legacy_ai::wanted(cmd, f, p)? {
return super::legacy_ai::encode(cmd, f, doc, p);
}
encode_ai_pages(cmd, f, doc, p, true)
}
/// [`encode_ai`] of a `.ai` file with or without PDF content, carrying the native document and
/// the editing copy for other apps when `editing` is true, and neither otherwise.
fn encode_ai_pages(cmd: &str, f: &Format, doc: &Document, p: &Value, editing: bool) -> Result<Encoded> {
let mut params = if p.is_object() { p.clone() } else { json!({}) };
if let Some(o) = params.as_object_mut() {
o.insert("preserveEditing".into(), json!(true));
o.insert("preserveEditing".into(), json!(editing));
// Keep upstream AI PDF layers, including hidden layers, unless a standard decides.
if o.get("standard").is_none_or(Value::is_null) {
o.entry("createLayers").or_insert(json!(true));
+59 -12
View File
@@ -402,28 +402,75 @@ fn ai_export_validates_options_even_when_editing_data_is_omitted() {
}
}
#[test]
fn ai_export_without_artboards_keeps_art_outside_the_original_pages() {
/// Two artboards, a visible 30 × 20 pt rectangle outside them at (180, 100) and a hidden one.
fn art_outside_the_artboards() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 80, "artboards": 2})).unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
s.execute("shape.rectangle", &json!({"x": 180, "y": 100, "width": 30, "height": 20})).unwrap();
s.execute("shape.rectangle", &json!({"x": 1000, "y": 1000, "width": 50, "height": 40})).unwrap();
s.execute("object.hide", &json!({})).unwrap();
s
}
/// Whether the `.ai` file `bytes` carries the editing copy of its art for other apps.
fn carries_private_data(bytes: &[u8]) -> bool {
let opts = LoadOptions { native: false, ..Default::default() };
load::load_with("a.ai", bytes, &opts).unwrap().editing_data
}
#[test]
fn an_ai_of_the_arts_bounds_carries_no_editing_data() {
let mut s = art_outside_the_artboards();
let before = comparable(&s.doc().unwrap().doc);
let r = s.execute("document.export", &json!({"format": "ai", "useArtboards": false, "range": "2"})).unwrap();
let bytes = b64(&r);
let pages = vectorcraft_pdf::import(&bytes).unwrap();
assert_eq!(pages.artboards.len(), 1);
assert_eq!((pages.artboards[0].rect.width(), pages.artboards[0].rect.height()), (30.0, 20.0));
let editing = vectorcraft_pdf::editing(&bytes).unwrap();
let exported = vectorcraft_format::load(&editing.data).unwrap();
assert_eq!(exported.artboards.len(), 1);
assert_eq!(exported.artboards[0].rect, vectorcraft_geom::Rect::new(180.0, 100.0, 210.0, 120.0));
assert_eq!(comparable(&s.doc().unwrap().doc), before);
let left_out = |v: &Value| v["warnings"].as_array().unwrap().iter().any(|w| w == super::save::AI_EDITING_NEEDS_THE_ARTBOARDS);
let path = tmp("art-bounds.ai");
for extra in [json!({}), json!({"range": "2"}), json!({"editingData": false}), json!({"path": path})] {
let mut params = json!({"format": "ai", "useArtboards": false});
params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
let r = s.execute("document.export", &params).unwrap();
let bytes = if params.get("path").is_some() { std::fs::read(&path).unwrap() } else { b64(&r) };
// One page, the visible art's bounds, whatever range names.
let pages = vectorcraft_pdf::import(&bytes).unwrap();
assert_eq!(pages.artboards.len(), 1, "{params}");
assert_eq!((pages.artboards[0].rect.width(), pages.artboards[0].rect.height()), (30.0, 20.0), "{params}");
assert!(vectorcraft_pdf::editing(&bytes).is_none(), "{params}");
assert!(!carries_private_data(&bytes), "{params}");
assert!(left_out(&r), "{params}: {r}");
assert_eq!(comparable(&s.doc().unwrap().doc), before);
}
// The artboards keep both editing copies, without the warning.
for params in [json!({"format": "ai"}), json!({"format": "ai", "useArtboards": true})] {
let r = s.execute("document.export", &params).unwrap();
let bytes = b64(&r);
let editing = vectorcraft_pdf::editing(&bytes).expect("editing data");
assert_eq!(vectorcraft_format::load(&editing.data).unwrap().artboards.len(), 2, "{params}");
assert!(carries_private_data(&bytes), "{params}");
assert!(!left_out(&r), "{params}: {r}");
}
assert!(s.execute("document.export", &json!({"format": "ai", "useArtboards": "yes"})).is_err());
}
#[test]
fn an_ai_of_the_arts_bounds_without_pdf_is_refused() {
let mut s = art_outside_the_artboards();
let before = comparable(&s.doc().unwrap().doc);
for extra in [json!({}), json!({"editingData": false}), json!({"editingData": true})] {
for command in ["document.export", "document.serialize"] {
let mut params = json!({"format": "ai", "useArtboards": false, "pdfCompatible": false});
params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
let e = s.execute(command, &params).unwrap_err().to_string();
assert!(e.contains(super::save::ART_PAGE_NEEDS_PDF), "{command} {params}: {e}");
assert_eq!(comparable(&s.doc().unwrap().doc), before);
}
}
// A document with no visible art is still refused for that.
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 80})).unwrap();
let e = s.execute("document.export", &json!({"format": "ai", "useArtboards": false})).unwrap_err().to_string();
assert!(e.contains("no visible art"), "{e}");
}
/// Color Halftone's Max Radius is in pixels of the raster effects resolution since document
/// version 3 (#3260). A PDF saved with Preserve Editing carries the native document, so one from
/// before that opens with the radius converted, drawing the same dots; one saved since opens as
+9 -3
View File
@@ -13,7 +13,7 @@ use serde_json::{Value, json};
use vectorcraft_doc::NodeKind;
use super::findfiles::{self, Limits, Visitor};
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, bool_or, checked_ids_param, cmd};
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, bool_or, cmd, ids_param};
/// The most linked files one search looks for.
const MAX_LINKS: usize = 1_000;
@@ -143,8 +143,14 @@ fn find(s: &mut Session, p: &Value) -> Result<Value> {
let ids = match p.get("ids") {
None | Some(Value::Null) => None,
Some(_) => {
let ids = checked_ids_param(s, p, "ids", C)?;
let linkable = |id: &NodeId| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_) | NodeKind::PlacedDocument(_)));
// Images and placed documents in opacity-mask art and in the art of symbols, graph
// designs and patterns are named by their ids too (`links.list`).
let ids = ids_param(p, "ids", C)?.unwrap_or_default();
let kind = |id: &NodeId| st.doc.stored_node(*id).map(|(n, _)| &n.kind);
if let Some(value) = ids.iter().find(|id| kind(id).is_none()).map(|id| id.0) {
return Err(bad(C, format!("no such object id {value}")));
}
let linkable = |id: &NodeId| matches!(kind(id), Some(NodeKind::Image(_) | NodeKind::PlacedDocument(_)));
if let Some(id) = ids.iter().find(|id| !linkable(id)) {
return Err(bad(C, format!("object {} is not an image or a linked file", id.0)));
}
+145 -73
View File
@@ -30,6 +30,7 @@ use serde_json::{Value, json};
use vectorcraft_doc::links::{Align, Preserve, hash_bytes};
use vectorcraft_doc::{
Appearance, DataValue, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, PlacedDocument, PlacementOptions,
StoredPlace, StoredRoot,
};
use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes};
@@ -43,7 +44,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Check Links",
[],
None,
"{ids?: [image or placed document ids] (default: every linked image and placed document)} where each linked file is and whether it changed since it was read → {links: [{name, path?, status: ok|modified|missing, ids, found?: path (found away from its path: relative to the document, or by name in its folder), preview: true (showing the low-resolution preview, not the file), refused?: why the path is not followed (another computer, a device or a URL: it counts as missing)}], missing, modified}; under automation read roots, path and found are left out when the file they name is outside the roots",
"{ids?: [image or placed document ids] (default: every linked image and placed document, in the layers and in opacity-mask art, symbols, graph designs and patterns)} where each linked file is and whether it changed since it was read → {links: [{name, path?, status: ok|modified|missing, ids, found?: path (found away from its path: relative to the document, or by name in its folder), preview: true (showing the low-resolution preview, not the file), refused?: why the path is not followed (another computer, a device or a URL: it counts as missing)}], missing, modified}; under automation read roots, path and found are left out when the file they name is outside the roots",
has_doc,
check
),
@@ -52,7 +53,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Update Links",
[],
None,
"{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. The images and placed documents inside symbols, graph designs, patterns and opacity masks that show the same content are read again too (by default also those only that art shows); they have no ids to list. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns]}",
"{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. Images and placed documents inside symbols, graph designs, patterns and opacity masks have ids of their own, as links.list gives them; those that show the same content as one read again are read again too. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns]}",
has_doc,
update
),
@@ -70,7 +71,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Relink",
[],
None,
"{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object in the layers linked to the same file as one of them) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's)}",
"{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object linked to the same file as one of them, in the layers, opacity-mask art, symbols, graph designs and patterns) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's)}",
has_doc,
relink
),
@@ -79,7 +80,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Links",
[],
None,
"{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first, dcsTransparency?: false (Show DCS Transparency Interactions: mark the images placed from DCS files that are transparent, themselves or a group or layer holding them, or that overlap a visible object with its own transparency; it looks at every object, so it takes longer)} every image object and placed document in the layers, as the Links panel lists them → {links: [{id, name, linked, status: ok|modified|missing|embedded, format (DCS for an image placed from a DCS file), pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels), dcsTransparency?: true (with dcsTransparency)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots",
"{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first, dcsTransparency?: false (Show DCS Transparency Interactions: mark the images placed from DCS files that are transparent, themselves or a group or layer holding them, or that overlap a visible object with its own transparency; it looks at every object, so it takes longer)} every image object and placed document the document stores, as the Links panel lists them: those in the layers, then those in opacity-mask art and in the art of symbols, graph designs and patterns (one row per stored object, never one per symbol instance or pattern tile) → {links: [{id, name, linked, status: ok|modified|missing|embedded, format (DCS for an image placed from a DCS file), pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels), dcsTransparency?: true (with dcsTransparency), owner?: {kind: layers|symbol|graphDesign|pattern, name? (of the symbol, graph design or pattern), maskOf?: id (in the opacity-mask art of that object)} (an object outside the layer tree)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots",
has_doc,
list
),
@@ -88,7 +89,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Go To Link",
[],
None,
"{id?} select image or placed document `id` (default: the first selected one); the Links panel scrolls it into view → {id, bounds: [x0, y0, x1, y1]}",
"{id?} select image or placed document `id` (default: the first selected one); the Links panel scrolls it into view → {id, bounds: [x0, y0, x1, y1], onCanvas: true}; one in opacity-mask art or in the art of a symbol, graph design or pattern has no place of its own on the canvas: the selection is cleared → {id, onCanvas: false, owner} (owner as links.list gives it)",
has_doc,
go_to
),
@@ -156,7 +157,8 @@ impl Status {
struct Group {
link: LinkInfo,
key: String,
/// The objects in the layers (images in symbols and patterns share the content, not an id).
/// The stored objects showing it: in the layers, in opacity-mask art and in the art of symbols,
/// graph designs and patterns ([`Document::visit_stored`]), each once.
ids: Vec<NodeId>,
/// Placed documents: what they show.
document: Option<Shown>,
@@ -177,8 +179,9 @@ fn linked(n: &Node) -> Option<(&LinkInfo, &str, Option<Shown>)> {
}
}
/// Every linked file of `d` with the ids of the objects showing it (for [`crate::link_watch`]): an
/// image placed from a DCS file has its plate files of their own too, beside its file.
/// Every linked file of `d` with the ids of the objects showing it, wherever they are stored (for
/// [`crate::link_watch`]): an image placed from a DCS file has its plate files of their own too,
/// beside its file.
pub(crate) fn linked_groups(d: &Document) -> Vec<(String, Vec<u64>)> {
let mut out = vec![];
for g in groups(d, None).into_iter().filter(|g| !g.ids.is_empty()) {
@@ -190,8 +193,10 @@ pub(crate) fn linked_groups(d: &Document) -> Vec<(String, Vec<u64>)> {
out
}
/// The linked images and placed documents of `d` by file and content: those in the layers (only `ids` when
/// given), then, without `ids`, the ones only symbols and patterns show.
/// The linked images and placed documents of `d` by file and content, wherever they are stored
/// (only `ids` when given), in [`Document::visit_stored`] order. An object whose id an object
/// visited before it has (art being edited on a layer and its definition) counts once, by its
/// first place; without `ids` its content is still grouped.
fn groups(d: &Document, ids: Option<&[NodeId]>) -> Vec<Group> {
let mut out: Vec<Group> = vec![];
let mut index: BTreeMap<(String, String, bool), usize> = BTreeMap::new();
@@ -210,24 +215,48 @@ fn groups(d: &Document, ids: Option<&[NodeId]>) -> Vec<Group> {
g.ids.push(id);
}
};
d.walk(|n| {
if let Some((l, key, document)) = linked(n)
&& wanted.as_ref().is_none_or(|ids| ids.contains(&n.id))
{
let mut seen = std::collections::HashSet::new();
d.visit_stored(|n, _| {
let Some((l, key, document)) = linked(n) else { return };
// Id 0 names no object.
let first = n.id.0 != 0 && seen.insert(n.id);
if first && wanted.as_ref().is_none_or(|ids| ids.contains(&n.id)) {
add(l, key, document, Some(n.id));
} else if ids.is_none() {
add(l, key, document, None);
}
});
if ids.is_none() {
d.visit_images(|_, im| {
if let Some(l) = &im.link {
add(l, &im.key, None, None);
}
});
d.visit_placed(|_, p| add(&p.link, &p.key, Some((p.bounding, p.page_box)), None));
}
out
}
/// Stored object `id` of `d` ([`Document::stored_node`]).
fn stored(d: &Document, id: NodeId) -> Option<&Node> {
d.stored_node(id).map(|(n, _)| &**n)
}
/// Of `ids`, the objects of `d` outside the layer tree (where [`Document::node`] finds none).
fn nested_ids(d: &Document, ids: &[NodeId]) -> std::collections::HashSet<NodeId> {
ids.iter().copied().filter(|id| d.node(*id).is_none()).collect()
}
/// `links.list`'s `owner` of an object stored at `place` of `d`, when it is not in the layer tree
/// itself: `{kind: layers|symbol|graphDesign|pattern, name?, maskOf?}`.
fn owner_json(d: &Document, place: StoredPlace) -> Option<Value> {
if place.in_layers() {
return None;
}
let mut owner = match place.root {
StoredRoot::Layer(_) => json!({ "kind": "layers" }),
StoredRoot::Symbol(i) => json!({ "kind": "symbol", "name": d.symbols.get(i).map(|s| s.name.as_str()) }),
StoredRoot::GraphDesign(i) => json!({ "kind": "graphDesign", "name": d.graph_designs.get(i).map(|g| g.name.as_str()) }),
StoredRoot::Pattern { pattern, .. } => json!({ "kind": "pattern", "name": d.patterns.get(pattern).map(|p| p.name.as_str()) }),
};
if let Some(m) = place.mask_of {
owner["maskOf"] = json!(m.0);
}
Some(owner)
}
/// A linked file where it was found.
struct Found {
path: String,
@@ -493,8 +522,8 @@ pub(crate) fn full_linked_images<'a>(d: &'a Document, base: LinkBase) -> (Cow<'a
}
/// The linked files of the open document `st` that `links.findFiles` looks for, each with the
/// objects in the layers that show it: the files of objects `ids` whatever their status, else the
/// files that can't be found.
/// stored objects that show it: the files of objects `ids` whatever their status, else the files
/// that can't be found.
pub(crate) fn files_to_find(st: &crate::DocState, ids: Option<&[NodeId]>) -> Vec<(LinkInfo, Vec<NodeId>)> {
groups(&st.doc, ids)
.into_iter()
@@ -708,7 +737,7 @@ fn clip_to(
type Remake<'a> = dyn FnMut(&Node, Option<(&PathData, FillRule)>) -> (Node, ClipTo) + 'a;
/// Remakes the linked objects outside the layer tree (in symbols, graph designs, patterns and
/// opacity masks, where [`Document::node`] finds no ids) that `pick` holds for.
/// opacity masks, where [`Document::node`] does not find them) that `pick` holds for.
struct Nested<'a> {
pick: &'a dyn Fn(&Node) -> bool,
make: &'a mut Remake<'a>,
@@ -854,10 +883,10 @@ impl Nested<'_> {
}
}
/// Placed documents `ids` show `src`, read from the file `link` points at, each placed as its
/// Placement Options say (`force`: as that Preserve choice says, whatever they say); with `also`
/// (a file's path and the content shown), so do the placed documents outside the layer tree that
/// show that content.
/// Placed documents `ids` (in the layers or outside them) show `src`, read from the file `link`
/// points at, each placed as its Placement Options say (`force`: as that Preserve choice says,
/// whatever they say); with `also` (a file's path and the content shown), so do the placed
/// documents outside the layer tree that show that content.
fn install_document(
d: &mut Document,
ids: &[NodeId],
@@ -872,8 +901,10 @@ fn install_document(
let o = PlacementOptions { preserve: force.unwrap_or(p.placement.preserve), ..p.placement };
placed_xf(p.xf, (p.width, p.height), (1.0, 1.0), (w, h), (1.0, 1.0), o)
};
if let Some(also) = also {
let pick = |n: &Node| shows(n, also, true);
let nested = nested_ids(d, ids);
if also.is_some() || !nested.is_empty() {
let pick =
|n: &Node| matches!(n.kind, NodeKind::PlacedDocument(_)) && (nested.contains(&n.id) || also.is_some_and(|also| shows(n, also, true)));
let mut make = |n: &Node, _: Option<(&PathData, FillRule)>| {
let mut n = n.clone();
let mut clip = ClipTo::Keep;
@@ -1037,26 +1068,39 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_
install(d, &[id], read, Some(Preserve::Bounds), None)
}
/// Image objects `ids` show the file read for `link` (`img`), each placed as its Placement
/// Options say (`force`: as that Preserve choice says, whatever they say); with `also` (a file's
/// path and the content shown), so do the images outside the layer tree that show that content.
/// Image objects `ids` (in the layers or outside them) show the file read for `link` (`img`), each
/// placed as its Placement Options say (`force`: as that Preserve choice says, whatever they say);
/// with `also` (a file's path and the content shown), so do the images outside the layer tree that
/// show that content.
fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Option<Preserve>, also: Option<(&str, &str)>) -> Result<()> {
let new_pt = super::place::pt_per_px(img.ppi);
let mut clips = vec![];
if let Some(also) = also {
// Every image picked shows content `also.1`, so one resolution serves them all.
let old_pt = file_pt(d, also.1);
let pick = |n: &Node| shows(n, also, false);
// The clipping path the old content's DCS file drew it through.
let old_clip = d.images.get(also.1).and_then(ImageBlob::separated_clip);
let nested = nested_ids(d, ids);
if also.is_some() || !nested.is_empty() {
let pick = |n: &Node| matches!(n.kind, NodeKind::Image(_)) && (nested.contains(&n.id) || also.is_some_and(|also| shows(n, also, false)));
// The resolution of each content the images picked show, and the clipping path its DCS file
// drew it through, looked up once each.
let mut old: BTreeMap<String, ((f64, f64), Option<PathData>)> = BTreeMap::new();
d.visit_stored(|n, _| {
if let NodeKind::Image(im) = &n.kind
&& pick(n)
&& !old.contains_key(&im.key)
{
old.insert(im.key.clone(), (file_pt(d, &im.key), d.images.get(&im.key).and_then(ImageBlob::separated_clip)));
}
});
let mut make = |n: &Node, held: Option<(&PathData, FillRule)>| {
let mut n = n.clone();
let mut clip = ClipTo::Keep;
if let NodeKind::Image(im) = &mut n.kind {
let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement };
let size = |w: u32, h: u32| (w as f64, h as f64);
let (old_pt, old_clip) = match old.get(&im.key) {
Some((pt, clip)) => (*pt, clip.as_ref()),
None => (super::place::pt_per_px(None), None),
};
let (xf, c) = placed_xf(im.xf, size(im.width, im.height), old_pt, size(img.width, img.height), new_pt, o);
clip = clip_to(im.xf, old_clip.as_ref(), c, &img, xf, held);
clip = clip_to(im.xf, old_clip, c, &img, xf, held);
(im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone()));
}
(n, clip)
@@ -1267,7 +1311,7 @@ pub fn resolve(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps
}
}
// The objects in symbols, graph designs, patterns and opacity masks that show the same file and
// content, which have no ids here, whatever else their links hold.
// content, whatever else their links hold, those whose id an earlier object has included.
if !moved.is_empty() {
let mut by_path: BTreeMap<String, Vec<(String, bool, LinkInfo)>> = BTreeMap::new();
for (path, key, document, new) in moved {
@@ -1302,13 +1346,25 @@ fn link_mut(n: &mut Node) -> Option<&mut LinkInfo> {
}
}
/// Linked image objects (or placed documents) `ids` link to `link`.
/// Linked image objects (or placed documents) `ids`, in the layers or outside them, link to `link`.
fn set_links(d: &mut Document, ids: &[NodeId], link: &LinkInfo) {
for id in ids {
let nested = nested_ids(d, ids);
for id in ids.iter().filter(|id| !nested.contains(id)) {
if let Some(l) = d.node_mut(*id).and_then(link_mut) {
*l = link.clone();
}
}
if !nested.is_empty() {
let pick = |n: &Node| nested.contains(&n.id) && linked(n).is_some();
let mut make = |n: &Node, _: Option<(&PathData, FillRule)>| {
let mut out = n.clone();
if let Some(l) = link_mut(&mut out) {
*l = link.clone();
}
(out, ClipTo::Keep)
};
Nested { pick: &pick, make: &mut make, next: 0 }.run(d);
}
}
/// Placed documents of the document saved at `path` (document `saved` of `s`) in the other open
@@ -1331,14 +1387,17 @@ pub(crate) fn refresh_placed(s: &mut Session, saved: u64, path: &str) {
if targets.is_empty() {
return;
}
// Each document is updated as the active one, without switching tools.
// Each document is updated as the active one, through its own profiles, without switching
// tools.
let back = s.active;
for i in targets {
s.active = Some(i);
s.sync_front_profiles();
// A file that can't be read leaves what its objects show: links.check reports it.
let _ = update_where(s, None, Some(&path));
}
s.active = back;
s.sync_front_profiles();
}
// ---------- relative paths ----------
@@ -1537,7 +1596,7 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> {
/// Update Links in the active document of `s` for objects `ids` (default: the linked files that
/// changed or show their preview), or with `path`, for the placed documents of the file at `path`
/// whatever their status. The objects in symbols, graph designs, patterns and opacity masks that
/// show the same content are read again too, and have no ids to report.
/// show the same content are read again too.
fn update_where(s: &mut Session, ids: Option<Vec<NodeId>>, path: Option<&str>) -> Result<Value> {
let st = s.doc()?;
let (mut reads, mut missing) = (vec![], vec![]);
@@ -1603,7 +1662,7 @@ enum Scope {
Each,
/// The objects given or selected.
Selected,
/// Every object in the layers linked to the same file as one given or selected.
/// Every stored object linked to the same file as one given or selected.
All,
/// The objects given or selected, then every other missing link whose file name is in the new
/// file's folder.
@@ -1687,7 +1746,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
};
// An image or a placed document, with its link.
let image = |id: &NodeId| {
st.doc.node(*id).and_then(|n| match &n.kind {
stored(&st.doc, *id).and_then(|n| match &n.kind {
NodeKind::Image(im) => Some(im.link.as_ref()),
NodeKind::PlacedDocument(p) => Some(Some(&p.link)),
_ => None,
@@ -1712,22 +1771,23 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
if ids.is_empty() {
return Err(bad(C, "select the images to relink, or pass ids"));
}
// All Instances: the other objects in the layers linked to the same files.
// All Instances: the other stored objects linked to the same files, each once.
if scope == Scope::All {
let paths: BTreeSet<&str> = ids.iter().filter_map(|id| image(id).flatten()).map(|l| l.path.as_str()).collect();
let given: BTreeSet<NodeId> = ids.iter().copied().collect();
let mut given: BTreeSet<NodeId> = ids.iter().copied().collect();
let mut more = vec![];
st.doc.walk(|n| {
st.doc.visit_stored(|n, _| {
if let Some((l, _, _)) = linked(n)
&& paths.contains(l.path.as_str())
&& !given.contains(&n.id)
&& n.id.0 != 0
&& given.insert(n.id)
{
more.push(n.id);
}
});
ids.extend(more);
}
if copy_to.is_some() && ids.iter().any(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::PlacedDocument(_)))) {
if copy_to.is_some() && ids.iter().any(|id| matches!(stored(&st.doc, *id).map(|n| &n.kind), Some(NodeKind::PlacedDocument(_)))) {
return Err(bad(C, "copy takes images only: relink placed documents where their files are"));
}
// (ids, the file) per file to read.
@@ -1763,7 +1823,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
let mut images = vec![];
let mut documents: Vec<((u32, bool, PageBox), Vec<NodeId>)> = vec![];
for id in ids {
match st.doc.node(id).map(|n| &n.kind) {
match stored(&st.doc, id).map(|n| &n.kind) {
Some(NodeKind::PlacedDocument(pl)) => {
let k = (pl.page(), pl.bounding, pl.page_box);
match documents.iter_mut().find(|(e, _)| *e == k) {
@@ -1913,9 +1973,9 @@ fn copy_into_folder(_: &str, _: &[u8], _: &Path) -> Result<(String, bool)> {
// ---------- the Links panel ----------
/// Image object `id` of `d`.
/// Image object `id` of `d`, wherever it is stored.
fn image_of(d: &Document, id: NodeId) -> Option<&ImageObject> {
match &d.node(id)?.kind {
match &stored(d, id)?.kind {
NodeKind::Image(im) => Some(im),
_ => None,
}
@@ -1933,7 +1993,7 @@ fn image_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result<NodeId> {
.ok_or_else(|| bad(cmd, "select an image, or pass id"))?;
match image_of(&st.doc, id) {
Some(_) => Ok(id),
None if st.doc.node(id).is_none() => Err(crate::EngineError::NoNode(id)),
None if stored(&st.doc, id).is_none() => Err(crate::EngineError::NoNode(id)),
None => Err(bad(cmd, format!("object {} is not an image", id.0))),
}
}
@@ -1947,9 +2007,9 @@ fn placement_mut(n: &mut Node) -> Option<&mut PlacementOptions> {
}
}
/// The Placement Options of image or placed document `id` of `d`.
/// The Placement Options of image or placed document `id` of `d`, wherever it is stored.
fn placement_of(d: &Document, id: NodeId) -> Option<PlacementOptions> {
match &d.node(id)?.kind {
match &stored(d, id)?.kind {
NodeKind::Image(im) => Some(im.placement),
NodeKind::PlacedDocument(p) => Some(p.placement),
_ => None,
@@ -1962,12 +2022,12 @@ fn linked_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result<NodeId> {
let id = object_param(p, "id", cmd)?.or_else(first).ok_or_else(|| bad(cmd, "select an image, or pass id"))?;
match placement_of(&st.doc, id) {
Some(_) => Ok(id),
None if st.doc.node(id).is_none() => Err(crate::EngineError::NoNode(id)),
None if stored(&st.doc, id).is_none() => Err(crate::EngineError::NoNode(id)),
None => Err(bad(cmd, format!("object {} is not an image or a linked file", id.0))),
}
}
/// Per linked image in the layers of `st`: its file's status, where it was found when away from
/// Per linked image or placed document of `st`, wherever it is stored: its file's status, where it was found when away from
/// its path, and whether the image shows its preview (each file probed once).
pub(crate) fn statuses(st: &crate::DocState) -> BTreeMap<NodeId, (Status, Option<String>, bool)> {
let mut out = BTreeMap::new();
@@ -2068,17 +2128,20 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
}
let interactions = if switch_or(p, "dcsTransparency", false, C)? { dcs_transparency(&st.doc) } else { BTreeSet::new() };
let statuses = statuses(st);
let mut objects = vec![];
st.doc.walk(|n| {
if matches!(n.kind, NodeKind::Image(_) | NodeKind::PlacedDocument(_)) {
objects.push(n);
// The layer tree's objects, top first as the Layers panel lists them, then the others in the
// order they are stored (opacity-mask art, symbols, graph designs, patterns), each once.
let (mut objects, mut nested) = (vec![], vec![]);
let mut seen = std::collections::HashSet::new();
st.doc.visit_stored(|n, place| {
if matches!(n.kind, NodeKind::Image(_) | NodeKind::PlacedDocument(_)) && n.id.0 != 0 && seen.insert(n.id) {
if place.in_layers() { objects.push((n, place)) } else { nested.push((n, place)) }
}
});
// Top first, as the Layers panel lists them.
objects.reverse();
objects.extend(nested);
let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
let mut rows = vec![];
for n in objects {
for (n, place) in objects {
let (status, found, preview) = match statuses.get(&n.id) {
Some((s, f, p)) => (s.as_str(), f.as_deref(), *p),
None => ("embedded", None, false),
@@ -2121,6 +2184,9 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
if preview {
row["preview"] = json!(true);
}
if let Some(owner) = owner_json(&st.doc, place) {
row["owner"] = owner;
}
if interactions.contains(&n.id) {
row["dcsTransparency"] = json!(true);
}
@@ -2141,15 +2207,21 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
fn go_to(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let id = linked_param(st, p, "links.goTo")?;
// An object in mask art or a definition has no place of its own on the canvas: the selection
// is cleared, and the reply names what holds it.
if let Some(owner) = st.doc.stored_node(id).and_then(|(_, place)| owner_json(&st.doc, place)) {
s.select(|_, sel| sel.set([]))?;
return Ok(json!({ "id": id.0, "onCanvas": false, "owner": owner }));
}
let b = st.doc.node(id).and_then(Node::geometric_bounds).unwrap_or_default();
s.select(|_, sel| sel.set([id]))?;
Ok(json!({ "id": id.0, "bounds": [b.x0, b.y0, b.x1, b.y1] }))
Ok(json!({ "id": id.0, "bounds": [b.x0, b.y0, b.x1, b.y1], "onCanvas": true }))
}
fn embed(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "links.embed";
let st = s.doc()?;
let kind = |id: &NodeId| st.doc.node(*id).map(|n| &n.kind);
let kind = |id: &NodeId| stored(&st.doc, *id).map(|n| &n.kind);
let linked = |id: &NodeId| match kind(id) {
Some(NodeKind::Image(im)) => im.link.is_some(),
Some(NodeKind::PlacedDocument(_)) => true,
@@ -2207,7 +2279,7 @@ fn embed(s: &mut Session, p: &Value) -> Result<Value> {
install(d, &ids, read, Some(Preserve::Bounds), None)?;
}
for id in &done {
if let Some(Node { kind: NodeKind::Image(im), .. }) = d.node_mut(*id) {
if let Some(Node { kind: NodeKind::Image(im), .. }) = d.stored_node_mut(*id) {
im.link = None;
}
}
@@ -2235,7 +2307,7 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "links.unembed";
let st = s.doc()?;
let id = image_param(st, p, C)?;
let n = st.doc.node(id).ok_or(crate::EngineError::NoNode(id))?;
let n = stored(&st.doc, id).ok_or(crate::EngineError::NoNode(id))?;
let im = image_of(&st.doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?;
if im.link.is_some() {
return Err(bad(C, format!("image {} is linked already", id.0)));
@@ -2321,7 +2393,7 @@ fn scale_rotation(xf: Affine, (px, py): (f64, f64)) -> (Value, Value) {
/// Link Info of placed document `id`.
fn placed_info(st: &crate::DocState, id: NodeId) -> Result<Value> {
let n = st.doc.node(id).ok_or(crate::EngineError::NoNode(id))?;
let n = stored(&st.doc, id).ok_or(crate::EngineError::NoNode(id))?;
let NodeKind::PlacedDocument(pl) = &n.kind else { return Err(bad("links.info", format!("object {} is not a placed document", id.0))) };
let size = n.geometric_bounds().unwrap_or_default();
let (scale, rotation) = scale_rotation(pl.xf, (1.0, 1.0));
@@ -2401,7 +2473,7 @@ fn placement_options(s: &mut Session, p: &Value) -> Result<Value> {
};
s.edit("Placement Options", |d, _| {
for id in &ids {
if let Some(o) = d.node_mut(*id).and_then(placement_mut) {
if let Some(o) = d.stored_node_mut(*id).and_then(placement_mut) {
set(o);
}
}
+207 -8
View File
@@ -481,6 +481,12 @@ fn join_point(sp: &mut SubPath, ai: usize, smooth: bool) {
}
}
#[cfg(test)]
thread_local! {
/// Anchors that [`merge_coincident`] moved to a lower index of their vector on this thread.
static ANCHOR_MOVES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Merge each run of `picked` neighbours of `sp` that lie on one another into one anchor, which
/// keeps the first one's incoming handle and the last one's outgoing handle. Returns how many
/// anchors went.
@@ -501,23 +507,68 @@ fn merge_coincident(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind:
join_point(sp, 0, smooth);
}
}
// Back to front, so the indices `picked` knows stay true for the anchors still to visit.
for i in (1..sp.anchors.len()).rev() {
// Back to front, so the indices `picked` knows stay true for the anchors still to visit. A
// merged anchor is only marked here; the marked anchors are removed in one pass at the end.
let closed = sp.closed;
let anchors = &mut sp.anchors;
let len = anchors.len();
let mut gone = vec![false; len];
// The anchor after `i` that is still on the path, and the last one still on it.
let mut next = None;
let mut last = len.saturating_sub(1);
for i in (1..len).rev() {
if picked(i - 1)
&& picked(i)
&& let Some([a, b]) = sp.anchors.get_mut(i - 1..=i)
&& let Some([a, b]) = anchors.get_mut(i - 1..=i)
&& same(a, b)
{
a.h_out = b.h_out;
sp.anchors.remove(i);
if let Some(smooth) = join_kind {
join_point(sp, i - 1, smooth);
if let Some(slot) = gone.get_mut(i) {
*slot = true;
}
if next.is_none() {
last = i - 1;
}
if let Some(smooth) = join_kind {
// The neighbors the anchor has on the path as it now stands, as `join_point` sees them.
let prev = if i > 1 { Some(i - 2) } else { closed.then_some(last) };
let after = next.or(closed.then_some(0));
join_point_between(anchors, i - 1, prev, after, smooth);
}
} else {
next = Some(i);
}
}
#[cfg(test)]
if let Some(first) = gone.iter().position(|&g| g) {
// `retain` moves each anchor it keeps after the first one it drops.
let dropped = gone.iter().filter(|&&g| g).count();
ANCHOR_MOVES.set(ANCHOR_MOVES.get() + (len - first - dropped));
}
if gone.contains(&true) {
let mut k = 0;
anchors.retain(|_| {
let keep = !gone.get(k).copied().unwrap_or(false);
k += 1;
keep
});
}
before - sp.anchors.len()
}
/// [`join_point`] on anchor `ai` of `anchors` with its neighbors given by index.
fn join_point_between(anchors: &mut [Anchor], ai: usize, prev: Option<usize>, next: Option<usize>, smooth: bool) {
let at = |j: Option<usize>| j.and_then(|j| anchors.get(j)).map(|a| a.p);
let (prev, next) = (at(prev), at(next));
if let Some(a) = anchors.get_mut(ai) {
if smooth {
a.smooth_between(prev, next);
} else {
a.retract();
}
}
}
/// Close subpath `si` of path `id`, merging coincident endpoints if present.
fn close_subpath_in_node(d: &mut Document, id: NodeId, si: usize, join_kind: Option<bool>) -> Result<()> {
let path = path_mut(d, id)?;
@@ -751,8 +802,19 @@ pub(super) fn join(s: &mut Session, p: &Value) -> Result<Value> {
let mut merged = vec![];
for (id, picked) in &st.selection.anchors {
let Some(mut path) = st.doc.node(*id).and_then(|n| n.path_data()).cloned() else { continue };
let n: usize =
path.subpaths.iter_mut().enumerate().map(|(si, sp)| merge_coincident(sp, |ai| picked.contains(&(si, ai)), join_kind)).sum();
// One flag per anchor; references past the end of a subpath or to a missing one pick nothing.
let mut masks: Vec<Vec<bool>> = path.subpaths.iter().map(|sp| vec![false; sp.anchors.len()]).collect();
for &(si, ai) in picked {
if let Some(flag) = masks.get_mut(si).and_then(|m| m.get_mut(ai)) {
*flag = true;
}
}
let n: usize = path
.subpaths
.iter_mut()
.zip(&masks)
.map(|(sp, mask)| merge_coincident(sp, |ai| mask.get(ai).copied().unwrap_or(false), join_kind))
.sum();
if n > 0 {
merged.push((*id, path));
}
@@ -1769,3 +1831,140 @@ fn cut_at_anchors(s: &mut Session, _: &Value) -> Result<Value> {
})?;
Ok(super::draw2::ids_json(&ids))
}
#[cfg(test)]
mod tests {
use super::*;
/// `merge_coincident` removing each merged anchor from the vector straight away, kept as the
/// reference the one-pass version must match.
fn merge_coincident_by_removal(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind: Option<bool>) -> usize {
let same = |a: &Anchor, b: &Anchor| a.p.distance(b.p) < 1e-6;
let before = sp.anchors.len();
if sp.closed
&& before > 2
&& picked(0)
&& picked(before - 1)
&& let [first, .., last] = sp.anchors.as_mut_slice()
&& same(first, last)
{
first.h_in = last.h_in;
sp.anchors.pop();
if let Some(smooth) = join_kind {
join_point(sp, 0, smooth);
}
}
for i in (1..sp.anchors.len()).rev() {
if picked(i - 1)
&& picked(i)
&& let Some([a, b]) = sp.anchors.get_mut(i - 1..=i)
&& same(a, b)
{
a.h_out = b.h_out;
sp.anchors.remove(i);
if let Some(smooth) = join_kind {
join_point(sp, i - 1, smooth);
}
}
}
before - sp.anchors.len()
}
/// Every field of every anchor, bit for bit.
fn bits(sp: &SubPath) -> (Vec<[u64; 6]>, Vec<AnchorKind>, bool) {
let b = |p: Point| [p.x.to_bits(), p.y.to_bits()];
let fields = sp.anchors.iter().map(|a| [b(a.p), b(a.h_in), b(a.h_out)].concat().try_into().unwrap()).collect();
(fields, sp.anchors.iter().map(|a| a.kind).collect(), sp.closed)
}
/// A small linear congruential generator, so the cases are the same on every run.
struct Lcg(u64);
impl Lcg {
fn below(&mut self, n: u64) -> u64 {
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(self.0 >> 33) % n
}
}
fn same_as_removal(sp: &SubPath, picked: &dyn Fn(usize) -> bool, join_kind: Option<bool>) {
let (mut ours, mut theirs) = (sp.clone(), sp.clone());
let n = merge_coincident(&mut ours, picked, join_kind);
let m = merge_coincident_by_removal(&mut theirs, picked, join_kind);
assert_eq!(n, m, "{sp:?} {join_kind:?}");
assert_eq!(bits(&ours), bits(&theirs), "{sp:?} {join_kind:?}");
}
/// Short paths with points on, near and just past the merge distance, selections with stale
/// indices, every anchor kind and every join kind give the same anchors, bit for bit, as
/// removing each merged anchor straight away.
#[test]
fn merging_coincident_anchors_matches_removing_them_one_by_one() {
let spots = [(0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (5e-7, 0.0), (0.0, 1.5e-6), (10.0, 0.0), (5.0, 5.0), (10.0, 0.0)];
let mut rng = Lcg(7);
for _ in 0..30_000 {
let n = rng.below(9) as usize;
let anchors = (0..n)
.map(|_| {
let (x, y) = spots[rng.below(spots.len() as u64) as usize];
let p = Point::new(x, y);
let handle = |rng: &mut Lcg| match rng.below(3) {
0 => p,
_ => p + Vec2::new(rng.below(7) as f64 - 3.0, rng.below(7) as f64 - 3.0),
};
let (h_in, h_out) = (handle(&mut rng), handle(&mut rng));
let kind = if rng.below(2) == 0 { AnchorKind::Corner } else { AnchorKind::Smooth };
Anchor { p, h_in, h_out, kind }
})
.collect();
let sp = SubPath::new(anchors, rng.below(2) == 0);
let picks: Vec<bool> = (0..n + 2).map(|_| rng.below(4) != 0).collect();
let join_kind = [None, Some(false), Some(true)][rng.below(3) as usize];
same_as_removal(&sp, &|i| picks.get(i).copied().unwrap_or(false), join_kind);
}
}
/// A smooth join of three anchors on one another takes the outgoing handle the middle anchor
/// was given when it joined the right one: an already smooth left anchor keeps that handle.
#[test]
fn a_smooth_join_of_three_anchors_keeps_the_handle_the_middle_one_got() {
let o = Point::ZERO;
let left = Anchor { p: o, h_in: Point::new(-2.0, 0.0), h_out: o, kind: AnchorKind::Smooth };
let right = Anchor { p: o, h_in: o, h_out: Point::new(0.0, 5.0), kind: AnchorKind::Corner };
let mut sp = SubPath::new(vec![left, Anchor::corner(o), right, Anchor::corner(Point::new(10.0, 0.0))], false);
assert_eq!(merge_coincident(&mut sp, |i| i < 3, Some(true)), 2);
let a = sp.anchors[0];
assert_eq!((a.h_in, a.h_out, a.kind), (Point::new(-2.0, 0.0), Point::new(10.0 / 3.0, 0.0), AnchorKind::Smooth));
assert_eq!(sp.anchors.len(), 2);
}
/// One long run of selected anchors on one another, open or closed, becomes one anchor.
#[test]
fn a_long_run_of_anchors_on_one_another_becomes_one() {
for closed in [false, true] {
for join_kind in [None, Some(false), Some(true)] {
let anchors = (0..50_000).map(|i| Anchor::smooth(Point::ZERO, Point::new(1.0, i as f64))).collect();
let sp = SubPath::new(anchors, closed);
same_as_removal(&sp, &|_| true, join_kind);
let mut ours = sp.clone();
assert_eq!(merge_coincident(&mut ours, |_| true, join_kind), 49_999);
assert_eq!((ours.anchors.len(), ours.closed), (1, closed));
}
}
}
/// A long selected run at the start of a path followed by as many anchors that stay: each
/// anchor after the run moves once, not once per merged anchor.
#[test]
fn a_long_run_before_many_other_anchors_merges_in_one_pass() {
let run = 300_000;
let anchors = (0..run).map(|_| Anchor::corner(Point::ZERO)).chain((1..=run).map(|i| Anchor::corner(Point::new(i as f64, 1.0)))).collect();
let mut sp = SubPath::new(anchors, false);
ANCHOR_MOVES.set(0);
assert_eq!(merge_coincident(&mut sp, |i| i < run, Some(false)), run - 1);
assert_eq!(ANCHOR_MOVES.get(), run);
assert_eq!(sp.anchors.len(), run + 1);
assert_eq!(sp.anchors[0].p, Point::ZERO);
assert_eq!(sp.anchors[1].p, Point::new(1.0, 1.0));
assert_eq!(sp.anchors[run].p, Point::new(run as f64, 1.0));
}
}
+2 -1
View File
@@ -944,7 +944,8 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
(None, [id]) => *id,
_ => return Err(bad(C, "select one image or pass id")),
};
let n = st.doc.node(id).ok_or(EngineError::NoNode(id))?;
// An image in opacity-mask art or a definition's art is found by its id too (`links.list`).
let n = st.doc.stored_node(id).map(|(n, _)| &**n).ok_or(EngineError::NoNode(id))?;
let NodeKind::Image(im) = &n.kind else { return Err(bad(C, format!("object {} is not an image", id.0))) };
// Effective resolution: 72 pt per inch over the points one pixel spans along each axis.
let [a, b, c, d, ..] = im.xf.as_coeffs();
+95 -8
View File
@@ -10,7 +10,7 @@ use std::sync::Arc;
use vectorcraft_brush::{Brush, BrushKind};
use vectorcraft_color::Paint;
use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind};
use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind, PatternDef, Symbol};
use super::unique_name;
@@ -118,11 +118,12 @@ impl Used {
type Renames = BTreeMap<String, (Option<String>, bool)>;
/// Names in `dst` for the `used` definitions of `src` (`def`): the same name when `dst` has none
/// (copied) or an equal one (shared), else a free variant (`taken`, copied).
fn names<T: PartialEq>(
/// (copied) or one that is the `same` (shared), else a free variant (`taken`, copied).
fn names<T>(
used: &[String],
def: impl Fn(&str) -> Option<T>,
existing: impl Fn(&str) -> Option<T>,
same: impl Fn(&T, &T) -> bool,
taken: impl Fn(&str) -> bool,
) -> Renames {
let mut out = Renames::new();
@@ -130,7 +131,7 @@ fn names<T: PartialEq>(
let Some(d) = def(name) else { continue };
let entry = match existing(name) {
None => (Some(name.clone()), true),
Some(e) if e == d => (Some(name.clone()), false),
Some(e) if same(&e, &d) => (Some(name.clone()), false),
Some(_) => {
(Some(unique_name(name, |c| taken(c) || used.iter().any(|u| u == c) || out.values().any(|(n, _)| n.as_deref() == Some(c)))), true)
}
@@ -140,6 +141,65 @@ fn names<T: PartialEq>(
out
}
/// `n` as `dst` would copy it in ([`Document::reid`]), with the ids a document of its own gives it:
/// art copied in once, which differs from the file's only in its ids, compares equal to the file's.
fn canon(dst: &Document, n: &Node) -> Node {
let mut own = Document::new(0.0, 0.0);
// Pixels the art carries take a key `dst` doesn't use for other pixels, as they do in `dst`.
let mut keys = vec![];
vectorcraft_doc::swatches::walk_with_masks(n, &mut |c| {
if let NodeKind::Image(im) = &c.kind
&& im.pixels.is_some()
{
keys.push(im.key.clone());
}
});
for (k, blob) in &dst.images {
if keys.iter().any(|key| k == key || k.strip_prefix(key.as_str()).is_some_and(|rest| rest.starts_with('-'))) {
own.images.insert(k.clone(), blob.clone());
}
}
own.reid(n)
}
/// Do symbols `a` and `b` draw the same, whatever ids their art has ([`canon`])?
fn same_symbol(dst: &Document, a: &Symbol, b: &Symbol) -> bool {
let own = |s: &Symbol| Symbol { art: Arc::new(canon(dst, &s.art)), ..s.clone() };
own(a) == own(b)
}
/// Do patterns `a` and `b` draw the same, whatever ids their art has ([`canon`])?
fn same_pattern(dst: &Document, a: &PatternDef, b: &PatternDef) -> bool {
let bare = |p: &PatternDef| PatternDef { art: vec![], ..p.clone() };
bare(a) == bare(b) && a.art.len() == b.art.len() && a.art.iter().zip(&b.art).all(|(x, y)| canon(dst, x) == canon(dst, y))
}
/// Does art `a` use a resource that `m` (images, symbols, patterns, brushes, swatches) gives
/// another name, or a swatch whose link `m` drops?
fn uses_moved(a: &Node, m: [&Renames; 5]) -> bool {
let moved = |map: &Renames, k: &str| map.get(k).is_some_and(|(new, _)| new.as_deref() != Some(k));
let (mut a, mut any) = (a.clone(), false);
refs(&mut a, &mut |r| {
any |= match r {
Ref::Image(k) => moved(m[0], k),
Ref::Symbol(k) => moved(m[1], k),
Ref::Pattern(k) => moved(m[2], k),
Ref::Brush(k) => moved(m[3], k),
Ref::Swatch(link) => link.as_deref().is_some_and(|k| moved(m[4], k)),
}
});
any
}
/// Copy each of `shared` in `map` under a free name, as [`names`] does for a definition `dst`
/// holds differently.
fn unshare(map: &mut Renames, shared: &[String], used: &[String], taken: impl Fn(&str) -> bool) {
for name in shared {
let free = unique_name(name, |c| taken(c) || used.iter().any(|u| u == c) || map.values().any(|(n, _)| n.as_deref() == Some(c)));
map.insert(name.clone(), (Some(free), true));
}
}
/// The renamed resources whose definitions are copied: (name in `src`, name in `dst`).
fn copies(m: &Renames) -> Vec<(&str, &str)> {
m.iter().filter(|(_, (_, copy))| *copy).filter_map(|(old, (new, _))| Some((old.as_str(), new.as_deref()?))).collect()
@@ -194,14 +254,17 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
}
}
let images = names(&used.images, |k| src.images.get(k), |k| dst.images.get(k), |c| dst.images.contains_key(c));
let symbols = names(
let images = names(&used.images, |k| src.images.get(k), |k| dst.images.get(k), |a, b| a == b, |c| dst.images.contains_key(c));
// Symbol and pattern art copied in takes ids of `dst`, so their art is compared by what it
// draws: placing the same file again shares what the first placement brought.
let mut symbols = names(
&used.symbols,
|n| src.symbols.iter().find(|s| s.name == n),
|n| dst.symbols.iter().find(|s| s.name == n),
|a, b| same_symbol(dst, a, b),
|c| dst.symbols.iter().any(|s| s.name == c),
);
let patterns = names(&used.patterns, |n| src.pattern(n), |n| dst.pattern(n), |c| dst.pattern(c).is_some());
let mut patterns = names(&used.patterns, |n| src.pattern(n), |n| dst.pattern(n), |a, b| same_pattern(dst, a, b), |c| dst.pattern(c).is_some());
// A swatch the document defines differently isn't renamed (that would add look-alike swatches):
// the colours linked to it keep their look, unlinked.
let swatches: Renames = used
@@ -236,12 +299,33 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
any
};
let mut dst_brushes = vectorcraft_brush::library(dst);
let brushes = names(
let mut brushes = names(
&used.brushes,
|n| src_brushes.iter().find(|b| b.name == n).map(|b| (b, moves_art(b))),
|n| dst_brushes.iter().find(|b| b.name == n).map(|b| (b, false)),
|a, b| a == b,
|c| dst_brushes.iter().any(|b| b.name == c),
);
// Likewise a symbol, pattern or brush whose art uses a resource that moves isn't the
// document's of that name: it is copied under a free name, which can move what uses it in turn.
loop {
let maps = [&images, &symbols, &patterns, &brushes, &swatches];
let shared = |map: &Renames| map.iter().filter(|(_, (_, copy))| !*copy).map(|(k, _)| k.clone()).collect::<Vec<_>>();
let sym: Vec<String> =
shared(&symbols).into_iter().filter(|n| src.symbols.iter().any(|s| s.name == *n && uses_moved(&s.art, maps))).collect();
let pat: Vec<String> =
shared(&patterns).into_iter().filter(|n| src.pattern(n).is_some_and(|p| p.art.iter().any(|a| uses_moved(a, maps)))).collect();
let bru: Vec<String> = shared(&brushes)
.into_iter()
.filter(|n| src_brushes.iter().find(|b| b.name == *n).is_some_and(|b| brush_art(&mut b.clone()).into_iter().any(|a| uses_moved(a, maps))))
.collect();
if sym.is_empty() && pat.is_empty() && bru.is_empty() {
break;
}
unshare(&mut symbols, &sym, &used.symbols, |c| dst.symbols.iter().any(|s| s.name == c));
unshare(&mut patterns, &pat, &used.patterns, |c| dst.pattern(c).is_some());
unshare(&mut brushes, &bru, &used.brushes, |c| dst_brushes.iter().any(|b| b.name == c));
}
let mut rename = |r: Ref| {
let (map, k) = match r {
@@ -272,6 +356,8 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
if let Some(mut def) = src.symbols.iter().find(|s| s.name == old).cloned() {
def.name = new.to_string();
refs(Arc::make_mut(&mut def.art), &mut rename);
// The art takes ids of `dst`: those of `src` may name objects of `dst` already.
def.art = Arc::new(dst.reid(&def.art));
dst.symbols.push(def);
}
}
@@ -280,6 +366,7 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
def.name = new.to_string();
for a in &mut def.art {
refs(Arc::make_mut(a), &mut rename);
*a = Arc::new(dst.reid(a));
}
dst.patterns.push(def);
}
+7 -1
View File
@@ -378,8 +378,10 @@ pub(crate) fn full_documents(d: &Document) -> (Cow<'_, Document>, Vec<String>) {
/// Placed document `id` of `d` replaced by an editable copy of its art, as placing its file
/// without Link gives (its resources joining `d`, renamed where `d` uses a name for something
/// else), keeping the object's id, place, name and transparency: Break Link and Object › Expand.
/// A placed document in opacity-mask art or in the art of a symbol, graph design or pattern is
/// replaced where it is stored.
pub(crate) fn expand(d: &mut Document, id: NodeId, cmd: &str) -> Result<()> {
let n = d.node(id).cloned().ok_or(EngineError::NoNode(id))?;
let n = d.stored_node(id).map(|(n, _)| Node::clone(n)).ok_or(EngineError::NoNode(id))?;
let NodeKind::PlacedDocument(p) = &n.kind else { return Err(bad(cmd, format!("object {} is not a placed document", id.0))) };
let blob = d.images.get(&p.key).ok_or_else(|| bad(cmd, format!("object {} has lost its file's contents: relink it", id.0)))?;
let bytes = vectorcraft_doc::placed_document::full_bytes(p, blob)
@@ -395,6 +397,10 @@ pub(crate) fn expand(d: &mut Document, id: NodeId, cmd: &str) -> Result<()> {
let art = super::transformed(Node::new(d.alloc_id(), NodeKind::Group { children, clip: a.clip.is_some() }), m);
let mut out = n.clone();
out.kind = art.kind;
if d.node(id).is_none() {
*d.stored_node_mut(id).ok_or(EngineError::NoNode(id))? = out;
return Ok(());
}
let (par, index, _) = d.position(id).ok_or(EngineError::NoNode(id))?;
d.remove(id)?;
d.insert(par, index, out)?;
+1
View File
@@ -413,6 +413,7 @@ pub(crate) fn transaction(s: &mut Session, label: &str, f: impl FnOnce(&mut Sess
st.interaction = None;
}
saved.restore(s);
s.sync_front_profiles();
Err(e)
}
}
+9 -5
View File
@@ -454,10 +454,10 @@ pub fn spec(key: &str) -> Option<&'static PrefSpec> {
/// Preferences kept as one object with a command of their own instead of [`PREF_SPECS`] rows (they
/// aren't in the Preferences dialog): the Eyedropper Options (`eyedropper.setOptions`), the
/// Perspective Grid Options (`perspective.widget.options`), the Pathfinder Options
/// (`object.pathfinder.options`) and the Snap to Glyph options (`view.snapToGlyph.options`).
/// `prefs.get` and `prefs.set` take them by key (a partial object updates what it names) and
/// `prefs.reset` without a category resets them.
pub const PREF_GROUPS: &[&str] = &["eyedropper", "perspectiveWidget", "pathfinder", "glyphSnap"];
/// (`object.pathfinder.options`), the Snap to Glyph options (`view.snapToGlyph.options`) and the
/// Pixel Snapping Options (`view.snapToPixel.options`). `prefs.get` and `prefs.set` take them by key
/// (a partial object updates what it names) and `prefs.reset` without a category resets them.
pub const PREF_GROUPS: &[&str] = &["eyedropper", "perspectiveWidget", "pathfinder", "glyphSnap", "pixelSnap"];
/// Validate a value for preference group `key` against `current`.
fn validate_group(key: &str, current: &Value, v: &Value) -> std::result::Result<Value, String> {
@@ -477,6 +477,10 @@ fn validate_group(key: &str, current: &Value, v: &Value) -> std::result::Result<
let cur: vectorcraft_tools::GlyphSnap = serde_json::from_value(current.clone()).unwrap_or_default();
cur.merged(v).map(|o| json!(o))
}
"pixelSnap" => {
let cur: vectorcraft_tools::PixelSnap = serde_json::from_value(current.clone()).unwrap_or_default();
cur.merged(v).map(|o| json!(o))
}
"perspectiveWidget" => {
let mut merged = current.clone();
if let (Some(o), Some(p)) = (merged.as_object_mut(), v.as_object()) {
@@ -788,7 +792,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export Preferences",
[],
None,
"{path?} write the preferences as a JSON file {format: \"vectorcraft-preferences\", version: 1, prefs: {key: value, …}}: every preference prefs.list lists and the eyedropper, perspectiveWidget, pathfinder and glyphSnap groups, without the folder preferences fontsFolder, pluginsFolder, recoveryFolder and templatesFolder and without saved presets; a file over 1 MB, which prefs.import would refuse, is an error and is not written → {path, count}; without path → {data: the file's text, count}",
"{path?} write the preferences as a JSON file {format: \"vectorcraft-preferences\", version: 1, prefs: {key: value, …}}: every preference prefs.list lists and the eyedropper, perspectiveWidget, pathfinder, glyphSnap and pixelSnap groups, without the folder preferences fontsFolder, pluginsFolder, recoveryFolder and templatesFolder and without saved presets; a file over 1 MB, which prefs.import would refuse, is an error and is not written → {path, count}; without path → {data: the file's text, count}",
always,
export
),
+33 -3
View File
@@ -1,5 +1,6 @@
//! View → New View… / Edit Views…: saved views stored in the document; per-document view
//! toggles (Show Transparency Grid); the Character panel's Snap to Glyph options.
//! toggles (Show Transparency Grid); the Character panel's Snap to Glyph options; the Pixel
//! Snapping Options.
use serde_json::{Value, json};
use vectorcraft_apischema::{Bound, Param, ParamSchema, Type, Writes};
@@ -72,6 +73,18 @@ static GLYPH_SNAP: ParamSchema = ParamSchema::new(
.returns("the options")
.writes(Writes::Preferences);
static PIXEL_SNAP: ParamSchema = ParamSchema::new(
&[
Param::new("drawing", Type::Boolean).optional(),
Param::new("moving", Type::Boolean).optional(),
Param::new("scaling", Type::Boolean).optional(),
],
"the Pixel Snapping Options, kept in the preferences (the pixelSnap group, all on by default): which edits View › Snap to Pixel lands on whole pixels: drawing (the points the drawing tools place, the rulers' origin and measured points), moving (the selection, its anchors and segments, artboards and ruler guides moved, and the Rotate, Reflect and Shear tools' drags) and scaling (the edges a bounding-box, Free Transform, artboard or slice handle drags, and the Scale tool's drag); an edit whose option is off snaps as it does with Snap to Pixel off; {} reads them",
)
.returns("the options")
.writes(Writes::Preferences)
.since(4);
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
@@ -125,6 +138,16 @@ pub fn specs() -> Vec<CommandSpec> {
glyph_snap_options,
schema: &GLYPH_SNAP
),
cmd!(
query "view.snapToPixel.options",
"Pixel Snapping Options",
[],
None,
"{drawing?: bool, moving?: bool, scaling?: bool} the Pixel Snapping Options, kept in the preferences (the pixelSnap group, all on by default): which edits View › Snap to Pixel lands on whole pixels: drawing (the points the drawing tools place, the rulers' origin and measured points), moving (the selection, its anchors and segments, artboards and ruler guides moved, and the Rotate, Reflect and Shear tools' drags) and scaling (the edges a bounding-box, Free Transform, artboard or slice handle drags, and the Scale tool's drag); an edit whose option is off snaps as it does with Snap to Pixel off; {} reads them → the options",
always,
pixel_snap_options,
schema: &PIXEL_SNAP
),
]
}
@@ -133,6 +156,11 @@ fn glyph_snap_options(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!(s.prefs.glyph_snap))
}
fn pixel_snap_options(s: &mut Session, p: &Value) -> Result<Value> {
s.prefs.pixel_snap = s.prefs.pixel_snap.merged(p).map_err(|e| bad("view.snapToPixel.options", e))?;
Ok(json!(s.prefs.pixel_snap))
}
fn caps_lock(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(on) = p.get("on") {
s.caps_lock = on.as_bool().ok_or_else(|| bad("view.capsLock", "on must be true or false"))?;
@@ -379,15 +407,17 @@ mod tests {
("view.saved.list", json!({"all": true}), "`all`"),
("view.transparencyGrid", json!({"on": 1}), "`on`"),
("view.snapToGlyph.options", json!({"bounds": "off"}), "`bounds`"),
("view.snapToPixel.options", json!({"moving": "off"}), "`moving`"),
("view.snapToPixel.options", json!({"drawing": false, "rotating": false}), "`rotating`"),
] {
let st = s.doc().unwrap();
let doc = (st.doc.views.clone(), st.history.undo.len(), st.is_dirty());
let (grid, caps, snap) = (st.transparency_grid, s.caps_lock, s.prefs.glyph_snap);
let (grid, caps, snap, pixel) = (st.transparency_grid, s.caps_lock, s.prefs.glyph_snap, s.prefs.pixel_snap);
let e = s.execute(id, &params).unwrap_err().to_string();
assert!(e.contains(id) && e.contains(named), "{id} {params}: {e}");
let st = s.doc().unwrap();
assert_eq!((&st.doc.views, st.history.undo.len(), st.is_dirty()), (&doc.0, doc.1, doc.2), "{id} {params}");
assert_eq!((st.transparency_grid, s.caps_lock, s.prefs.glyph_snap), (grid, caps, snap), "{id} {params}");
assert_eq!((st.transparency_grid, s.caps_lock, s.prefs.glyph_snap, s.prefs.pixel_snap), (grid, caps, snap, pixel), "{id} {params}");
}
}
+3 -1
View File
@@ -19,7 +19,9 @@ pub const ON_ACTIVE_ARTBOARD: [&str; 8] = [
/// The commands that resize the artboards the app passes (Object › Artboards): the app passes the
/// selected artboards to Fit to Artwork Bounds as its `indices`, and the active artboard to Fit to
/// Selected Art as its `index`. A `command.batch` given `artboard` passes it on, as `index`, to
/// each of their steps that names none.
/// each of their steps that names none; a Fit to Artwork Bounds step that names neither `index` nor
/// `indices`, while the Artboard tool is chosen with several artboards selected, gets those as its
/// `indices` instead.
pub const FIT_ACTIVE_ARTBOARD: [&str; 2] = ["artboard.fitToArt", "artboard.fitToSelection"];
/// `(command, param)` pairs the journal records only so a replay reproduces the original run
+4
View File
@@ -260,6 +260,9 @@ pub struct Prefs {
/// Character panel › Show Snap to Glyph Options: which guides View › Snap to Glyph gives
/// (`view.snapToGlyph.options`; a preference group, see [`cmd::prefscmds::PREF_GROUPS`]).
pub glyph_snap: vectorcraft_tools::GlyphSnap,
/// Pixel Snapping Options: whether View › Snap to Pixel snaps drawing, moving and scaling
/// (`view.snapToPixel.options`; a preference group, see [`cmd::prefscmds::PREF_GROUPS`]).
pub pixel_snap: vectorcraft_tools::PixelSnap,
/// Edit → Transparency Flattener Presets: the user's presets (the built-in ones aren't stored).
/// Not a `prefs.set` key or group (resetting the preferences keeps them): `flattener.presets.*`
/// edit it.
@@ -523,6 +526,7 @@ impl Default for Prefs {
eyedropper: Default::default(),
pathfinder: Default::default(),
glyph_snap: Default::default(),
pixel_snap: Default::default(),
flattener_presets: vec![],
trace_presets: vec![],
gradient_presets: vec![],
+10 -3
View File
@@ -26,10 +26,11 @@ use crate::cmd::{CommandSpec, bad, command_specs};
use crate::{EngineError, Result};
/// The API level of the commands' parameters.
pub const API_VERSION: u32 = 3;
pub const API_VERSION: u32 = 4;
/// [`schema_hash`] at each API level, oldest first; the last row is [`API_VERSION`]'s.
pub const SCHEMA_HASHES: &[(u32, u64)] = &[(1, 0x9cdb_1087_7074_855c), (2, 0x0e31_5d96_7bc9_2653), (3, 0xffe0_58a3_2f0c_aa2a)];
pub const SCHEMA_HASHES: &[(u32, u64)] =
&[(1, 0x9cdb_1087_7074_855c), (2, 0x0e31_5d96_7bc9_2653), (3, 0xffe0_58a3_2f0c_aa2a), (4, 0x1be4_be72_fe16_54c4)];
/// The hash of every built-in command's schema ([`vectorcraft_apischema::hash`]).
pub fn schema_hash() -> u64 {
@@ -311,12 +312,17 @@ mod tests {
("view.transparencyGrid", json!({"on": 1})),
("view.snapToGlyph.options", json!({"bounds": false, "angular": true})),
("view.snapToGlyph.options", json!({"bounds": null})),
("view.snapToPixel.options", json!({"drawing": false, "scaling": true})),
("view.snapToPixel.options", json!({"moving": null})),
("view.snapToPixel.options", json!({"moving": "off"})),
("view.snapToPixel.options", json!({"rotating": false})),
("view.capsLock", json!(null)),
("view.saved.new", json!(null)),
("view.saved.edit", json!(null)),
("view.saved.list", json!(null)),
("view.transparencyGrid", json!(null)),
("view.snapToGlyph.options", json!(null)),
("view.snapToPixel.options", json!(null)),
("view.capsLock", json!([])),
("view.saved.new", json!(5)),
("view.transparencyGrid", json!("on")),
@@ -325,7 +331,7 @@ mod tests {
("engine.apiReference", json!({"prefix": "view."})),
("engine.apiReference", json!([])),
];
assert_eq!(schemas().len(), 7);
assert_eq!(schemas().len(), 8);
for (id, schema) in schemas() {
let written = schema.to_json();
check_schema(&written, id).unwrap_or_else(|e| panic!("{e}\n{written:#}"));
@@ -423,6 +429,7 @@ mod tests {
("view.saved.list", "nothing"),
("view.transparencyGrid", "session"),
("view.snapToGlyph.options", "preferences"),
("view.snapToPixel.options", "preferences"),
];
for (id, writes) in expected {
let got = listed.iter().find(|(c, _)| *c == id).map(|(_, w)| w.clone());
+5
View File
@@ -672,6 +672,7 @@ impl Savepoint {
s.pending_paint = self.pending_paint;
self.choices.put(s);
s.journal.truncate(self.journal);
s.sync_front_profiles();
exact
}
}
@@ -2231,6 +2232,9 @@ fn failure_text(report: &Value) -> String {
fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result::Result<Progress, RunError>, String> {
let depth = std::mem::replace(&mut s.depth, 0);
job.world.swap(s);
// The run's front document draws and converts through its own profiles, and the interface's
// again after the slice.
s.sync_front_profiles();
s.script_in_run = true;
let cell = job.host.session.clone();
std::mem::swap(s, &mut *cell.borrow_mut());
@@ -2253,6 +2257,7 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
s.script_in_run = false;
job.world.swap(s);
s.depth = depth;
s.sync_front_profiles();
r
}
+16 -1
View File
@@ -221,6 +221,7 @@ impl Session {
self.active = Some(index);
if switched {
self.sync_front_composite_fonts();
self.sync_front_profiles();
}
true
} else {
@@ -228,6 +229,15 @@ impl Session {
}
}
/// Make the profiles the document in front is assigned the ones colors are drawn and converted
/// through, in place of the working spaces (with no document open, or none assigned: the working
/// spaces), after a switch, an open, a close, a revert or a restored document brought another
/// document or another assignment to the front. The open documents redraw when the active color
/// settings change.
pub(crate) fn sync_front_profiles(&mut self) {
cmd::colormgmt::use_front_profiles(self);
}
/// Register the composite fonts of the document now in front ([`cmd::compositefonts::sync`]),
/// after a switch or a close brought it there. Its type set in a composite font that differs
/// from the one of that name before (added, changed or removed) is measured again, and type not
@@ -317,6 +327,7 @@ impl Session {
let i = self.docs.len() - 1;
self.active = Some(i);
self.sync_opened_composite_fonts(i);
self.sync_front_profiles();
if self.depth == 0
&& let Some(label) = self.explicit_undo_group.clone()
{
@@ -385,7 +396,10 @@ impl Session {
}
match back_names {
Some(names) => self.refresh_document_text_bounds(index, |t| t.cached_bounds.is_none() && !sets_in_any(t, &names)),
None => self.sync_opened_composite_fonts(index),
None => {
self.sync_opened_composite_fonts(index);
self.sync_front_profiles();
}
}
true
}
@@ -404,6 +418,7 @@ impl Session {
}
self.active = if self.docs.is_empty() { None } else { Some(index.min(self.docs.len() - 1)) };
self.sync_front_composite_fonts();
self.sync_front_profiles();
true
}
+4
View File
@@ -332,6 +332,8 @@ impl Session {
self.paint = paint.clone();
}
self.pending_paint = None;
// The previous preview's Assign Profile is undone with it.
self.sync_front_profiles();
let rw = cmd::distortcmds::perspective_rewrite(self, cmd, params).or_else(|| cmd::bounds_rewrite(self, cmd, params));
let (cmd, params) = rw.as_ref().map_or((cmd, params), |(c, p)| (c.as_str(), p));
// A selected object's converted appearance must not replace the current paints while
@@ -457,6 +459,8 @@ impl Session {
st.undo_interaction();
// Guides locked and slices locked or hidden during the interaction stay deselected.
deselect_hidden(&menu, &st.doc, &mut st.selection);
// A canceled preview's Assign Profile is undone with it.
self.sync_front_profiles();
// With New Art Has Basic Appearance off, new art takes the appearance of the selection as
// the document has it again, not as a preview left it.
self.inherit_new_art();
+4
View File
@@ -196,6 +196,10 @@ impl Session {
let (doc, journal, grouped) = (self.active().map(|d| d.uid), self.journal.len(), self.undo_group_docs());
let open = (self.depth == 0).then(|| self.docs.iter().map(|d| d.uid).collect::<Vec<_>>());
let r = if self.depth == 0 { self.run_guarded(id, run) } else { self.run_nested(run) };
// Colors are drawn and converted through the profiles of the document in front now, also
// after an undone or redone Assign Profile, a failed or panicked command's documents put
// back, and a batch step, before the next step converts through them.
self.sync_front_profiles();
if r.is_err() && self.depth == 0 {
self.batch_paint_docs.clear();
// A failed or panicked command's documents are put back: type is drawn in their
+6
View File
@@ -164,6 +164,10 @@ impl Session {
if self.depth == 0 {
self.trim_histories();
}
// A canceled group's Assign Profile is undone with it.
if cancel {
self.sync_front_profiles();
}
}
/// When journal entry `n` is a `command.batch` with `steps` noted in canceled undo groups and
@@ -280,5 +284,7 @@ impl Session {
g.journal.retain(|&(n, _)| n < scope.journal);
g.steps.retain(|&(n, _)| n < scope.journal);
}
// A canceled scope's Assign Profile is undone with it.
self.sync_front_profiles();
}
}
+32
View File
@@ -4033,6 +4033,38 @@ fn snap_to_pixel_rounds_drawing_and_moves() {
assert_eq!((b.x0, b.y0), (17.0, 16.0));
}
/// Pixel Snapping Options (`view.snapToPixel.options`): with While Drawing off a rectangle drawn
/// with Snap to Pixel on keeps its fractional corners while a move still lands on whole pixels, and
/// with While Moving off a move keeps its fractional offset while drawing snaps again.
#[test]
fn pixel_snapping_options_choose_the_edits_snap_to_pixel_rounds() {
let mut s = session();
let v = ViewInfo { snap_to_pixel: true, smart_guides: false, snap_to_point: false, ..Default::default() };
let drag = |s: &mut Session, tool: &str, from: (f64, f64), to: (f64, f64)| {
s.select_tool(tool, v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, from.0, from.1), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, to.0, to.1), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, to.0, to.1), v).unwrap();
};
let bounds = |s: &Session, id| {
let b = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap();
(b.x0, b.y0, b.x1, b.y1)
};
s.execute("view.snapToPixel.options", &json!({"drawing": false})).unwrap();
drag(&mut s, "rectangle", (10.25, 10.5), (60.5, 40.25));
let id = s.doc().unwrap().selection.objects[0];
assert_eq!(bounds(&s, id), (10.25, 10.5, 60.5, 40.25), "drawing does not snap");
drag(&mut s, "selection", (30.0, 30.0), (37.5, 34.75));
assert_eq!(bounds(&s, id).0, 18.0, "moving still snaps the left edge");
assert_eq!(bounds(&s, id).1, 15.0, "moving still snaps the top edge");
s.execute("view.snapToPixel.options", &json!({"drawing": true, "moving": false})).unwrap();
drag(&mut s, "selection", (40.0, 30.0), (45.25, 33.5));
assert_eq!((bounds(&s, id).0, bounds(&s, id).1), (23.25, 18.5), "moving does not snap");
drag(&mut s, "rectangle", (100.25, 100.5), (140.5, 130.75));
let drawn = s.doc().unwrap().selection.objects[0];
assert_eq!(bounds(&s, drawn), (100.0, 101.0, 141.0, 131.0), "drawing snaps again");
}
#[test]
fn shaper_turns_rough_strokes_into_live_shapes_and_scribbles_punch_fills() {
let mut s = session();
+97
View File
@@ -3788,6 +3788,103 @@ fn a_trace_run_needs_the_library_colours_it_traced_with() {
assert!(!run.current(&s), "{name} changed");
}
/// `image_doc`'s image with its disc 20 px to the left: the same size, other pixels.
fn moved_disc_png() -> Vec<u8> {
vectorcraft_trace::Raster::from_fn(100, 100, |x, y| {
let (dx, dy) = (x as f64 + 0.5 - 30.0, y as f64 + 0.5 - 50.0);
if dx * dx + dy * dy <= 900.0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }
})
.encode_png()
}
/// Puts `bytes` under the image key `key`, or takes the key's image data away (`None`).
fn set_image_data(s: &mut Session, key: &str, bytes: Option<Vec<u8>>) {
s.edit("image data", |d, _| {
match bytes {
Some(b) => d.images.insert(key.into(), ImageBlob::new("image/png", b)),
None => d.images.remove(key),
};
Ok(())
})
.unwrap();
}
/// The middle of the first traced path of the Image Trace object the reply `r` names, in x.
fn traced_center_x(s: &Session, r: &Value) -> f64 {
outline(&traced_paths(&node(s, NodeId(r["id"].as_u64().unwrap())))[0]).0.bounds().unwrap().center().x
}
/// A trace made away from its command no longer applies once the pixels under its image's key
/// change, though the object, its image record and the settings stay as they were; both commands
/// then trace the pixels there now. The same bytes in another allocation still apply.
#[test]
fn a_trace_run_needs_the_pixels_it_traced() {
let p = json!({"params": {"ignoreWhite": true}});
for command in ["imageTrace.make", "imageTrace.makeAndExpand"] {
let mut s = session();
image_doc(&mut s);
let run = cmd::TraceRun::prepare(&s, command, &p).unwrap();
let traced = run.run(&|_, _| true).unwrap();
// The same bytes, allocated anew: still current.
let same = s.doc().unwrap().doc.images["img1"].bytes.to_vec();
set_image_data(&mut s, "img1", Some(same));
assert!(run.current(&s), "{command}: equal bytes");
// Other pixels under the same key: no longer current, and the hand-off is dropped.
set_image_data(&mut s, "img1", Some(moved_disc_png()));
assert!(!run.current(&s), "{command}: other pixels");
traced.hand_in(&mut s);
let r = s.execute(command, run.params()).unwrap();
assert!(s.trace_hand_off.is_none(), "{command}: dropped");
// The disc is now at image x 30, which the ×2 placement at 50 puts at 110.
let x = traced_center_x(&s, &r);
assert!((x - 110.0).abs() < 1.5, "{command}: traced the pixels there now, at {x}");
}
}
/// Image data that is missing or empty: a run made before it went no longer applies, the run's
/// command gives the error it gives without a run, and nothing panics.
#[test]
fn a_trace_run_of_missing_or_empty_image_data() {
let p = json!({"params": {"ignoreWhite": true}});
let mut s = session();
image_doc(&mut s);
let run = cmd::TraceRun::prepare(&s, "imageTrace.make", &p).unwrap();
let traced = run.run(&|_, _| true).unwrap();
set_image_data(&mut s, "img1", None);
assert!(!run.current(&s), "missing");
traced.hand_in(&mut s);
let e = s.execute(run.command(), run.params()).unwrap_err().to_string();
assert!(e.contains("image data `img1` is missing"), "{e}");
set_image_data(&mut s, "img1", Some(vec![]));
assert!(!run.current(&s), "empty");
let empty = cmd::TraceRun::prepare(&s, "imageTrace.make", &p).unwrap();
assert!(empty.current(&s), "two empty blobs are equal");
assert!(matches!(empty.run(&|_, _| true), Err(EngineError::Other(_))));
assert!(matches!(s.execute(run.command(), run.params()), Err(EngineError::Other(_))));
}
/// Tracing an Image Trace object again follows the same rule: once the pixels of the image it
/// holds change, a run made before no longer applies, and the command traces the pixels there now.
#[test]
fn a_trace_run_of_an_image_trace_object_needs_its_pixels() {
let p = json!({"params": {"ignoreWhite": true}});
let mut s = session();
image_doc(&mut s);
let g = s.execute("imageTrace.make", &p).unwrap()["id"].as_u64().unwrap();
let again = json!({"id": g, "params": {"ignoreWhite": true}});
let run = cmd::TraceRun::prepare(&s, "imageTrace.make", &again).unwrap();
assert_eq!(run.target(), NodeId(g));
let traced = run.run(&|_, _| true).unwrap();
assert!(run.current(&s));
set_image_data(&mut s, "img1", Some(moved_disc_png()));
assert!(!run.current(&s));
traced.hand_in(&mut s);
let r = s.execute(run.command(), run.params()).unwrap();
assert!(s.trace_hand_off.is_none(), "dropped");
let x = traced_center_x(&s, &r);
assert!((x - 110.0).abs() < 1.5, "traced the pixels there now, at {x}");
}
/// Shapes: the disc of the test image comes out as a live ellipse where the image lies, the same
/// circle as its traced path; without the option it is a plain path.
#[test]
+25
View File
@@ -326,6 +326,31 @@ fn update_link_takes_the_files_clipping_path_into_symbols_too() {
assert_eq!(symbol_clip_width(&s, "Pic"), None);
}
#[test]
fn update_and_relink_by_id_keep_the_clipping_path_of_a_dcs_image_in_a_symbol() {
let dir = temp_dir("symbol-clip-by-id");
let path = write(&dir, "pic.eps", &two_plates());
let mut s = session();
let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap();
s.execute("symbol.new", &json!({ "name": "Pic", "ids": [r["ids"][0]] })).unwrap();
let list = s.execute("links.list", &json!({})).unwrap();
let row = list["links"].as_array().unwrap().iter().find(|r| r["owner"]["kind"] == "symbol").cloned().expect("the symbol's image is listed");
let id = row["id"].as_u64().unwrap();
assert_eq!(row["format"], "DCS", "{list}");
let before = symbol_clip_width(&s, "Pic").expect("the file's clipping path");
// The composite now drawn through the left quarter of the page (same length).
let text = String::from_utf8(two_plates()).unwrap().replacen("10 0 lineto 10 10 lineto", " 5 0 lineto 5 10 lineto", 1);
std::fs::write(&path, text.as_bytes()).unwrap();
assert_eq!(s.execute("links.update", &json!({ "ids": [id] })).unwrap()["updated"], json!([id]));
let after = symbol_clip_width(&s, "Pic").expect("still clipped");
assert!((after - before / 2.0).abs() < 1e-6, "the symbol's clipping path follows the file: {before} → {after}");
// Relinked by its id to a plain image: the DCS file's clipping path goes.
let png = dir.join("plain.png");
image::RgbImage::from_pixel(2, 2, image::Rgb([9, 9, 9])).save(&png).unwrap();
s.execute("links.relink", &json!({ "ids": [id], "path": png.to_string_lossy() })).unwrap();
assert_eq!(symbol_clip_width(&s, "Pic"), None);
}
#[test]
fn a_file_that_lost_its_clipping_path_unclips_the_image() {
let dir = temp_dir("update-lost-clip");
+31
View File
@@ -1367,6 +1367,37 @@ fn smooth_tool_reduces_jagged_path() {
assert_eq!(p.subpaths[0].anchors[0].p, Point::new(100.0, 200.0));
}
/// A drag of the Smooth tool along a line jagged by up to 6 pt leaves no corner between a curve and
/// a line: every anchor between the path's ends turns by at most 1°.
#[test]
fn smooth_tool_leaves_no_corner_where_a_curve_meets_a_line() {
let mut s = session();
let mut seed = 7u64;
let anchors: Vec<_> = (0..=60)
.map(|i| {
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
let noise = ((seed >> 11) as f64 / (1u64 << 53) as f64) * 2.0 - 1.0;
json!({"x": 100.0 + f64::from(i) * 5.0, "y": 200.0 + 6.0 * noise})
})
.collect();
let r = s.execute("path.create", &json!({"anchors": anchors})).unwrap();
let id = NodeId(r["id"].as_u64().unwrap());
let drag_points: Vec<(f64, f64)> = (0..=64).map(|i| (90.0 + f64::from(i) * 5.0, 200.0)).collect();
drag(&mut s, "smooth", &drag_points, Mods::default());
let p = path(&s, id);
let sp = &p.subpaths[0];
assert!(sp.anchors.len() < 61, "the path is smoothed: {}", sp.anchors.len());
let dir = |v: kurbo::Vec2, w: kurbo::Vec2, chord: kurbo::Vec2| [v, w, chord].into_iter().find(|d| d.hypot() > 1e-9).unwrap_or(chord);
for i in 1..sp.segment_count() {
let (prev, next) = (sp.segment(i - 1), sp.segment(i));
let arrive = dir(prev.p3 - prev.p2, prev.p3 - prev.p1, prev.p3 - prev.p0);
let leave = dir(next.p1 - next.p0, next.p2 - next.p0, next.p3 - next.p0);
let turn = arrive.cross(leave).atan2(arrive.dot(leave)).abs().to_degrees();
let kinds = (sp.segment_is_line(i - 1), sp.segment_is_line(i));
assert!(turn <= 1.0, "anchor {i} turns {turn}° (lines before and after: {kinds:?}): {:?}", sp.anchors[i]);
}
}
/// Smoothing a path with direct-selected anchors leaves the path selected whole: the selection no
/// longer names anchors by indices into the anchors the smooth replaced. A selected path the drag
/// does not reach keeps its anchors selected, and undo brings the old selection back.
+81
View File
@@ -192,6 +192,87 @@ fn fit_steps_take_the_batchs_artboard_and_actions_leave_out_their_index() {
assert_eq!(action, [fit("artboard.fitToArt"), fit("artboard.fitToArt"), fit("artboard.fitToSelection")]);
}
/// A document of three artboards with art of its own on each → its artboards before any fit.
fn three_artboards_with_art(s: &mut Session) -> Vec<vectorcraft_geom::Rect> {
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3, "created": null})).unwrap();
for (x, h) in [(10, 30), (130, 20), (250, 40)] {
s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": h})).unwrap();
}
s.execute("select.all", &json!({})).unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
s.execute("select.none", &json!({})).unwrap();
s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect()
}
/// The artboards of [`three_artboards_with_art`], each fitted to its art.
fn three_fitted_artboards() -> [vectorcraft_geom::Rect; 3] {
let rect = vectorcraft_geom::Rect::new;
[rect(10.0, 10.0, 30.0, 40.0), rect(130.0, 10.0, 150.0, 30.0), rect(250.0, 10.0, 270.0, 50.0)]
}
/// A Fit to Artwork Bounds step that names neither `index` nor `indices`, while the Artboard tool
/// is chosen with several artboards selected, fits each of those (not the batch's artboard), as the
/// command does on its own; a step's own `index` or `indices` wins, and with one artboard or none
/// selected the step takes the batch's artboard.
#[test]
fn a_batch_fit_step_uses_the_artboard_tool_selection() {
let fitted = three_fitted_artboards();
let boards = |s: &Session| s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
let fit = |params: Value| json!({"artboard": 1, "commands": [{"command": "artboard.fitToArt", "params": params}]});
let session = |picks: &Value| {
let mut s = Session::new();
let was = three_artboards_with_art(&mut s);
s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
s.set_tool_option("selected", picks);
(s, was)
};
let (mut s, was) = session(&json!([2, 0]));
s.execute("command.batch", &fit(json!({}))).unwrap();
assert_eq!(boards(&s), [fitted[0], was[1], fitted[2]], "artboards 1 and 3, the selected ones, and not the batch's artboard 2");
let (mut s, was) = session(&json!([2, 0]));
s.execute("command.batch", &fit(json!({"index": 1}))).unwrap();
assert_eq!(boards(&s), [was[0], fitted[1], was[2]], "a step's own index");
let (mut s, was) = session(&json!([2, 0]));
s.execute("command.batch", &fit(json!({"indices": [1, 2]}))).unwrap();
assert_eq!(boards(&s), [was[0], fitted[1], fitted[2]], "a step's own indices");
for picks in [json!([2]), json!([])] {
let (mut s, was) = session(&picks);
s.execute("command.batch", &fit(json!({}))).unwrap();
assert_eq!(boards(&s), [was[0], fitted[1], was[2]], "the batch's artboard with {picks} selected");
}
}
/// The journal records the artboards a batch's Fit to Artwork Bounds step took from the Artboard
/// tool, so a replay in a new session fits the same ones; an action leaves them out and fits the
/// artboards selected when it plays.
#[test]
fn a_batch_fit_selection_replays_but_an_action_uses_the_current_selection() {
let fitted = three_fitted_artboards();
let boards = |s: &Session| s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
let mut s = Session::new();
let was = three_artboards_with_art(&mut s);
s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
s.set_tool_option("selected", &json!([0, 2]));
let start = s.journal.len();
let steps = json!([{"command": "artboard.fitToArt", "params": {}}]);
s.execute("command.batch", &json!({"artboard": 1, "commands": steps})).unwrap();
assert_eq!(boards(&s), [fitted[0], was[1], fitted[2]]);
let (id, p) = s.journal.last().unwrap().clone();
assert_eq!((id.as_str(), &p["commands"][0]["params"]), ("command.batch", &json!({"indices": [0, 2]})));
let r = replayed(&s);
assert_ne!(r.tool_id(), "artboard", "the new session's tool selects no artboards");
assert_eq!(boards(&r), boards(&s), "the replay fits the recorded artboards");
let action = s.journal_for_action(start);
assert_eq!(action, [("command.batch".to_string(), json!({"commands": steps}))]);
// Played on a fresh copy of the document with other artboards selected.
let mut a = Session::new();
three_artboards_with_art(&mut a);
a.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
a.set_tool_option("selected", &json!([1, 2]));
a.execute("command.batch", &json!({"artboard": 0, "commands": action[0].1["commands"]})).unwrap();
assert_eq!(boards(&a), [was[0], fitted[1], fitted[2]], "the action fits the artboards selected when it plays");
}
#[test]
fn a_save_records_its_date_and_replays_it() {
let path = vectorcraft_testkit::temp_dir("journal-save").join("a.vectorcraft").to_string_lossy().into_owned();
+198 -6
View File
@@ -5,7 +5,7 @@
use std::path::{Path, PathBuf};
use serde_json::{Value, json};
use vectorcraft_doc::{Document, ImageObject, LinkInfo, NodeKind};
use vectorcraft_doc::{Document, ImageObject, LinkInfo, NodeKind, StoredRoot};
use vectorcraft_geom::Rect;
use crate::*;
@@ -446,8 +446,8 @@ fn links_outside_the_layers_find_their_files_after_the_folder_moves() {
}
/// With Update Links: Automatically, a file in a symbol and in the layers that changed and moved
/// with the document is read again for the layers' image and for the symbol's, and both links take
/// its new path, size and hash.
/// with the document is read again for the layers' image and for the symbol's, both are listed by
/// their ids, and both links take its new path, size and hash.
#[test]
fn a_symbols_link_to_a_moved_and_modified_file_takes_its_new_path() {
let a = Folder::new("nested-modified-a");
@@ -458,13 +458,14 @@ fn a_symbols_link_to_a_moved_and_modified_file_takes_its_new_path() {
s.execute("prefs.set", &json!({"key": "updateLinks", "value": "automatically"})).unwrap();
let id = place(&mut s, &pic);
s.execute("symbol.new", &json!({"name": "Mark", "ids": [id.0]})).unwrap();
let in_symbol = stored_image_in(&s, StoredRoot::Symbol(0));
let id = place(&mut s, &pic);
save(&mut s, &a.file("poster.vectorcraft"));
write(&pic, &png(30, 30, BLUE));
std::fs::remove_dir_all(&b.0).unwrap();
std::fs::rename(&a.0, &b.0).unwrap();
let r = open(&mut s, &b.file("poster.vectorcraft"));
assert_eq!((r["modifiedLinks"].clone(), r["updatedLinks"][0]["ids"].clone()), (json!([]), json!([id.0])), "{r}");
assert_eq!((r["modifiedLinks"].clone(), r["updatedLinks"][0]["ids"].clone()), (json!([]), json!([id.0, in_symbol.0])), "{r}");
let moved = PathBuf::from(b.file("art/photo.png"));
let blue = png(30, 30, BLUE);
let mut images = vec![];
@@ -521,7 +522,8 @@ fn a_symbols_link_without_a_relative_path_follows_the_moved_file() {
/// Update Links reads a changed file again for the images inside symbols, patterns and opacity
/// masks too: those showing the same content as an image in the layers, and those no object in the
/// layers shows. Each takes the file's place as its own Placement Options say, in one undo step.
/// layers shows. Each takes the file's place as its own Placement Options say, in one undo step,
/// and the reply lists each by its id.
#[test]
fn update_links_reads_files_again_inside_symbols_patterns_and_masks() {
let dir = Folder::new("nested-update");
@@ -533,11 +535,13 @@ fn update_links_reads_files_again_inside_symbols_patterns_and_masks() {
let id = place(&mut s, &photo);
s.execute("links.placementOptions", &json!({"ids": [id.0], "preserve": "fill", "clip": true})).unwrap();
s.execute("symbol.new", &json!({"name": "Mark", "ids": [id.0]})).unwrap();
let in_symbol = stored_image_in(&s, StoredRoot::Symbol(0));
let id = place(&mut s, &photo);
// logo.png only in a pattern and in an opacity mask.
let p = place(&mut s, &logo);
s.execute("object.pattern.make", &json!({"ids": [p.0], "edit": false})).unwrap();
s.execute("edit.clear", &json!({"ids": [p.0]})).unwrap();
let p = stored_image_in(&s, StoredRoot::Pattern { pattern: 0, art: 0 });
let masked = super::rect(&mut s, 10.0, 10.0, 60.0, 60.0);
let mask = place(&mut s, &logo);
s.execute("transparency.makeOpacityMask", &json!({"ids": [masked.0, mask.0]})).unwrap();
@@ -546,7 +550,8 @@ fn update_links_reads_files_again_inside_symbols_patterns_and_masks() {
write(&photo, &blue);
write(&logo, &green);
let u = s.execute("links.update", &json!({})).unwrap();
assert_eq!(u, json!({"updated": [id.0], "missing": []}));
// By file: photo.png in the layers and the symbol, then logo.png in the mask and the pattern.
assert_eq!(u, json!({"updated": [id.0, in_symbol.0, mask.0, p.0], "missing": []}));
// (name, size, hash, pixel size) of each image, which shows its file's pixels.
let images = |s: &Session| {
let d = &s.doc().unwrap().doc;
@@ -576,6 +581,193 @@ fn update_links_reads_files_again_inside_symbols_patterns_and_masks() {
assert!(images(&s).iter().all(|(_, _, _, size)| *size == (20, 10)), "{:?}", images(&s));
}
/// The files only art outside the layers shows: one in a symbol, a graph design, a pattern and an
/// opacity mask each, no object in the layers linked to any of them.
const NESTED: [&str; 4] = ["symbol.png", "design.png", "pattern.png", "mask.png"];
/// A document whose only links are [`NESTED`]'s files in `dir`.
fn nested_links(dir: &Folder) -> Session {
for (i, name) in (0u8..).zip(NESTED) {
write(&dir.file(name), &png(20, 10, [20 + 50 * i, 90, 160]));
}
let mut s = session();
let id = place(&mut s, &dir.file("symbol.png"));
s.execute("symbol.new", &json!({"name": "Mark", "ids": [id.0]})).unwrap();
s.execute("edit.clear", &json!({"ids": [s.doc().unwrap().selection.objects[0].0]})).unwrap();
let id = place(&mut s, &dir.file("design.png"));
s.execute("graph.design", &json!({"new": "Bar"})).unwrap();
s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap();
let id = place(&mut s, &dir.file("pattern.png"));
s.execute("object.pattern.make", &json!({"ids": [id.0], "edit": false})).unwrap();
s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap();
let masked = super::rect(&mut s, 10.0, 10.0, 60.0, 60.0);
let mask = place(&mut s, &dir.file("mask.png"));
s.execute("transparency.makeOpacityMask", &json!({"ids": [masked.0, mask.0]})).unwrap();
s.execute("select.set", &json!({"ids": []})).unwrap();
s
}
/// The id of the `links.list` row of file `name`.
fn row_id(s: &mut Session, name: &str) -> u64 {
let list = s.execute("links.list", &json!({})).unwrap();
let row = list["links"].as_array().unwrap().iter().find(|r| r["name"] == name).unwrap_or_else(|| panic!("{name} in {list}"));
row["id"].as_u64().unwrap()
}
/// The link of stored object `id`.
fn stored_link(s: &Session, id: u64) -> Option<LinkInfo> {
match &s.doc().unwrap().doc.stored_node(NodeId(id)).unwrap().0.kind {
NodeKind::Image(im) => im.link.clone(),
k => panic!("not an image: {k:?}"),
}
}
/// The id of the first image stored in the art of `root`.
fn stored_image_in(s: &Session, root: StoredRoot) -> NodeId {
let mut found = None;
s.doc().unwrap().doc.visit_stored(|n, place| {
if found.is_none() && place.root == root && matches!(n.kind, NodeKind::Image(_)) {
found = Some(n.id);
}
});
found.unwrap_or_else(|| panic!("no image in {root:?}"))
}
/// Images in symbols, graph designs, patterns and opacity masks are listed and checked with ids of
/// their own, one row each with what holds it, and the missing filter counts them.
#[test]
fn links_outside_the_layers_are_listed_and_checked_with_ids() {
let dir = Folder::new("nested-ids");
let mut s = nested_links(&dir);
let list = s.execute("links.list", &json!({})).unwrap();
let rows = list["links"].as_array().unwrap();
let owners: Vec<(&str, &str)> = rows.iter().map(|r| (r["name"].as_str().unwrap(), r["owner"]["kind"].as_str().unwrap_or("-"))).collect();
assert_eq!(owners, [("mask.png", "layers"), ("symbol.png", "symbol"), ("design.png", "graphDesign"), ("pattern.png", "pattern")], "{list}");
assert_eq!(rows[1]["owner"]["name"], "Mark");
let masked = s.doc().unwrap().doc.layers[0].children().unwrap().iter().find(|n| n.extras().mask.is_some()).unwrap().id;
assert_eq!(rows[0]["owner"]["maskOf"], json!(masked.0));
let ids: std::collections::BTreeSet<u64> = rows.iter().map(|r| r["id"].as_u64().unwrap()).collect();
assert_eq!(ids.len(), 4, "{list}");
assert!(rows.iter().all(|r| r["status"] == "ok" && r["linked"] == true), "{list}");
let check = s.execute("links.check", &json!({})).unwrap();
let checked: Vec<(&str, &Value)> = check["links"].as_array().unwrap().iter().map(|l| (l["name"].as_str().unwrap(), &l["ids"])).collect();
assert_eq!(checked.len(), 4, "{check}");
for (name, ids) in checked {
assert_eq!(*ids, json!([row_id(&mut s, name)]), "{check}");
}
std::fs::remove_file(dir.file("design.png")).unwrap();
let check = s.execute("links.check", &json!({})).unwrap();
assert_eq!((check["missing"].as_u64(), check["modified"].as_u64()), (Some(1), Some(0)), "{check}");
let design = row_id(&mut s, "design.png");
let missing = s.execute("links.list", &json!({"show": "missing"})).unwrap();
assert_eq!((missing["missing"].as_u64(), &missing["links"][0]["id"]), (Some(1), &json!(design)), "{missing}");
let one = s.execute("links.check", &json!({"ids": [design]})).unwrap();
assert_eq!(one["links"][0]["status"], "missing", "{one}");
}
/// Every links command takes the id of an image outside the layers and acts on that object: Link
/// Info, Go To (which clears the selection and names the symbol), Placement Options, Relink, Update and
/// Embed.
#[test]
fn links_commands_act_on_images_outside_the_layers_by_id() {
let dir = Folder::new("nested-act");
let mut s = nested_links(&dir);
let symbol = row_id(&mut s, "symbol.png");
let info = s.execute("links.info", &json!({"id": symbol})).unwrap();
assert_eq!((info["fileName"].as_str(), info["status"].as_str(), info["id"].as_u64()), (Some("symbol.png"), Some("ok"), Some(symbol)), "{info}");
let other = super::rect(&mut s, 0.0, 0.0, 5.0, 5.0);
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
let go = s.execute("links.goTo", &json!({"id": symbol})).unwrap();
assert_eq!(
(go["onCanvas"].clone(), go["owner"]["kind"].clone(), go["owner"]["name"].clone()),
(json!(false), json!("symbol"), json!("Mark")),
"{go}"
);
assert!(s.doc().unwrap().selection.objects.is_empty(), "nothing on the canvas is selected");
s.execute("links.placementOptions", &json!({"ids": [symbol], "preserve": "fit"})).unwrap();
let placement = s.execute("links.placementOptions", &json!({"ids": [symbol]})).unwrap();
assert_eq!(placement["placement"]["preserve"], "fit");
// Relink: the symbol's image shows the new file.
let other = dir.file("other.png");
write(&other, &png(40, 20, BLUE));
let r = s.execute("links.relink", &json!({"ids": [symbol], "path": other})).unwrap();
assert_eq!(r["relinked"], json!([symbol]), "{r}");
assert_eq!(stored_link(&s, symbol).unwrap().path, other);
// Update: a changed pattern file is read again for the pattern's image.
let pattern = row_id(&mut s, "pattern.png");
let changed = png(30, 30, RED);
write(&dir.file("pattern.png"), &changed);
let r = s.execute("links.update", &json!({"ids": [pattern]})).unwrap();
assert_eq!(r["updated"], json!([pattern]), "{r}");
assert_eq!(stored_link(&s, pattern).unwrap().size, Some(changed.len() as u64));
// Embed: the design's image keeps its pixels and no longer links.
let design = row_id(&mut s, "design.png");
let r = s.execute("links.embed", &json!({"ids": [design]})).unwrap();
assert_eq!(r["embedded"], json!([design]), "{r}");
assert!(stored_link(&s, design).is_none());
let row = s.execute("links.list", &json!({"show": "embedded"})).unwrap();
assert_eq!(row["links"][0]["id"], json!(design), "{row}");
// Relink All Instances takes the other stored objects linked to the same file.
let mask = row_id(&mut s, "mask.png");
let r = s.execute("links.relink", &json!({"ids": [symbol], "path": dir.file("mask.png"), "scope": "all"})).unwrap();
assert_eq!(r["relinked"], json!([symbol]), "{r}");
let r = s.execute("links.relink", &json!({"ids": [mask], "path": other, "scope": "all"})).unwrap();
let mut relinked: Vec<u64> = r["relinked"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
relinked.sort();
let mut both = vec![symbol, mask];
both.sort();
assert_eq!(relinked, both, "{r}");
}
/// Opening a document reports missing and modified files that only art outside the layers shows,
/// by their objects' ids, and those ids stay the same after the document is saved and opened again.
#[test]
fn open_reports_links_outside_the_layers_by_id() {
let dir = Folder::new("nested-open");
let mut s = nested_links(&dir);
let path = dir.file("poster.vectorcraft");
save(&mut s, &path);
let ids: Vec<u64> = NESTED.iter().map(|name| row_id(&mut s, name)).collect();
std::fs::remove_file(dir.file("symbol.png")).unwrap();
write(&dir.file("pattern.png"), &png(30, 30, RED));
let r = open(&mut s, &path);
let names = |k: &str| r[k].as_array().unwrap().iter().map(|l| (l["name"].as_str().unwrap().to_string(), l["ids"].clone())).collect::<Vec<_>>();
assert_eq!(names("missingLinks"), [("symbol.png".to_string(), json!([ids[0]]))], "{r}");
assert_eq!(names("modifiedLinks"), [("pattern.png".to_string(), json!([ids[2]]))], "{r}");
let again: Vec<u64> = NESTED.iter().map(|name| row_id(&mut s, name)).collect();
assert_eq!(again, ids, "the ids are saved");
}
/// A document whose symbol and mask art repeat the ids of objects in the layers (or have none)
/// opens with ids of their own there, the layer tree's kept; the links commands then tell them apart.
#[test]
fn nested_objects_that_repeat_ids_open_with_ids_of_their_own() {
let dir = Folder::new("nested-repeat");
let mut s = nested_links(&dir);
let layer_image = place(&mut s, &dir.file("symbol.png"));
let path = dir.file("poster.vectorcraft");
save(&mut s, &path);
// The symbol's image takes the id of the image in the layers, the mask's image none.
let mut saved: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
saved["document"]["symbols"][0]["art"]["id"] = json!(layer_image.0);
let layer = &mut saved["document"]["layers"][0]["kind"]["children"];
let masked = layer.as_array_mut().unwrap().iter_mut().find(|n| n.get("mask").is_some() || n["extras"].get("mask").is_some()).unwrap();
let mask = if masked.get("mask").is_some() { &mut masked["mask"] } else { &mut masked["extras"]["mask"] };
mask["art"]["id"] = json!(0);
std::fs::write(&path, serde_json::to_vec(&saved).unwrap()).unwrap();
open(&mut s, &path);
let list = s.execute("links.list", &json!({})).unwrap();
let ids: Vec<u64> = list["links"].as_array().unwrap().iter().map(|r| r["id"].as_u64().unwrap()).collect();
let unique: std::collections::BTreeSet<u64> = ids.iter().copied().collect();
assert_eq!((ids.len(), unique.len()), (5, 5), "{list}");
assert!(!ids.contains(&0), "{list}");
assert_eq!(list["links"][0]["id"], json!(layer_image.0), "the layer tree keeps its ids: {list}");
let symbol = list["links"].as_array().unwrap().iter().find(|r| r["owner"]["kind"] == "symbol").unwrap()["id"].as_u64().unwrap();
s.execute("links.embed", &json!({"ids": [symbol]})).unwrap();
assert!(stored_link(&s, symbol).is_none());
assert!(image(&s, layer_image).link.is_some(), "the image in the layers stays linked");
}
/// An image that Placement Options clip, alone in a group the user made, goes into a new clip group
/// inside that group when its file grows, in the layers and in a symbol's art; the user's group
/// stays a plain group.
+1 -1
View File
@@ -213,7 +213,7 @@ fn go_to_selects_the_image() {
run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}));
assert_ne!(s.doc().unwrap().selection.objects, vec![id]);
let r = run(&mut s, "links.goTo", json!({"id": id.0}));
assert_eq!(r, json!({"id": id.0, "bounds": [-100.0, 0.0, 500.0, 300.0]}));
assert_eq!(r, json!({"id": id.0, "bounds": [-100.0, 0.0, 500.0, 300.0], "onCanvas": true}));
assert_eq!(s.doc().unwrap().selection.objects, vec![id]);
let rect = s.doc().unwrap().doc.layers[0].children().unwrap()[1].id;
assert!(s.execute("links.goTo", &json!({"id": rect.0})).is_err(), "not an image");
+24
View File
@@ -47,6 +47,30 @@ fn update_changed_reads_changed_files_again_once() {
assert_eq!(s.execute("links.check", &json!({})).unwrap()["modified"], 1);
}
/// A file only a symbol's art shows is watched too, and read again by the id of the symbol's image.
#[test]
fn update_changed_reads_a_file_only_a_symbol_shows() {
let dir = Folder::new("watch-symbol");
let path = dir.file("art.png");
std::fs::write(&path, png(40, 40, RED)).unwrap();
let mut s = session();
let id = place(&mut s, &path);
s.execute("symbol.new", &json!({"name": "Mark", "ids": [id.0]})).unwrap();
let instance = s.doc().unwrap().selection.objects[0];
s.execute("edit.clear", &json!({"ids": [instance.0]})).unwrap();
let mut in_symbol = None;
s.doc().unwrap().doc.symbols[0].art.walk(&mut |n| {
if matches!(n.kind, vectorcraft_doc::NodeKind::Image(_)) {
in_symbol = Some(n.id.0);
}
});
let in_symbol = in_symbol.expect("the symbol's image");
assert_eq!(s.execute("links.updateChanged", &json!({})).unwrap()["updated"], json!([]));
save(&path, &png(40, 40, BLUE));
assert_eq!(s.execute("links.updateChanged", &json!({})).unwrap()["updated"], json!([in_symbol]));
assert_eq!(s.execute("links.check", &json!({})).unwrap()["modified"], 0);
}
#[test]
fn a_background_look_follows_update_links() {
for (mode, key) in [("automatically", "updated"), ("askWhenModified", "ask"), ("manually", "modified")] {
+95
View File
@@ -662,6 +662,101 @@ fn placed_art_brings_its_symbols_and_swatches_renaming_on_conflict() {
assert!(linked, "still linked to the swatch it brought");
}
/// The symbol and pattern art placed art brings takes ids of the document's own: the file's ids
/// already name other objects there, and the Links panel names linked art in symbols by its id.
#[test]
fn placed_art_brings_its_symbols_and_patterns_with_ids_of_the_documents_own() {
let mut src = session();
src.execute("shape.ellipse", &json!({"x": 50, "y": 10, "width": 20, "height": 20})).unwrap();
src.execute("symbol.new", &json!({"name": "Star"})).unwrap();
src.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap();
let tile = src.doc().unwrap().selection.objects[0];
src.execute("object.pattern.make", &json!({"ids": [tile.0], "edit": false, "name": "Dots"})).unwrap();
src.execute("paint.setFill", &json!({"ids": [tile.0], "swatch": "Dots"})).unwrap();
let bytes = serialize(&mut src, "vectorcraft");
// The document's objects take the same ids the file's do.
let mut s = session();
for x in [0, 20, 40, 60] {
s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 5, "height": 5})).unwrap();
}
s.execute("symbol.new", &json!({"name": "Box"})).unwrap();
place(&mut s, "logo.vectorcraft", &bytes, json!({}));
let doc = &s.doc().unwrap().doc;
assert!(doc.symbols.iter().any(|x| x.name == "Star") && doc.pattern("Dots").is_some());
let mut ids = vec![];
doc.visit_stored(|n, _| ids.push(n.id.0));
let unique: std::collections::BTreeSet<u64> = ids.iter().copied().collect();
assert_eq!(unique.len(), ids.len(), "{ids:?}");
}
/// Placing the same file again shares the symbols and patterns the first placement brought: their
/// art differs from the file's only in its ids, so no `Star 2` or `Dots 2` joins the document.
#[test]
fn placing_the_same_art_again_shares_its_symbols_and_patterns() {
let mut src = session();
src.execute("shape.ellipse", &json!({"x": 50, "y": 10, "width": 20, "height": 20})).unwrap();
src.execute("symbol.new", &json!({"name": "Star"})).unwrap();
src.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap();
let tile = src.doc().unwrap().selection.objects[0];
src.execute("object.pattern.make", &json!({"ids": [tile.0], "edit": false, "name": "Dots"})).unwrap();
src.execute("paint.setFill", &json!({"ids": [tile.0], "swatch": "Dots"})).unwrap();
let bytes = serialize(&mut src, "vectorcraft");
let mut s = session();
let counts = |s: &Session| {
let doc = &s.doc().unwrap().doc;
(doc.symbols.len(), doc.patterns.len())
};
place(&mut s, "logo.vectorcraft", &bytes, json!({}));
let once = counts(&s);
for _ in 0..2 {
place(&mut s, "logo.vectorcraft", &bytes, json!({}));
}
assert_eq!(counts(&s), once);
let doc = &s.doc().unwrap().doc;
assert!(!doc.symbols.iter().any(|x| x.name == "Star 2") && doc.pattern("Dots 2").is_none());
}
/// A symbol whose art matches the document's own but uses a pattern the document defines
/// differently is not shared: it comes in under a free name, using the pattern it brings.
#[test]
fn placed_art_does_not_share_a_symbol_whose_pattern_moves() {
let mut src = session();
src.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap();
let tile = src.doc().unwrap().selection.objects[0];
src.execute("object.pattern.make", &json!({"ids": [tile.0], "edit": false, "name": "Dots"})).unwrap();
src.execute("paint.setFill", &json!({"ids": [tile.0], "swatch": "Dots"})).unwrap();
src.execute("symbol.new", &json!({"name": "Star", "ids": [tile.0]})).unwrap();
let bytes = serialize(&mut src, "vectorcraft");
let mut s = session();
place(&mut s, "logo.vectorcraft", &bytes, json!({}));
// The document's "Dots" changes; its "Star" still matches the file's.
let st = s.doc_mut().unwrap();
let d = Arc::make_mut(&mut st.doc);
let dots = d.pattern_mut("Dots").unwrap();
dots.tile = Rect::new(0.0, 0.0, 50.0, 50.0);
let r = place(&mut s, "logo.vectorcraft", &bytes, json!({}));
let mut symbol = None;
node(&s, &r["ids"][0]).walk(&mut |n| {
if let NodeKind::SymbolInstance { symbol: name, .. } = &n.kind {
symbol = Some(name.clone());
}
});
assert_eq!(symbol.as_deref(), Some("Star 2"));
let doc = &s.doc().unwrap().doc;
let star2 = doc.symbols.iter().find(|x| x.name == "Star 2").unwrap();
let mut fills = vec![];
star2.art.walk(&mut |n| {
fills.extend(n.appearance.items.iter().filter_map(|i| match i {
AppearanceItem::Fill(f) => match &f.paint {
Paint::Pattern { pattern, .. } => Some(pattern.clone()),
_ => None,
},
_ => None,
}))
});
assert_eq!(fills, ["Dots 2"]);
}
#[test]
fn placed_art_brings_its_brushes_renaming_on_conflict() {
// The file: a path with its own brush, and one with a brush the defaults hold.
+33
View File
@@ -753,6 +753,9 @@ fn precise_cursors_replace_every_pen_state() {
Cursor::ShapeBuilderErase,
Cursor::AnchorPoint,
Cursor::Curvature,
Cursor::LivePaintBucket,
Cursor::LivePaintBucketFace,
Cursor::LivePaintBucketEdge,
] {
assert_eq!(c.precise(), Cursor::Crosshair, "{c:?}");
}
@@ -2795,3 +2798,33 @@ fn snap_to_glyph_options_read_set_and_reset() {
s.execute("prefs.reset", &json!({})).unwrap();
assert_eq!(s.execute("view.snapToGlyph.options", &json!({})).unwrap(), all);
}
/// Pixel Snapping Options: `view.snapToPixel.options` reads and sets While Drawing, While Moving
/// and While Scaling, all on by default, kept as the `pixelSnap` preference group; bad keys and
/// values change nothing, preferences saved without the group read it as all on, and resetting the
/// preferences turns them all back on.
#[test]
fn pixel_snapping_options_read_set_and_reset() {
let mut s = Session::new();
let all = json!({"drawing": true, "moving": true, "scaling": true});
assert_eq!(s.execute("view.snapToPixel.options", &json!({})).unwrap(), all);
let set = json!({"drawing": true, "moving": false, "scaling": true});
assert_eq!(s.execute("view.snapToPixel.options", &json!({"moving": false})).unwrap(), set);
assert_eq!(s.execute("prefs.get", &json!({"key": "pixelSnap"})).unwrap(), set);
assert!(!s.prefs.pixel_snap.moving && s.prefs.pixel_snap.drawing && s.prefs.pixel_snap.scaling);
for bad in [json!({"moving": 1}), json!({"rotating": false})] {
assert!(s.execute("view.snapToPixel.options", &bad).is_err(), "{bad}");
assert!(s.execute("prefs.set", &json!({"key": "pixelSnap", "value": bad})).is_err(), "{bad}");
assert_eq!(s.execute("view.snapToPixel.options", &json!({})).unwrap(), set, "{bad}");
}
s.execute("prefs.set", &json!({"key": "pixelSnap", "value": {"scaling": false}})).unwrap();
let both = json!({"drawing": true, "moving": false, "scaling": false});
assert_eq!(s.execute("view.snapToPixel.options", &json!({})).unwrap(), both);
// Preferences written before the group existed, and a group that names only some options.
let older: Prefs = serde_json::from_value(json!({"keyboardIncrement": 4})).unwrap();
assert_eq!(older.pixel_snap, vectorcraft_tools::PixelSnap::default());
let partial: Prefs = serde_json::from_value(json!({"pixelSnap": {"drawing": false}})).unwrap();
assert_eq!(partial.pixel_snap, vectorcraft_tools::PixelSnap { drawing: false, moving: true, scaling: true });
s.execute("prefs.reset", &json!({})).unwrap();
assert_eq!(s.execute("view.snapToPixel.options", &json!({})).unwrap(), all);
}
+3 -1
View File
@@ -25,7 +25,8 @@ pub struct ViewInfo {
/// View → Pixel Preview: while it is on, the tools use no Smart Guides.
pub pixel_preview: bool,
pub show_bbox: bool,
/// View → Snap to Pixel: drawing and moving land on whole pixels (points at 72 ppi).
/// View → Snap to Pixel: drawing, moving and scaling land on whole pixels (points at 72 ppi),
/// each while its Pixel Snapping option (`view.snapToPixel.options`) is on.
pub snap_to_pixel: bool,
/// View → Snap to Point: picked points (a transform's reference point) land on anchors.
pub snap_to_point: bool,
@@ -368,6 +369,7 @@ impl Session {
// Snap to Grid and Snap to Pixel are exclusive, as in Illustrator; left both on, the grid
// wins instead of pixels quietly rounding every drag to whole points (#1816).
snap_to_pixel: view.snap_to_pixel && !view.snap_to_grid,
pixel_snap: self.prefs.pixel_snap,
snap_to_point: view.snap_to_point,
snap_tangent: self.prefs.snap_tangent,
snap_perpendicular: self.prefs.snap_perpendicular,
+100
View File
@@ -180,6 +180,106 @@ fn a_batch_converts_through_the_profile_it_assigns() {
assert_eq!(converted, fill(&device, b));
}
/// The profiles a document is assigned are in use while it is in front: a new or opened document
/// assigned none draws through the working spaces, switching back to the assigned document puts its
/// profile in use again, and closing a document puts the profiles of the document left in front, or
/// with none open the working spaces, in use.
#[test]
fn assigned_profiles_follow_the_front_document() {
let _g = settings();
let dir = fresh_dir("front-profiles");
let _reset = ColorSettingsReset { profile: None, paths: vec![dir.clone()] };
std::fs::create_dir_all(&dir).unwrap();
let tagged = dir.join("tagged.vectorcraft");
let mut s = session();
let working = cms::working_settings();
assert_ne!(working.cmyk, cms::DEVICE_CMYK);
exec(&mut s, "edit.assignProfile", json!({"cmyk": cms::DEVICE_CMYK}));
exec(&mut s, "file.saveAs", json!({"path": tagged.to_str().unwrap()}));
exec(&mut s, "file.new", json!({"width": 100, "height": 100}));
assert_eq!(cms::active_settings(), working, "a new document draws through the working spaces");
exec(&mut s, "document.activate", json!({"index": 0}));
assert_eq!(cms::active_settings().cmyk, cms::DEVICE_CMYK, "back in front, the document draws through its profile");
assert!(s.set_active(1));
assert_eq!(cms::active_settings(), working, "a tab switch to the untagged document");
exec(&mut s, "file.close", json!({}));
assert_eq!(cms::active_settings().cmyk, cms::DEVICE_CMYK, "the document left in front draws through its profile");
exec(&mut s, "file.close", json!({}));
assert_eq!(cms::active_settings(), working, "no document open: the working spaces");
exec(&mut s, "document.open", json!({"path": tagged.to_str().unwrap()}));
assert_eq!(cms::active_settings().cmyk, cms::DEVICE_CMYK, "an opened document draws through its saved profile");
}
/// Undo and Redo of Assign Profile, and File › Revert to a file assigned no profile, put the
/// profiles the document has then in use.
#[test]
fn undo_redo_and_revert_put_the_document_profiles_in_use() {
let _g = settings();
let dir = fresh_dir("undo-profiles");
let _reset = ColorSettingsReset { profile: None, paths: vec![dir.clone()] };
std::fs::create_dir_all(&dir).unwrap();
let untagged = dir.join("untagged.vectorcraft");
let mut s = session();
let working = cms::working_settings();
exec(&mut s, "file.saveAs", json!({"path": untagged.to_str().unwrap()}));
exec(&mut s, "edit.assignProfile", json!({"cmyk": cms::DEVICE_CMYK}));
assert_eq!(cms::active_settings().cmyk, cms::DEVICE_CMYK);
exec(&mut s, "edit.undo", json!({}));
assert_eq!(doc_profiles(&s.doc().unwrap().doc), (None, None));
assert_eq!(cms::active_settings(), working, "undone: the working spaces");
exec(&mut s, "edit.redo", json!({}));
assert_eq!(doc_profiles(&s.doc().unwrap().doc), (None, Some(cms::DEVICE_CMYK.to_string())));
assert_eq!(cms::active_settings().cmyk, cms::DEVICE_CMYK, "redone: the assigned profile");
exec(&mut s, "file.revert", json!({}));
assert_eq!(doc_profiles(&s.doc().unwrap().doc), (None, None));
assert_eq!(cms::active_settings(), working, "reverted: the working spaces");
}
/// A batch that assigns a profile and then fails puts the document back without it, and the
/// working spaces back in use.
#[test]
fn a_failed_batch_puts_the_profiles_in_use_back() {
let _g = settings();
let _reset = ColorSettingsReset { profile: None, paths: vec![] };
let mut s = session();
let working = cms::working_settings();
let steps = json!([
{"command": "edit.assignProfile", "params": {"cmyk": cms::DEVICE_CMYK}},
{"command": "document.activate", "params": {"index": 99}},
]);
assert!(s.execute("command.batch", &json!({"commands": steps})).is_err());
assert_eq!(doc_profiles(&s.doc().unwrap().doc), (None, None));
assert_eq!(cms::active_settings(), working);
}
/// A batch step that switches documents makes the next step convert through the profiles of the
/// document it switched to, not those of the document the batch began in.
#[test]
fn a_batch_converts_the_document_it_switches_to_through_its_profiles() {
let _g = settings();
let _reset = ColorSettingsReset { profile: None, paths: vec![] };
let blue = |s: &mut Session| {
let id = rect(s, 10.0, 10.0, 50.0, 50.0);
exec(s, "paint.setFill", json!({"ids": [id.0], "color": "#3366cc"}));
id
};
let fill = |s: &Session, id| s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint().color();
let mut working = session();
let w = blue(&mut working);
exec(&mut working, "file.documentColorMode", json!({"mode": "cmyk"}));
let mut s = session();
let b = blue(&mut s);
exec(&mut s, "file.new", json!({"width": 100, "height": 100}));
exec(&mut s, "edit.assignProfile", json!({"cmyk": cms::DEVICE_CMYK}));
let steps = json!([
{"command": "document.activate", "params": {"index": 0}},
{"command": "file.documentColorMode", "params": {"mode": "cmyk"}},
]);
exec(&mut s, "command.batch", json!({"commands": steps}));
assert_eq!(s.active_index(), Some(0));
assert_eq!(fill(&s, b), fill(&working, w), "converted through the working CMYK space");
}
/// View › Proof Setup › Working CMYK simulates the working CMYK space of Color Settings in a
/// document assigned another CMYK profile, in Proof Colors and in Separations Preview, and a change
/// of the working CMYK space shows in the next proof while the document keeps its profile.
+118
View File
@@ -7110,6 +7110,124 @@ fn every_effect_a_graphic_style_holds_is_read_back() {
assert!(p.contains("7.5 /Real (moveV_Pts) ,") && p.contains("0.5236 /Real (rotate_Radians) ,"), "{p}");
}
/// An embedded 8 × 8 image of a color ramp, `Photo`, 80 pt square at (20, 10) in `doc`, at half
/// opacity, with `effects`.
fn warped_photo(doc: &mut Document, effects: Vec<vectorcraft_doc::Effect>) -> Node {
let ramp = image::RgbImage::from_fn(8, 8, |x, y| image::Rgb([(x * 32) as u8, (y * 32) as u8, 160]));
let mut photo = image_node(doc, ImageBlob::png(png_of(ramp.into())), (8, 8), Affine::new([10.0, 0.0, 0.0, 10.0, 20.0, 10.0]), None);
photo.name = Some("Photo".into());
photo.opacity = 0.5;
photo.appearance = Appearance { effects, ..Appearance::default() }.into();
photo
}
/// A 200 × 100 document holding `photo`, made by [`warped_photo`].
fn photo_doc(photo: impl FnOnce(&mut Document) -> Node) -> Document {
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
let n = photo(&mut doc);
doc.insert(Some(layer), usize::MAX, n).unwrap();
doc
}
/// An embedded image with one Warp is written with an art style of that Warp, its bent pieces as its
/// drawn look and the image itself on `%_` lines: it reads back as the image, its pixels, placement,
/// name and opacity as they were, with its Warp live and its settings kept.
#[test]
fn an_image_with_a_warp_reads_back_with_its_warp_live() {
// GUARDS: an image with a Warp was written as its drawn pieces alone, and read back without its Warp.
for (id, params) in [
("warp.arc", serde_json::json!({"bend": 40.0})),
("warp.flag", serde_json::json!({"bend": -30.0, "horizontal": 10.0, "vertical": 0.0, "orientation": "vertical"})),
] {
let doc = photo_doc(|d| warped_photo(d, vec![fx(id, params.clone())]));
let out = export_ai_editing(&doc, &opts()).unwrap();
assert!(!out.warnings.iter().any(|w| w == writer::EFFECTS), "{id}: {:?}", out.warnings);
let back = read_back(&doc);
let art = back.layers[0].children().unwrap();
assert_eq!(art.len(), 1, "{id}: {:#?} {:?}", lines(&back), out.warnings);
let (mut want, mut got) = (vec![], vec![]);
pictures(&doc, doc.layers[0].children().unwrap(), "", &mut want);
pictures(&back, art, "", &mut got);
assert_eq!(got, want, "{id}");
let [warp] = art[0].appearance.effects.as_slice() else { panic!("{id}: {:?}", art[0].appearance) };
assert_eq!(warp.id, id);
let (w, g) = (vectorcraft_effects::merged_params(id, &params), vectorcraft_effects::merged_params(&warp.id, &warp.params));
for key in ["bend", "horizontal", "vertical"] {
assert!((g[key].as_f64().unwrap() - w[key].as_f64().unwrap()).abs() < 6e-3, "{id} {key}: {g} for {w}");
}
assert_eq!(g["orientation"], w["orientation"], "{id}");
}
}
/// An image whose style's Warp bends it another way than its drawn look keeps that look, with the
/// note, and the file as written opens with the image.
#[test]
fn an_image_whose_warp_draws_otherwise_than_its_look_keeps_its_look() {
// GUARDS: an image read with its Warp live whatever its drawn look showed.
let doc = photo_doc(|d| warped_photo(d, vec![fx("warp.arc", serde_json::json!({"bend": 40.0}))]));
let program = export_ai_editing(&doc, &opts()).unwrap().program;
let (from, to) = (b"0.4 /Real (DeformValue)".as_slice(), b"-0.4 /Real (DeformValue)".as_slice());
let at = program.windows(from.len()).position(|w| w == from).expect("the warp's bend");
let mut other = program.clone();
other.splice(at..at + from.len(), to.iter().copied());
let (back, warnings) = crate::ai_alone(&other).unwrap();
let art = back.layers[0].children().unwrap();
assert_eq!(art.len(), 1, "{art:#?}");
assert!(matches!(art[0].kind, NodeKind::Group { .. }), "the drawn look: {:?}", art[0].kind);
assert!(art[0].appearance.effects.is_empty(), "{:?}", art[0].appearance);
assert!(warnings.iter().any(|w| w.contains("drawn look")), "{warnings:?}");
let (back, _) = crate::ai_alone(&program).unwrap();
assert!(matches!(back.layers[0].children().unwrap()[0].kind, NodeKind::Image(_)));
}
/// An image on `%_` lines is the copy of a styled object, as other objects there are: with a style
/// the file doesn't define, its drawn look stands for it, named as it is, and the image doesn't come
/// in beside the look.
#[test]
fn an_image_on_hidden_lines_does_not_come_in_beside_its_look() {
// GUARDS: an image whose samples were on `%_` lines came in as a second, visible object.
let doc = photo_doc(|d| warped_photo(d, vec![fx("warp.arc", serde_json::json!({"bend": 40.0}))]));
let program = export_ai_editing(&doc, &opts()).unwrap().program;
let (from, to) = (b"1 (Anon 1) XW".as_slice(), b"1 (Unknown) XW".as_slice());
let at = program.windows(from.len()).position(|w| w == from).expect("the image's style");
let mut unknown = program.clone();
unknown.splice(at..at + from.len(), to.iter().copied());
let (back, _) = crate::ai_alone(&unknown).unwrap();
let art = back.layers[0].children().unwrap();
assert_eq!(art.len(), 1, "{:#?}", lines(&back));
assert!(matches!(art[0].kind, NodeKind::Group { .. }), "the drawn look: {:?}", art[0].kind);
assert_eq!(art[0].name.as_deref(), Some("Photo"));
}
/// A linked image, an image with an opacity mask, and an image with a Warp and another effect are
/// written as their drawn art, with no art style.
#[test]
fn other_warped_images_are_written_as_their_drawn_art() {
let arc = || fx("warp.arc", serde_json::json!({"bend": 40.0}));
let linked = photo_doc(|d| {
let mut n = warped_photo(d, vec![arc()]);
if let NodeKind::Image(im) = &mut n.kind {
im.link = Some(vectorcraft_doc::LinkInfo::new("/art/photo.png"));
}
n
});
let masked = photo_doc(|d| {
let mut n = warped_photo(d, vec![arc()]);
let white =
Node::path(d.alloc_id(), shapes::rectangle(Rect::new(20.0, 10.0, 100.0, 90.0)), Appearance::basic(solid(Color::WHITE), Paint::None, 0.0));
n.extras_mut().mask = Some(Box::new(OpacityMask::new(white, false)));
n
});
let stacked = photo_doc(|d| warped_photo(d, vec![arc(), fx("stylize.feather", serde_json::json!({"radius": 2.0}))]));
for (what, doc) in [("linked", linked), ("masked", masked), ("stacked", stacked)] {
assert!(!program_shown(&doc).contains("1 (Anon"), "{what}");
let back = read_back(&doc);
let art = back.layers[0].children().unwrap();
assert!(art.iter().all(|n| n.appearance.effects.is_empty()), "{what}: {art:#?}");
}
}
/// Every kind of appearance a style isn't written for is written as its drawn look, with a warning.
#[test]
fn appearances_written_as_their_drawn_look() {
+27 -8
View File
@@ -41,7 +41,8 @@ pub(in crate::ai_editing) fn style_links(doc: &Document) -> usize {
/// The objects of `doc`'s layers that may be written with an art style ([`Writer::styled_object`]),
/// by id: paths and compound paths with points and groups, with live effects, linked to a graphic
/// style or (paths and compound paths) with a brush on a stroke, without Opacity & Mask Define
/// style or (paths and compound paths) with a brush on a stroke, and embedded images with one Warp
/// ([`warped_image`]), without Opacity & Mask Define
/// Knockout Shape (the reader takes an object's transparency
/// from its look, which doesn't carry it). A group's members are paths, compound paths or such
/// groups, none with effects or anything baking changes.
@@ -86,10 +87,22 @@ fn candidate(n: &Node) -> bool {
NodeKind::Path { path, guide: false, clipping: false, .. } => has_points(path),
NodeKind::Compound { .. } => has_points(&compound_path(n)),
NodeKind::Group { children, clip: false } => !n.is_compound_shape() && children.iter().all(|c| plain_member(c)),
NodeKind::Image(_) => warped_image(n),
_ => false,
}
}
/// Is `n` an embedded image without an opacity mask whose appearance is one Warp, with no fills or
/// strokes that paint and no effects on them: an image the reader reads with its Warp live
/// ([`crate::import::read_art_style`]'s `image_warp`)?
fn warped_image(n: &Node) -> bool {
let NodeKind::Image(im) = &n.kind else { return false };
im.link.is_none()
&& n.extras().mask.is_none()
&& matches!(n.appearance.effects.as_slice(), [e] if e.id.starts_with("warp."))
&& n.appearance.items.iter().all(|i| i.paint().is_none() && i.effects().is_empty())
}
/// Does `n` have a stroke with a brush that paints, one that its art style holds ([`Writer::style_text`]
/// leaves out what paints nothing)?
fn brushed(n: &Node) -> bool {
@@ -666,7 +679,7 @@ impl Writer<'_> {
return Some(name);
}
let brushed = brushed(orig);
if (orig.appearance.effects.is_empty() && !brushed) || !own_style_holds(&orig.appearance) {
if (orig.appearance.effects.is_empty() && !brushed) || !(own_style_holds(&orig.appearance) || warped_image(orig)) {
return None;
}
let graded = orig.appearance.items.iter().any(|i| matches!(i.paint(), Paint::Gradient(_)));
@@ -704,7 +717,8 @@ impl Writer<'_> {
/// glows or feathers, the object's transparency
/// after the group's end, `0 0 Xd`, `6 () XW`); the object itself on `%_` lines (a path's or
/// compound path's points painted with nothing, or with its gradient fill when its style has
/// one; a group with its members), its name and opacity mask; then `1 (name) XW`.
/// one; a group with its members; an image with its pixels), its name and opacity mask; then
/// `1 (name) XW`.
/// The look's group and the object itself are counted first ([`Self::take_objects`]): without
/// room for them, nothing is written, and the object counts neither as written with its graphic
/// style nor as written with a brush on its stroke.
@@ -712,7 +726,7 @@ impl Writer<'_> {
let own = match &orig.kind {
NodeKind::Path { path, .. } => super::object_count(path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).count()),
NodeKind::Compound { .. } => super::object_count(compound_path(orig).subpaths.iter().filter(|sp| !sp.anchors.is_empty()).count()),
NodeKind::Group { .. } => 1,
NodeKind::Group { .. } | NodeKind::Image(_) => 1,
_ => 0,
};
if !self.take_objects(1 + own) {
@@ -752,13 +766,14 @@ impl Writer<'_> {
let saved = std::mem::take(&mut self.body);
self.hidden += 1;
let fit = drawn_outline(n, orig).map(|p| p.bounding_box());
// A path's objects were kept for it above; it counts them itself.
// A path's or an image's objects were kept for it above; it counts them itself.
if !matches!(orig.kind, NodeKind::Group { .. }) {
self.objects -= own;
}
match &orig.kind {
NodeKind::Path { path, rule, .. } => self.styled_outline(orig, path, *rule, fit, xy),
NodeKind::Compound { rule, .. } => self.styled_outline(orig, &compound_path(orig), *rule, fit, xy),
NodeKind::Image(im) => self.image(&self.doc.shown_image(orig, im), xy),
NodeKind::Group { children, .. } => {
self.line("u");
for c in children {
@@ -847,7 +862,8 @@ fn object_rule(n: &Node) -> FillRule {
/// Can appearance `ap` be written as a style of an object's own: fills and strokes that paint without
/// transparency or effects of their own, and no Warp, Distort & Transform or Blur effect? Those
/// are written only in the Graphic Styles panel's styles.
/// are written only in the Graphic Styles panel's styles, apart from a Warp on an image
/// ([`warped_image`]).
fn own_style_holds(ap: &Appearance) -> bool {
let plain = |i: &AppearanceItem| i.opacity() >= 1.0 && i.blend() == BlendMode::Normal && i.effects().is_empty();
let panel_only = |e: &Effect| ["warp.", "distort.", "blur."].iter().any(|p| e.id.starts_with(p));
@@ -870,13 +886,16 @@ fn panel_reads(g: &GraphicStyle, text: &str) -> bool {
/// Does the reader read object `n` written with style text `text` as it is: a path or compound
/// path with a style it reads on any object, filled by the non-zero rule when the style fills it,
/// or a group with no fills or strokes of its own, with effects that move the outline only where the
/// reader reads them ([`crate::import::style_moves_with`])?
/// reader reads them ([`crate::import::style_moves_with`]), or an image ([`warped_image`]) with a
/// style of one Warp? The reader takes such an image's Warp where it draws as its drawn look.
fn object_reads(n: &Node, text: &str) -> bool {
let section = known_style("x", text);
let own = n.appearance.fill().map(|f| &f.paint).filter(|p| matches!(p, Paint::Gradient(_)));
let Some(mut read) = crate::import::read_art_style(section.as_bytes(), "x", own) else { return false };
let group = matches!(n.kind, NodeKind::Group { .. });
if !read.simple
let image = matches!(n.kind, NodeKind::Image(_));
if (image && !(read.image_warp && warped_image(n)))
|| (!image && !read.simple)
|| (group && !read.appearance.items.is_empty())
|| (!group && read.pathfinder)
|| !crate::import::style_moves_with(section.as_bytes(), "x", n)
+5 -1
View File
@@ -483,6 +483,9 @@ struct Reader<'a> {
/// a global process colour, so these make swatches only for names no colour operator defines.
stop_spots: Vec<Named>,
raster: Option<Raster>,
/// The samples of the image being read are on `%_` lines (`%_%%BeginData`): it is the copy of
/// a styled object there, as the other objects on those lines are.
image_hidden: bool,
/// The file `XG` names for the image after it (`XF`), until an image is read.
image_link: Option<String>,
/// The placed file being read (`%AI5_BeginPlace` … `~`).
@@ -736,6 +739,7 @@ impl<'a> Reader<'a> {
spots: Vec::new(),
stop_spots: Vec::new(),
raster: None,
image_hidden: false,
image_link: None,
place: None,
foreign_data: None,
@@ -846,7 +850,7 @@ impl<'a> Reader<'a> {
self.op(w, hidden)?;
}
Tok::Comment(c) => self.comment(c, hidden)?,
Tok::Data(d) => self.image(d)?,
Tok::Data(d) => self.image(d, hidden)?,
Tok::Preview(d) => {
if let Some(p) = self.place.as_mut() {
p.preview = preview_png(d);
+10 -5
View File
@@ -370,15 +370,18 @@ impl<'a> Reader<'a> {
// ---- images ----------------------------------------------------------------------------
/// The samples after `XI`, its operands on the stack.
pub(super) fn image(&mut self, data: &[u8]) -> Result<(), String> {
/// The samples after `XI`, its operands on the stack; `hidden` when they are on `%_` lines.
pub(super) fn image(&mut self, data: &[u8], hidden: bool) -> Result<(), String> {
let vals = self.operands();
// Operands that came before an `XI` on their own line.
let vals = match self.raster.as_mut().and_then(|r| r.operands.take()) {
Some(before) if !vals.iter().any(|v| matches!(v, V::Arr(_))) => before,
_ => vals,
};
self.image_from(vals, data, false)
self.image_hidden = hidden;
let read = self.image_from(vals, data, false);
self.image_hidden = false;
read
}
/// The matrix and the numbers of an image's operands (`[a b c d tx ty] llx lly urx ury w h bits
@@ -713,7 +716,8 @@ impl<'a> Reader<'a> {
/// Add the image `blob` (`w` × `h` pixels), which the matrix `m` maps into art space, with
/// `alpha` (its alpha channel, one byte a pixel) as its opacity mask when it hides part of the
/// image, and `colorize` as the color that colorizes it.
/// image, and `colorize` as the color that colorizes it. It is on `%_` lines when its samples
/// are ([`Self::image`]).
fn add_raster(&mut self, blob: ImageBlob, alpha: Option<&[u8]>, m: &[f64], (w, h): (u32, u32), colorize: Option<Paint>) -> Result<(), String> {
// The matrix is an art-space matrix (y up) applied to the pixels with their rows running
// downwards, (u, -v): pixels → (u, -v) → art space. Flipping the matrix's result instead
@@ -735,7 +739,8 @@ impl<'a> Reader<'a> {
let key = blob.content_key();
self.doc.images.entry(key.clone()).or_insert(blob);
let im = ImageObject { key, width: w, height: h, xf, link: None, placement: Default::default(), pixels: None };
self.add_image_colorized(im, mask, colorize, false)
// An image on `%_` lines is the copy of a styled object, as the other objects there are.
self.add_image_colorized(im, mask, colorize, self.image_hidden)
}
/// An image that isn't read is left out, with `warning`; in a symbol's art, the symbol isn't
+142 -9
View File
@@ -748,6 +748,7 @@ impl<'a> Reader<'a> {
}
let space = self.space();
self.note_brushes_kept();
let page = self.page_in_doc();
let Some(f) = self.frames.last_mut() else { return };
let n = f.children.len();
let (Some(object), Some(look)) = (n.checked_sub(1).and_then(|i| f.children.get(i)), n.checked_sub(2).and_then(|i| f.children.get(i))) else {
@@ -780,7 +781,7 @@ impl<'a> Reader<'a> {
look
};
// A style read here: the object, painted as it says.
if let Some(mut appearance) = self.styles.get(&style).and_then(|st| {
let appearance = self.styles.get(&style).and_then(|st| {
styled(
object,
look,
@@ -796,13 +797,32 @@ impl<'a> Reader<'a> {
space,
},
)
}) {
// Strokes and effects at the document's scale, as the art (a Large Canvas copy's is scaled up).
let k = space.determinant().abs().sqrt();
if k.is_finite() && k > 0.0 && (k - 1.0).abs() > 1e-9 {
appearance.scale_strokes(k);
appearance.scale_effects(k, vectorcraft_effects::scale_effect);
.map(|mut appearance| {
// Strokes and effects at the document's scale, as the art (a Large Canvas copy's is scaled up).
let k = space.determinant().abs().sqrt();
if k.is_finite() && k > 0.0 && (k - 1.0).abs() > 1e-9 {
appearance.scale_strokes(k);
appearance.scale_effects(k, vectorcraft_effects::scale_effect);
}
appearance
})
});
// An image with a Warp is the object only where its live warp draws as its drawn look, and
// while the import has a check left for it; otherwise its drawn look stays.
let appearance = match appearance {
Some(ap) if matches!(object.kind, NodeKind::Image(_)) && ap.effects.iter().any(|e| e.id.starts_with("warp.")) => {
let alike = self.envelope_checks > 0 && {
self.envelope_checks -= 1;
let layer = self.doc.alloc_id();
let shared = crate::import::ai::envelope::Shared { patterns: &self.doc.patterns, images: &self.doc.images };
let shown = !hidden && object.visible && look.visible;
image_warp_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, page.filter(|_| shown), &mut self.envelope_spent)
};
alike.then_some(ap)
}
other => other,
};
if let Some(appearance) = appearance {
let Some(mut object) = f.children.pop() else { return };
let Some(look) = f.children.pop() else { return };
let left_out = look.visual_bounds().filter(|_| !hidden && object.visible && look.visible);
@@ -1116,6 +1136,41 @@ fn moves_with(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool {
})
}
/// Is `object` an image without an opacity mask, and `st` one Warp on it with nothing else that
/// paints ([`crate::import::ai::style::ArtStyle::image_warp`])? Such an image is read with its Warp
/// live where that draws as its drawn look ([`image_warp_alike`]).
fn image_warps(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool {
matches!(object.kind, NodeKind::Image(_)) && object.extras().mask.is_none() && st.image_warp
}
/// Does image `object` with `appearance` (its style's Warp) draw as `look`, its drawn look, compared
/// over all that the warp draws ([`crate::import::ai::envelope::warped_alike`]) on `layer`, a layer
/// id no other node has? Both are drawn shown, opaque and in the Normal mode. Unless the look is on
/// `%_` lines itself (`hidden`), the copies in it that are on `%_` lines (`hidden_ids`) are left out.
#[allow(clippy::too_many_arguments)]
fn image_warp_alike(
object: &Node,
appearance: &Appearance,
look: &Node,
hidden_ids: &HashSet<NodeId>,
hidden: bool,
layer: NodeId,
shared: &crate::import::ai::envelope::Shared<'_>,
page: Option<Rect>,
spent: &mut crate::import::ai::envelope::Spent,
) -> bool {
let mut live = object.clone();
live.appearance = appearance.clone().into();
let mut plain = look.clone();
if !hidden {
strip(&mut plain, hidden_ids);
}
for n in [&mut live, &mut plain] {
(n.visible, n.opacity, n.blend) = (true, 1.0, BlendMode::Normal);
}
crate::import::ai::envelope::warped_alike(&live, &plain, layer, shared, page, spent)
}
/// What [`placed_paints`] keys a pattern's name with, apart from the gradients' names.
const PATTERN_KEY: &str = "\u{1}pattern ";
@@ -1128,11 +1183,13 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p
let slot = slot_of(object.name.as_deref()).is_some();
// Several fills and strokes, on a path or a compound path.
let stacked = !slot && !st.simple && st.stacked && matches!(object.kind, NodeKind::Path { .. } | NodeKind::Compound { .. });
// One Warp on an image, checked against its drawn look by the caller ([`image_warp_alike`]).
let image_warp = !st.simple && image_warps(object, st);
// A symbol instance draws its symbol's art: it keeps its drawn look.
if !st.plain
|| matches!(object.kind, NodeKind::SymbolInstance { .. })
// A look with no outline in it to keep takes a variable-width stroke as the object's own.
|| (!slot && !st.simple && !stacked && (!st.uneven || draws(look, &HashSet::new())))
|| (!slot && !st.simple && !stacked && !image_warp && (!st.uneven || draws(look, &HashSet::new())))
|| (object.is_container() && !slot && !matches!(object.kind, NodeKind::Compound { .. }) && !st.items.is_empty())
|| (st.pathfinder
&& (slot || !st.items.is_empty() || object.is_compound_shape() || !matches!(object.kind, NodeKind::Group { clip: false, .. })))
@@ -1266,6 +1323,9 @@ pub(crate) struct StyleRead {
pub appearance: Appearance,
/// An object other than type is read with it ([`crate::import::ai::style::ArtStyle::simple`]).
pub simple: bool,
/// An image without an opacity mask is read with it where its live warp draws as its drawn
/// look ([`crate::import::ai::style::ArtStyle::image_warp`]).
pub image_warp: bool,
/// It has Effect › Pathfinder effects, which only a group with no fills or strokes is read with.
pub pathfinder: bool,
/// The opacity, blending mode, isolation and knockout its blend filter gives.
@@ -1310,7 +1370,7 @@ pub(crate) fn read_art_style(section: &[u8], name: &str, own_gradient: Option<&P
s.brush = Some(brush);
}
}
Some(StyleRead { appearance, simple: st.simple, pathfinder: st.pathfinder, transparency: st.transparency })
Some(StyleRead { appearance, simple: st.simple, image_warp: st.image_warp, pathfinder: st.pathfinder, transparency: st.transparency })
}
/// Is art style `name` of `section` read on `object` as far as an effect that moves the outline
@@ -1519,6 +1579,79 @@ mod tests {
assert!(styled(&Node::new(NodeId(4), NodeKind::Image(Box::new(image))), &look, st, &paints).is_none());
}
/// The style `Fx`: `effects` (each a filter's name and its dictionary's keys) on the whole
/// object, over a fill and a stroke that `paints` turns on (`0 1`: the fill paints blue).
fn effects_style(effects: &[(&str, &str)], paints: &str) -> crate::import::ai::style::ArtStyle {
let filters: String = effects
.iter()
.map(|(name, keys)| {
format!("/BasicFilter :\n({name}) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n{keys}; /Dict ;\n /Part ,\n")
})
.collect();
let text = format!(
"%AI9_BeginArtStyles\n/KnownStyle :\n(Fx) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
{filters}/CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
/BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/StrokeStyle : 0 1 0 0 0 Xy\n0 0 Xd\n/Def ;\n (StrokeStyle) ,\n; /Dict ;\n /Part ,\n\
/BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n\
/BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n0 0 0 0 0 0 1 Xa\n{paints} Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\
;\n /Part ,\n;\n%AI9_EndArtStyles\n"
);
crate::import::ai::style::art_styles(text.as_bytes()).remove("Fx").unwrap_or_default()
}
/// An image takes a style of one Warp, under fills and strokes that paint nothing, and no
/// other style with a geometry effect: those keep its drawn look. A path, and an image with an
/// opacity mask, keep their drawn look with the Warp too.
#[test]
fn an_image_takes_a_style_of_one_warp_alone() {
// GUARDS: an image with a Warp in its art style came in as its drawn look.
let warp = ("Adobe Deform", "1 /Int (DeformStyle) ,\n0.4 /Real (DeformValue) ,\n"); // brand-ok: the filter's name in the files
let (gradients, patterns, names, v7_patterns, bending) =
(HashMap::new(), HashMap::new(), ShownNames::default(), HashSet::new(), HashSet::new());
let paints = StylePaints {
gradients: &gradients,
patterns: &patterns,
names: &names,
v7_patterns: &v7_patterns,
brushes: &[],
kept: &[],
bending: &bending,
space: Affine::IDENTITY,
};
let look = Node::group(NodeId(1), vec![square(2, Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)))]);
let image =
ImageObject { key: "a".into(), width: 1, height: 1, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None };
let image = Node::new(NodeId(4), NodeKind::Image(Box::new(image)));
let st = effects_style(&[warp], "0 0");
assert!(st.image_warp && !st.simple, "{st:?}");
let ap = styled(&image, &look, &st, &paints).expect("an image takes one Warp");
let ids: Vec<&str> = ap.effects.iter().map(|e| e.id.as_str()).collect();
assert_eq!(ids, ["warp.arc"]);
assert!(ap.items.iter().all(|i| i.paint().is_none()), "{ap:?}");
// Not on a path, nor on an image with an opacity mask.
assert!(styled(&square(3, Paint::None), &look, &st, &paints).is_none());
let mut masked = image.clone();
masked.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(Node::group(NodeId(7), vec![]), true)));
assert!(styled(&masked, &look, &st, &paints).is_none());
// A Warp over a fill that paints, a Warp with another effect, and the other geometry effects.
let still = ("Adobe Punk and Bloat", "0 /Real (d_factor) ,\n");
let others: [(&[(&str, &str)], &str); 8] = [
(&[warp], "0 1"),
(&[warp, still], "0 0"),
(&[still, warp], "0 0"),
(&[("Adobe Twirl", "45 /Real (angle) ,\n")], "0 0"),
(&[("Adobe Free Distort", "")], "0 0"),
(&[("Adobe Punk and Bloat", "-50 /Real (d_factor) ,\n")], "0 0"),
(&[("Adobe Zigzag", "3 /Real (amount) ,\n1 /Real (absoluteness) ,\n")], "0 0"),
(&[("Adobe Transform", "5 /Real (moveH_Pts) ,\n0.5 /Real (rotate_Radians) ,\n0 /Bool (transformPatterns) ,\n")], "0 0"),
];
for (effects, painted) in others {
let st = effects_style(effects, painted);
assert!(!st.image_warp, "{effects:?} {painted}");
assert!(styled(&image, &look, &st, &paints).is_none(), "{effects:?} {painted}");
}
}
#[test]
fn data_stops_at_its_end_or_a_marker_of_the_section() {
let section = Some(("BeginTextDocument", "EndTextDocument"));
+8
View File
@@ -193,6 +193,10 @@ pub(super) struct ArtStyle {
/// the effects any object takes that don't move the outline: what a path or compound path is
/// read with when each gradient is placed as its drawn look has it (`read::ops`' `styled`).
pub stacked: bool,
/// It is one Warp on the whole object, under fills and strokes that paint nothing and have no
/// effects of their own: what an image is read with when its live warp draws as its drawn look
/// (`read::ops`' `styled`).
pub image_warp: bool,
/// Its fills and strokes, bottom first.
pub items: Vec<StyleItem>,
/// Each item's own visibility, transparency and effects, in the order of [`Self::items`].
@@ -1778,6 +1782,10 @@ fn style(filters: &[Filter]) -> ArtStyle {
&& st.items.iter().all(|i| matches!(i, StyleItem::Fill(_) | StyleItem::Gradient { .. } | StyleItem::Stroke { brush: None, .. }))
&& st.looks.iter().all(|l| l.effects.is_empty())
&& st.effects.iter().all(any_object_takes);
st.image_warp = st.plain
&& matches!(st.effects.as_slice(), [e] if e.id.starts_with("warp."))
&& st.items.iter().all(|i| matches!(i, StyleItem::Fill(p) | StyleItem::Stroke { paint: p, .. } if p.is_none()))
&& st.looks.iter().all(|l| l.effects.is_empty());
st
}
+21 -15
View File
@@ -165,6 +165,26 @@ impl Anchor {
pub fn reversed(&self) -> Self {
Self { p: self.p, h_in: self.h_out, h_out: self.h_in, kind: self.kind }
}
/// Make the anchor smooth between the points `prev` and `next` (its own point for a missing
/// one): handles in line with them, each a third of the way to that side's point. A smooth
/// anchor with both handles keeps them. False, with no change, when the two points give no
/// direction. [`SubPath::smooth_anchor`] calls it with the anchor's neighbors.
pub fn smooth_between(&mut self, prev: Option<Point>, next: Option<Point>) -> bool {
if self.kind == AnchorKind::Smooth && self.has_in() && self.has_out() {
return true;
}
let (pp, nn) = (prev.unwrap_or(self.p), next.unwrap_or(self.p));
let dir = nn - pp;
let l = dir.hypot();
if l <= 1e-9 {
return false;
}
let u = dir / l;
self.h_in = self.p - u * (self.p.distance(pp) / 3.0);
self.h_out = self.p + u * (self.p.distance(nn) / 3.0);
self.kind = AnchorKind::Smooth;
true
}
/// Remove both handles (convert to a sharp corner).
pub fn retract(&mut self) {
self.h_in = self.p;
@@ -398,21 +418,7 @@ impl SubPath {
};
let at = |j: Option<usize>| j.and_then(|j| self.anchors.get(j)).map(|a| a.p);
let (prev, next) = (at(prev), at(next));
let Some(a) = self.anchors.get_mut(i) else { return false };
if a.kind == AnchorKind::Smooth && a.has_in() && a.has_out() {
return true;
}
let (pp, nn) = (prev.unwrap_or(a.p), next.unwrap_or(a.p));
let dir = nn - pp;
let l = dir.hypot();
if l <= 1e-9 {
return false;
}
let u = dir / l;
a.h_in = a.p - u * (a.p.distance(pp) / 3.0);
a.h_out = a.p + u * (a.p.distance(nn) / 3.0);
a.kind = AnchorKind::Smooth;
true
self.anchors.get_mut(i).is_some_and(|a| a.smooth_between(prev, next))
}
/// Cut at the anchors `at`: each becomes the end of one open piece and the start of the next,
/// its handle off each piece retracted (the shape doesn't change). A closed subpath opens at
+73 -15
View File
@@ -45,10 +45,62 @@ fn text_of(result: &Value) -> String {
result["content"].as_array().unwrap().iter().filter(|c| c["type"] == "text").map(|c| c["text"].as_str().unwrap().to_string()).collect()
}
fn tmp(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("vectorcraft-mcp-test-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
dir.join(name)
/// A test's own folder under the temp dir, `vectorcraft-mcp-<tag>-<pid>`, made empty when created
/// and removed with everything in it when dropped, also when the test panics. A removal that fails
/// (a file still open) is ignored.
struct TempFolder(std::path::PathBuf);
impl TempFolder {
fn new(tag: &str) -> Self {
let dir = std::env::temp_dir().join(format!("vectorcraft-mcp-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
Self(dir)
}
/// The path of `name` in the folder.
fn file(&self, name: &str) -> std::path::PathBuf {
self.0.join(name)
}
}
impl std::ops::Deref for TempFolder {
type Target = std::path::Path;
fn deref(&self) -> &std::path::Path {
&self.0
}
}
impl Drop for TempFolder {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// A `TempFolder` starts empty, and dropping it removes it with the files and folders in it, also
/// when the test that holds it panics.
#[test]
fn temp_folders_start_empty_and_are_removed_when_dropped() {
let leftover = std::env::temp_dir().join(format!("vectorcraft-mcp-drop-check-{}", std::process::id()));
std::fs::create_dir_all(&leftover).unwrap();
std::fs::write(leftover.join("old.txt"), b"old").unwrap();
let dir = TempFolder::new("drop-check");
assert_eq!(std::fs::read_dir(&*dir).unwrap().count(), 0, "a leftover folder is emptied");
std::fs::write(dir.file("a.txt"), b"a").unwrap();
std::fs::create_dir(dir.file("sub")).unwrap();
std::fs::write(dir.file("sub").join("b.txt"), b"b").unwrap();
let path = dir.to_path_buf();
drop(dir);
assert!(!path.exists(), "{} is removed", path.display());
let panicked = std::panic::catch_unwind(|| {
let dir = TempFolder::new("panic-check");
std::fs::write(dir.file("a.txt"), b"a").unwrap();
panic!("the test fails with {} in use", dir.display());
});
assert!(panicked.is_err());
let path = std::env::temp_dir().join(format!("vectorcraft-mcp-panic-check-{}", std::process::id()));
assert!(!path.exists(), "{} is removed after a panic", path.display());
}
// ---------- framing ----------
@@ -286,6 +338,7 @@ fn headless_command_list_includes_ui_commands() {
#[test]
fn headless_end_to_end() {
let dir = TempFolder::new("headless-end-to-end");
let mut s = server();
rpc(&mut s, 1, "initialize", json!({"protocolVersion": PROTOCOL_VERSION}));
s.handle_line(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#);
@@ -334,7 +387,7 @@ fn headless_end_to_end() {
assert_eq!(call(&mut s, 44, "doc_inspect", json!({"ids": [999_999]}))["isError"], true);
// Screenshot returns image content (base64 PNG) and text.
let shot_path = tmp("shot.png");
let shot_path = dir.file("shot.png");
let r = call(&mut s, 5, "screenshot", json!({"path": shot_path.to_str().unwrap()}));
assert_eq!(r["isError"], false, "{r}");
let img = r["content"].as_array().unwrap().iter().find(|c| c["type"] == "image").expect("image content");
@@ -344,14 +397,14 @@ fn headless_end_to_end() {
assert_eq!(std::fs::read(&shot_path).unwrap(), png);
// Export SVG.
let svg_path = tmp("out.svg");
let svg_path = dir.file("out.svg");
let r = call(&mut s, 6, "export", json!({"path": svg_path.to_str().unwrap()}));
assert_eq!(r["isError"], false, "{r}");
let svg = std::fs::read_to_string(&svg_path).unwrap();
assert!(svg.contains("<svg") && (svg.contains("<rect") || svg.contains("<path")), "{svg}");
// Save native, open it back.
let dc = tmp("out.vectorcraft");
let dc = dir.file("out.vectorcraft");
assert_eq!(call(&mut s, 7, "save_file", json!({"path": dc.to_str().unwrap()}))["isError"], false);
let r = call(&mut s, 8, "open_file", json!({"path": dc.to_str().unwrap()}));
assert_eq!(r["isError"], false, "{r}");
@@ -359,9 +412,9 @@ fn headless_end_to_end() {
assert_eq!(r["isError"], false, "{r}");
// PDF and PDF-compatible .ai open headless too.
let pdf_path = tmp("out.pdf");
let pdf_path = dir.file("out.pdf");
assert_eq!(call(&mut s, 20, "export", json!({"path": pdf_path.to_str().unwrap()}))["isError"], false);
let ai_path = tmp("out.ai");
let ai_path = dir.file("out.ai");
std::fs::copy(&pdf_path, &ai_path).unwrap();
for (id, p) in [(21, &pdf_path), (22, &ai_path)] {
let r = call(&mut s, id, "open_file", json!({"path": p.to_str().unwrap()}));
@@ -386,9 +439,10 @@ fn headless_end_to_end() {
/// succeeds, the expanded trace holds no image, and its paths keep the image's colors.
#[test]
fn trace_and_style_prompt_steps_run_in_order() {
let dir = TempFolder::new("trace-and-style");
let mut s = server();
// 60 × 40 pixels: a red and a blue block on white.
let png = tmp("trace-and-style.png");
let png = dir.file("trace-and-style.png");
image::RgbImage::from_fn(60, 40, |x, y| match (x, y) {
(5..25, 5..35) => image::Rgb([220, 30, 30]),
(35..55, 5..35) => image::Rgb([30, 60, 200]),
@@ -441,8 +495,9 @@ fn trace_and_style_prompt_steps_run_in_order() {
/// result, as exports do. The image is a dark disc (r = 30 px) on blue, traced with Ignore White.
#[test]
fn screenshot_and_render_preview_draw_the_trace_view_with_trace_views() {
let dir = TempFolder::new("trace-views");
let mut s = server();
let png = tmp("trace-views.png");
let png = dir.file("trace-views.png");
image::RgbImage::from_fn(100, 100, |x, y| {
let (dx, dy) = (f64::from(x) + 0.5 - 50.0, f64::from(y) + 0.5 - 50.0);
if dx * dx + dy * dy <= 900.0 { image::Rgb([0, 0, 0]) } else { image::Rgb([170, 210, 255]) }
@@ -490,6 +545,7 @@ fn screenshot_and_render_preview_draw_the_trace_view_with_trace_views() {
#[test]
fn headless_path_gesture_undo() {
let dir = TempFolder::new("path-gesture-undo");
let mut s = server();
let count = |s: &mut Server| -> u64 {
let r = call(s, 90, "inspect_document", json!({}));
@@ -543,9 +599,9 @@ fn headless_path_gesture_undo() {
assert_eq!(r["isError"], false, "{r}");
let r = call(&mut s, 11, "select_tool", json!({"tool": "pen"}));
assert_eq!(r["isError"], false, "{r}");
let r = call(&mut s, 12, "export", json!({"path": tmp("x.png").to_str().unwrap(), "scale": 0.5}));
let r = call(&mut s, 12, "export", json!({"path": dir.file("x.png").to_str().unwrap(), "scale": 0.5}));
assert_eq!(r["isError"], false, "{r}");
assert_eq!(&std::fs::read(tmp("x.png")).unwrap()[..4], b"\x89PNG");
assert_eq!(&std::fs::read(dir.file("x.png")).unwrap()[..4], b"\x89PNG");
}
/// A hover's reply comes once the tool's highlight is ready, also when the tool finds it on another
@@ -1074,8 +1130,9 @@ fn relative_to_cwd(p: &std::path::Path) -> Option<std::path::PathBuf> {
#[test]
fn headless_file_tools_take_relative_paths() {
let dir = TempFolder::new("relative-paths");
let mut s = server();
let file = tmp("relative.vectorcraft");
let file = dir.file("relative.vectorcraft");
let Some(rel) = relative_to_cwd(&file) else { return };
let rel = rel.to_str().unwrap();
assert!(std::path::Path::new(rel).is_relative());
@@ -1547,13 +1604,14 @@ fn text_effect_pathfinder_transform_graph_and_wrap_tools() {
#[test]
fn oversized_screenshot_and_png_export_are_errors() {
// 16383 pt at the maximum scale (16) is 262 128 px a side: an error result, not a crashed server.
let dir = TempFolder::new("oversized-export");
let mut s = server();
let r = call(&mut s, 1, "run_command", json!({"command": "file.new", "params": {"width": 16383, "height": 16383}}));
assert_eq!(r["isError"], false, "{r}");
let r = call(&mut s, 2, "screenshot", json!({"scale": 16}));
assert_eq!(r["isError"], true, "{r}");
assert!(text_of(&r).contains("pixels"), "{r}");
let path = tmp("huge.png");
let path = dir.file("huge.png");
let r = call(&mut s, 3, "export", json!({"path": path.to_str().unwrap(), "scale": 16}));
assert_eq!(r["isError"], true, "{r}");
assert!(!path.exists());
+3 -2
View File
@@ -10,6 +10,7 @@ use std::time::{Duration, Instant};
use serde_json::{Value, json};
use vectorcraft_engine::cancel;
use super::TempFolder;
use crate::{Backend, Server};
/// A backend whose `engine.execute` runs until cancelled (or for `limit`), like a long export.
@@ -318,8 +319,8 @@ impl Backend for Gated {
#[test]
fn a_cancelled_export_through_the_real_engine_writes_nothing_and_leaves_the_session_usable() {
let path = vectorcraft_testkit::temp_dir("mcp-cancel").join("out.pdf");
std::fs::remove_file(&path).ok();
let dir = TempFolder::new("cancel");
let path = dir.file("out.pdf");
let (read, mut to_server) = std::io::pipe().unwrap();
let (tx, replies) = mpsc::channel();
let (started_tx, started) = mpsc::channel();
+4 -8
View File
@@ -3,6 +3,7 @@
use serde_json::{Value, json};
use super::TempFolder;
use crate::{Backend, Headless, call_tool};
fn text(r: &crate::ToolResult) -> Value {
@@ -48,9 +49,7 @@ fn an_option_no_format_takes_is_an_error() {
/// write anything.
#[test]
fn a_save_or_screens_option_no_format_takes_is_an_error() {
let dir = std::env::temp_dir().join(format!("vc-mcp-save-options-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let dir = TempFolder::new("save-options");
let mut h = Headless::new();
h.call("engine.execute", json!({"command": "file.new", "params": {"width": 50, "height": 30}})).unwrap();
let pdf = dir.join("a.pdf").to_string_lossy().into_owned();
@@ -71,9 +70,8 @@ fn a_save_or_screens_option_no_format_takes_is_an_error() {
let e = h.call("engine.execute", json!({"command": "file.exportForScreens", "params": params})).unwrap_err();
assert!(e.contains(named), "file.exportForScreens: {e}");
}
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "nothing was written");
assert_eq!(std::fs::read_dir(&*dir).unwrap().count(), 0, "nothing was written");
h.call("app.save", json!({"path": pdf})).unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
@@ -97,8 +95,7 @@ fn raster_export_uses_document_resolution_unless_overridden() {
#[test]
fn export_with_a_range_writes_one_file_per_artboard() {
let mut h = three_boards();
let dir = std::env::temp_dir().join(format!("vectorcraft-mcp-exportas-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let dir = TempFolder::new("exportas");
let path = dir.join("icon.png").to_string_lossy().to_string();
let args = json!({"path": path, "range": "1, 3", "options": {"useArtboards": true, "ppi": 144, "background": "white"}});
let r = text(&call_tool(&mut h, "export", &args));
@@ -120,5 +117,4 @@ fn export_with_a_range_writes_one_file_per_artboard() {
let r = text(&call_tool(&mut h, "export", &json!({"format": format, "range": "1, 3"})));
assert_eq!(r["files"].as_array().map(Vec::len), Some(2), "{format}: {r}");
}
let _ = std::fs::remove_dir_all(dir);
}
+44 -37
View File
@@ -5,12 +5,12 @@ use std::io::{BufRead, BufReader, Write};
use serde_json::{Value, json};
use super::TempFolder;
use crate::{Backend, Headless, Remote, Server, call_tool, tool_definitions};
fn tmp(name: &str) -> String {
let dir = std::env::temp_dir().join(format!("vectorcraft-mcp-fileio-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
dir.join(name).to_string_lossy().to_string()
/// The path of `name` in `dir`, as a string.
fn tmp(dir: &TempFolder, name: &str) -> String {
dir.file(name).to_string_lossy().to_string()
}
fn text(r: &crate::ToolResult) -> Value {
@@ -29,22 +29,23 @@ fn two_boards() -> Headless {
#[test]
fn headless_opens_pdf_ai_and_templates() {
let dir = TempFolder::new("fileio-open");
let mut h = two_boards();
let pdf = h.call("engine.execute", json!({"command": "document.serialize", "params": {"format": "pdf"}})).unwrap();
let pdf = vectorcraft_format::base64_decode(pdf["dataBase64"].as_str().unwrap()).unwrap();
for name in ["x.pdf", "x.ai"] {
let path = tmp(name);
let path = tmp(&dir, name);
std::fs::write(&path, &pdf).unwrap();
let r = text(&call_tool(&mut h, "open_file", &json!({"path": path})));
assert_eq!(r["title"], name);
assert_eq!(h.session.doc().unwrap().doc.artboards.len(), 2, "one artboard per page");
}
let ait = tmp("x.ait");
let ait = tmp(&dir, "x.ait");
std::fs::write(&ait, &pdf).unwrap();
let r = text(&call_tool(&mut h, "open_file", &json!({"path": ait})));
assert!(r["title"].as_str().unwrap().starts_with("Untitled-"), "{r}");
let saved = h.call("engine.execute", json!({"command": "file.saveAsTemplate", "params": {"path": tmp("t.vectorcraft")}})).unwrap();
let tpl = tmp("t.vctemplate");
let saved = h.call("engine.execute", json!({"command": "file.saveAsTemplate", "params": {"path": tmp(&dir, "t.vectorcraft")}})).unwrap();
let tpl = tmp(&dir, "t.vctemplate");
assert_eq!(saved["path"], tpl.as_str(), "saved with the template's extension: {saved}");
let r = text(&call_tool(&mut h, "open_file", &json!({"path": tpl})));
assert!(r["title"].as_str().unwrap().starts_with("Untitled-"), "{r}");
@@ -147,10 +148,11 @@ fn the_raster_scale_leaves_other_formats_alone() {
#[test]
fn exporting_native_keeps_the_document_path() {
let dir = TempFolder::new("fileio-keep-path");
let mut h = two_boards();
let doc = tmp("keep.vectorcraft");
let doc = tmp(&dir, "keep.vectorcraft");
h.call("app.save", json!({"path": doc})).unwrap();
let copy = tmp("copy.vectorcraft");
let copy = tmp(&dir, "copy.vectorcraft");
let r = text(&call_tool(&mut h, "export", &json!({"path": copy})));
assert_eq!(r["format"], "vectorcraft");
assert_eq!(h.session.doc().unwrap().path.as_deref(), Some(doc.as_str()));
@@ -167,9 +169,9 @@ fn exporting_native_keeps_the_document_path() {
assert_eq!(h.session.doc().unwrap().path.as_deref(), Some(doc.as_str()));
}
/// The bytes `save_file` writes to `name` with `args`.
fn saved_with(h: &mut Headless, name: &str, mut args: Value) -> Vec<u8> {
let path = tmp(name);
/// The bytes `save_file` writes to `name` in `dir` with `args`.
fn saved_with(h: &mut Headless, dir: &TempFolder, name: &str, mut args: Value) -> Vec<u8> {
let path = tmp(dir, name);
args["path"] = json!(path);
let r = text(&call_tool(h, "save_file", &args));
assert_eq!(r["format"], "vectorcraft", "{r}");
@@ -178,22 +180,23 @@ fn saved_with(h: &mut Headless, name: &str, mut args: Value) -> Vec<u8> {
#[test]
fn save_file_takes_the_native_save_options() {
let dir = TempFolder::new("fileio-save-options");
let mut h = two_boards();
let gz = saved_with(&mut h, "gz.vectorcraft", json!({"compress": true}));
let gz = saved_with(&mut h, &dir, "gz.vectorcraft", json!({"compress": true}));
assert_eq!(gz[..2], [0x1f, 0x8b], "gzipped");
let plain = saved_with(&mut h, "plain.vectorcraft", json!({"compress": false}));
let plain = saved_with(&mut h, &dir, "plain.vectorcraft", json!({"compress": false}));
assert_eq!(plain[0], b'{', "plain JSON");
let nodes = h.session.doc().unwrap().doc.node_count();
for name in ["gz.vectorcraft", "plain.vectorcraft"] {
let mut back = Headless::new();
text(&call_tool(&mut back, "open_file", &json!({"path": tmp(name)})));
text(&call_tool(&mut back, "open_file", &json!({"path": tmp(&dir, name)})));
assert_eq!(back.session.doc().unwrap().doc.node_count(), nodes, "{name} reopens");
}
let opt = saved_with(&mut h, "opt.vectorcraft", json!({"options": {"compress": true}}));
let opt = saved_with(&mut h, &dir, "opt.vectorcraft", json!({"options": {"compress": true}}));
assert_eq!(opt[..2], [0x1f, 0x8b], "`options` carries them too");
let v3: Value = serde_json::from_slice(&saved_with(&mut h, "v3.vectorcraft", json!({"version": 3, "preview": null}))).unwrap();
let v3: Value = serde_json::from_slice(&saved_with(&mut h, &dir, "v3.vectorcraft", json!({"version": 3, "preview": null}))).unwrap();
assert_eq!(v3["version"], 3);
let shown = saved_with(&mut h, "preview.vectorcraft", json!({"preview": true}));
let shown = saved_with(&mut h, &dir, "preview.vectorcraft", json!({"preview": true}));
assert!(vectorcraft_format::preview(&shown).is_some(), "a preview");
assert!(vectorcraft_format::preview(&plain).is_none(), "off by default");
// `precision` rounds the path coordinates of that save only.
@@ -201,12 +204,12 @@ fn save_file_takes_the_native_save_options() {
p.call("engine.execute", json!({"command": "file.new", "params": {"width": 100, "height": 100}})).unwrap();
p.call("engine.execute", json!({"command": "path.create", "params": {"anchors": [{"x": 10.123456, "y": 20.654321}, {"x": 30.5, "y": 40.25}]}}))
.unwrap();
let exact = String::from_utf8(saved_with(&mut p, "exact.vectorcraft", json!({"compress": false}))).unwrap();
let exact = String::from_utf8(saved_with(&mut p, &dir, "exact.vectorcraft", json!({"compress": false}))).unwrap();
assert!(exact.contains("10.123456") && exact.contains("20.654321"), "{exact}");
let rounded = String::from_utf8(saved_with(&mut p, "rounded.vectorcraft", json!({"compress": false, "precision": 1}))).unwrap();
let rounded = String::from_utf8(saved_with(&mut p, &dir, "rounded.vectorcraft", json!({"compress": false, "precision": 1}))).unwrap();
assert!(!rounded.contains("10.123456") && !rounded.contains("20.654321") && rounded.contains("20.7"), "{rounded}");
// Version 2 files can't be compressed: the engine's error comes back.
let r = call_tool(&mut h, "save_file", &json!({"path": tmp("v2.vectorcraft"), "version": 2, "compress": true}));
let r = call_tool(&mut h, "save_file", &json!({"path": tmp(&dir, "v2.vectorcraft"), "version": 2, "compress": true}));
assert!(r.is_error && r.content[0]["text"].as_str().unwrap().contains("can't be compressed"), "{r:?}");
// The options are in the schema; a misspelled one is still refused.
@@ -214,9 +217,9 @@ fn save_file_takes_the_native_save_options() {
let call = |s: &mut Server, args: Value| {
s.handle(json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "save_file", "arguments": args}})).unwrap()
};
let r = call(&mut s, json!({"path": tmp("ok.vectorcraft"), "compress": true}));
let r = call(&mut s, json!({"path": tmp(&dir, "ok.vectorcraft"), "compress": true}));
assert_eq!(r["result"]["isError"], false, "{r}");
let r = call(&mut s, json!({"path": tmp("typo.vectorcraft"), "compresss": true}));
let r = call(&mut s, json!({"path": tmp(&dir, "typo.vectorcraft"), "compresss": true}));
assert_eq!(r["error"]["code"], -32602, "{r}");
assert!(r["error"]["message"].as_str().unwrap().contains("unknown argument `compresss`"), "{r}");
}
@@ -225,12 +228,13 @@ fn save_file_takes_the_native_save_options() {
/// that disagrees with the same key in `options` is an error.
#[test]
fn save_file_warns_about_options_it_does_not_use() {
let dir = TempFolder::new("fileio-unused-options");
let mut h = two_boards();
let warnings = |r: &Value| -> Vec<String> { r["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap().to_string()).collect() };
let ignored = |w: &[String], key: &str| w.iter().any(|w| w.starts_with(&format!("`{key}` was not used")));
// SVG reads none of them, at the top level or in `options`.
let path = tmp("ignored.svg");
let path = tmp(&dir, "ignored.svg");
let r = text(&call_tool(&mut h, "save_file", &json!({"path": path, "compress": true, "version": 3, "options": {"preview": true}})));
assert_eq!(r["format"], "svg", "{r}");
let w = warnings(&r);
@@ -239,16 +243,15 @@ fn save_file_warns_about_options_it_does_not_use() {
assert!(w.iter().any(|w| w.contains("SVG")), "names the format: {w:?}");
assert!(std::fs::read(&path).unwrap().starts_with(b"<"), "plain SVG");
// A .ai file reads `compress` but not `version`.
let r = text(&call_tool(&mut h, "save_file", &json!({"path": tmp("ignored.ai"), "compress": false, "version": 3})));
let r = text(&call_tool(&mut h, "save_file", &json!({"path": tmp(&dir, "ignored.ai"), "compress": false, "version": 3})));
let w = warnings(&r);
assert!(ignored(&w, "version") && !ignored(&w, "compress"), "{w:?}");
// `precision` is read by native files only.
let r = text(&call_tool(&mut h, "save_file", &json!({"path": tmp("ignored-precision.svg"), "precision": 2})));
let r = text(&call_tool(&mut h, "save_file", &json!({"path": tmp(&dir, "ignored-precision.svg"), "precision": 2})));
assert!(ignored(&warnings(&r), "precision"), "{r}");
// A top-level value that disagrees with `options` is refused, and nothing is written.
let path = tmp("both.vectorcraft");
let _ = std::fs::remove_file(&path);
let path = tmp(&dir, "both.vectorcraft");
let r = call_tool(&mut h, "save_file", &json!({"path": path, "compress": true, "options": {"compress": false}}));
let e = r.content[0]["text"].as_str().unwrap();
assert!(r.is_error && e.contains("`compress: true` and `options.compress: false` disagree"), "{r:?}");
@@ -257,7 +260,7 @@ fn save_file_warns_about_options_it_does_not_use() {
for mut args in
[json!({"compress": true, "options": {"compress": true}}), json!({"compress": false, "version": 3, "preview": true, "precision": 4})]
{
args["path"] = json!(tmp("quiet.vectorcraft"));
args["path"] = json!(tmp(&dir, "quiet.vectorcraft"));
let r = text(&call_tool(&mut h, "save_file", &args));
assert_eq!(r["warnings"], json!([]), "{args}: {r}");
}
@@ -286,6 +289,7 @@ fn save_file_warns_about_options_it_does_not_use() {
/// when the save reuses the options the document was last saved with.
#[test]
fn save_file_notes_name_the_ai_file_it_writes() {
let dir = TempFolder::new("fileio-ai-notes");
let mut h = Headless::with_document();
let notes = |r: &Value| -> Vec<String> {
r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).filter(|w| w.contains("was not used")).map(str::to_string).collect()
@@ -296,21 +300,22 @@ fn save_file_notes_name_the_ai_file_it_writes() {
("no-pdf.ai", json!({"pdfCompatible": false, "preview": true}), "non-PDF-compatible .ai"),
("pdf.ai", json!({"pdfCompatible": true, "preview": true}), "PDF-compatible .ai"),
] {
let r = text(&call_tool(&mut h, "save_file", &json!({"path": tmp(name), "version": 3, "options": options})));
let r = text(&call_tool(&mut h, "save_file", &json!({"path": tmp(&dir, name), "version": 3, "options": options})));
let expected =
[format!("`version` was not used: {label} files don't read it"), format!("`options.preview` was not used: {label} files don't read it")];
assert_eq!(notes(&r), expected, "{name}: {r}");
}
// A save given no option the file reads writes it as last saved: a legacy `.ai` again.
text(&call_tool(&mut h, "save_file", &json!({"path": tmp("again.ai"), "options": {"aiVersion": "7"}})));
let r = text(&call_tool(&mut h, "save_file", &json!({"path": tmp("again.ai"), "options": {"preview": true}})));
text(&call_tool(&mut h, "save_file", &json!({"path": tmp(&dir, "again.ai"), "options": {"aiVersion": "7"}})));
let r = text(&call_tool(&mut h, "save_file", &json!({"path": tmp(&dir, "again.ai"), "options": {"preview": true}})));
assert_eq!(notes(&r), ["`options.preview` was not used: legacy .ai (version 7) files don't read it"], "{r}");
assert!(std::fs::read(tmp("again.ai")).unwrap().starts_with(b"%!PS"), "a legacy .ai is written");
assert!(std::fs::read(tmp(&dir, "again.ai")).unwrap().starts_with(b"%!PS"), "a legacy .ai is written");
}
#[test]
fn save_file_is_the_same_call_in_the_app_and_headless() {
let path = tmp("app.vectorcraft");
let dir = TempFolder::new("fileio-app-save");
let path = tmp(&dir, "app.vectorcraft");
let (addr, app) = recording_app();
let mut remote = Remote::connect(&addr).unwrap();
let args = json!({"path": path, "compress": true, "version": 3, "preview": null, "precision": 2, "options": {"preview": true}});
@@ -392,7 +397,8 @@ fn pdf_pages(pdf: &[u8]) -> usize {
/// only, in the document and in the exported PDF.
#[test]
fn document_color_mode_puts_rgb_greys_on_the_black_plate() {
let svg = tmp("greys.svg");
let dir = TempFolder::new("fileio-greys");
let svg = tmp(&dir, "greys.svg");
std::fs::write(
&svg,
r##"<svg xmlns="http://www.w3.org/2000/svg" width="200pt" height="50pt" viewBox="0 0 200 50">
@@ -447,7 +453,8 @@ fn open_file_passes_the_importer_on() {
let tools = tool_definitions();
let open = tools.iter().find(|t| t["name"] == "open_file").unwrap();
assert!(open["inputSchema"]["properties"].get("importer").is_some(), "{open}");
let svg = tmp("importer.svg");
let dir = TempFolder::new("fileio-importer");
let svg = tmp(&dir, "importer.svg");
std::fs::write(&svg, r#"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="10"><rect width="5" height="5"/></svg>"#).unwrap();
let mut h = Headless::new();
assert_eq!(text(&call_tool(&mut h, "open_file", &json!({"path": svg})))["format"], "svg");
+3 -4
View File
@@ -3,6 +3,7 @@
use serde_json::{Value, json};
use super::TempFolder;
use crate::{Headless, call_tool};
fn run(h: &mut Headless, command: &str, params: Value) -> Value {
@@ -13,9 +14,8 @@ fn run(h: &mut Headless, command: &str, params: Value) -> Value {
#[test]
fn headless_links_report_missing_files_and_relink() {
let dir = std::env::temp_dir().join(format!("vectorcraft-mcp-links-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = |n: &str| dir.join(n).to_string_lossy().into_owned();
let dir = TempFolder::new("links");
let file = |n: &str| dir.file(n).to_string_lossy().into_owned();
let mut h = Headless::new();
run(&mut h, "file.new", json!({"width": 300, "height": 200}));
let png = run(&mut h, "document.serialize", json!({"format": "png"}));
@@ -30,5 +30,4 @@ fn headless_links_report_missing_files_and_relink() {
let r = run(&mut h, "links.relink", json!({"ids": [id], "path": file("b.png")}));
assert_eq!(r["relinked"], json!([id]));
assert_eq!(run(&mut h, "links.check", json!({}))["links"][0]["status"], "ok");
let _ = std::fs::remove_dir_all(dir);
}
+24 -2
View File
@@ -195,7 +195,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
("view.pixelPreview", "Pixel Preview", "Cmd+Alt+Y", "{}"),
("view.trimView", "Trim View", "", "{} toggle: hide everything outside the artboards"),
("view.cornerWidget", "Hide Corner Widget", "", "{} toggle the live corner widgets"),
("view.snapToPixel", "Snap to Pixel", "", "{} toggle: drawing and moving land on whole pixels"),
(
"view.snapToPixel",
"Snap to Pixel",
"",
"{} toggle: drawing, moving and scaling land on whole pixels, each while its option in view.snapToPixel.options is on",
),
(
"view.snapToGlyph",
"Snap to Glyph",
@@ -563,7 +568,24 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"",
"{name: string} delete the toolbar made with New Toolbar called `name`, and the groups torn off it, from the current workspace, as Manage Toolbars' trash can does",
),
("window.toolbar.list", "List Toolbars", "", "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots}]"),
(
"window.toolbar.dock",
"Dock Toolbar",
"",
"{name: string, side?: left|right, order?: int} dock the toolbar made with New Toolbar called `name` in the lane along the window's left or right edge (omitted: the edge it docked at last, the left at first), as Dock to Left and Dock to Right in its title bar's context menu and dropping its title bar on that edge do; `order` is its place in that edge's stack, 0 at the top (omitted: the end, or where it is when it is docked at that edge already); a bad `side` or `order` is an error and changes nothing; returns {toolbar, floating, side, order, pos}",
),
(
"window.toolbar.float",
"Float Toolbar",
"",
"{name: string, x?: number, y?: number} float the toolbar made with New Toolbar called `name` with its top-left corner at x, y in screen points (both or neither; omitted: where it floated last), as Float Toolbar in its title bar's context menu and dragging its title bar out of its lane do; returns {toolbar, floating, side, order, pos}",
),
(
"window.toolbar.list",
"List Toolbars",
"",
"{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, floating, side, order}], `side` the edge it docks at (while floating, the edge it docked at last) and `order` its place in that edge's stack while docked (else null)",
),
("window.taskBar", "Contextual Task Bar", "", "{}"),
(
"window.pathfinder.compoundShapes",
+28 -3
View File
@@ -348,14 +348,39 @@ fn refit_part(part: &[(&Seg, usize)], opts: &SimplifyOptions, tol: f64, mut ends
}
// The fit may be `tol * 0.98` from the lines between the samples, those lines may be
// `SAMPLE_GAP` of `tol` from the path, and the curve the test below turns into a line moves by up
// to 1.5% of `tol`: 3/4 of how far its handles may be from the line.
// to 1.5% of `tol`: 3/4 of how far its handles may be from the line. The fitted curves join
// smoothly, so a curve becomes a line only when the line keeps both of its joins smooth. The last
// curve of a loop fitted across its start leaves along the loop's first segment.
let (t0, t1) = ends.map_or((start_tangent(&first.c), end_tangent(&last.c)), |d| (d, d));
for c in fit_cubics(&pts, t0, t1, tol * 0.98) {
let line = is_straight(&c, tol * 0.02);
let fitted = fit_cubics(&pts, t0, t1, tol * 0.98);
let from = result.len();
let mut arrive = t0;
for (k, &c) in fitted.iter().enumerate() {
let leave = match fitted.get(k + 1) {
Some(next) => start_tangent(next),
None if ends.is_some() => result.get(from).map_or(t1, |s| start_tangent(&s.c)),
None => t1,
};
let line = is_straight(&c, tol * 0.02) && line_keeps_joins(&c, arrive, leave);
arrive = if line { unit(c.p3 - c.p0).unwrap_or(arrive) } else { end_tangent(&c) };
result.push(if line { Seg::line(c.p0, c.p3) } else { Seg { c, line } });
}
}
/// Most degrees between the line from a refitted curve's start to its end and the directions the
/// path arrives and leaves along, for the curve to become that line: so every join next to such a
/// line turns by at most this much. VectorCraft's own value.
const LINE_JOIN_DEG: f64 = 0.5;
/// Whether the line from `c.p0` to `c.p3` is within [`LINE_JOIN_DEG`] of `arrive`, the direction the
/// path arrives at `c.p0` along, and of `leave`, the direction it leaves `c.p3` along. A curve whose
/// ends are at one point, or a direction of no length, gives `false`.
fn line_keeps_joins(c: &CubicBez, arrive: Vec2, leave: Vec2) -> bool {
let (Some(dir), Some(arrive), Some(leave)) = (unit(c.p3 - c.p0), unit(arrive), unit(leave)) else { return false };
let min = LINE_JOIN_DEG.to_radians().cos();
dir.dot(arrive) >= min && dir.dot(leave) >= min
}
/// `pts` (a run's samples, in order) smoothed along the path: each point becomes the Gaussian-weighted
/// mean of the points around it, `sigma` points of arc length wide, the window narrowing towards the
/// ends so that the first and last points stay where they are. Consecutive samples within
+71
View File
@@ -417,6 +417,77 @@ fn simplify_keeps_square_corners() {
assert!(!has_curves(&s));
}
/// The largest turn, in degrees, at an anchor of `sp` that is not an end of an open subpath: the
/// angle between the direction a segment arrives along and the one the next leaves along.
fn largest_join_turn(sp: &SubPath) -> f64 {
let dir = |v: kurbo::Vec2, w: kurbo::Vec2, chord: kurbo::Vec2| [v, w, chord].into_iter().find(|d| d.hypot() > 1e-9).unwrap_or(chord);
let n = sp.segment_count();
let first = usize::from(!sp.closed);
(first..n)
.map(|i| {
let (prev, next) = (sp.segment((i + n - 1) % n), sp.segment(i));
let arrive = dir(prev.p3 - prev.p2, prev.p3 - prev.p1, prev.p3 - prev.p0);
let leave = dir(next.p1 - next.p0, next.p2 - next.p0, next.p3 - next.p0);
arrive.cross(leave).atan2(arrive.dot(leave)).abs().to_degrees()
})
.fold(0.0, f64::max)
}
/// A refitted curve becomes a line only when the line keeps the smooth joins on both sides of it:
/// with no corners kept, the refit of a jagged line or of an arc running into a line turns by at most
/// 0.5° at every anchor. Points that all lie on one line still become one line.
#[test]
fn simplify_turns_a_curve_into_a_line_only_where_the_joins_stay_smooth() {
let mut seed = 7u64;
let mut noise = || {
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
((seed >> 11) as f64 / (1u64 << 53) as f64) * 2.0 - 1.0
};
let jagged: Vec<Point> = (0..=60).map(|i| Point::new(100.0 + f64::from(i) * 5.0, 200.0 + 6.0 * noise())).collect();
let mut arc_into_line: Vec<Point> =
(0..=40).map(|i| Point::new(50.0 * (f64::from(i) / 80.0 * PI).cos(), 50.0 * (f64::from(i) / 80.0 * PI).sin())).collect();
arc_into_line.extend((1..=20).map(|i| Point::new(-f64::from(i) * 2.0, 50.0)));
for pts in [&jagged, &arc_into_line] {
let path = PathData::single(SubPath::polyline(pts, false));
for tolerance in [1.0, 2.5, 5.0] {
let s = simplify_with(&path, &SimplifyOptions { tolerance, corner_angle_deg: 179.0, ..Default::default() });
let turn = largest_join_turn(&s.subpaths[0]);
assert!(turn <= 0.5 + 1e-9, "{tolerance} pt: an anchor turns {turn}°: {s:?}");
assert!(max_deviation(&path, &s) <= tolerance + 1e-6, "{tolerance} pt: {}", max_deviation(&path, &s));
}
}
let in_line: Vec<Point> = [0.0, 3.0, 10.0, 11.0, 40.0, 41.5, 90.0, 100.0].map(|x| Point::new(x, 0.5 * x)).to_vec();
let s = simplify_with(&PathData::single(SubPath::polyline(&in_line, false)), &SimplifyOptions { tolerance: 1.0, ..Default::default() });
assert_eq!(s.anchor_count(), 2, "{s:?}");
assert!(!has_curves(&s), "{s:?}");
}
/// A smoothed loop with no corner is fitted across its start, and the join there also turns by at
/// most 0.5°. Each loop is a flat side that bends by 0.6° at the loop's start, closed by an arc of
/// `n` lines `height` tall, with `inner` anchors along each half of the side.
#[test]
fn simplify_keeps_the_join_at_the_start_of_a_smoothed_loop_smooth() {
for (half, height, n, inner, tolerance, smooth) in
[(40.0, 20.0, 8, 3, 2.5, 2.0), (80.0, 60.0, 8, 3, 5.0, 0.5), (160.0, 200.0, 24, 3, 10.0, 2.0), (160.0, 20.0, 24, 8, 10.0, 5.0)]
{
let rise = half * 0.3f64.to_radians().tan();
let along = |i: i32| Point::new(half * f64::from(i) / f64::from(inner), -rise * f64::from(i.abs()) / f64::from(inner));
let mut pts: Vec<Point> = (0..=inner).map(along).collect();
pts.extend((1..n).map(|i| {
let a = f64::from(i) / f64::from(n) * PI;
Point::new(half * a.cos(), -rise - height * a.sin())
}));
pts.extend((-inner..0).map(along));
let path = PathData::single(SubPath::polyline(&pts, true));
let s = simplify_with(&path, &SimplifyOptions { tolerance, corner_angle_deg: 179.0, smooth, ..Default::default() });
let sp = &s.subpaths[0];
assert!(sp.closed && sp.anchors.len() < pts.len(), "{tolerance} pt: {s:?}");
assert!(sp.segment_is_line(0), "{tolerance} pt: the first segment is a curve: {s:?}");
let turn = largest_join_turn(sp);
assert!(turn <= 0.5 + 1e-9, "{tolerance} pt: an anchor turns {turn}°: {s:?}");
}
}
#[test]
fn simplify_straight_lines_option() {
let c = dense_circle(50.0, 200);
+2 -2
View File
@@ -9,8 +9,8 @@
mod solid;
mod visibility;
pub use solid::{
Bevel, BevelShape, Extrude, FaceMap, Facet, Inflate, PlanarFace, TOO_COMPLEX_SOLID, View, extrude, extrude_face_map, inflate, inflate_each,
inflate_together, plane, plane_face_map,
Bevel, BevelShape, DepthPlane, Extrude, FaceMap, Facet, Inflate, PlanarFace, TOO_COMPLEX_SOLID, View, extrude, extrude_face_map, inflate,
inflate_each, inflate_together, plane, plane_face_map,
};
pub use visibility::{VisibleFace, visible_faces};
mod shading;
+42
View File
@@ -292,12 +292,53 @@ pub struct Facet {
/// The planar end of the solid the facet is: Extrude & Bevel's front or back cap, or a plane
/// (its front). `None` for every other facet.
pub end: Option<PlanarFace>,
/// The face's plane in view space and the projection it was drawn with, for its depth at a
/// point of the drawing ([`Facet::depth_at`]). `None` for Revolve's faces and for a face whose
/// corners lie more than 0.001 pt off one plane (a piece of a twisted wall).
pub plane: Option<DepthPlane>,
/// The contours in view space, before projection, for tests that measure depths.
#[cfg(test)]
view: Vec<Vec<V3>>,
}
/// A facet's plane in view space (x right, y down, z toward the viewer): the points `v` with
/// `normal · v = offset`, drawn by a projection about `center` with the eye `eye` in front of the
/// object's center plane (`None` without perspective).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DepthPlane {
pub normal: [f64; 3],
pub offset: f64,
pub center: Point,
pub eye: Option<f64>,
}
impl DepthPlane {
/// The view-space depth (larger is nearer the viewer) of the point of the plane that projects
/// to `p`, a point of the drawing. `None` when the plane is seen edge-on there or the point is
/// not in front of the eye.
pub fn depth_at(&self, p: Point) -> Option<f64> {
let [nx, ny, nz] = self.normal;
let (x, y) = (p.x - self.center.x, p.y - self.center.y);
let z = match self.eye {
None => (nz.abs() > 1e-9).then(|| (self.offset - nx * x - ny * y) / nz)?,
Some(e) => {
// On the ray through `p`, the point at depth z is at (x, y) × (e - z) / e.
let a = (nx * x + ny * y) / e;
let den = nz - a;
let z = (den.abs() > 1e-9).then(|| (self.offset - a * e) / den)?;
(z < e).then_some(z)?
}
};
z.is_finite().then_some(z)
}
}
impl Facet {
/// The view-space depth of the facet at `p`, a point of the drawing ([`DepthPlane::depth_at`]).
pub fn depth_at(&self, p: Point) -> Option<f64> {
self.plane.as_ref()?.depth_at(p)
}
/// About how thick the facet is across: twice its area over its perimeter (a w × l rectangle
/// long against its width gives about w).
pub fn thickness(&self) -> f64 {
@@ -339,6 +380,7 @@ impl Facet {
// A revolved cap is not one of the planar faces graphics map onto.
end: None,
away: false,
plane: None,
#[cfg(test)]
view: vec![],
}
+11 -2
View File
@@ -6,8 +6,8 @@ use super::rings::{
solid_rings_traced,
};
use super::{
Bevel, Extrude, Facet, FillRule, MAX_FACES, MAX_SOLID_FACES, ParamCurve, PathData, PlanarFace, Point, Rect, Revolve, V3, View, eye_distance,
perspective_scale,
Bevel, DepthPlane, Extrude, Facet, FillRule, MAX_FACES, MAX_SOLID_FACES, ParamCurve, PathData, PlanarFace, Point, Rect, Revolve, V3, View,
eye_distance, perspective_scale,
};
use crate::shadow::Projection;
@@ -129,6 +129,14 @@ impl Builder<'_> {
} else {
(V3(-n.0, -n.1, -n.2), false)
};
// A face whose corners lie off one plane (a piece of a twisted wall bent into a saddle) has
// no plane to measure its depth on. Nor has a face with a corner at or past the eye: the
// projection holds that corner just in front of the eye, so the drawing no longer matches
// the plane's projection there.
let offset = n.dot(centre);
let held = self.camera.eye.is_some_and(|e| contours.iter().flatten().any(|v| e - v.2 < e * 1e-3));
let flat = !held && contours.iter().flatten().all(|v| (n.dot(*v) - offset).abs() <= 1e-3);
let plane = flat.then_some(DepthPlane { normal: [n.0, n.1, n.2], offset, center: self.camera.origin, eye: self.camera.eye });
#[cfg(test)]
let view = contours.clone();
let contours: Vec<Vec<Point>> = contours.iter().map(|c| c.iter().map(|v| self.camera.project(*v)).collect()).collect();
@@ -156,6 +164,7 @@ impl Builder<'_> {
side: false,
away: behind,
end: None,
plane,
#[cfg(test)]
view,
});
+40
View File
@@ -154,6 +154,46 @@ fn taper_shrinks_the_back_and_twist_turns_it() {
assert!(open.len() > 2 * 8, "{}", open.len());
}
/// A flat facet carries its plane: the depth it gives at each corner of its drawing is the corner's
/// view-space depth, with and without perspective. A piece of a twisted wall whose corners lie off
/// one plane has none.
#[test]
fn a_flat_facet_measures_its_depth_on_its_plane() {
let (p, b) = shape(&square(0.0, 0.0, 100.0));
let o = Extrude { depth: 60.0, cap: true, ..Extrude::default() };
for perspective in [0.0, 50.0] {
let view = View { rotation_x: -20.0, rotation_y: 30.0, perspective, ..front() };
let flat = extrude(&p, FillRule::EvenOdd, b, o, view).unwrap();
assert!(!flat.is_empty());
for f in &flat {
assert!(f.plane.is_some(), "{perspective}");
for (q, v) in f.contours.iter().flatten().zip(f.view.iter().flatten()) {
let d = f.depth_at(*q);
assert!(d.is_some_and(|d| close(d, v.2, 1e-6)), "{perspective}: {d:?} against {}", v.2);
}
}
let twisted = extrude(&p, FillRule::EvenOdd, b, Extrude { twist: 90.0, ..o }, view).unwrap();
assert!(twisted.iter().any(|f| f.side && f.plane.is_none()), "{perspective}");
}
}
/// A flat face with a corner at or past the eye, which the projection holds just in front of the
/// eye, has no plane: its drawing no longer matches the plane's projection there.
#[test]
fn a_face_reaching_past_the_eye_has_no_plane() {
use super::build::{Builder, Order};
let (_, b) = shape(&square(0.0, 0.0, 100.0));
let camera = Camera::new(View { perspective: 50.0, ..front() }, b, 0.0);
let eye = camera.center_and_eye().1.unwrap();
for (far, has_plane) in [(eye / 2.0, true), (2.0 * eye, false)] {
let mut builder = Builder { camera: &camera, closed: false, hidden: false, facets: vec![], mesh: None };
let corners = vec![V3(-10.0, -10.0, 0.0), V3(10.0, -10.0, 0.0), V3(0.0, 10.0, far)];
builder.face(vec![corners], V3(0.0, -far, 20.0), Order::Depth).unwrap();
assert_eq!(builder.facets.len(), 1, "{far}");
assert_eq!(builder.facets[0].plane.is_some(), has_plane, "{far}");
}
}
#[test]
fn a_bevel_inside_shrinks_the_cap_and_outside_grows_the_walls() {
let (p, b) = shape(&square(0.0, 0.0, 100.0));
+112 -20
View File
@@ -49,6 +49,42 @@ fn lp_part_at<'a>(doc: &'a Document, p: Point, tol: f64, edge: bool, takes: &dyn
best.map(|(_, g, e)| (g, Some(e)))
}
/// The face and edge of a Live Paint group at `p`, among the groups `takes` takes, by the rules of
/// [`lp_part_at`], in one walk of the document. Inside a visible face of a group, the face is the
/// front-most such group's visible face under `p`, and with `edge` the edge is that group's visible
/// edge nearest `p` within `tol`. Outside every visible face there is no face, and with `edge` the
/// edge is the visible edge nearest `p` within `tol` among the groups (the front-most group's on a
/// tie).
fn lp_face_and_edge<'a>(
doc: &'a Document,
p: Point,
tol: f64,
edge: bool,
takes: &dyn Fn(NodeId) -> bool,
) -> (Option<&'a Arc<Node>>, Option<&'a Arc<Node>>) {
let mut in_face: Option<(&Arc<Node>, Option<&Arc<Node>>)> = None;
let mut best: Option<(f64, &Arc<Node>)> = None;
doc.walk(|n| {
if !is_live_paint(n) || !takes(n.id) {
return;
}
let near = if edge { visible_edge_near(n, p, tol) } else { None };
if let Some(f) = visible_face_at(n, p) {
in_face = Some((f, near));
}
if let Some(e) = near
&& let Some((.., d)) = e.path_data().and_then(|pd| pd.nearest(p))
&& best.is_none_or(|b| d <= b.0)
{
best = Some((d, e));
}
});
match in_face {
Some((f, e)) => (Some(f), e),
None => (None, best.map(|b| b.1)),
}
}
/// Whether the Live Paint Bucket takes Live Paint group `id`: it is visible, with every layer and
/// group around it.
fn lp_visible(cx: &ToolContext, id: NodeId) -> bool {
@@ -62,17 +98,25 @@ fn lp_selectable(cx: &ToolContext, id: NodeId) -> bool {
cx.doc.is_editable(id) && crate::direct::in_scope(cx.doc, cx.isolation, id)
}
/// Whether every selected object is a Live Paint group (true with nothing selected). A selection
/// that also holds other paths has regions outside its groups' faces that a click fills, making
/// one Live Paint group of the selection.
fn lp_sel_all_live(cx: &ToolContext) -> bool {
cx.selection.objects.iter().all(|id| cx.doc.node(*id).is_some_and(is_live_paint))
}
/// What the Live Paint tools highlight at `p`: the part of a Live Paint group ([`lp_part_at`], among
/// the groups `takes` takes), else with `cache` the region of the selection under `p`. A large
/// selection's regions are found on another thread ([`RegionCache::ready`]), and until they are, no
/// region is highlighted.
/// the groups `takes` takes), else with `cache` the region of the selection under `p` when the
/// selection is not only Live Paint groups ([`lp_sel_all_live`]). A large selection's regions are
/// found on another thread ([`RegionCache::ready`]), and until they are, no region is highlighted.
fn lp_hover(cx: &ToolContext, cache: Option<&mut RegionCache>, p: Point, edge: bool, takes: &dyn Fn(NodeId) -> bool) -> LpHover {
if let Some((_, part)) = lp_part_at(cx.doc, p, cx.tol(4.0), edge, takes) {
let path = part.and_then(|n| n.path_data()).map(|pd| pd.to_bezpath());
return path.map(|bp| if edge { LpHover::Edge(bp) } else { LpHover::Part(bp) }).unwrap_or_default();
}
let sel_is_live = cx.selection.objects.iter().any(|id| cx.doc.node(*id).is_some_and(is_live_paint));
if !sel_is_live && let Some(i) = cache.and_then(|c| c.ready(cx, true)).and_then(|m| m.region_at(p)) {
if !lp_sel_all_live(cx)
&& let Some(i) = cache.and_then(|c| c.ready(cx, true)).and_then(|m| m.region_at(p))
{
return LpHover::Region(i);
}
LpHover::None
@@ -125,7 +169,8 @@ enum LpPaint {
/// Shift-click fills the face. With both on, a click paints the edge nearest the pointer when one
/// is within 4 pixels, else it fills the face, and Shift-click fills the face. With both off, a
/// click paints nothing. With Highlight off, the face or edge under the pointer is not
/// highlighted.
/// highlighted. The cursor is a filled bucket where a click fills a face, a brush where it paints
/// an edge and an empty bucket where it paints nothing; with Alt it is the Eyedropper.
pub struct LivePaintBucketTool {
pub(super) cache: RegionCache,
pub(super) hover: LpHover,
@@ -202,21 +247,68 @@ impl LivePaintBucketTool {
}
/// The highlight at `p` for a pointer with Shift and Alt held as given: none with Alt or with
/// Highlight off, else the face or edge a click there paints.
/// Highlight off, else the face or edge a click there paints. With Highlight off the selection's
/// map is still made, for the cursor ([`Self::paints_at`]).
fn hover_at(&mut self, cx: &ToolContext, p: Point, shift: bool, alt: bool) -> LpHover {
if alt || !self.highlight {
if alt {
return LpHover::None;
}
let takes = |id| lp_visible(cx, id);
match self.paints(shift) {
LpPaint::Nothing => LpHover::None,
LpPaint::Fills => lp_hover(cx, Some(&mut self.cache), p, false, &takes),
// A click paints no region of the selection, so none is highlighted.
LpPaint::Strokes => lp_hover(cx, None, p, true, &takes),
LpPaint::Both => match lp_part_at(cx.doc, p, cx.tol(4.0), true, &takes) {
Some((_, Some(e))) => e.path_data().map(|pd| LpHover::Edge(pd.to_bezpath())).unwrap_or_default(),
_ => lp_hover(cx, Some(&mut self.cache), p, false, &takes),
},
let target = self.target_at(cx, p, shift);
if self.highlight { target } else { LpHover::None }
}
/// What a click at `p` reaches, Shift held or not: whether it fills a face and paints an edge,
/// with the face and the edge of a Live Paint group there ([`lp_face_and_edge`]). The document
/// is walked once: the highlight and the cursor are asked for on every pointer update.
fn parts_at<'a>(&self, cx: &ToolContext<'a>, p: Point, shift: bool) -> (bool, Option<&'a Arc<Node>>, Option<&'a Arc<Node>>) {
let (wants_face, wants_edge) = match self.paints(shift) {
LpPaint::Nothing => return (false, None, None),
LpPaint::Fills => (true, false),
LpPaint::Strokes => (false, true),
LpPaint::Both => (true, true),
};
let (face, edge) = lp_face_and_edge(cx.doc, p, cx.tol(4.0), wants_edge, &|id| lp_visible(cx, id));
(wants_face, face, edge)
}
/// The face or edge a click at `p` paints, Shift held or not. With Paint Strokes alone, a click
/// paints no region of the selection, so none is highlighted.
fn target_at(&mut self, cx: &ToolContext, p: Point, shift: bool) -> LpHover {
let (wants_face, face, edge) = self.parts_at(cx, p, shift);
let path = |n: &Arc<Node>| n.path_data().map(|pd| pd.to_bezpath());
if let Some(e) = edge {
return path(e).map(LpHover::Edge).unwrap_or_default();
}
if !wants_face {
return LpHover::None;
}
if let Some(f) = face {
return path(f).map(LpHover::Part).unwrap_or_default();
}
if !lp_sel_all_live(cx)
&& let Some(i) = self.cache.ready(cx, true).and_then(|m| m.region_at(p))
{
return LpHover::Region(i);
}
LpHover::None
}
/// The cursor for a click at `p`, Shift held or not: [`Cursor::LivePaintBucketEdge`] where it
/// paints an edge of a Live Paint group, [`Cursor::LivePaintBucketFace`] where it fills a face
/// of one or a region of the selected paths, else [`Cursor::LivePaintBucket`]. A region counts
/// once the selection's map is made (the pointer moving over it makes it), as it is highlighted.
fn paints_at(&self, cx: &ToolContext, p: Point, shift: bool) -> Cursor {
let (wants_face, face, edge) = self.parts_at(cx, p, shift);
let edge = edge.is_some();
let region =
|| !lp_sel_all_live(cx) && self.cache.key.as_ref() == Some(&RegionCache::key_for(cx, true)) && self.cache.map.region_at(p).is_some();
let face = wants_face && !edge && (face.is_some() || region());
if edge {
Cursor::LivePaintBucketEdge
} else if face {
Cursor::LivePaintBucketFace
} else {
Cursor::LivePaintBucket
}
}
}
@@ -315,8 +407,8 @@ impl Tool for LivePaintBucketTool {
lp_overlays(&self.hover, &self.cache, self.color, self.width as f32, (self.width * LP_BUCKET_EDGE_FRACTION) as f32)
}
fn cursor(&self, _cx: &ToolContext, _p: Point, m: Mods) -> Cursor {
if m.alt { Cursor::Eyedropper } else { Cursor::LivePaintBucket }
fn cursor(&self, cx: &ToolContext, p: Point, m: Mods) -> Cursor {
if m.alt { Cursor::Eyedropper } else { self.paints_at(cx, p, m.shift) }
}
fn options(&self) -> Value {
+99 -2
View File
@@ -1140,6 +1140,103 @@ fn bucket_options_choose_what_a_click_paints() {
assert_eq!(t.options()["paintFills"], false);
}
/// The cursor says what a click paints: a filled bucket over a face it fills, a brush over an
/// edge it paints, an empty bucket where it paints nothing, under each Paint Fills / Paint Strokes
/// setting and Shift; Alt keeps the Eyedropper, and Use Precise Cursors turns each into the
/// crosshair.
#[test]
fn bucket_cursor_shows_what_a_click_paints() {
let (d, ..) = live_group_doc();
let s = Selection::default();
let p = paint();
let cx = cx(&d, &s, &p);
let shift = Mods { shift: true, ..Default::default() };
let alt = Mods { alt: true, ..Default::default() };
let at = |t: &LivePaintBucketTool, x: f64, m: Mods| t.cursor(&cx, Point::new(x, 25.0), m);
let (face, edge, none) = (Cursor::LivePaintBucketFace, Cursor::LivePaintBucketEdge, Cursor::LivePaintBucket);
let mut t = LivePaintBucketTool::default();
// Paint Fills alone: the face, and with Shift the edge in reach.
assert_eq!([at(&t, 51.0, Mods::default()), at(&t, 75.0, Mods::default()), at(&t, 400.0, Mods::default())], [face, face, none]);
assert_eq!([at(&t, 51.0, shift), at(&t, 75.0, shift)], [edge, none]);
assert_eq!([at(&t, 51.0, alt), at(&t, 400.0, alt)], [Cursor::Eyedropper, Cursor::Eyedropper]);
// Paint Strokes alone: the edge in reach, nothing farther away; Shift fills the face.
t.set_option("paintFills", &json!(false));
t.set_option("paintStrokes", &json!(true));
assert_eq!([at(&t, 51.0, Mods::default()), at(&t, 75.0, Mods::default())], [edge, none]);
assert_eq!([at(&t, 51.0, shift), at(&t, 75.0, shift)], [face, face]);
// Both: the edge in reach, else the face; Shift fills the face.
t.set_option("paintFills", &json!(true));
assert_eq!([at(&t, 51.0, Mods::default()), at(&t, 75.0, Mods::default()), at(&t, 400.0, Mods::default())], [edge, face, none]);
assert_eq!(at(&t, 51.0, shift), face);
// Both off: a click paints nothing.
t.set_option("paintFills", &json!(false));
t.set_option("paintStrokes", &json!(false));
assert_eq!([at(&t, 51.0, Mods::default()), at(&t, 75.0, shift)], [none, none]);
// Highlight off: the cursor still says what a click paints.
let mut t = LivePaintBucketTool::default();
t.set_option("highlight", &json!(false));
assert_eq!([at(&t, 75.0, Mods::default()), at(&t, 51.0, shift)], [face, edge]);
for c in [face, edge, none] {
assert_eq!(c.precise(), Cursor::Crosshair, "{c:?}");
assert_eq!(c.stand_in(), None, "{c:?} is drawn");
}
}
/// Over a region of selected ordinary paths the cursor is the filled bucket once the pointer has
/// moved there (the move makes the selection's map), with Highlight on or off; with Paint Strokes
/// alone, a click there paints nothing and the bucket stays empty.
#[test]
fn bucket_cursor_fills_a_region_of_the_selected_paths() {
let (d, a, b) = two_rects();
let mut s = Selection::default();
s.set([a, b]);
let p = paint();
let cx = cx(&d, &s, &p);
let pos = Point::new(75.0, 50.0);
for highlight in [true, false] {
let mut t = LivePaintBucketTool::default();
t.set_option("highlight", &json!(highlight));
assert_eq!(t.cursor(&cx, pos, Mods::default()), Cursor::LivePaintBucket, "no map yet, highlight {highlight}");
t.pointer(&cx, &ev(PointerKind::Move, 75.0, 50.0));
t.poll(&cx, true);
assert_eq!(t.cursor(&cx, pos, Mods::default()), Cursor::LivePaintBucketFace, "highlight {highlight}");
assert_eq!(t.cursor(&cx, Point::new(400.0, 400.0), Mods::default()), Cursor::LivePaintBucket, "highlight {highlight}");
t.set_option("paintFills", &json!(false));
t.set_option("paintStrokes", &json!(true));
assert_eq!(t.cursor(&cx, pos, Mods::default()), Cursor::LivePaintBucket, "highlight {highlight}");
assert!(t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)).is_empty());
}
}
/// With a Live Paint group and ordinary paths selected, a region of the paths outside the group
/// is highlighted and shows the filled bucket, as a click there fills it; with only the group
/// selected, the same point shows the empty bucket.
#[test]
fn bucket_fills_a_region_of_a_selection_that_mixes_a_group_and_paths() {
let (mut d, a, b) = two_rects_at(200.0);
let (g, _) = live_square(&mut d, Rect::new(0.0, 0.0, 50.0, 50.0));
let p = paint();
let pos = Point::new(275.0, 50.0);
let mut s = Selection::default();
s.set([g, a, b]);
let mixed = cx(&d, &s, &p);
let mut t = LivePaintBucketTool::default();
t.pointer(&mixed, &ev(PointerKind::Move, pos.x, pos.y));
t.poll(&mixed, true);
assert!(!t.overlays(&mixed).is_empty(), "the region is highlighted");
assert_eq!(t.cursor(&mixed, pos, Mods::default()), Cursor::LivePaintBucketFace);
let acts = t.pointer(&mixed, &ev(PointerKind::Down, pos.x, pos.y));
assert!(matches!(acts.as_slice(), [Action::Begin(_), Action::Preview(id, v)] if id == "livePaint.fill" && v.get("ids").is_some()), "{acts:?}");
let mut s = Selection::default();
s.set([g]);
let live = cx(&d, &s, &p);
let mut t = LivePaintBucketTool::default();
t.pointer(&live, &ev(PointerKind::Move, pos.x, pos.y));
t.poll(&live, true);
assert!(t.overlays(&live).is_empty());
assert_eq!(t.cursor(&live, pos, Mods::default()), Cursor::LivePaintBucket);
}
#[test]
fn bucket_strokes_alone_paints_and_highlights_no_region_of_the_selection() {
let (d, a, b) = two_rects();
@@ -1269,7 +1366,7 @@ fn bucket_alt_shift_samples_only_solid_color_and_restores_hover() {
let alt = Mods { alt: true, ..Default::default() };
let both = Mods { alt: true, shift: true, ..Default::default() };
let pos = Point::new(75.0, 25.0);
assert_eq!(t.cursor(&cx, pos, Mods::default()), Cursor::LivePaintBucket);
assert_eq!(t.cursor(&cx, pos, Mods::default()), Cursor::LivePaintBucketFace);
t.pointer(&cx, &ev(PointerKind::Move, 75.0, 25.0));
assert!(!t.overlays(&cx).is_empty());
t.pointer(&cx, &ev(PointerKind::Move, 75.0, 25.0).with_mods(alt));
@@ -1282,7 +1379,7 @@ fn bucket_alt_shift_samples_only_solid_color_and_restores_hover() {
);
assert!(t.pointer(&cx, &ev(PointerKind::Down, 400.0, 400.0).with_mods(both)).is_empty());
t.pointer(&cx, &ev(PointerKind::Move, 75.0, 25.0));
assert_eq!(t.cursor(&cx, pos, Mods::default()), Cursor::LivePaintBucket);
assert_eq!(t.cursor(&cx, pos, Mods::default()), Cursor::LivePaintBucketFace);
assert!(!t.overlays(&cx).is_empty());
}
+61 -1
View File
@@ -117,6 +117,53 @@ impl GlyphSnap {
}
}
/// The Pixel Snapping Options (`view.snapToPixel.options`): which edits View › Snap to Pixel lands
/// on whole pixels. All on by default.
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct PixelSnap {
/// While Drawing: points placed by the drawing tools, ruler origins and measurements.
pub drawing: bool,
/// While Moving: the selection, its anchors and segments, artboards and ruler guides moved.
pub moving: bool,
/// While Scaling: the edges a bounding-box, Free Transform, Scale tool, artboard or slice
/// handle drags.
pub scaling: bool,
}
impl Default for PixelSnap {
fn default() -> Self {
Self { drawing: true, moving: true, scaling: true }
}
}
impl PixelSnap {
/// These options with the ones `p` names (booleans), or why `p` can't set them.
pub fn merged(self, p: &serde_json::Value) -> Result<Self, String> {
let mut o = serde_json::to_value(self).map_err(|e| e.to_string())?;
match (p, o.as_object_mut()) {
(serde_json::Value::Null, _) => {}
(serde_json::Value::Object(given), Some(cur)) => {
for (k, v) in given {
let slot = cur.get_mut(k).ok_or_else(|| format!("unknown Pixel Snapping option `{k}`"))?;
*slot = serde_json::Value::Bool(v.as_bool().ok_or_else(|| format!("`{k}` must be true or false"))?);
}
}
_ => return Err("the Pixel Snapping options must be an object".into()),
}
serde_json::from_value(o).map_err(|e| e.to_string())
}
}
/// The kind of edit a snap serves, which picks the Pixel Snapping option that applies to it
/// ([`ToolContext::snaps_to_pixel`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PixelOp {
Drawing,
Moving,
Scaling,
}
/// Read-only context a tool sees.
pub struct ToolContext<'a> {
pub doc: &'a Document,
@@ -141,8 +188,11 @@ pub struct ToolContext<'a> {
pub snap_to_grid: bool,
/// Bounding box shown (View → Show/Hide Bounding Box).
pub show_bbox: bool,
/// View → Snap to Pixel.
/// View → Snap to Pixel. Which edits it snaps is [`Self::pixel_snap`]'s choice
/// ([`Self::snaps_to_pixel`]).
pub snap_to_pixel: bool,
/// The Pixel Snapping Options: whether Snap to Pixel snaps drawing, moving and scaling.
pub pixel_snap: PixelSnap,
/// View → Snap to Point: with Smart Guides off, dragged selections, drawn points and picked
/// points (a transform's reference point) land on anchors and ruler guides within
/// [`Self::snap_tolerance`].
@@ -342,6 +392,16 @@ impl ToolContext<'_> {
let (dist, ang, dx, dy) = xform::measure(a, b);
format!("D: {}\nAngle: {ang:.1}°\n{}", self.len(dist), self.offset_label(dx, dy))
}
/// Does View › Snap to Pixel land an edit of kind `op` on whole pixels: is it on, with the
/// Pixel Snapping option for `op` on too?
pub fn snaps_to_pixel(&self, op: PixelOp) -> bool {
self.snap_to_pixel
&& match op {
PixelOp::Drawing => self.pixel_snap.drawing,
PixelOp::Moving => self.pixel_snap.moving,
PixelOp::Scaling => self.pixel_snap.scaling,
}
}
/// What Snap to Grid snaps to: the grid's subdivisions (or its lines without any).
pub fn grid_step(&self) -> f64 {
self.doc.grid.spacing / self.doc.grid.subdivisions.max(1) as f64
+8 -2
View File
@@ -141,8 +141,13 @@ pub enum Cursor {
Knife,
/// The Shaper tool.
Shaper,
/// The Live Paint Bucket.
/// The Live Paint Bucket where a click paints nothing: an empty paint bucket.
LivePaintBucket,
/// The Live Paint Bucket where a click fills a face (of a Live Paint group, or a region of
/// the selected paths): a filled paint bucket.
LivePaintBucketFace,
/// The Live Paint Bucket where a click paints an edge of a Live Paint group: a brush.
LivePaintBucketEdge,
/// The Measure tool.
Measure,
/// The Print Tiling tool.
@@ -280,6 +285,8 @@ impl Cursor {
| Cursor::Knife
| Cursor::Shaper
| Cursor::LivePaintBucket
| Cursor::LivePaintBucketFace
| Cursor::LivePaintBucketEdge
| Cursor::Measure
| Cursor::PrintTiling
| Cursor::SymbolSprayer
@@ -320,7 +327,6 @@ impl Cursor {
| Cursor::Join
| Cursor::Knife
| Cursor::Shaper
| Cursor::LivePaintBucket
| Cursor::Measure
| Cursor::ObjectsOnPath
| Cursor::PrintTiling
+34 -5
View File
@@ -439,7 +439,10 @@ designer = false
[[cursor]]
id = "Eyedropper"
group = "Colour and gradient"
shown_when = ["The Eyedropper tool, whatever the modifier keys. With Use Precise Cursors on, the crosshair shows instead."]
shown_when = [
"The Eyedropper tool, whatever the modifier keys. With Use Precise Cursors on, the crosshair shows instead.",
"The Live Paint Bucket with Alt held (a click samples paint).",
]
hotspot = "The pipette's tip."
look = "A pipette."
@@ -475,8 +478,32 @@ hotspot = "Where the mesh point goes."
[[cursor]]
id = "LivePaintBucket"
group = "Colour and gradient"
shown_when = ["The Live Paint Bucket: a click fills a face (or an edge) of a Live Paint group."]
hotspot = "Where the paint pours out."
shown_when = [
"The Live Paint Bucket where a click paints nothing: away from Live Paint groups and the selected paths' regions, or over a part the Paint Fills and Paint Strokes options (and Shift) leave unpainted.",
"With Use Precise Cursors on, the crosshair shows instead.",
]
hotspot = "The drop the paint pours onto."
look = "An empty paint bucket tipped toward the hotspot, a small drop on it. LivePaintBucketFace is the same bucket filled."
[[cursor]]
id = "LivePaintBucketFace"
group = "Colour and gradient"
shown_when = [
"The Live Paint Bucket over a face of a Live Paint group, or a region of the selected paths, that a click fills.",
"With Use Precise Cursors on, the crosshair shows instead.",
]
hotspot = "The drop the paint pours onto."
look = "LivePaintBucket filled, with a larger drop on the hotspot."
[[cursor]]
id = "LivePaintBucketEdge"
group = "Colour and gradient"
shown_when = [
"The Live Paint Bucket over an edge of a Live Paint group that a click paints with the stroke.",
"With Use Precise Cursors on, the crosshair shows instead.",
]
hotspot = "The brush's tip."
look = "A brush pointing down-left: bristles at the hotspot, then a white ferrule and a dark handle."
# ── Width, blend, slice and shape builder ─────────────────────────────────────────────────────────
@@ -599,14 +626,14 @@ look = "PencilStraight's badge with a small filled square at the line's lower en
[[cursor]]
id = "Paintbrush"
group = "Drawing and editing tools"
shown_when = ["The Paintbrush tool: draws a brushed freeform path (with pen pressure), continuing a selected path from its end; Alt closes it."]
shown_when = ["The Paintbrush tool: draws a brushed freeform path (with pen pressure), continuing a selected path from its end; Alt closes it, except that Alt held at the press with a path selected that the Smooth tool can act on smooths that path (see Smooth)."]
hotspot = "The bristle tip."
[[cursor]]
id = "PaintbrushClose"
group = "Drawing and editing tools"
shown_when = [
"The Paintbrush tool with Alt held, before a press and while drawing: releasing the mouse button with Alt still held closes the path.",
"The Paintbrush tool with Alt held while drawing, or before a press when no path is selected that the Smooth tool can act on (with one selected, Smooth shows): releasing the mouse button with Alt still held closes the path.",
"The Paintbrush tool while a stroke is drawn back to within Close Paths When Ends Are Within of its start: releasing the mouse button there closes the path.",
]
hotspot = "The bristle tip."
@@ -632,6 +659,8 @@ group = "Drawing and editing tools"
shown_when = [
"The Smooth tool: a drag along a selected path smooths it.",
"The Pencil tool with Alt key toggles to Smooth Tool on: with Alt held before a stroke begins to draw, and through a drag that smooths.",
"The Paintbrush tool with Alt held before a press while a path is selected that the Smooth tool can act on (an editable path, not a guide, with three or more anchors on one of its subpaths), and through a drag that smooths.",
"The Blob Brush tool with Alt held before a press, or before the drag has moved from the press point, and through a drag that smooths.",
]
hotspot = "The tip."
+7 -7
View File
@@ -66,7 +66,7 @@ use crate::meshedit::{MeshEdit, grid_of};
use crate::pathtype::{self, BracketDrag, near_bracket};
use crate::rulerguide::GuideEdit;
use crate::select::{MoveSnap, hit_center, hold_point, is_area_type, is_path_type, matrix_json, release_guide_at, selection_bounds};
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
#[derive(Clone, Debug)]
enum State {
@@ -1465,11 +1465,11 @@ impl DirectSelectionTool {
}
out.push(Action::Begin("Move".into()));
self.state = State::MoveAnchors { start, grab, began: true, segment };
self.anchor_snap = Some(PointSnap::new(cx, || Targets::for_anchor_drag(cx.doc, cx.selection)));
self.anchor_snap = Some(PointSnap::moving(cx, || Targets::for_anchor_drag(cx.doc, cx.selection)));
self.line_end = line_end_leave(cx, grab);
// A segment held by a point along it lands its anchors on the grid (the box round
// them, an edge on a gridline on each axis), not that point (#3835).
let grid = segment && (cx.snap_to_grid || cx.snap_to_pixel);
let grid = segment && (cx.snap_to_grid || cx.snaps_to_pixel(PixelOp::Moving));
self.partial_grid =
grid.then(|| MoveSnap::grid_only(vectorcraft_effects::preview::anchor_bounds_with(cx.selection, cx.doc, cx.bounds_measure())));
}
@@ -1505,8 +1505,8 @@ impl DirectSelectionTool {
// them and the objects selected whole (`path.moveAnchors`), as an anchor drag
// does, while Alt is up; the other anchors of a partly selected path stay in
// place. The history names the move or the copy at the end.
self.partial_snap = (!cx.selection.anchors.is_empty()).then(|| PointSnap::new(cx, || Targets::for_anchor_drag(cx.doc, cx.selection)));
let grid = self.partial_snap.is_some() && grab.is_none() && (cx.snap_to_grid || cx.snap_to_pixel);
self.partial_snap = (!cx.selection.anchors.is_empty()).then(|| PointSnap::moving(cx, || Targets::for_anchor_drag(cx.doc, cx.selection)));
let grid = self.partial_snap.is_some() && grab.is_none() && (cx.snap_to_grid || cx.snaps_to_pixel(PixelOp::Moving));
self.partial_grid =
grid.then(|| MoveSnap::grid_only(vectorcraft_effects::preview::anchor_bounds_with(cx.selection, cx.doc, cx.bounds_measure())));
let copy = ev.mods.alt && self.partial_snap.is_none();
@@ -1514,8 +1514,8 @@ impl DirectSelectionTool {
self.state = State::MoveObject { start, grab, hold, began: true, deselect: None };
if grab.is_some() {
// Alt can go down or up at any time: gather both while nothing has moved.
self.anchor_snap = Some(PointSnap::new(cx, || Targets::for_anchor_drag(cx.doc, cx.selection)));
self.copy_snap = Some(PointSnap::new(cx, || Targets::for_anchor_drag(cx.doc, &Selection::default())));
self.anchor_snap = Some(PointSnap::moving(cx, || Targets::for_anchor_drag(cx.doc, cx.selection)));
self.copy_snap = Some(PointSnap::moving(cx, || Targets::for_anchor_drag(cx.doc, &Selection::default())));
// As a move with the Selection tool does ([`MoveSnap::new`]).
let back = cx.smart_guides && !cx.snap_to_grid && cx.snap_to_last_location;
self.last_location = back.then(|| (Targets::last_location(cx), selection_bounds(cx)));
+27
View File
@@ -634,6 +634,33 @@ fn snap_to_pixel_wins_over_snap_to_last_location_for_a_path_moved_by_its_anchor(
assert!(labels.is_empty(), "{labels:?}");
}
/// Pixel Snapping Options › While Moving off: a direct-selected anchor dragged with Snap to Pixel
/// on keeps its fractional offset; with the option on it lands on whole pixels.
#[test]
fn an_anchor_drag_follows_the_while_moving_option() {
use crate::PixelSnap;
let mut d = vectorcraft_doc::Document::new(500.0, 500.0);
let l = d.layers[0].id;
let id = d.alloc_id();
let square = vectorcraft_geom::shapes::rectangle(Rect::new(100.3, 100.4, 200.3, 200.4));
d.insert(Some(l), 0, vectorcraft_doc::Node::path(id, square, vectorcraft_doc::Appearance::default_art())).unwrap();
let s = anchors_of(id, &[(0, 0)]);
let p = paint();
let moved = |pixel_snap: PixelSnap| {
let c = ToolContext { snap_to_pixel: true, pixel_snap, smart_guides: false, snap_to_point: false, ..cx(&d, &s, &p) };
let mut t = DirectSelectionTool::new(false);
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 100.3, 100.4));
let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 106.3, 105.4));
let Some(Action::Preview(command, v)) = a.last() else { panic!("{a:?}") };
assert_eq!(command, "path.moveAnchors");
Vec2::new(v["dx"].as_f64().unwrap_or(f64::NAN), v["dy"].as_f64().unwrap_or(f64::NAN))
};
let m = moved(PixelSnap { moving: false, ..PixelSnap::default() });
assert!((m - Vec2::new(6.0, 5.0)).hypot() < 1e-9, "{m:?}");
let m = moved(PixelSnap { drawing: false, scaling: false, moving: true });
assert!((m - Vec2::new(5.7, 4.6)).hypot() < 1e-9, "{m:?}");
}
/// A click (no drag) on an anchor that is selected with others, whether the whole path is or
/// some of its anchors, selects that anchor alone, as in Illustrator: a press keeps the
/// selection so a drag moves it all, the release without a drag narrows it. Shift still
+3 -3
View File
@@ -216,10 +216,10 @@ impl GestureTool {
}
/// Does a straight Knife cut snap to anchors and paths? Only with Smart Guides on, which Snap to
/// Pixel and Snap to Grid turn off (`PointSnap::new`). Its ends snap as the Pencil's straight
/// line's do: the press, and the release unless Shift keeps it on a 45° step.
/// Pixel (for drawing) and Snap to Grid turn off (`PointSnap::new`). Its ends snap as the
/// Pencil's straight line's do: the press, and the release unless Shift keeps it on a 45° step.
fn knife_snaps(&self, cx: &ToolContext) -> bool {
self.id == "knife" && self.straight && cx.smart_guides && !cx.snap_to_pixel && !cx.snap_to_grid
self.id == "knife" && self.straight && cx.smart_guides && !cx.snaps_to_pixel(crate::PixelOp::Drawing) && !cx.snap_to_grid
}
/// Does the end of a straight line snap: the Pencil's Alt line's, or a straight Knife cut's
+10 -2
View File
@@ -1034,6 +1034,8 @@ fn paintbrush_alt_after_press_closes_without_smoothing_and_empty_selection_draws
let selected_cx = cx(&d, &selected, &p);
t.pointer(&selected_cx, &PointerEvent::new(PointerKind::Down, pts[0].0, pts[0].1));
t.pointer(&selected_cx, &PointerEvent::new(PointerKind::Drag, pts[1].0, pts[1].1).with_mods(alt));
// While drawing, Alt shows the closing ring though the selection could be smoothed.
assert_eq!(t.cursor(&selected_cx, Point::new(pts[1].0, pts[1].1), alt), Cursor::PaintbrushClose);
let last = t.pointer(&selected_cx, &PointerEvent::new(PointerKind::Up, pts[2].0, pts[2].1).with_mods(alt));
assert!(matches!(last.first(), Some(Action::Preview(c, v)) if c == "path.freehand" && v["closed"] == true), "{last:?}");
let cx = cx(&d, &empty, &p);
@@ -1041,7 +1043,8 @@ fn paintbrush_alt_after_press_closes_without_smoothing_and_empty_selection_draws
assert!(matches!(last.last().and_then(|a| a.first()), Some(Action::Preview(c, v)) if c == "path.freehand" && v["closed"] == true), "{last:?}");
}
/// The Paintbrush shows Smooth before an Alt press only with a selected path.
/// The Paintbrush shows Smooth before an Alt press only with a selected path, and through the
/// drag that smooths it, with Alt let go too.
#[test]
fn paintbrush_alt_cursor_matches_selection_at_press() {
let (d, id) = doc_with_rect();
@@ -1050,9 +1053,14 @@ fn paintbrush_alt_cursor_matches_selection_at_press() {
let empty = Selection::default();
let p = paint();
let alt = Mods { alt: true, ..Default::default() };
let t = GestureTool::new("paintbrush");
let mut t = GestureTool::new("paintbrush");
assert_eq!(t.cursor(&cx(&d, &selected, &p), Point::new(50.0, 150.0), alt), Cursor::Smooth);
assert_eq!(t.cursor(&cx(&d, &empty, &p), Point::new(50.0, 150.0), alt), Cursor::PaintbrushClose);
let selected_cx = cx(&d, &selected, &p);
t.pointer(&selected_cx, &PointerEvent::new(PointerKind::Down, 50.0, 150.0).with_mods(alt));
t.pointer(&selected_cx, &PointerEvent::new(PointerKind::Drag, 150.0, 150.0).with_mods(alt));
assert_eq!(t.cursor(&selected_cx, Point::new(150.0, 150.0), alt), Cursor::Smooth);
assert_eq!(t.cursor(&selected_cx, Point::new(150.0, 150.0), Mods::default()), Cursor::Smooth);
}
/// A selected text object leaves Alt Paintbrush drawing a closed stroke with its close cursor.
+37 -9
View File
@@ -3,6 +3,7 @@ use super::{
Affine, GlyphSnap, GuideStyle, Handle, HitOptions, Line, NodeId, OrientedBox, Overlay, ParamCurve, ParamCurveDeriv, ParamCurveNearest, PathSeg,
Point, Rect, ScreenFrame, ToolContext, Vec2, constrain_angle_from, hit_test,
};
use crate::PixelOp;
/// Where curves `a` and `b` cross near `p`: a point projected from one onto the other and back
/// settles where they meet (none when they don't nearby).
@@ -100,11 +101,29 @@ pub struct PointSnap {
/// The smart guide targets, or with Smart Guides off those of Snap to Point, and how near (in
/// screen pixels) they pull; none with pixels or the grid snapping instead, or nothing on.
targets: Option<(Targets, f64)>,
/// The kind of edit the point serves: whether Snap to Pixel rounds it
/// ([`ToolContext::snaps_to_pixel`]).
op: PixelOp,
}
impl PointSnap {
/// Snapping for a drawn point.
pub fn new(cx: &ToolContext, targets: impl FnOnce() -> Targets) -> Self {
let targets = if cx.snap_to_pixel || cx.snap_to_grid {
Self::for_op(cx, PixelOp::Drawing, targets)
}
/// Snapping for a moved point (an anchor, or the selection held by one).
pub fn moving(cx: &ToolContext, targets: impl FnOnce() -> Targets) -> Self {
Self::for_op(cx, PixelOp::Moving, targets)
}
/// Snapping for a dragged handle that scales ([`Self::snap_scale`]).
pub fn scaling(cx: &ToolContext, targets: impl FnOnce() -> Targets) -> Self {
Self::for_op(cx, PixelOp::Scaling, targets)
}
fn for_op(cx: &ToolContext, op: PixelOp, targets: impl FnOnce() -> Targets) -> Self {
let targets = if cx.snaps_to_pixel(op) || cx.snap_to_grid {
None
} else if cx.smart_guides {
// Snap to Point keeps pulling points onto the ruler guides with Smart Guides on (#812).
@@ -116,7 +135,7 @@ impl PointSnap {
} else {
None
};
Self { targets }
Self { targets, op }
}
/// Snapping for a point placed anywhere, as a drawing tool's ([`DrawSnap`]) is: the art in the
@@ -135,7 +154,7 @@ impl PointSnap {
/// showing why. Pixels and the grid round it before Shift turns it onto its angle.
pub fn snap_from(&self, cx: &ToolContext, p: Point, from: Option<&Leave>) -> (Point, Vec<Overlay>) {
let keep = |q: Point| from.and_then(|f| f.constrained(q)).unwrap_or(q);
if cx.snap_to_pixel {
if cx.snaps_to_pixel(self.op) {
return (keep(Point::new(p.x.round(), p.y.round())), vec![]);
}
if cx.snap_to_grid {
@@ -148,9 +167,10 @@ impl PointSnap {
}
/// Snap a bounding-box resize ([`Targets::snap_scale`]) as [`Self::snap`] snaps a point. With
/// Snap to Pixel on, the corner or side the handle moves lines up with whole pixels, and with
/// Snap to Grid on it lines up with the nearest gridline, however far that is; neither shows
/// guides. Otherwise the handle snaps to the targets [`Self::new`] gathered.
/// Snap to Pixel on for scaling, the corner or side the handle moves lines up with whole
/// pixels, and with Snap to Grid on it lines up with the nearest gridline, however far that
/// is; neither shows guides. Otherwise the handle snaps to the targets [`Self::scaling`]
/// gathered.
pub fn snap_scale(
&self,
cx: &ToolContext,
@@ -160,7 +180,7 @@ impl PointSnap {
proportional: bool,
from_center: bool,
) -> (Affine, Vec<Overlay>) {
let step = if cx.snap_to_pixel {
let step = if cx.snaps_to_pixel(PixelOp::Scaling) {
Some(1.0)
} else if cx.snap_to_grid {
Some(cx.grid_step()).filter(|s| s.is_finite() && *s > 0.0)
@@ -327,7 +347,15 @@ impl SnapKey {
revision: cx.revision,
exclude: exclude.to_vec(),
screen: cx.screen,
view: [cx.smart_guides, cx.snap_to_point, cx.snap_to_pixel, cx.snap_to_grid, cx.guides, cx.snap_tangent, cx.snap_perpendicular],
view: [
cx.smart_guides,
cx.snap_to_point,
cx.snaps_to_pixel(PixelOp::Drawing),
cx.snap_to_grid,
cx.guides,
cx.snap_tangent,
cx.snap_perpendicular,
],
snap_to_glyph: (cx.snap_to_glyph && cx.smart_guides && cx.alignment_guides).then_some(cx.glyph_snap),
style: GuideStyle::of(cx),
tolerances: [cx.snapping_tolerance, cx.snap_tolerance],
@@ -381,7 +409,7 @@ impl DrawSnap {
/// Guides snapping tolerance (the Knife's straight cut). The targets serve this press only.
pub fn press_on_paths(&mut self, cx: &ToolContext, p: Point) -> Point {
let targets = Targets::for_drawing(cx.doc, &[], visible(cx), None).styled(cx).anchors_and_paths();
self.targets = Some((None, PointSnap { targets: Some((targets, cx.snapping_tolerance)) }));
self.targets = Some((None, PointSnap { targets: Some((targets, cx.snapping_tolerance)), op: PixelOp::Drawing }));
self.snap(cx, p, None)
}
+4 -4
View File
@@ -168,13 +168,13 @@ impl Targets {
/// or nothing for a copy, which leaves it behind), styled as `cx` asks, and with Smart Guides ›
/// Spacing Guides the objects it spaces itself evenly with ([`Self::snap_rect`]). With Smart
/// Guides › Snap to Last Location, a move (not a copy, which has nothing in `exclude`) goes back
/// to where it began when it comes near ([`Self::snap_back`]), unless Snap to Pixel is on.
/// to where it began when it comes near ([`Self::snap_back`]), unless Snap to Pixel snaps moves.
pub fn for_move(cx: &ToolContext, exclude: &[NodeId]) -> Self {
let mut t = Self::collect(cx.doc, exclude, None).styled(cx);
if cx.spacing_guides {
t.boxes = object_boxes(cx.doc, &cx.selection.objects);
}
t.last_location = cx.snap_to_last_location && !cx.snap_to_pixel && !exclude.is_empty();
t.last_location = cx.snap_to_last_location && !cx.snaps_to_pixel(crate::PixelOp::Moving) && !exclude.is_empty();
t
}
@@ -189,9 +189,9 @@ impl Targets {
/// Targets that hold nothing but Smart Guides › Snap to Last Location ([`Self::snap_back`]),
/// styled as `cx` asks: for a move of the selection whose other snaps come from other targets,
/// such as paths selected whole that Direct Selection moves held by an anchor. Snap to Pixel
/// turns it off, as it does every Smart Guides snap.
/// snapping moves turns it off, as it does every Smart Guides snap.
pub fn last_location(cx: &ToolContext) -> Self {
Self { last_location: cx.snap_to_last_location && !cx.snap_to_pixel, ..Self::default() }.styled(cx)
Self { last_location: cx.snap_to_last_location && !cx.snaps_to_pixel(crate::PixelOp::Moving), ..Self::default() }.styled(cx)
}
/// Targets for scaling the selection: the other art, styled as `cx` asks, and with Smart Guides ›
+5 -3
View File
@@ -58,7 +58,7 @@ mod context;
mod cursor;
mod input;
pub use context::{GlyphSnap, MarqueeMode, PaintDefaults, ScreenFrame, ToolContext};
pub use context::{GlyphSnap, MarqueeMode, PaintDefaults, PixelOp, PixelSnap, ScreenFrame, ToolContext};
pub use cursor::Cursor;
pub use input::{Action, Mods, PenPose, PointerEvent, PointerKind, ToolKey};
@@ -542,6 +542,7 @@ pub(crate) mod testutil {
snap_to_grid: false,
show_bbox: true,
snap_to_pixel: false,
pixel_snap: crate::PixelSnap::default(),
snap_to_point: true,
snap_tangent: true,
snap_perpendicular: true,
@@ -641,10 +642,11 @@ mod cursor_tests {
] {
assert_eq!(cursor_at(id, &d, away), c, "{id}");
assert_eq!(c.precise(), Cursor::Crosshair, "{id}");
// The Blob Brush's and the Eraser's dot is drawn: their tip outline goes round it.
// The Blob Brush's and the Eraser's dot is drawn: their tip outline goes round it. The
// Live Paint Bucket's bucket is drawn.
let stand_in = match id {
"mesh" => Some(Cursor::PenAdd),
"blobBrush" | "eraser" => None,
"blobBrush" | "eraser" | "livePaintBucket" => None,
_ => Some(Cursor::Crosshair),
};
assert_eq!(c.stand_in(), stand_in, "{id}");
+5 -4
View File
@@ -17,7 +17,7 @@ use vectorcraft_doc::{Guide, NodeId};
use vectorcraft_geom::{Point, Rect};
use crate::guides::{PointSnap, Targets};
use crate::{Action, Cursor, Overlay, PointerEvent, PointerKind, ToolContext};
use crate::{Action, Cursor, Overlay, PixelOp, PointerEvent, PointerKind, ToolContext};
/// The ruler guide under `p`, by its index in `guide.list`: the nearest within the selection
/// tolerance (the newest of equals).
@@ -123,7 +123,7 @@ struct GuideSnap {
impl GuideSnap {
fn new(cx: &ToolContext) -> Self {
let targets = || Targets::collect(cx.doc, &[], None);
let targets = if cx.snap_to_pixel || cx.snap_to_grid {
let targets = if cx.snaps_to_pixel(PixelOp::Moving) || cx.snap_to_grid {
None
} else if cx.smart_guides {
Some((targets().styled(cx), cx.snapping_tolerance))
@@ -136,7 +136,8 @@ impl GuideSnap {
}
/// Where a guide dragged to `v` (the x of a vertical one, the y of a horizontal one) goes:
/// with Shift on the nearest ruler tick, else on whole pixels, the grid or a target.
/// with Shift on the nearest ruler tick, else on whole pixels (Snap to Pixel's While Moving
/// option), the grid or a target.
fn snap(&mut self, cx: &ToolContext, vertical: bool, v: f64, shift: bool) -> f64 {
self.snapped.clear();
if shift {
@@ -144,7 +145,7 @@ impl GuideSnap {
let origin = if vertical { origin.x } else { origin.y };
return origin + cx.unit.snap_to_ruler_tick(v - origin, cx.zoom);
}
if cx.snap_to_pixel {
if cx.snaps_to_pixel(PixelOp::Moving) {
return v.round();
}
if cx.snap_to_grid {
+18
View File
@@ -253,6 +253,24 @@ fn new_ruler_guide_alt_snaps_on_the_effective_axis() {
}
}
/// A guide dragged out of a ruler snaps to whole pixels with Snap to Pixel only while the Pixel
/// Snapping Options' While Moving is on; While Drawing and While Scaling do not change it.
#[test]
fn new_ruler_guide_follows_the_while_moving_option() {
use crate::PixelSnap;
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let off = ToolContext { smart_guides: false, snap_to_point: false, snap_to_pixel: true, ..cx(&d, &s, &p) };
for (pixel_snap, expected) in
[(PixelSnap { moving: false, ..PixelSnap::default() }, 226.4), (PixelSnap { drawing: false, scaling: false, moving: true }, 226.0)]
{
let c = ToolContext { pixel_snap, ..off };
let mut g = NewGuide::new(&c, true, None);
let actions = g.pointer(&c, &ev(PointerKind::Drag, 226.4, 237.6, Mods::default()), true);
assert_eq!(actions.last(), Some(&Action::Preview("guide.add".into(), json!({"vertical": true, "pos": expected}))), "{pixel_snap:?}");
}
}
/// With Smart Guides off, Snap to Point pulls a dragged guide onto the anchors (within its
/// distance), not the edges' midpoints.
#[test]
+7 -6
View File
@@ -56,7 +56,7 @@ use crate::pie::{self, PieDrag};
use crate::rulerguide::GuideEdit;
use crate::shaperwidget;
use crate::typewidget;
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey, json_ids};
use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey, json_ids};
/// Direction is read on screen, even in a turned view. Within three pixels of the press's
/// horizontal position, retain the previous rule so hand jitter does not flip it.
@@ -228,8 +228,9 @@ fn distance_overlays(cx: &ToolContext, to: DistanceTo) -> Vec<Overlay> {
/// Snap to Grid lands its edges on the grid (#740), taking over from the rest; otherwise Smart
/// Guides line its bounds up with the other art, and with them off, View → Snap to Point lands the
/// point it was grabbed by (an anchor pressed near, else the pressed point) on an anchor or a ruler
/// guide. Snap to Pixel puts its top-left on whole pixels. A copy (Alt, which can go down or up at
/// any time during the drag) leaves the original behind, so it snaps to the original too.
/// guide. Snap to Pixel puts its top-left on whole pixels while its While Moving option is on. A
/// copy (Alt, which can go down or up at any time during the drag) leaves the original behind, so
/// it snaps to the original too.
pub(crate) struct MoveSnap {
bounds: Option<Rect>,
targets: Option<Targets>,
@@ -314,7 +315,7 @@ impl MoveSnap {
}
}
}
if cx.snap_to_pixel
if cx.snaps_to_pixel(PixelOp::Moving)
&& let Some(b) = self.bounds
{
d = Vec2::new((b.x0 + d.x).round() - b.x0, (b.y0 + d.y).round() - b.y0);
@@ -388,7 +389,7 @@ impl MoveSnap {
guides = ov;
}
}
if cx.snap_to_pixel
if cx.snaps_to_pixel(PixelOp::Moving)
&& let Some(b) = self.bounds
{
let at = Point::new(b.x0, b.y0) + d;
@@ -1655,7 +1656,7 @@ impl SelectionTool {
// What the handle moves snaps as a dragged point does: to pixels or the
// grid, else with Smart Guides to the other objects, else with Snap to
// Point to their anchors; the ruler guides with Snap to Point.
self.targets = Some(PointSnap::new(cx, || Targets::for_scale(cx)));
self.targets = Some(PointSnap::scaling(cx, || Targets::for_scale(cx)));
self.last_backquote = false;
self.last_box_pos = None;
self.state = State::Scaling { handle, bx, areas };
+45
View File
@@ -1794,6 +1794,51 @@ fn handle_drag_lands_what_it_moves_on_whole_pixels() {
assert!(near(r, Rect::new(100.0, 100.0, 212.0, 231.0)), "{r:?}");
}
/// Pixel Snapping Options › While Scaling off: a handle drag keeps the fractional size it is
/// dragged to with Snap to Pixel on, and turned back on, the drag lands on whole pixels again; While
/// Drawing and While Moving do not change it.
#[test]
fn handle_drag_follows_the_while_scaling_option() {
use crate::PixelSnap;
let (d, id) = doc_with_rect();
let mut s = Selection::default();
s.add(id);
let p = paint();
let drag = |pixel_snap: PixelSnap| {
let c = ToolContext { snap_to_pixel: true, pixel_snap, smart_guides: false, snap_to_point: false, ..cx(&d, &s, &p) };
let mut t = SelectionTool::default();
t.pointer(&c, &ev(PointerKind::Down, 200.0, 200.0));
scaled(&t.pointer(&c, &ev(PointerKind::Drag, 212.4, 230.7)))
};
let r = drag(PixelSnap { scaling: false, ..PixelSnap::default() });
assert!(near(r, Rect::new(100.0, 100.0, 212.4, 230.7)), "{r:?}");
let r = drag(PixelSnap { drawing: false, moving: false, scaling: true });
assert!(near(r, Rect::new(100.0, 100.0, 212.0, 231.0)), "{r:?}");
}
/// Pixel Snapping Options › While Moving off: a move keeps its fractional offset with Snap to
/// Pixel on, and Smart Guides › Snap to Last Location works again for it.
#[test]
fn move_follows_the_while_moving_option() {
use crate::PixelSnap;
let (d, id) = doc_with_rect();
let mut s = Selection::default();
s.add(id);
let p = paint();
let pixel_snap = PixelSnap { moving: false, ..PixelSnap::default() };
let c = ToolContext { snap_to_pixel: true, pixel_snap, smart_guides: false, snap_to_point: false, ..cx(&d, &s, &p) };
let snap = MoveSnap::new(&c);
let (dv, _) = snap.snap(&c, Point::new(150.0, 150.0), Vec2::new(3.3, 4.6), false);
assert!((dv - Vec2::new(3.3, 4.6)).hypot() < 1e-9, "{dv:?}");
let on = ToolContext { pixel_snap: PixelSnap::default(), ..c };
let (dv, _) = MoveSnap::new(&on).snap(&on, Point::new(150.0, 150.0), Vec2::new(3.3, 4.6), false);
assert!((dv - Vec2::new(3.0, 5.0)).hypot() < 1e-9, "{dv:?}");
let back = ToolContext { smart_guides: true, snap_to_last_location: true, snapping_tolerance: 10.0, ..c };
assert!(Targets::for_move(&back, &back.selection.objects).snap_back(None, Vec2::new(1.0, 1.0), back.snap_tol()).is_some());
let pixels = ToolContext { pixel_snap: PixelSnap::default(), ..back };
assert!(Targets::for_move(&pixels, &pixels.selection.objects).snap_back(None, Vec2::new(1.0, 1.0), pixels.snap_tol()).is_none());
}
/// #2054: with Smart Guides off, View › Snap to Point lands a dragged handle on another
/// object's anchor or a ruler guide within its distance (2 px); with Smart Guides on, the
/// ruler guides still pull it within the Snapping Tolerance (4 px), as a move does (#1534).
+1 -1
View File
@@ -236,7 +236,7 @@ impl ShapeTool {
self.selection = if let Some((handle, bx)) = self.over_handle(cx, ev.pos) {
let is_area = |id: &vectorcraft_doc::NodeId| cx.doc.node(*id).is_some_and(is_area_type);
let areas = cx.selection.objects.iter().any(is_area);
Some(SelectionDrag::Scale { handle, bx, areas, snap: Box::new(PointSnap::new(cx, || Targets::for_scale(cx))), last: None })
Some(SelectionDrag::Scale { handle, bx, areas, snap: Box::new(PointSnap::scaling(cx, || Targets::for_scale(cx))), last: None })
} else {
match hit_center(cx, ev.pos, cx.point_tol()) {
Some((_, hold)) => Some(SelectionDrag::Move { start: ev.pos, hold, began: false, snap: Box::new(MoveSnap::new(cx)) }),
+1 -1
View File
@@ -161,7 +161,7 @@ struct ResizeSnap {
impl ResizeSnap {
fn new(cx: &ToolContext) -> Self {
Self { art: PointSnap::new(cx, || Targets::collect(cx.doc, &[], None)), rulers: Targets::rulers(cx) }
Self { art: PointSnap::scaling(cx, || Targets::collect(cx.doc, &[], None)), rulers: Targets::rulers(cx) }
}
/// Snap the resize `a` ([`scale_for_drag`]) of the slice `rect` by `handle` as [`snap`] snaps
+9 -7
View File
@@ -37,7 +37,7 @@ use vectorcraft_geom::{Affine, Point, Rect, Vec2};
use super::{BLUE, polygon, rect_corners};
use crate::bbox::{Handle, hit_handle, scale_for_drag};
use crate::guides::{DrawSnap, Leave, Targets};
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
#[derive(Clone, Copy, Debug)]
enum Drag {
@@ -205,11 +205,12 @@ impl ArtboardTool {
self.copy_targets = cx.smart_guides.then(|| Targets::for_artboard(cx.doc, usize::MAX, &[]).styled(cx));
}
/// Snap a dragged handle: to whole pixels, the grid, or Smart Guides (in that order, as when
/// drawing). With Smart Guides the bleed edge `bleed` beyond the handle may snap instead.
/// Snap a dragged handle: to whole pixels (Snap to Pixel's While Scaling option), the grid, or
/// Smart Guides (in that order, as when drawing). With Smart Guides the bleed edge `bleed`
/// beyond the handle may snap instead.
fn snap_handle(&mut self, cx: &ToolContext, p: Point, bleed: Vec2) -> Point {
self.guides.clear();
if cx.snap_to_pixel {
if cx.snaps_to_pixel(PixelOp::Scaling) {
return Point::new(p.x.round(), p.y.round());
}
if cx.snap_to_grid {
@@ -222,12 +223,13 @@ impl ArtboardTool {
q
}
/// Snap a move (or an Alt-drag `copy`) of `rect` by `d`: its top-left to whole pixels or the
/// grid, or any of its edges and centre to Smart Guides. Returns the snapped delta.
/// Snap a move (or an Alt-drag `copy`) of `rect` by `d`: its top-left to whole pixels (Snap to
/// Pixel's While Moving option) or the grid, or any of its edges and centre to Smart Guides.
/// Returns the snapped delta.
fn snap_move(&mut self, cx: &ToolContext, rect: Rect, d: Vec2, copy: bool) -> Vec2 {
self.guides.clear();
let tl = Point::new(rect.x0, rect.y0);
if cx.snap_to_pixel {
if cx.snaps_to_pixel(PixelOp::Moving) {
return Vec2::new((tl.x + d.x).round() - tl.x, (tl.y + d.y).round() - tl.y);
}
if cx.snap_to_grid {
+1 -1
View File
@@ -248,7 +248,7 @@ impl Tool for FreeTransformTool {
self.drag = None;
let Some(bx) = selection_box(cx) else { return vec![] };
if let Some(op) = self.classify(cx, &bx, p, ev.mods) {
self.targets = op.handle().is_some().then(|| PointSnap::new(cx, || Targets::for_scale(cx)));
self.targets = op.handle().is_some().then(|| PointSnap::scaling(cx, || Targets::for_scale(cx)));
self.drag = Some(Drag { op, bx, start: p, began: false });
}
vec![]
+1 -1
View File
@@ -43,7 +43,7 @@ pub(crate) fn end_point(cx: &ToolContext, snap: &mut DrawSnap, a: Point, p: Poin
return a;
}
let u = d / len;
let to_point = cx.snap_to_point && !(cx.smart_guides || cx.snap_to_grid || cx.snap_to_pixel);
let to_point = cx.snap_to_point && !(cx.smart_guides || cx.snap_to_grid || cx.snaps_to_pixel(crate::PixelOp::Drawing));
let s = if to_point { snap.measure(cx, p, None) } else { p };
let q = a + u * (s - a).dot(u);
let leave = crate::guides::Leave::segment(cx, a, true);
+5 -2
View File
@@ -238,8 +238,11 @@ impl Tool for TransformTool {
return out;
}
d.began = true;
// The selection moves, so only the other objects are targets.
self.snap = Some(PointSnap::new(cx, || Targets::collect(cx.doc, &cx.selection.objects, None)));
// The selection moves, so only the other objects are targets. The Scale tool's
// drag scales; the others move the art about the reference point.
let targets = || Targets::collect(cx.doc, &cx.selection.objects, None);
self.snap =
Some(if self.kind == TransformKind::Scale { PointSnap::scaling(cx, targets) } else { PointSnap::moving(cx, targets) });
out.push(Action::Begin(self.kind.label().into()));
}
let (p, guides) = self.snap.as_ref().map_or((p, vec![]), |s| s.snap(cx, p));
@@ -52,12 +52,19 @@ pub struct Present {
pub has: [bool; 4],
}
/// The statuses the `links.list` result `list` holds, in [`STATUSES`] order.
/// The statuses the rows of the `links.list` result `list` that can be selected hold, in
/// [`STATUSES`] order.
pub(crate) fn statuses_in(list: &Value) -> [bool; 4] {
let rows = list["links"].as_array().map_or(&[][..], Vec::as_slice);
let rows = canvas_rows(list);
STATUSES.map(|(status, ..)| rows.iter().any(|r| command_status(r) == status))
}
/// The rows of the `links.list` result `list` of objects in the layer tree, which can be
/// selected (a row with an `owner` is in a symbol, graph design, pattern or opacity mask).
fn canvas_rows(list: &Value) -> Vec<Value> {
list["links"].as_array().into_iter().flatten().filter(|r| r["owner"].is_null()).cloned().collect()
}
/// The status of a `links.list` row as the command names it (`ok` is `linked`).
fn command_status(row: &Value) -> &str {
match row["status"].as_str().unwrap_or_default() {
@@ -154,11 +161,11 @@ pub(crate) fn message(statuses: &[&str], count: u64, reasons: &[&str]) -> String
crate::i18n::msg_n(reasons.len() as u64, one, other, &[("selected", &selected)])
}
/// The dialog's fields to start with: every image and placed document (`__rows`, as `links.list`
/// lists them, read once), those selected chosen, All shown, Zoom to Selection on.
/// The dialog's fields to start with: every image and placed document in the layer tree (`__rows`,
/// as `links.list` lists them, read once), those selected chosen, All shown, Zoom to Selection on.
pub(crate) fn fields(app: &mut VectorcraftApp) -> Value {
let list = app.session.execute("links.list", &json!({})).unwrap_or_default();
let rows: Vec<Value> = list["links"].as_array().cloned().unwrap_or_default();
let rows = canvas_rows(&list);
let selected: Vec<u64> = app.session.active().map(|st| st.selection.objects.iter().map(|id| id.0).collect()).unwrap_or_default();
let chosen: Vec<u64> = rows.iter().filter_map(|r| r["id"].as_u64()).filter(|id| selected.contains(id)).collect();
json!({ "__rows": rows, "ids": chosen, "show": "all", "zoom": true })
@@ -138,6 +138,27 @@ fn menu_items_are_on_for_the_statuses_present_and_shift_adds() {
assert!(on("Select Embedded"));
}
/// A missing link kept only in a symbol's art can't be selected: Select Missing stays off and
/// the dialog does not list it.
#[test]
fn links_inside_a_symbol_are_left_out_of_selecting_by_status() {
let dir = Folder::new("symbol");
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let path = dir.file("inside.png", &png(30, 20));
let id = app.run("file.place", json!({"path": path, "at": [100, 100]})).unwrap()["ids"][0].as_u64().unwrap();
app.run("symbol.new", json!({"name": "Mark", "ids": [id]})).unwrap();
app.run("edit.clear", json!({})).unwrap();
std::fs::remove_file(&path).unwrap();
let list = app.run("links.list", json!({})).unwrap();
assert_eq!(list["missing"], 1, "{list}");
refresh(&mut app, 0.0);
let entries = menus::menu_entries(&app);
let missing = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Selection Tools"] && e.label == "Select Missing").unwrap();
assert!(!missing.enabled);
assert_eq!(super::fields(&mut app)["__rows"], json!([]));
}
#[test]
fn the_links_panel_menu_lists_the_select_items() {
let dir = Folder::new("flyout");
+2
View File
@@ -599,6 +599,8 @@ impl VectorcraftApp {
// Toolbar too.
toolbar::show_custom(self, ui.ctx());
}
// The lanes along the window's edges where toolbars made with New Toolbar dock.
crate::custom_toolbars::lanes(self, ui);
panels::library_panel::tidy(self);
// The canvas and the panels: one docking layout. Tab hides the panels but not the canvas.
egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.pasteboard)).show(ui, |ui| panel_docking::show(self, ui));
+1
View File
@@ -16,6 +16,7 @@ impl VectorcraftApp {
native_menu::run(self, ctx);
if self.fonts_ready {
tools_float::cancel_move_on_escape(self, ctx);
crate::custom_toolbars::cancel_move_on_escape(self, ctx);
shortcuts::handle(self, ctx);
}
// A Copy taken in this UI phase (an egui copy event, or a command it runs) is published in
+1 -1
View File
@@ -123,6 +123,7 @@ pub(super) fn cursor_icon(c: Cursor) -> egui::CursorIcon {
Cursor::TypeArea | Cursor::TypeOnPath => C::Text,
// The system has no tip outline to go round: its crosshair aims as well.
Cursor::BlobBrush | Cursor::Eraser => C::Crosshair,
Cursor::LivePaintBucket | Cursor::LivePaintBucketFace | Cursor::LivePaintBucketEdge => C::Crosshair,
// Not drawn yet: the cursor each borrows.
Cursor::Lasso
| Cursor::MagicWand
@@ -133,7 +134,6 @@ pub(super) fn cursor_icon(c: Cursor) -> egui::CursorIcon {
| Cursor::Join
| Cursor::Knife
| Cursor::Shaper
| Cursor::LivePaintBucket
| Cursor::Measure
| Cursor::PrintTiling
| Cursor::SymbolSprayer
+3
View File
@@ -184,6 +184,9 @@ fn system_cursors_show_the_same_crosshair_with_precise_cursors_on_or_off() {
Cursor::PencilNew,
Cursor::PencilStraight,
Cursor::PencilContinue,
Cursor::LivePaintBucket,
Cursor::LivePaintBucketFace,
Cursor::LivePaintBucketEdge,
] {
assert_eq!(cursor_icon(c), egui::CursorIcon::Crosshair, "{c:?}");
assert_eq!(cursor_icon(c), cursor_icon(c.precise()), "{c:?}");
+6 -1
View File
@@ -78,7 +78,8 @@ pub(super) const ISOLATION_BUTTON: &str = "cb-isolation";
/// less, the menu is left out so those controls still fit the narrowest window.
const ARTBOARD_SNAPPING_WIDTH: f32 = 900.0;
/// The Control bar's snapping quick access; every change uses its existing command.
/// The Control bar's snapping quick access; every change uses its existing command, and Pixel
/// Snapping Options… opens the dialog of `view.snapToPixel.options`.
fn snapping_menu(app: &mut VectorcraftApp, ui: &mut Ui) {
ui.menu_button(tl!("Snapping"), |ui| {
for (label, cmd, on) in [
@@ -92,6 +93,10 @@ fn snapping_menu(app: &mut VectorcraftApp, ui: &mut Ui) {
crate::menus::invoke(app, cmd, json!({}));
}
}
if ui.button(tl!("Pixel Snapping Options…")).clicked() {
ui.close();
crate::menus::invoke(app, "view.snapToPixel.options", json!({}));
}
ui.separator();
for (key, label, on) in [
("alignmentGuides", tl!("Alignment Guides"), app.session.prefs.alignment_guides),
+76
View File
@@ -2247,6 +2247,82 @@ fn the_control_bar_snapping_menu_shares_glyph_and_alignment_settings() {
check(&nodes, "Alignment Guides", true);
}
/// The Control bar's Snapping menu opens Pixel Snapping Options with the current options; OK sets
/// the three choices the dialog shows, and a dialog closed without OK changes nothing.
#[test]
fn the_control_bar_snapping_menu_opens_pixel_snapping_options() {
struct RestoreLanguage(crate::i18n::Lang);
impl Drop for RestoreLanguage {
fn drop(&mut self) {
crate::i18n::set_current(self.0);
}
}
let _language = RestoreLanguage(crate::i18n::current());
crate::i18n::set_current(crate::i18n::Lang::EN);
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("view.snapToPixel.options", json!({"moving": false})).unwrap();
let ctx = egui::Context::default();
ctx.enable_accesskit();
crate::theme::install_fonts(&ctx);
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 400.0));
let frame = |app: &mut crate::VectorcraftApp, events: Vec<egui::Event>| {
let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| super::control_bar(app, ui));
out.textures_delta.clear();
out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default()
};
let center = |nodes: &[(egui::accesskit::NodeId, egui::accesskit::Node)], name: &str| {
let n = nodes.iter().find(|(_, n)| n.label() == Some(name)).map(|(_, n)| n.clone()).unwrap_or_else(|| panic!("missing {name}"));
let b = n.bounds().expect("a visible menu control");
egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32)
};
let click = |app: &mut crate::VectorcraftApp, at: egui::Pos2| {
let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
frame(app, vec![egui::Event::PointerMoved(at), press(true)]);
frame(app, vec![press(false)]);
frame(app, vec![]);
frame(app, vec![])
};
frame(&mut app, vec![]);
let nodes = frame(&mut app, vec![]);
let menu = center(&nodes, "Snapping");
let nodes = click(&mut app, menu);
let entry = center(&nodes, "Pixel Snapping Options…");
click(&mut app, entry);
let d = app.ui.dialog.as_ref().expect("Pixel Snapping Options");
assert_eq!(d.kind, crate::dialogs::pixel_snap_options::KIND);
assert_eq!(serde_json::Value::Object(d.fields.clone()), json!({"drawing": true, "moving": false, "scaling": true}));
// While View › Snap to Pixel is off, the dialog says the options wait for it.
// A new window is laid out unseen in its first frame, so the second frame is read.
let note = |app: &mut crate::VectorcraftApp| {
let mut nodes = vec![];
for _ in 0..2 {
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| crate::dialogs::show(app, ui.ctx()));
out.textures_delta.clear();
nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default();
}
let shown = |text: &str| nodes.iter().any(|(_, n)| n.label().or(n.value()).is_some_and(|l| l.contains(text)));
(shown("Snap to Pixel While Drawing"), shown("take effect when View › Snap to Pixel is on"))
};
assert!(!app.ui.view.snap_to_pixel);
assert_eq!(note(&mut app), (true, true), "the note shows with Snap to Pixel off");
app.ui.view.snap_to_pixel = true;
assert_eq!(note(&mut app), (true, false), "the note is hidden with Snap to Pixel on");
let before = app.session.prefs.pixel_snap;
let d = app.ui.dialog.as_mut().unwrap();
d.fields.insert("drawing".into(), json!(false));
app.ui.dialog = None;
assert_eq!(app.session.prefs.pixel_snap, before, "a dialog closed without OK changes nothing");
crate::menus::invoke(&mut app, "view.snapToPixel.options", json!({}));
let d = app.ui.dialog.as_mut().expect("Pixel Snapping Options");
d.fields.insert("drawing".into(), json!(false));
d.fields.insert("moving".into(), json!(true));
d.fields.insert("scaling".into(), json!(false));
crate::dialogs::confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none());
assert_eq!(app.session.prefs.pixel_snap, vectorcraft_tools::PixelSnap { drawing: false, moving: true, scaling: false });
}
/// The window the Control bar docking tests draw the bar in.
const DOCK_SCREEN: egui::Rect = egui::Rect { min: egui::Pos2::ZERO, max: egui::pos2(1200.0, 300.0) };
+42 -1
View File
@@ -432,6 +432,42 @@ fn shape_builder(p: &mut Ink, o: Pos2, erase: bool) {
}
}
/// The Live Paint Bucket: a paint bucket tipped toward the hotspot at its lower left, its mouth
/// down-left with a rim across it, and a drop on the hotspot. Empty (white) with a small drop where
/// a click paints nothing; filled, with a larger drop, where a click fills a face.
fn paint_bucket(p: &mut Ink, o: Pos2, filled: bool) {
// `u` runs from the hotspot up-right into the bucket, `v` across it.
let (d, n) = (vec2(1.0, -1.0).normalized(), vec2(1.0, 1.0).normalized());
let at = |u: f32, v: f32| o + u * d + v * n;
poly(p, vec![at(5.5, -6.0), at(16.5, -4.5), at(16.5, 4.5), at(5.5, 6.0)], if filled { INK } else { HALO }, INK);
poly(p, vec![at(4.5, -7.0), at(6.5, -7.0), at(6.5, 7.0), at(4.5, 7.0)], INK, INK);
if filled {
p.circle_filled(o, 3.5, HALO);
p.circle_filled(o, 2.2, INK);
} else {
p.circle_filled(o, 2.5, HALO);
p.circle_filled(o, 1.25, INK);
}
}
/// The Live Paint Bucket over an edge it paints: a brush, its bristles' tip on the hotspot, the
/// white ferrule and the black handle running up-right.
fn paint_brush(p: &mut Ink, o: Pos2) {
let (d, n) = (vec2(1.0, -1.0).normalized(), vec2(1.0, 1.0).normalized());
let at = |u: f32, v: f32| o + u * d + v * n;
let bristles = vec![at(0.0, 0.0), at(4.0, -2.2), at(6.0, -2.2), at(6.0, 2.2), at(4.0, 2.2)];
let ferrule = vec![at(6.0, -2.0), at(9.0, -2.0), at(9.0, 2.0), at(6.0, 2.0)];
let handle = vec![at(9.0, -1.5), at(19.0, -1.2), at(19.0, 1.2), at(9.0, 1.5)];
// Every halo first, so no part's halo covers another's outline.
for part in [&bristles, &ferrule, &handle] {
p.add(Shape::closed_line(part.clone(), Stroke::new(3.0, HALO)));
}
for (part, fill) in [(bristles, INK), (ferrule, HALO), (handle, INK)] {
p.add(Shape::convex_polygon(part.clone(), fill, Stroke::NONE));
p.add(Shape::closed_line(part, Stroke::new(1.0, INK)));
}
}
/// The Hand tool and Space: an open hand (palm and four fingers, thumb to the left), or the same
/// hand closed while it drags the view. Windows has no system hand that isn't a pointing finger
/// (winit maps egui's Grab and Grabbing to the four-headed move cursor), so it is drawn like the
@@ -480,7 +516,7 @@ fn magnifier(p: &mut Ink, o: Pos2, out: bool) {
/// Every cursor with a glyph: its own, drawn here, or the one it borrows.
#[cfg(test)]
const GLYPHS: [Cursor; 93] = [
const GLYPHS: [Cursor; 95] = [
Cursor::Hand,
Cursor::HandGrab,
Cursor::ZoomIn,
@@ -548,6 +584,8 @@ const GLYPHS: [Cursor; 93] = [
Cursor::Knife,
Cursor::Shaper,
Cursor::LivePaintBucket,
Cursor::LivePaintBucketFace,
Cursor::LivePaintBucketEdge,
Cursor::Measure,
Cursor::PrintTiling,
Cursor::SymbolSprayer,
@@ -669,6 +707,9 @@ fn glyph(c: Cursor, p: Pos2) -> Option<Vec<Shape>> {
Cursor::LoadedText => loaded_text(ink, p),
Cursor::ShapeBuilder => shape_builder(ink, p, false),
Cursor::ShapeBuilderErase => shape_builder(ink, p, true),
Cursor::LivePaintBucket => paint_bucket(ink, p, false),
Cursor::LivePaintBucketFace => paint_bucket(ink, p, true),
Cursor::LivePaintBucketEdge => paint_brush(ink, p),
Cursor::Hand => hand(ink, p, false),
Cursor::HandGrab => hand(ink, p, true),
Cursor::ZoomIn => magnifier(ink, p, false),
+39
View File
@@ -292,6 +292,45 @@ fn the_pencil_continuation_cursor_is_the_straight_line_cursor_with_an_end_point(
}
}
/// The Live Paint Bucket's cursors are drawn, not the crosshair: an empty bucket where a click
/// paints nothing, a filled bucket with a larger drop on the hotspot where it fills a face, and a
/// brush with its tip on the hotspot where it paints an edge.
#[test]
fn the_live_paint_bucket_shows_a_bucket_or_a_brush() {
for ppp in [1.0f32, 2.0] {
let img = |c| rasterize(c, ppp).unwrap_or_else(|| panic!("{c:?} at {ppp}"));
let (cross, empty, filled, brush) =
(img(Cursor::Crosshair), img(Cursor::LivePaintBucket), img(Cursor::LivePaintBucketFace), img(Cursor::LivePaintBucketEdge));
// The pixel nearest the point `u` points up-right of the hotspot and `v` down-right across.
let at = |img: &CustomCursorImage, u: f32, v: f32| {
let s = std::f32::consts::FRAC_1_SQRT_2;
let [hx, hy] = img.hotspot.map(f32::from);
let (x, y) = ((hx + (u + v) * s * ppp - 0.5).round(), (hy + (v - u) * s * ppp - 0.5).round());
let inside = x >= 0.0 && y >= 0.0 && x < f32::from(img.size[0]) && y < f32::from(img.size[1]);
if inside { pixel(img, x as usize, y as usize) } else { [0; 4] }
};
let inked = |p: [u8; 4]| p[3] > 200 && p[0] < 64;
let white = |p: [u8; 4]| p[3] > 200 && p[0] > 192;
assert!(white(at(&empty, 11.0, 2.0)), "the empty bucket's body is white at {ppp}");
assert!(inked(at(&filled, 11.0, 2.0)), "the filled bucket's body is ink at {ppp}");
assert!(at(&empty, 0.0, 0.0)[3] > 0 && inked(at(&filled, 0.0, 0.0)), "a drop on the hotspot at {ppp}");
if ppp == 2.0 {
assert!(inked(at(&filled, 1.4, 0.0)) && !inked(at(&empty, 2.0, 0.0)), "the filled bucket's drop is larger");
}
assert!(inked(at(&brush, 3.0, 0.0)), "the bristles by the hotspot at {ppp}");
assert!(white(at(&brush, 7.5, 0.0)), "the white ferrule at {ppp}");
assert!(inked(at(&brush, 14.0, 0.0)), "the handle at {ppp}");
assert!(!inked(at(&brush, 11.0, 4.0)), "the brush is thin where the bucket is wide at {ppp}");
assert!(white(at(&empty, 14.0, 0.0)), "the empty bucket has no handle there at {ppp}");
for (c, i) in [(Cursor::LivePaintBucket, &empty), (Cursor::LivePaintBucketFace, &filled), (Cursor::LivePaintBucketEdge, &brush)] {
assert!(c.stand_in().is_none(), "{c:?} is drawn");
assert_ne!(i, &cross, "{c:?} is not the crosshair at {ppp}");
assert_eq!(rasterize(c.precise(), ppp).as_ref(), Some(&cross), "{c:?} with Use Precise Cursors at {ppp}");
}
assert!(empty != filled && filled != brush && empty != brush, "three looks at {ppp}");
}
}
#[test]
fn each_bitmap_is_made_once_so_the_os_cursor_is_kept() {
let mut images = Images::default();
File diff suppressed because it is too large. Load diff
+2
View File
@@ -88,6 +88,7 @@ pub mod perspective_grid;
pub mod perspective_options;
pub mod perspective_plane;
pub mod perspective_presets;
pub mod pixel_snap_options;
pub mod place;
pub mod placement_options;
pub mod plugin;
@@ -452,6 +453,7 @@ registry! {
LayersPanelOptions: [layers_panel_options::KIND] => layers_panel_options::SPEC,
NavigatorPanelOptions: [navigator_panel_options::KIND] => navigator_panel_options::SPEC,
PathfinderOptions: [pathfinder_options::KIND] => pathfinder_options::SPEC,
PixelSnapOptions: [pixel_snap_options::KIND] => pixel_snap_options::SPEC,
RearrangeArtboards: [rearrange_artboards::KIND] => rearrange_artboards::SPEC,
RenameArtboards: [rename_artboards::KIND] => rename_artboards::SPEC,
PathToolOptions: [crate::addons::pathtools::KIND] => crate::addons::pathtools::OPTIONS_SPEC,
Loaded 100 of 157 files, more files were not shown because too many files have changed in this diff. Show more