Merge main into feat/print-overprint-black

This commit is contained in:
dotCooCoo
2026-11-16 19:56:05 -08:00
210 changed files with 12976 additions and 1318 deletions
@@ -0,0 +1,167 @@
//! `cargo run --release -p vectorcraft-engine --example cut_path_select_bench` prints the time
//! Cut Path at Selected Anchor Points takes to select the cut ends, on synthetic documents of 500,
//! 2,000 and 5,000 open paths of 10 anchors each with the 8 anchors between the ends of each
//! direct-selected, and on one path of 2,000 open subpaths selected the same way. For each it times two ways of building the same
//! selection from the cut ends: clearing the selection and adding each path in turn (each add looks
//! through the paths already added), and one `Selection::set` call followed by the anchors. It
//! checks that both give the same selection, every field, before it times them, and then times the
//! whole command once per run on the 2,000-path document.
//! `ITERS` sets the runs per row (default 7); the two ways run in alternating order, each run
//! builds the selection 20 times, and each row is the median time of one build. On Linux the times are the CPU time of the main thread, which runs everything, in
//! ms; elsewhere they are wall times.
// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::hint::black_box;
use std::time::Instant;
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, Node, NodeId, Selection};
use vectorcraft_engine::Session;
use vectorcraft_geom::{Anchor, PathData, Point, SubPath};
/// The anchors of each path, or of each subpath of the one compound path.
const ANCHORS: usize = 10;
/// The builds of the selection in each timed run; a row gives the time of one build.
const REPS: usize = 20;
/// What the command selects for one cut end: the path and its anchor (subpath, anchor).
type Pick = (NodeId, (usize, usize));
/// A way of building the selection from the cut ends.
type Rebuild = fn(&mut Selection, &[Pick]);
fn iters() -> usize {
std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1)
}
fn median(mut ms: Vec<f64>) -> f64 {
ms.sort_by(f64::total_cmp);
ms[ms.len() / 2]
}
/// The CPU time of the calling thread in ns, from `/proc/thread-self/schedstat` (Linux only).
fn thread_cpu_ns() -> Option<u64> {
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
}
/// The time `f` takes, in ms: CPU time where the system reports it, wall time otherwise.
fn measure(f: impl FnOnce()) -> f64 {
match thread_cpu_ns() {
Some(start) => {
f();
thread_cpu_ns().map_or(f64::NAN, |end| end.saturating_sub(start) as f64 / 1e6)
}
None => {
let t = Instant::now();
f();
t.elapsed().as_secs_f64() * 1000.0
}
}
}
/// The selection built by clearing it and adding each path in turn.
fn one_by_one(sel: &mut Selection, picked: &[Pick]) {
sel.clear();
for (id, a) in picked {
sel.add(*id);
sel.anchors.entry(*id).or_default().insert(*a);
}
}
/// The selection built with one `Selection::set` call, as the command builds it.
fn one_call(sel: &mut Selection, picked: &[Pick]) {
sel.set(picked.iter().map(|(id, _)| *id));
for (id, a) in picked {
sel.anchors.entry(*id).or_default().insert(*a);
}
}
fn exec(s: &mut Session, cmd: &str, p: Value) -> Value {
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
}
/// An open subpath of [`ANCHORS`] corner anchors 10 pt apart along row `row`.
fn row(row: usize) -> SubPath {
let y = row as f64 * 20.0;
SubPath::new((0..ANCHORS).map(|i| Anchor::corner(Point::new(i as f64 * 10.0, y))).collect(), false)
}
/// A session with the paths in `paths` and every anchor of theirs but the two ends of each
/// subpath direct-selected (a path with all its anchors selected counts as selected whole).
fn fixture(paths: Vec<PathData>) -> Session {
let mut doc = Document::new(1600.0, 1200.0);
let l = doc.layers.first().map(|l| l.id);
let mut items = vec![];
for pd in paths {
let id = doc.alloc_id();
let refs: Vec<[usize; 2]> =
pd.subpaths.iter().enumerate().flat_map(|(si, sp)| (1..sp.anchors.len().saturating_sub(1)).map(move |ai| [si, ai])).collect();
doc.insert(l, usize::MAX, Node::path(id, pd, Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0))).unwrap();
items.push(json!({"id": id.0, "anchors": refs}));
}
let mut s = Session::new();
s.add_document(doc, None);
exec(&mut s, "select.anchorsMany", json!({"items": items}));
s
}
/// The cut ends the command selects, in the order it selects them: read back from the selection it
/// leaves, which holds each cut path once in that order.
fn picked_after_cut(s: &Session) -> Vec<Pick> {
let sel = &s.doc().unwrap().selection;
sel.objects.iter().flat_map(|id| sel.anchors[id].iter().map(move |a| (*id, *a))).collect()
}
fn bench(name: &str, paths: impl Fn() -> Vec<PathData>) {
let mut s = fixture(paths());
exec(&mut s, "path.cutAtAnchors", json!({}));
let picked = picked_after_cut(&s);
let mut start = Selection::default();
one_by_one(&mut start, &[(NodeId(u64::MAX), (0, 3))]);
let (mut a, mut b) = (start.clone(), start.clone());
one_by_one(&mut a, &picked);
one_call(&mut b, &picked);
assert_eq!(a, b, "both ways give the same selection");
assert_eq!(b, s.doc().unwrap().selection, "the command gives that selection");
let (mut old, mut new) = (vec![], vec![]);
for i in 0..iters() {
let run = |f: Rebuild, out: &mut Vec<f64>| {
let ms = measure(|| {
for _ in 0..REPS {
let mut sel = start.clone();
f(&mut sel, black_box(&picked));
black_box(&sel);
}
});
out.push(ms / REPS as f64);
};
if i % 2 == 0 {
run(one_by_one, &mut old);
run(one_call, &mut new);
} else {
run(one_call, &mut new);
run(one_by_one, &mut old);
}
}
let (old, new) = (median(old), median(new));
println!(" {name:<44} {:>7} {:>6} {old:>12.3} {new:>12.3} {:>8.1}x", picked.len(), b.objects.len(), old / new);
}
fn main() {
let unit = if thread_cpu_ns().is_some() { "CPU ms" } else { "wall ms" };
println!(" {:<44} {:>7} {:>6} {:>12} {:>12} {:>9}", "document", "picked", "ids", format!("add, {unit}"), format!("set, {unit}"), "speedup");
for n in [500, 2_000, 5_000] {
bench(&format!("{n} open paths, {ANCHORS} anchors each"), || (0..n).map(|i| PathData::single(row(i))).collect());
}
bench("one path of 2,000 open subpaths", || vec![PathData::new((0..2_000).map(row).collect())]);
let whole: Vec<f64> = (0..iters())
.map(|_| {
let mut s = fixture((0..2_000).map(|i| PathData::single(row(i))).collect());
measure(|| drop(black_box(exec(&mut s, "path.cutAtAnchors", json!({})))))
})
.collect();
println!(" path.cutAtAnchors, 2,000 open paths, whole command: {:.3} {unit}", median(whole));
}
@@ -0,0 +1,145 @@
//! `cargo run --release -p vectorcraft-engine --example direction_handles_bench` prints the time
//! Select › Object › Direction Handles takes to select every path of documents of 2,000, 10,000 and
//! 20,000 rectangles, spread over two layers with one group. For each size it times, on the same
//! paths and anchors, the selection built one path at a time (a clear, then an add per path) and
//! the selection built with one `Selection::set` call, checks that the two are equal, and then
//! times the whole `select.object.directionHandles` command.
//! On Linux each row is the thread's CPU time, read from `/proc/thread-self/schedstat`; elsewhere
//! it is wall time, and the first line says which. `ITERS` sets the runs per row (default 7); each
//! row is the median in ms. A run of the two selection rows repeats the selection 1,000,000 / paths
//! times and gives the time of one.
// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::collections::BTreeSet;
use std::hint::black_box;
use std::time::Instant;
use serde_json::json;
use vectorcraft_color::Color;
use vectorcraft_doc::{Document, NodeId, Selection};
use vectorcraft_engine::Session;
use vectorcraft_geom::Rect;
use vectorcraft_testkit::fixtures::DocBuilder;
type Items = Vec<(NodeId, BTreeSet<(usize, usize)>)>;
fn iters() -> usize {
std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7)
}
/// The thread's CPU time in ns, or `None` where `/proc/thread-self/schedstat` cannot be read.
fn cpu_ns() -> Option<u64> {
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
}
/// The time `f` takes in ms: CPU time when [`cpu_ns`] reads, wall time otherwise.
fn ms(f: impl FnOnce()) -> f64 {
let (cpu, wall) = (cpu_ns(), Instant::now());
f();
match (cpu, cpu_ns()) {
(Some(a), Some(b)) => (b - a) as f64 / 1e6,
_ => wall.elapsed().as_secs_f64() * 1000.0,
}
}
fn median(mut v: Vec<f64>) -> f64 {
v.sort_by(f64::total_cmp);
v[v.len() / 2]
}
/// `n` 10 pt squares: a tenth of them in one group and the rest loose, half on each of two layers.
fn document(n: usize) -> Document {
let mut b = DocBuilder::new(4000.0, 4000.0);
let square = |b: &mut DocBuilder, i: usize| {
let (x, y) = ((i % 200) as f64 * 12.0, (i / 200) as f64 * 12.0);
b.rect_node(Rect::new(x, y, x + 10.0, y + 10.0), Color::rgb(0.2, 0.4, 0.6))
};
let grouped = n / 10;
let kids = (0..grouped).map(|i| square(&mut b, i)).collect();
b.group(kids, false);
for i in grouped..n {
if i == n / 2 {
b.layer("Layer 2");
}
let node = square(&mut b, i);
b.add(node);
}
b.build()
}
/// Selects `items` one path at a time: a clear, then an add and an anchor insert per path.
fn one_by_one(sel: &mut Selection, items: Items) {
sel.clear();
for (id, refs) in items {
sel.add(id);
sel.anchors.insert(id, refs);
}
}
/// Selects `items` with one `Selection::set` call and one extend of the anchors.
fn with_set(sel: &mut Selection, items: Items) {
sel.set(items.iter().map(|(id, _)| *id));
sel.anchors.extend(items);
}
fn row(name: &str, ms: f64) {
println!(" {name:<44} {ms:>10.3} ms");
}
fn bench(n: usize) {
println!("{n} paths");
let mut s = Session::new();
s.add_document(document(n), None);
s.execute("select.all", &json!({})).unwrap();
let start = s.doc().unwrap().selection.clone();
s.execute("select.object.directionHandles", &json!({})).unwrap();
let command = s.doc().unwrap().selection.clone();
// The paths and anchors the command selects, in its order.
let items: Items = command.objects.iter().map(|id| (*id, command.anchors[id].clone())).collect();
assert_eq!(items.len(), n);
// Each run selects `reps` times, on copies made before the clock starts, and gives the time of one.
let reps = (1_000_000 / n).max(1);
let time = |f: fn(&mut Selection, Items)| -> (f64, Selection) {
let mut last = Selection::default();
let runs = (0..iters())
.map(|_| {
let mut work: Vec<(Selection, Items)> = (0..reps).map(|_| (start.clone(), items.clone())).collect();
let t = ms(|| {
for (sel, it) in &mut work {
f(sel, black_box(std::mem::take(it)));
}
});
last = work.pop().unwrap().0;
t / reps as f64
})
.collect();
(median(runs), last)
};
let (old, a) = time(one_by_one);
let (new, b) = time(with_set);
assert_eq!(a, b, "both ways give the same selection");
let mut want = start.clone();
with_set(&mut want, items.clone());
assert_eq!(want.objects, command.objects);
assert_eq!(want.anchors, command.anchors);
row("selection, one add per path", old);
row("selection, one set call", new);
println!(" {:<44} {:>10.1}x", "ratio", old / new);
let runs = (0..iters())
.map(|_| {
s.execute("select.all", &json!({})).unwrap();
ms(|| drop(black_box(s.execute("select.object.directionHandles", &json!({})).unwrap())))
})
.collect();
row("select.object.directionHandles, whole command", median(runs));
}
fn main() {
println!("{}", if cpu_ns().is_some() { "thread CPU time, median of runs" } else { "wall time, median of runs" });
for n in [2_000, 10_000, 20_000] {
bench(n);
}
}
+17 -8
View File
@@ -4,6 +4,8 @@
//! be edited, selected or not. What it removes is worked out by
//! [`vectorcraft_tools::addons::trim::plan`], which the tool also uses to show it beforehand.
use std::collections::HashSet;
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_geom::{Point, Rect};
@@ -100,20 +102,21 @@ fn trim(s: &mut Session, p: &Value) -> Result<Value> {
compounds.dedup();
let mut beside = Beside::replacing(d, &trimmed);
let mut all = vec![];
// The selection is read through a set and changed once at the end, so a trim of many
// paths does not go through the selected objects once per path and per piece.
let mut selected_ids: HashSet<NodeId> = sel.objects.iter().copied().collect();
let mut joining: Vec<NodeId> = vec![];
let mut gone: Vec<NodeId> = vec![];
for (id, pieces) in plan {
let selected = sel.contains(id);
let selected = selected_ids.contains(&id);
sel.anchors.remove(&id);
sel.segments.remove(&id);
let made = replace_with_pieces(d, &mut beside, id, pieces)?;
// The pieces of a selected path are selected; what was not selected stays so.
if made.is_empty() {
sel.remove(id);
gone.push(id);
} else if selected {
for n in &made {
if !sel.contains(*n) {
sel.add(*n);
}
}
joining.extend(made.iter().copied().filter(|n| selected_ids.insert(*n)));
}
all.extend(made);
}
@@ -121,9 +124,15 @@ fn trim(s: &mut Session, p: &Value) -> Result<Value> {
for c in compounds {
if d.node(c).is_some_and(|n| n.children().is_some_and(|ch| ch.is_empty())) {
d.remove(c)?;
sel.remove(c);
gone.push(c);
}
}
sel.remove_all(gone);
if let Some((first, rest)) = joining.split_first() {
// `add` clears what any change to the object selection clears; the rest are new ids.
sel.add(*first);
sel.objects.extend_from_slice(rest);
}
Ok(all)
})?;
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "removed": removed }))
@@ -2,8 +2,9 @@
//! one undo step, and what takes no part.
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_doc::{NodeId, NodeKind, Selection};
use vectorcraft_geom::{PathData, Point};
use vectorcraft_tools::addons::trim::plan::{self, Limits, Stretches};
use crate::Session;
@@ -420,6 +421,139 @@ fn the_selection_stays_as_it_was_and_the_pieces_of_a_selected_path_are_selected(
assert!(s.doc().unwrap().selection.is_empty(), "a removed path leaves the selection");
}
/// Run the command with `p`, and check that it leaves the selection exactly as changing it one
/// id at a time does: for each trimmed path in the plan's order, its anchors and segments let go,
/// a path with no pieces left removed, and each piece of a selected path added; then each emptied
/// compound path removed. Returns the selection.
fn same_selection_as_one_id_at_a_time(s: &mut Session, p: Value) -> Selection {
let st = s.doc().unwrap();
let pick = super::pick(&p).unwrap();
let root = crate::cmd::ordinary_isolation(st);
let plan: Vec<(NodeId, usize)> =
plan::plan(&st.doc, root, &pick, Limits::COMMAND, &mut Stretches::default()).unwrap().into_iter().map(|t| (t.id, t.pieces.len())).collect();
let mut compounds: Vec<NodeId> = plan
.iter()
.filter_map(|(id, _)| st.doc.parent_of(*id))
.filter(|c| matches!(st.doc.node(*c).map(|n| &n.kind), Some(NodeKind::Compound { .. })))
.collect();
compounds.dedup();
let mut want = st.selection.clone();
let made = ids(&s.execute(TRIM, &p).unwrap());
assert_eq!(made.len(), plan.iter().map(|(_, n)| n).sum::<usize>());
let mut made = made.into_iter();
for (id, n) in plan {
let selected = want.contains(id);
want.anchors.remove(&id);
want.segments.remove(&id);
let pieces: Vec<NodeId> = made.by_ref().take(n).collect();
if pieces.is_empty() {
want.remove(id);
} else if selected {
for piece in pieces {
if !want.contains(piece) {
want.add(piece);
}
}
}
}
let st = s.doc().unwrap();
for c in compounds {
if st.doc.node(c).is_none() {
want.remove(c);
}
}
want.prune(&st.doc);
assert_eq!(st.selection, want);
st.selection.clone()
}
/// Two lines across split by a rectangle, one of them selected; a selected line nothing crosses
/// and a selected compound path of two such lines, which the rectangle removes whole; and a
/// selected line elsewhere with an anchor and a segment direct-selected. Returns (the selected
/// line across, the line removed whole, the compound path, the line elsewhere).
fn trim_scene(s: &mut Session) -> (NodeId, NodeId, NodeId, NodeId) {
let (h, ..) = across_and_uprights(s);
line(s, &[(0.0, 120.0), (300.0, 120.0)], false);
let alone = line(s, &[(145.0, 200.0), (155.0, 200.0)], false);
let c1 = line(s, &[(145.0, 170.0), (155.0, 170.0)], false);
let c2 = line(s, &[(145.0, 180.0), (155.0, 180.0)], false);
s.execute("select.set", &json!({"ids": [c1.0, c2.0]})).unwrap();
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let elsewhere = line(s, &[(0.0, 250.0), (10.0, 250.0), (20.0, 250.0)], false);
s.execute("select.set", &json!({"ids": [elsewhere.0, h.0, alone.0, compound.0]})).unwrap();
s.edit("direct", |_, sel| {
sel.anchors.insert(elsewhere, [(0, 1)].into());
sel.anchors.insert(h, [(0, 0)].into());
sel.segments.insert(elsewhere, [(0, 0)].into());
Ok(())
})
.unwrap();
(h, alone, compound, elsewhere)
}
#[test]
fn the_selection_after_a_trim_is_the_one_changing_it_one_id_at_a_time_gives() {
// A removed key object stops being the key.
let mut s = session();
let (h, alone, compound, elsewhere) = trim_scene(&mut s);
s.edit("key", |_, sel| {
sel.key = Some(alone);
Ok(())
})
.unwrap();
let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 90, 20, 120]}));
assert_eq!(sel.key, None);
assert!(!sel.contains(alone) && !sel.contains(compound));
assert_eq!(&sel.objects[..2], [elsewhere, h]);
assert_eq!(sel.objects.len(), 3, "{:?}", sel.objects);
assert!(sel.anchors.contains_key(&elsewhere) && sel.segments.contains_key(&elsewhere) && !sel.anchors.contains_key(&h));
// A key object that keeps its first piece stays the key.
let mut s = session();
let (h, alone, compound, _) = trim_scene(&mut s);
s.edit("key", |_, sel| {
sel.key = Some(h);
Ok(())
})
.unwrap();
let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 90, 20, 120]}));
assert_eq!(sel.key, Some(h));
assert!(!sel.contains(alone) && !sel.contains(compound));
// Trimming only paths that are not selected leaves a targeted object targeted.
let mut s = session();
let (h, _, _, elsewhere) = trim_scene(&mut s);
s.execute("select.set", &json!({"ids": [elsewhere.0]})).unwrap();
s.edit("target", |_, sel| {
sel.target = Some(elsewhere);
Ok(())
})
.unwrap();
let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 90, 20, 40]}));
assert_eq!((sel.objects.as_slice(), sel.target), ([elsewhere].as_slice(), Some(elsewhere)));
assert!(exists(&s, h));
// A selected path that gains a piece changes the object selection, which lets go of the target.
let mut s = session();
let (h, _, _, elsewhere) = trim_scene(&mut s);
s.execute("select.set", &json!({"ids": [elsewhere.0, h.0]})).unwrap();
s.edit("target", |_, sel| {
sel.target = Some(elsewhere);
Ok(())
})
.unwrap();
let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 90, 20, 40]}));
assert_eq!((sel.objects.len(), sel.target), (3, None));
// So does a selected path that is removed whole.
let mut s = session();
let (_, alone, _, elsewhere) = trim_scene(&mut s);
s.execute("select.set", &json!({"ids": [elsewhere.0, alone.0]})).unwrap();
s.edit("target", |_, sel| {
sel.target = Some(elsewhere);
Ok(())
})
.unwrap();
let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 190, 20, 20]}));
assert_eq!((sel.objects.as_slice(), sel.target), ([elsewhere].as_slice(), None));
}
#[test]
fn many_paths_far_from_the_trimmed_one_cost_no_crossing_search() {
let mut s = session();
+92 -2
View File
@@ -5,15 +5,16 @@ use super::{
// ---------- brushes ----------
/// Brushable nodes (paths and compound paths) under `ids`.
/// Brushable nodes (paths and compound paths) under `ids`, in walk order, each listed once where it is first reached.
pub(crate) fn brush_targets(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
let mut out = vec![];
let mut seen = std::collections::HashSet::new();
for id in ids {
let Some(n) = d.node(*id) else { continue };
n.walk(&mut |c| {
let own = matches!(c.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. });
let in_compound = d.parent_of(c.id).and_then(|p| d.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. }));
if own && !in_compound && !out.contains(&c.id) {
if own && !in_compound && seen.insert(c.id) {
out.push(c.id);
}
});
@@ -748,3 +749,92 @@ pub(super) fn brush_freehand(s: &mut Session, p: &Value) -> Result<Value> {
let checked = crate::schemas::check(spec, p, s.replaying())?;
crate::cmd::draw2::freehand_brushed(s, checked.as_ref().unwrap_or(p), name.as_deref())
}
#[cfg(test)]
mod tests {
use super::*;
use vectorcraft_doc::Appearance;
use vectorcraft_geom::PathData;
/// The collector with a linear search of its output, kept to compare results with.
fn listed_targets(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
let mut out = vec![];
for id in ids {
let Some(n) = d.node(*id) else { continue };
n.walk(&mut |c| {
let own = matches!(c.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. });
let in_compound = d.parent_of(c.id).and_then(|p| d.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. }));
if own && !in_compound && !out.contains(&c.id) {
out.push(c.id);
}
});
}
out
}
fn path(d: &mut Document) -> Node {
Node::path(d.alloc_id(), PathData::default(), Appearance::default())
}
fn compound(d: &mut Document, children: Vec<Node>) -> Node {
Node::new(d.alloc_id(), NodeKind::Compound { children: children.into_iter().map(Arc::new).collect(), rule: Default::default() })
}
fn add(d: &mut Document, node: Node) -> NodeId {
let layer = d.layers.first().map(|l| l.id);
d.insert(layer, usize::MAX, node).unwrap()
}
#[test]
fn brush_targets_list_each_target_once_in_first_reached_order() {
let mut d = Document::new(400.0, 300.0);
let a = path(&mut d);
let a = add(&mut d, a);
let mut guide = path(&mut d);
if let NodeKind::Path { guide: g, .. } = &mut guide.kind {
*g = true;
}
let guide = add(&mut d, guide);
let mut clip = path(&mut d);
if let NodeKind::Path { clipping, .. } = &mut clip.kind {
*clipping = true;
}
let clip = add(&mut d, clip);
// A group holding a path and a compound path of two members.
let p1 = path(&mut d);
let p1_id = p1.id;
let (m1, m2) = (path(&mut d), path(&mut d));
let m1_id = m1.id;
let cp1 = compound(&mut d, vec![m1, m2]);
let cp1_id = cp1.id;
let group = Node::group(d.alloc_id(), vec![Arc::new(p1), Arc::new(cp1)]);
let group = add(&mut d, group);
// A compound path holding a compound path.
let m3 = path(&mut d);
let cp3 = compound(&mut d, vec![m3]);
let cp3_id = cp3.id;
let cp2 = compound(&mut d, vec![cp3]);
let cp2 = add(&mut d, cp2);
let ids = [cp1_id, a, group, p1_id, a, guide, clip, m1_id, cp2, cp3_id, NodeId(u64::MAX)];
let got = brush_targets(&d, &ids);
assert_eq!(got, [cp1_id, a, p1_id, cp2], "repeats keep their first place; guides, clipping paths and compound members are left out");
assert_eq!(got, listed_targets(&d, &ids));
assert!(brush_targets(&d, &[]).is_empty());
// Many paths in groups, each group listed with some of its members.
let mut ids = vec![];
for _ in 0..50 {
let members: Vec<Node> = (0..20).map(|_| path(&mut d)).collect();
let member_ids: Vec<NodeId> = members.iter().map(|m| m.id).collect();
let g = Node::group(d.alloc_id(), members.into_iter().map(Arc::new).collect());
let g = add(&mut d, g);
ids.push(member_ids[7]);
ids.push(g);
ids.push(member_ids[3]);
}
let got = brush_targets(&d, &ids);
assert_eq!(got.len(), 50 * 20);
assert_eq!(got, listed_targets(&d, &ids));
}
}
+94 -7
View File
@@ -57,6 +57,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
flare
),
cmd!(
"shape.circleThroughPoints",
"Circle Through Points",
[],
None,
"{points?: [[x, y], [x, y], [x, y]] (left out: the three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the three points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same or three on one line are an error, and nothing is drawn",
has_doc,
circle_through_points
),
cmd!("shape.line", "Line Segment", [], None, "{x1, y1, x2, y2, fill?: bool (Fill Line: the current fill, else none)} → {id}", has_doc, line),
cmd!("shape.spiral", "Spiral", [], None, "{cx, cy, radius, decay=80 (%), segments=10, clockwise?} → {id}", has_doc, spiral),
cmd!(
@@ -131,14 +140,21 @@ pub(crate) fn add_look(s: &mut Session, label: &str, kind: NodeKind, look: NewAr
/// [`add_look`] that selects the new object only when `select` is set; otherwise the selection
/// stays as it was.
pub(crate) fn insert_look(s: &mut Session, label: &str, kind: NodeKind, look: NewArt, name: Option<String>, select: bool) -> Result<Value> {
insert_look_turned(s, label, kind, look, name, select, 0.0)
insert_look_turned(s, label, kind, look, name, select, 0.0, true)
}
/// [`add_art`] for an object made turned by a `rotation` param (degrees, clockwise on the page):
/// its bounding box turns with it, as after the Rotate tool.
fn add_art_turned(s: &mut Session, label: &str, kind: NodeKind, rotation: f64) -> Result<Value> {
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
insert_look_turned(s, label, kind, look, None, true, bbox_turn(rotation))
insert_look_turned(s, label, kind, look, None, true, bbox_turn(rotation), true)
}
/// [`add_art`] for an object whose geometry must stay where it was computed: it is not
/// pixel-aligned, even while the document's Align New Objects to Pixel Grid is on.
fn add_art_unaligned(s: &mut Session, label: &str, kind: NodeKind) -> Result<Value> {
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
insert_look_turned(s, label, kind, look, None, true, 0.0, false)
}
/// The bounding-box angle (counter-clockwise, as `Node::bbox_angle` and the Rotate tool keep it)
@@ -162,8 +178,10 @@ fn constrained_turn(s: &Session, rotation: f64) -> f64 {
}
}
/// [`insert_look`] with the new object's bounding box turned to `bbox_angle`. A new path or
/// compound path is pixel-aligned while the document's Align New Objects to Pixel Grid is on.
/// [`insert_look`] with the new object's bounding box turned to `bbox_angle`. With `align`, a new
/// path or compound path is pixel-aligned while the document's Align New Objects to Pixel Grid is
/// on.
#[allow(clippy::too_many_arguments)]
fn insert_look_turned(
s: &mut Session,
label: &str,
@@ -172,6 +190,7 @@ fn insert_look_turned(
name: Option<String>,
select: bool,
bbox_angle: f64,
align: bool,
) -> Result<Value> {
let parent = s.doc()?.target_parent()?;
let mode = s.draw_mode;
@@ -181,7 +200,9 @@ fn insert_look_turned(
let id = d.alloc_id();
let mut n = Node::new(id, kind);
look.apply(d, &mut n);
super::object::align_new_object(d, &mut n);
if align {
super::object::align_new_object(d, &mut n);
}
n.name = name;
n.bbox_angle = bbox_angle;
let mut into = None;
@@ -390,6 +411,71 @@ fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), rotation)
}
/// A live ellipse whose edge passes through three points: `points`, or the three selected anchor
/// points ([`selected_anchor_points`]). One undo step, named as an Ellipse tool drag is.
fn circle_through_points(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "shape.circleThroughPoints";
let points = match p.get("points").filter(|v| !v.is_null()) {
Some(v) => three_points(v).ok_or_else(|| bad(C, "`points` must be three [x, y] pairs of numbers"))?,
None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select three anchor points, or give `points`"))?,
};
let [a, b, c] = points;
let (center, radius) = shapes::circle_through(a, b, c)
.ok_or_else(|| bad(C, "no circle passes through these points: two are the same or all three lie on one line"))?;
let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
// Not pixel-aligned: the circle stays through the points.
let mut out = add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?;
out["cx"] = json!(center.x);
out["cy"] = json!(center.y);
out["radius"] = json!(radius);
Ok(out)
}
/// The three points `[[x, y], [x, y], [x, y]]` holds, each pair two finite numbers.
fn three_points(v: &Value) -> Option<[Point; 3]> {
let pair = |v: &Value| match v.as_array().map(Vec::as_slice) {
Some([x, y]) => x.as_f64().zip(y.as_f64()).filter(|(x, y)| x.is_finite() && y.is_finite()).map(|(x, y)| Point::new(x, y)),
_ => None,
};
match v.as_array().map(Vec::as_slice) {
Some([a, b, c]) => Some([pair(a)?, pair(b)?, pair(c)?]),
_ => None,
}
}
/// The positions of the selected anchor points, when there are exactly three. They are counted as
/// the other anchor commands count them ([`super::path::anchor_targets`]): a selected path with
/// anchors picked by Direct Selection gives those, and a path selected whole gives all of its own.
/// A selected segment's ends are not selected anchor points, so a selection with segments gives
/// none; so does a selection holding an object that is not a path, or an anchor that is gone.
fn selected_anchor_points(s: &Session) -> Result<Option<[Point; 3]>> {
let st = s.doc()?;
if st.selection.segments.values().any(|set| !set.is_empty()) {
return Ok(None);
}
let mut points = Vec::with_capacity(4);
for id in &st.selection.objects {
let Some(pd) = st.doc.node(*id).and_then(|n| n.path_data()) else { return Ok(None) };
match st.selection.anchors.get(id) {
Some(set) => {
for &(si, ai) in set.iter().take(4) {
let Some(a) = pd.subpaths.get(si).and_then(|sp| sp.anchors.get(ai)) else { return Ok(None) };
points.push(a.p);
}
}
None => points.extend(pd.anchors().take(4).map(|(_, _, a)| a.p)),
}
if points.len() > 3 {
return Ok(None);
}
}
Ok(match points.as_slice() {
&[a, b, c] => Some([a, b, c]),
_ => None,
})
}
/// The whole-number count `p` gives for `key` (`5` or `5.0`), or `default` when it is left out or
/// null. A fraction, a negative, a non-finite or a non-number is an error rather than the default.
fn count_or(p: &Value, key: &str, default: u64, cmd: &str) -> Result<u64> {
@@ -651,7 +737,7 @@ fn arc(s: &mut Session, p: &Value) -> Result<Value> {
if s.paint.stroke.is_none() { vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) } else { s.paint.stroke.clone() },
s.paint.stroke_width.max(0.1),
);
insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, bbox_angle)
insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, bbox_angle, true)
}
/// The grid `paths` (bottom first) as one selected group in the new-art stroke, filled with the
@@ -831,7 +917,8 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
// Lays the text out (and sizes an Auto Size frame).
super::typecmd::refresh_bounds(&mut t);
}
let made = insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation))?;
let made =
insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation), true)?;
let id = made.get("id").and_then(Value::as_u64).map(NodeId);
let made = super::typecmd::with_bounds(s, id, made);
let mut made = super::typecmd::with_overflow(s, id.as_slice(), made);
+12 -8
View File
@@ -6,7 +6,7 @@ use std::collections::{BTreeSet, HashMap, HashSet};
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{CharStyle, Guide, Node, NodeId, NodeKind, SavedSelection, TextKind};
use vectorcraft_doc::{CharStyle, Guide, Node, NodeId, NodeKind, SavedSelection, Selection, TextKind};
use vectorcraft_geom::Vec2;
use super::edit::selected_roots;
@@ -495,16 +495,17 @@ fn direction_handles(s: &mut Session, _: &Value) -> Result<Value> {
}
}
let total: usize = items.iter().map(|x| x.1.len()).sum();
s.select(|_, sel| {
sel.clear();
for (id, refs) in items {
sel.add(id);
sel.anchors.insert(id, refs);
}
})?;
s.select(|_, sel| select_anchors(sel, items))?;
Ok(json!({ "anchors": total }))
}
/// Replaces `sel` with the paths of `items` in order, each once, and direct-selects the anchors
/// listed with each path. A path listed twice keeps its first place and its last anchor set.
fn select_anchors(sel: &mut Selection, items: Vec<(NodeId, BTreeSet<(usize, usize)>)>) {
sel.set(items.iter().map(|(id, _)| *id));
sel.anchors.extend(items);
}
fn save_selection(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "select.save";
let st = s.doc()?;
@@ -1026,3 +1027,6 @@ fn close_all(s: &mut Session, _: &Value) -> Result<Value> {
}
Ok(json!({ "closed": n }))
}
#[cfg(test)]
mod tests;
+68
View File
@@ -0,0 +1,68 @@
//! The selection that Select ▸ Object ▸ Direction Handles builds.
use std::collections::{BTreeSet, HashSet};
use std::sync::Arc;
use vectorcraft_doc::{NodeId, Selection, SymbolPart};
use super::select_anchors;
type Items = Vec<(NodeId, BTreeSet<(usize, usize)>)>;
/// Selects `items` one path at a time: a clear, then an add and an anchor insert per path.
fn one_by_one(sel: &mut Selection, items: Items) {
sel.clear();
for (id, refs) in items {
sel.add(id);
sel.anchors.insert(id, refs);
}
}
/// A selection with every field set, as one left by earlier selecting.
fn busy() -> Selection {
let mut sel = Selection::default();
sel.set([NodeId(90), NodeId(91)]);
sel.anchors.insert(NodeId(90), BTreeSet::from([(0, 0)]));
sel.segments.insert(NodeId(91), BTreeSet::from([(0, 1)]));
sel.key = Some(NodeId(91));
sel.target = Some(NodeId(92));
sel.slices = vec![NodeId(93)];
sel.guides = vec![NodeId(94)];
sel.key_guide = Some(NodeId(94));
sel.key_anchor = Some((NodeId(90), (0, 0)));
sel.symbol_part = Some(SymbolPart { instance: NodeId(95), path: vec![0, 1] });
sel.on_path_member = Some(NodeId(96));
sel.new_art = Arc::new(HashSet::from([NodeId(97)]));
sel
}
fn refs(n: usize) -> BTreeSet<(usize, usize)> {
(0..n).map(|i| (0, i)).collect()
}
#[test]
fn select_anchors_gives_the_selection_one_by_one_selecting_gives() {
let cases: Vec<Items> = vec![
vec![],
vec![(NodeId(1), refs(4))],
(1..=500).map(|i| (NodeId(i), refs(4))).collect(),
// A path listed again keeps its first place and its last anchors.
vec![(NodeId(3), refs(1)), (NodeId(1), refs(4)), (NodeId(3), refs(2)), (NodeId(2), BTreeSet::new()), (NodeId(1), refs(3))],
];
for items in cases {
for start in [Selection::default(), busy()] {
let (mut want, mut got) = (start.clone(), start);
one_by_one(&mut want, items.clone());
select_anchors(&mut got, items.clone());
assert_eq!(got, want, "{items:?}");
}
}
let mut got = busy();
select_anchors(&mut got, vec![(NodeId(3), refs(1)), (NodeId(1), refs(4)), (NodeId(3), refs(2))]);
assert_eq!(got.objects, vec![NodeId(3), NodeId(1)]);
assert_eq!(got.anchors[&NodeId(3)], refs(2));
assert!(got.segments.is_empty() && got.slices.is_empty() && got.guides.is_empty());
assert_eq!((got.key, got.target, got.key_guide, got.key_anchor, got.on_path_member), (None, None, None, None, None));
assert!(got.symbol_part.is_none());
assert_eq!(*got.new_art, HashSet::from([NodeId(97)]), "selecting leaves the new-art list alone");
}
+1 -3
View File
@@ -399,9 +399,7 @@ fn select_found(s: &mut Session, p: &Value, ids: &[NodeId]) -> Result<Value> {
let compound = |n: &Node| matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. });
let members = st.isolation.and_then(|i| st.doc.ancestry(i)).is_some_and(|a| a.iter().any(|i| st.doc.node(*i).is_some_and(compound)));
let found: BTreeSet<NodeId> = ids.iter().copied().collect();
super::select::select_where(s, "document.find", p, |d, n| {
found.contains(&n.id) && (members || !d.parent_of(n.id).and_then(|p| d.node(p)).is_some_and(compound))
})
super::select::select_where(s, "document.find", p, |_, n, parent| found.contains(&n.id) && (members || !parent.is_some_and(compound)))
}
/// Render an artboard at an image's size, drawn as a PNG export draws it (linked images and placed
+67 -26
View File
@@ -1040,7 +1040,8 @@ impl RasterBudget {
/// of their own. Random in a Transform effect takes its seed from the id, and the canvas draws the
/// pieces with the ids they have before that. `kept` gets the new id of each object in them that
/// had an id `skip` lists before. Returns what each of those other members' expansions lists, by
/// the member's new id.
/// the member's new id. `Err` when such a member still holds a random Transform effect after the
/// raster budget left part of it as it is: its new ids would give that effect another seed.
#[allow(clippy::too_many_arguments)]
fn expand_pieces(
d: &mut Document,
@@ -1051,7 +1052,7 @@ fn expand_pieces(
kept: &mut Vec<NodeId>,
stroke_art: effects::StrokeArt,
raster: &mut RasterBudget,
) -> std::collections::HashMap<NodeId, Vec<Listed>> {
) -> std::result::Result<std::collections::HashMap<NodeId, Vec<Listed>>, OverBudget> {
let id = m.id;
let mut seen = std::collections::HashSet::from([id]);
let mut expanded = std::collections::HashMap::new();
@@ -1065,7 +1066,12 @@ fn expand_pieces(
if all || c.id == id {
effects::expand_art(d, c, stroke_art);
} else if has_seeded(c) && repeats_an_id(c, &seen) {
listed = Some(expand_in_place(d, c, brushes, skip, raster));
let left = raster.left;
let expanded = expand_in_place(d, c, brushes, skip, raster);
if raster.left > left && has_seeded(c) {
return Err(OverBudget);
}
listed = Some(expanded);
}
let mut was = vec![];
if !skip.is_empty() {
@@ -1086,7 +1092,7 @@ fn expand_pieces(
expanded.insert(c.id, listed);
}
}
expanded
Ok(expanded)
}
/// `m`, the art a 3D effect expanded into, with each object in it that has effects of its own (a
@@ -1301,6 +1307,19 @@ fn carries_copies(n: &Node) -> bool {
is_container(n) && effects::outer_effects(n).len() != n.appearance.effects.len()
}
/// Does `n`, something in it, or the art of the symbol it places when a color adjustment makes it
/// that art, hold a random Transform effect ([`has_seeded`])? The raster budget can then leave `n`
/// as it is after part of it expanded ([`expand_pieces`], Crop Marks).
fn holds_seeded(d: &Document, n: &Node) -> bool {
has_seeded(n)
|| match &n.kind {
NodeKind::SymbolInstance { symbol, .. } if effects::has_adjustment(n) => {
d.symbols.iter().find(|s| s.name == *symbol).is_some_and(|s| has_seeded(&s.art))
}
_ => false,
}
}
/// [`expand_node`] of `n`, which need not be in `d`: `n` with its appearance expanded, `None` when
/// it has nothing to expand. `out` gets the objects whose appearance expands, by places in the walk
/// of the expanded `n`, `n`'s first when its own does. The objects `skip` lists are not expanded.
@@ -1331,12 +1350,22 @@ fn expanded_node(
_ => None,
};
// The embedded images before the adjustment and the expansions of the copies
// ([`copies_carrying_raster`]), when the raster budget may yet leave `n` as it is: the
// recolored copies and the images those add then go again.
let images_before = ((effects::has_adjustment(&n) && !rasterfx::raster_fx(&n).is_empty()) || carries_copies(&n))
// ([`copies_carrying_raster`]) and of the members that hold a random Transform effect, when the
// raster budget may yet leave `n` as it is: the recolored copies and the images those add then
// go again.
let images_before = ((effects::has_adjustment(&n) && !rasterfx::raster_fx(&n).is_empty()) || carries_copies(&n) || holds_seeded(d, &n))
.then(|| d.images.keys().cloned().collect::<std::collections::HashSet<_>>());
// What the raster budget had left before those expansions: it gets back what they took.
let budget_before = (raster.images, raster.pixels);
// `n` stays as it is: `out` lists nothing of it, and the document and the raster budget lose
// what expanding it added and took.
let leave = |d: &mut Document, out: &mut Vec<Listed>, raster: &mut RasterBudget| {
out.truncate(listed_before);
if let Some(keys) = &images_before {
d.images.retain(|k, _| keys.contains(k));
}
(raster.images, raster.pixels) = budget_before;
};
if effects::has_adjustment(&n)
&& let Some(m) = effects::adjust_in_document(d, &n, symbol_art)
{
@@ -1352,14 +1381,21 @@ fn expanded_node(
let container = is_container(&n);
// Crop Marks: the object and its marks become a group. The object expands on its own first,
// with `id`: the canvas draws it with that id, which Random in a Transform effect takes its
// seed from. Then the object and the marks get ids of their own.
// seed from. Then the object and the marks get ids of their own. When the raster budget leaves
// a random Transform effect in the object, `n` stays as it is: new ids would give that effect
// another seed.
if let Some(mut m) = effects::crop_marks_art(&n) {
let mut seen = std::collections::HashSet::from([id]);
let mut expanded = vec![];
for (i, c) in m.children_mut().into_iter().flatten().enumerate() {
let c = Arc::make_mut(c);
if i == 0 {
let left = raster.left;
expanded = expand_in_place(d, c, brushes, skip, raster);
if raster.left > left && has_seeded(c) {
leave(d, out, raster);
return None;
}
fresh_ids_listed(d, c, &mut seen, &mut expanded);
} else {
effects::fresh_ids(d, c, &mut seen);
@@ -1390,16 +1426,13 @@ fn expanded_node(
let copies = copies_carrying_raster(d, &mut n, (brushes, skip), &mut kept, &mut members, (out, &mut listed_n), raster);
// Raster effects whose image would go past the budget stay: so does the object, with what is
// inside it and its color adjustments (a symbol instance stays an instance of its symbol), and
// so does a group or layer whose copies keep a random Transform effect the budget left.
// so does a group or layer whose copies or members keep a random Transform effect the budget
// left.
let Ok(image) = copies.and_then(|copied| {
changed |= copied;
raster_image(d, &n, raster)
}) else {
out.truncate(listed_before);
if let Some(keys) = images_before {
d.images.retain(|k, _| keys.contains(k));
}
(raster.images, raster.pixels) = budget_before;
leave(d, out, raster);
return None;
};
let mut v = n.clone();
@@ -1413,18 +1446,20 @@ fn expanded_node(
image => {
let m = if (container || matches!(n.kind, NodeKind::Text(_))) && (effects::has_solid(&v) || effects::has_revolve(&v)) {
// A 3D effect on a group or layer, or on type: the shaded faces of its solids.
effects::expand_leaf(d, &v, &mut stroke_art)
Ok::<_, OverBudget>(effects::expand_leaf(d, &v, &mut stroke_art))
} else if container {
// A group's or layer's own fills and strokes become art among its members.
effects::evaluate_container(Some(&*d), &v).map(|mut m| {
members.extend(expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art, raster));
m
})
effects::evaluate_container(Some(&*d), &v)
.map(|mut m| {
members.extend(expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art, raster)?);
Ok(m)
})
.transpose()
} else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
&& !effects::has_transform_art(&v)
&& !effects::has_transform_copies(&v)
{
effects::expand_leaf(d, &v, &mut stroke_art)
Ok(effects::expand_leaf(d, &v, &mut stroke_art))
} else {
// Type, images, symbol instances, live objects (and paths whose Transform effect copies
// them, each copy an object of its own, or changes their fills and strokes): through
@@ -1440,12 +1475,18 @@ fn expanded_node(
let row_raster = image.is_some() && effects::has_instance_row_raster(&n);
let outlined = effects::expand_outlined(Some(&*d), &v, symbol.as_ref())
.or_else(|| if row_raster { effects::instance_as_art(Some(&*d), &v, symbol.as_ref()) } else { None });
outlined.map(|mut m| {
let mut budget = vectorcraft_doc::MAX_SYMBOL_NODES;
expand_nested_instances(d, &mut m, 1, &mut budget, raster);
expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art, raster);
m
})
outlined
.map(|mut m| {
let mut budget = vectorcraft_doc::MAX_SYMBOL_NODES;
expand_nested_instances(d, &mut m, 1, &mut budget, raster);
expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art, raster)?;
Ok(m)
})
.transpose()
};
let Ok(m) = m else {
leave(d, out, raster);
return None;
};
// A 3D effect's shadow blurred by the light's Softness keeps its blur in the art: it
// expands in turn, to an image.
+87
View File
@@ -1189,3 +1189,90 @@ fn copies_the_raster_budget_leaves_keep_their_random_moves() {
assert_eq!((budget.images, budget.pixels), (images, u64::MAX), "{images}: the budget gets back what the copies took");
}
}
/// A group whose Transform effect copies its symbol instance, which has a drop shadow and a random
/// Transform effect that takes its seed from the instance's id: each copy's instance has that id.
/// When the raster budget has no image left for a copy's shadow, with none left or with one for the
/// first copy's, the group stays as it is: the copies keep the ids their random moves are drawn
/// with, the group draws as before, and the document holds no image the first copy's expansion
/// made, nor the budget its charge. With the whole budget, the group expands and each object gets
/// an id of its own.
#[test]
fn a_member_the_raster_budget_leaves_keeps_its_random_move() {
let (mut s, id) = session_with_rect();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let id = NodeId(s.execute("symbol.new", &json!({"name": "Box"})).unwrap()["id"].as_u64().unwrap());
let shadow = json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"});
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "stylize.dropShadow", "params": shadow})).unwrap();
let random = json!({"moveH": 40, "moveV": 40, "random": true});
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "distort.transform", "params": random})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("effect.apply", &json!({"ids": [g.0], "effect": "distort.transform", "params": {"moveV": 150, "copies": 1}})).unwrap();
let draw = |d: &vectorcraft_doc::Document| {
vectorcraft_render::Renderer::new().render(d, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels
};
for images in [0, 1, 1_024] {
let mut d = s.doc().unwrap().doc.as_ref().clone();
let before = d.node(g).cloned().unwrap();
assert!(effects::outer_effects(&before).len() == before.appearance.effects.len(), "the copies carry no shadow of the group's");
let art = effects::evaluate_container(Some(&d), &before).unwrap();
let mut instances = 0;
art.walk(&mut |n| instances += usize::from(n.id == id && super::has_seeded(n)));
assert!(instances >= 2, "{images}: each copy's instance has the id and its random effect: {instances}");
let (drawn, keys) = (draw(&d), d.images.keys().cloned().collect::<Vec<_>>());
let mut budget = super::RasterBudget { images, pixels: u64::MAX, left: 0 };
let mut out = vec![];
super::expand_node(&mut d, g, &[], &mut out, &mut budget);
if images < 2 {
assert!(budget.left > 0, "{images}: a shadow is left");
assert!(out.is_empty(), "{images}: nothing expands: {out:?}");
assert_eq!(d.node(g), Some(&before), "{images}: the group stays as it is");
assert!(draw(&d) == drawn, "{images}: the group draws as before");
assert_eq!(d.images.keys().cloned().collect::<Vec<_>>(), keys, "{images}: no image is added");
assert_eq!((budget.images, budget.pixels), (images, u64::MAX), "{images}: the budget gets back what the copies took");
} else {
assert_eq!(budget.left, 0, "no shadow is left");
assert!(!out.is_empty(), "the group expands");
let (mut ids, mut count, mut seeded) = (std::collections::HashSet::new(), 0, false);
d.node(g).unwrap().walk(&mut |n| {
ids.insert(n.id);
count += 1;
seeded |= super::has_seeded(n);
});
assert_eq!(ids.len(), count, "each object has an id of its own");
assert!(!seeded, "no random Transform effect is left");
}
}
}
/// An object with Crop Marks, a drop shadow and a random Transform effect that takes its seed from
/// the object's id stays as it is when the raster budget has no image left for its shadow: the
/// object keeps its id and its random move, and draws as before.
#[test]
fn crop_marks_the_raster_budget_leaves_keep_their_random_move() {
let (mut s, id) = session_with_rect();
let shadow = json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"});
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "stylize.dropShadow", "params": shadow})).unwrap();
let random = json!({"moveH": 40, "moveV": 40, "random": true});
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "distort.transform", "params": random})).unwrap();
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "cropMarks", "params": {}})).unwrap();
let draw = |d: &vectorcraft_doc::Document| {
vectorcraft_render::Renderer::new().render(d, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels
};
let mut d = s.doc().unwrap().doc.as_ref().clone();
let before = d.node(id).cloned().unwrap();
assert!(effects::crop_marks_art(&before).is_some(), "the object has crop marks");
let (drawn, keys) = (draw(&d), d.images.keys().cloned().collect::<Vec<_>>());
let mut budget = super::RasterBudget { images: 0, pixels: u64::MAX, left: 0 };
let mut out = vec![];
super::expand_node(&mut d, id, &[], &mut out, &mut budget);
assert!(budget.left > 0, "the shadow is left");
assert!(out.is_empty(), "nothing expands: {out:?}");
assert_eq!(d.node(id), Some(&before), "the object stays as it is");
assert!(draw(&d) == drawn, "the object draws as before");
assert_eq!(d.images.keys().cloned().collect::<Vec<_>>(), keys, "no image is added");
assert_eq!((budget.images, budget.pixels), (0, u64::MAX), "the budget is as it was");
}
File diff suppressed because one or more lines are too long
+63 -18
View File
@@ -209,6 +209,8 @@ struct Row {
options: Value,
/// What makes two rows the same file: format, size, suffix and options.
key: String,
/// The row or the format's settings set `bleed` (a PDF row's own bleed, zero included).
bleed_given: bool,
}
impl Row {
@@ -248,12 +250,19 @@ impl Row {
}
// A file per artboard is for viewing: it doesn't carry the whole document to edit.
options.entry("preserveEditing").or_insert(json!(false));
let bleed_given = options.get("bleed").is_some_and(|b| !b.is_null());
let options = Value::Object(options);
// A PDF preset (built-in or saved) becomes its settings.
let options = if format.id == "pdf" { super::pdf::expand_preset(s, C, &options)?.into_owned() } else { options };
// Two rows that would write the same bytes under the same name are one file.
let key = format!("{}|{}|{suffix}|{options}", format.id, size.label());
Ok(Self { format, size, suffix, folder, options, key })
let mut row = Self { format, size, suffix, folder, options, key: String::new(), bleed_given };
row.key = row.file_key();
Ok(row)
}
/// What makes two rows the same file: two rows that would write the same bytes under the same
/// name are one file.
fn file_key(&self) -> String {
format!("{}|{}|{}|{}", self.format.id, self.size.label(), self.suffix, self.options)
}
/// Formats that hold a whole document to edit (native, Illustrator, EPS): written from a
@@ -525,6 +534,8 @@ fn rows_of(s: &Session, p: &Value, preset: Option<&str>) -> Result<Vec<Row>> {
if let Some(m) = r.options.as_object_mut() {
m.entry("antiAlias").or_insert_with(|| aa.clone());
}
// Two rows whose options are now the same are one file.
r.key = r.file_key();
}
}
Ok(rows)
@@ -1137,17 +1148,22 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
let naming = Naming::of(&o, st.path.as_deref().unwrap_or(&st.doc.title))?;
let selection = o.selection_mode()?;
let selected = if selection.is_some() { selected_artwork(s)? } else { vec![] };
let doc = s.doc()?.doc.clone();
let original = s.doc()?.doc.clone();
// Include Bleed: each artboard grown by the document's bleed.
let doc = if o.include_bleed && doc.setup.has_bleed() {
let mut d = (*doc).clone();
let grown = o.include_bleed && original.setup.has_bleed();
let doc = if grown {
let mut d = (*original).clone();
for a in &mut d.artboards {
a.rect = doc.setup.bleed_rect(a.rect);
a.rect = original.setup.bleed_rect(a.rect);
}
Arc::new(d)
} else {
doc
original.clone()
};
// A PDF page of an artboard keeps the artboard as its TrimBox and puts its row's bleed around
// it once: it is written from the document with the artboards as they are. Assets, layers and
// a selection are written on a page of their own bounds, which Include Bleed doesn't grow.
let ungrown = (grown && o.assets.is_none() && o.layers.is_none() && o.selection.is_none()).then_some(original);
let crop = rows.iter().any(|r| r.format.id != "pdf");
let items = items(&doc, &o, selection, &selected, &naming.filename, crop, true)?;
// Before the folder is made or any row is written, with the artboards each file holds.
@@ -1164,8 +1180,26 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
// Appearance of Black › Printing / Exporting for RGB raster rows.
// Include Artboard Fill off: the encoders leave the background colors out.
let fill = if o.include_artboard_fill == Some(false) { json!({ "includeArtboardFill": false }) } else { json!({}) };
let rows = rows.into_iter().map(|r| Row { options: merge(with_black_output(s, &r.options), fill.clone()), ..r }).collect();
let export = ScreenExport { cmd: C, o, rows, naming, items, unused, hidden: None };
let rows = rows
.into_iter()
.map(|mut r| {
// Include Bleed: a PDF row that sets no bleed of its own, and whose preset gives none,
// puts the document's bleed around the artboard, and is the same file as a row that
// asks for the document's bleed. A saved preset's bleed values stay, as they do in
// that row.
if ungrown.is_some() && r.format.id == "pdf" && !r.bleed_given && !pdf_bleeds(&r.options) {
match r.options.get_mut("bleed").and_then(Value::as_object_mut) {
Some(b) => {
b.insert("useDocument".into(), json!(true));
}
None => r.options["bleed"] = json!({ "useDocument": true }),
}
r.key = r.file_key();
}
Row { options: merge(with_black_output(s, &r.options), fill.clone()), ..r }
})
.collect();
let export = ScreenExport { cmd: C, o, rows, naming, items, unused, hidden: None, ungrown };
match &mut s.screens_hand_off {
Some(slot) => {
*slot = Some(export);
@@ -1175,6 +1209,14 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
}
}
/// Do the PDF `options` (a built-in preset's settings under them) give the pages a bleed: the
/// document's, or a value above 0 on some side? Options the PDF encoder refuses count as giving
/// one, so they are left as they are for the encoder to refuse.
fn pdf_bleeds(options: &Value) -> bool {
super::pdf::settings(C, options)
.map_or(true, |s| s.bleed.use_document || [s.bleed.top, s.bleed.bottom, s.bleed.left, s.bleed.right].iter().any(|b| *b > 0.0))
}
/// An export as `document.exportForScreens` and `assets.export` take it from the session: the
/// params, the format rows, the naming, and each item with the document it writes
/// ([`Session::prepare_screen_export`]). [`ScreenExport::write`] encodes and writes its files
@@ -1192,6 +1234,9 @@ pub struct ScreenExport {
/// folder came from the `exportPreset` and is outside that request's read roots: the reply and
/// the errors of [`ScreenExport::write`] name it as [`export_for_screens`] does.
hidden: Option<(String, String)>,
/// Include Bleed with artboards: the document with the artboards as they are, which PDF rows
/// write (the items hold the artboards grown by the bleed).
ungrown: Option<Arc<Document>>,
}
impl Session {
@@ -1252,7 +1297,7 @@ impl ScreenExport {
/// [`ScreenExport::write`].
fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
let ScreenExport { o, rows, naming, items, unused, .. } = export;
let ScreenExport { o, rows, naming, items, unused, ungrown, .. } = export;
let folder = o.folder.as_deref().filter(|f| !f.is_empty());
if let Some(dir) = folder {
create_dir(dir)?;
@@ -1263,13 +1308,12 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
for text in unused {
add_note(&mut notes, Note::setting(text));
}
// Include Bleed: a grown artboard already holds the bleed. Assets, layers and a selection are
// written on a page of their own bounds, which it doesn't grow.
let bleed_on_page = o.include_bleed && o.assets.is_none() && o.layers.is_none() && o.selection.is_none();
// The document a PDF row writes: with Include Bleed, the artboards as they are.
let pdf_doc = ungrown.as_deref();
let mut write = |doc: &Document, format: &str, options: &Value| -> Result<Vec<u8>> {
// The steps are the files: an encoder's own steps (artboards, pages) are not reported.
let (bytes, given) = vectorcraft_doc::cancel::quiet(|| encode_with_notes(doc, format, options))?;
for n in given.into_iter().filter(|n| !(bleed_on_page && n.text == super::pdf::BLEED_LEFT_OUT)) {
for n in given {
add_note(&mut notes, n);
}
Ok(bytes)
@@ -1306,12 +1350,12 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
let bytes = if let Some(boards) = single {
let mut options = r.options.clone();
options["range"] = json!(boards.iter().map(|b| (b + 1).to_string()).collect::<Vec<_>>().join(", "));
write(&item.doc, "pdf", &options)?
write(pdf_doc.unwrap_or(&item.doc), "pdf", &options)?
} else if let (Some(all), "pdf") = (&item.every_artboard, r.format.id) {
// One page per artboard.
let mut options = r.options.clone();
options["range"] = json!("all");
write(all, "pdf", &options)?
write(pdf_doc.unwrap_or(all), "pdf", &options)?
} else if r.whole_document() && item.artboard.is_some() {
let b = item.artboard.unwrap_or(0);
// That artboard alone, as Save's separateArtboards writes it: its art, not the others' (#3868).
@@ -1334,7 +1378,8 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
}
write(&d, r.format.id, &options)?
} else {
write(&item.doc, r.format.id, &r.options_for(item.region, item.artboard)?)?
let doc = if r.format.id == "pdf" { pdf_doc.unwrap_or(&item.doc) } else { &item.doc };
write(doc, r.format.id, &r.options_for(item.region, item.artboard)?)?
};
out.put(folder, o.zip, name, bytes, writer)?;
files += 1;
@@ -830,3 +830,78 @@ fn flattening_keeps_the_group_in_the_clipping_layer_when_the_layer_below_differs
}
assert!(wrong.is_empty(), "{wrong:#?}");
}
/// #6861: Layer opacity, blend modes, sublayers with transparency, and empty transparent layers:
/// PDF/X-1a, PDF/X-3, and PDF 1.3 automatically flatten and reduce transparency without failing,
/// and the output contains no transparency dictionary or soft mask.
#[test]
fn pdfx_flattens_layer_and_sublayer_transparency() {
let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 200, "height": 200, "colorMode": "cmyk"}));
// Bottom layer: base artwork
let _layer1 = s.doc().unwrap().doc.layers[0].id.0;
run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}));
run(&mut s, "paint.setFill", json!({"color": {"c": 1.0, "m": 0.0, "y": 0.0, "k": 0.0}}));
// Middle layer with 50% opacity and Multiply blend mode
let layer2 = run(&mut s, "layer.new", json!({}))["id"].as_u64().unwrap();
run(&mut s, "shape.rectangle", json!({"x": 40, "y": 40, "width": 80, "height": 80}));
run(&mut s, "paint.setFill", json!({"color": {"c": 0.0, "m": 1.0, "y": 0.0, "k": 0.0}}));
run(&mut s, "transparency.set", json!({"ids": [layer2], "opacity": 50, "blendMode": "multiply"}));
// Sublayer inside layer2 with 70% opacity
let sublayer = run(&mut s, "layer.newSublayer", json!({"parent": layer2}))["id"].as_u64().unwrap();
run(&mut s, "shape.rectangle", json!({"x": 60, "y": 60, "width": 80, "height": 80}));
run(&mut s, "paint.setFill", json!({"color": {"c": 0.0, "m": 0.0, "y": 1.0, "k": 0.0}}));
run(&mut s, "transparency.set", json!({"ids": [sublayer], "opacity": 70}));
// Empty layer with opacity (must not leave /CA or /ca in output)
let empty_layer = run(&mut s, "layer.new", json!({}))["id"].as_u64().unwrap();
run(&mut s, "transparency.set", json!({"ids": [empty_layer], "opacity": 40}));
for standard in ["pdfX1a", "pdfX3"] {
let (text, warnings) = pdf(&mut s, json!({"standard": standard}));
assert!(text.starts_with("%PDF-1.3"), "{standard}");
assert!(warnings.iter().any(|w| w.contains("flattened")), "{standard}: expected flattening warning");
for no in ["/SMask", "/S/Transparency", "/ca ", "/CA "] {
assert!(!text.contains(no), "{standard}: forbidden token '{no}' found in text:\n{text}");
}
// Verify it can be imported back and renders artwork
let v = s.execute("document.exportPdf", &json!({"standard": standard})).unwrap();
let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap();
let imported = vectorcraft_pdf::import(&bytes).unwrap();
assert!(!imported.layers.is_empty());
let rendered = drawn(&imported);
let non_white = rendered.pixels.as_chunks::<4>().0.iter().filter(|p| p[..3].iter().any(|c| *c < 240)).count();
assert!(non_white > 1000, "{standard}: flattened artwork failed to render, only {non_white} pixels");
}
// PDF 1.3 export with compatibility: 1.3
let (text, warnings) = pdf(&mut s, json!({"compatibility": "1.3", "preserveEditing": false}));
assert!(text.starts_with("%PDF-1.3"));
assert!(warnings.iter().any(|w| w.contains("flattened")));
for no in ["/SMask", "/S/Transparency", "/ca ", "/CA "] {
assert!(!text.contains(no), "PDF 1.3: forbidden token '{no}' found in text");
}
}
#[test]
fn pdf_outlining_does_not_wrap_layer_transparency_into_groups() {
let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
let layer1 = s.doc().unwrap().doc.layers[0].id.0;
run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}));
run(&mut s, "transparency.set", json!({"ids": [layer1], "opacity": 60}));
let o = crate::cmd::FlattenOptions { text_to_outlines: true, ..Default::default() };
let doc = s.doc().unwrap().doc.clone();
let flattened = crate::cmd::flatten::flatten_expanded(&doc, &o).unwrap();
let resulting_doc = flattened.as_ref().unwrap_or(&doc);
assert_eq!(resulting_doc.layers.len(), 1);
let l = &resulting_doc.layers[0];
assert_eq!(l.opacity, 0.6);
assert!(!matches!(l.children().unwrap()[0].kind, vectorcraft_doc::NodeKind::Group { .. }));
}
+94 -1
View File
@@ -594,7 +594,8 @@ fn include_bleed_grows_each_artboard() {
assert_eq!(size(&files(&r)[0].1), (40, 30), "without it, the artboard alone");
}
/// Include Bleed puts the bleed on a PDF/X row's page, so the row doesn't warn that it leaves the bleed out.
/// Include Bleed puts the bleed on a PDF/X row's page, so the row doesn't warn that it leaves the
/// bleed out, unless the row sets a bleed of 0 itself.
#[test]
fn include_bleed_pdfx_rows_do_not_warn_about_the_bleed() {
let mut s = session(1);
@@ -603,11 +604,103 @@ fn include_bleed_pdfx_rows_do_not_warn_about_the_bleed() {
let row = json!([{"format": "pdf", "standard": "pdfX4"}]);
assert!(warned(&export(&mut s, json!({"formats": row}))));
assert!(!warned(&export(&mut s, json!({"includeBleed": true, "formats": row}))));
let zero = json!([{"format": "pdf", "standard": "pdfX4", "bleed": {"top": 0, "bottom": 0, "left": 0, "right": 0}}]);
assert!(warned(&export(&mut s, json!({"includeBleed": true, "formats": zero}))), "the row's own bleed of 0 leaves the bleed out");
// A selection is written on a page of its own bounds, which Include Bleed doesn't grow.
s.execute("shape.rectangle", &json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap();
assert!(warned(&export(&mut s, json!({"includeBleed": true, "selection": "one", "formats": row}))));
}
/// Each `[x0 y0 x1 y1]` that follows `key` in a PDF's bytes, in the order the file has them, read
/// as text without VectorCraft's PDF reader (PDF 32000-1:2008, 14.11.2, Page Boundaries).
fn raw_boxes(pdf: &[u8], key: &str) -> Vec<[f64; 4]> {
let text = String::from_utf8_lossy(pdf);
text.match_indices(key)
.map(|(at, _)| {
let mut words = text[at + key.len()..].split(|c: char| c.is_whitespace() || matches!(c, '[' | ']')).filter(|w| !w.is_empty());
std::array::from_fn(|_| words.next().and_then(|w| w.parse().ok()).unwrap_or(f64::NAN))
})
.collect()
}
/// A page's MediaBox, BleedBox and TrimBox sizes `(width, height)` in points, and the trim's
/// distance from the bleed box's left and bottom edges.
type PageSizes = ((f64, f64), (f64, f64), (f64, f64), (f64, f64));
/// [`PageSizes`] of each page of `pdf`.
fn page_sizes(pdf: &[u8]) -> Vec<PageSizes> {
let size = |b: &[f64; 4]| (b[2] - b[0], b[3] - b[1]);
let (media, bleed, trim) = (raw_boxes(pdf, "/MediaBox"), raw_boxes(pdf, "/BleedBox"), raw_boxes(pdf, "/TrimBox"));
assert!(!trim.is_empty() && media.len() == trim.len() && bleed.len() == trim.len(), "a MediaBox, BleedBox and TrimBox per page");
(0..trim.len()).map(|i| (size(&media[i]), size(&bleed[i]), size(&trim[i]), (trim[i][0] - bleed[i][0], trim[i][1] - bleed[i][1]))).collect()
}
/// With Include Bleed, a PDF page keeps the artboard as its TrimBox and puts the bleed around it
/// once (PDF 32000-1:2008, 14.11.2: the trim box is the finished page, the bleed box holds it): the
/// document's bleed when the row asks for it or sets none, else the row's own values.
#[test]
fn include_bleed_pdf_pages_trim_at_the_artboard() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
s.execute("document.setup", &json!({"bleed": 9})).unwrap();
let pages = |s: &mut Session, p: Value| -> Vec<PageSizes> {
let r = export(s, p);
files(&r).iter().filter(|(n, _)| n.ends_with(".pdf")).flat_map(|(_, b)| page_sizes(b)).collect()
};
let one = |media: f64, bleed: f64, trim: f64| ((media, media), (bleed, bleed), (trim, trim), ((bleed - trim) / 2.0, (bleed - trim) / 2.0));
let document = json!({"format": "pdf", "bleed": {"useDocument": true}});
let sides = |b: f64| json!({"top": b, "bottom": b, "left": b, "right": b});
for (p, want) in [
(json!({"includeBleed": true, "artboard": 0, "formats": [document]}), one(118.0, 118.0, 100.0)),
(json!({"includeBleed": true, "artboard": 0, "formats": [{"format": "pdf"}]}), one(118.0, 118.0, 100.0)),
(json!({"includeBleed": true, "artboard": 0, "formats": [{"format": "pdf", "preset": "High Quality Print"}]}), one(118.0, 118.0, 100.0)),
(json!({"includeBleed": true, "artboard": 0, "formats": [{"format": "pdf", "bleed": sides(3.0)}]}), one(106.0, 106.0, 100.0)),
(json!({"includeBleed": true, "artboard": 0, "formats": [{"format": "pdf", "bleed": sides(0.0)}]}), one(100.0, 100.0, 100.0)),
(json!({"artboard": 0, "formats": [document]}), one(118.0, 118.0, 100.0)),
(json!({"artboard": 0, "formats": [{"format": "pdf"}]}), one(100.0, 100.0, 100.0)),
] {
assert_eq!(pages(&mut s, p.clone()), [want], "{p}");
}
// Every page of a single file and of the Full Document, each artboard its own trim.
for p in [
json!({"includeBleed": true, "pdfs": "single", "formats": [document]}),
json!({"includeBleed": true, "fullDocument": true, "formats": [document]}),
] {
assert_eq!(pages(&mut s, p.clone()), [one(118.0, 118.0, 100.0); 2], "{p}");
}
// A row with printer's marks: the sheet grows past the bleed box for them, around the same trim.
let marked = pages(
&mut s,
json!({"includeBleed": true, "artboard": 0, "formats": [{"format": "pdf", "bleed": {"useDocument": true}, "marks": {"trim": true}}]}),
);
let [(media, bleed, trim, at)] = marked[..] else { panic!("one page: {marked:?}") };
assert_eq!((bleed, trim, at), ((118.0, 118.0), (100.0, 100.0), (9.0, 9.0)));
assert!(media.0 > 118.0 && media.1 > 118.0, "{media:?}");
// A row that sets no bleed writes the same file as one that asks for the document's: one file.
let r = export(&mut s, json!({"includeBleed": true, "artboard": 0, "formats": [{"format": "pdf"}, document]}));
assert_eq!(names(&r).len(), 1, "{:?}", names(&r));
// So does it with a top-level anti-aliasing mode, which both rows take.
let r = export(&mut s, json!({"includeBleed": true, "artboard": 0, "antiAlias": "art", "formats": [{"format": "pdf"}, document]}));
assert_eq!(names(&r).len(), 1, "{:?}", names(&r));
// And with a saved PDF preset, which writes out every bleed value for both rows.
s.execute("pdf.preset.save", &json!({"name": "Saved Default"})).unwrap();
let saved = |bleed: Option<Value>| {
let mut row = json!({"format": "pdf", "preset": "Saved Default"});
if let Some(b) = bleed {
row["bleed"] = b;
}
row
};
let r = export(&mut s, json!({"includeBleed": true, "artboard": 0, "formats": [saved(None), saved(Some(json!({"useDocument": true})))]}));
assert_eq!(names(&r).len(), 1, "{:?}", names(&r));
assert_eq!(pages(&mut s, json!({"includeBleed": true, "artboard": 0, "formats": [saved(None)]})), [one(118.0, 118.0, 100.0)]);
// A raster row of the same export still holds the bleed in its pixels.
let r = export(&mut s, json!({"includeBleed": true, "artboard": 0, "formats": [document, {"format": "png"}]}));
let png = files(&r).into_iter().find(|(n, _)| n.ends_with(".png")).unwrap().1;
assert_eq!(size(&png), (118, 118));
}
#[test]
fn png_8_rows_write_indexed_colour() {
let mut s = session(1);
+125 -12
View File
@@ -5,8 +5,8 @@ use super::compose::{Builder, CLEAR, Composer, Elem, Fill, Kind, Px, WHITE};
use super::options::FlattenOptions;
use super::{
Affine, Appearance, AppearanceItem, Arc, BlendMode, Color, ColorMode, Document, EngineError, FillLayer, FillRule, ImageBlob, ImageObject, Inks,
MAX_PIXELS, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, composite, effects, isolated_doc, leaves, outline_strokes, planes_cmyk, po,
separate, shape_node, shapes, unique_key,
Knockout, MAX_PIXELS, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, composite, effects, isolated_doc, leaves, outline_strokes,
planes_cmyk, po, separate, shape_node, shapes, unique_key,
};
// ---------- plan ----------
@@ -756,27 +756,140 @@ pub(crate) fn flatten_document(doc: &Document, o: &FlattenOptions) -> Result<Opt
Ok(flatten_expanded(expanded.as_ref().unwrap_or(doc), o)?.or(expanded))
}
fn has_layer_container_transparency(n: &Node) -> bool {
!n.has_default_transparency() || n.children().into_iter().flatten().any(|c| c.is_layer() && has_layer_container_transparency(c))
}
/// [`flatten_document`] for `doc` whose pattern tile images were expanded already
/// ([`expand_transparent_tile_images`]).
pub(crate) fn flatten_expanded(doc: &Document, o: &FlattenOptions) -> Result<Option<Document>> {
let outlining = o.text_to_outlines || o.strokes_to_outlines || !o.preserve_overprints;
if !outlining && !doc.layers.iter().any(|l| o.shows_transparency(doc, l) || o.draws_see_through_image(l)) {
return Ok(None);
}
let mut roots = vec![];
for l in doc.layers.iter().filter(|l| l.visible && !matches!(l.kind, NodeKind::Layer { template: true, .. })) {
let children = l.children().map_or(&[][..], Vec::as_slice);
roots.extend(children.iter().skip(usize::from(l.clips())).filter(|c| c.visible && !c.is_ruler_guide()).map(|c| c.id));
}
let plan = plan(doc, &roots, o, true)?;
if plan.flat.is_empty() && !plan.work.iter().any(|k| k.changes) {
let needs_flatten = outlining
|| doc.layers.iter().any(|l| {
(o.no_transparency.is_some() && has_layer_container_transparency(l)) || o.shows_transparency(doc, l) || o.draws_see_through_image(l)
});
if !needs_flatten {
return Ok(None);
}
let mut d = doc.clone();
let changed = o.no_transparency.is_some() && normalize_layer_transparency(&mut d, o);
let mut roots = vec![];
for l in d.layers.iter().filter(|l| l.visible && !matches!(l.kind, NodeKind::Layer { template: true, .. })) {
let children = l.children().map_or(&[][..], Vec::as_slice);
roots.extend(children.iter().skip(usize::from(l.clips())).filter(|c| c.visible && !c.is_ruler_guide()).map(|c| c.id));
}
let plan = plan(&d, &roots, o, true)?;
if plan.flat.is_empty() && !plan.work.iter().any(|k| k.changes) {
if changed {
if o.no_transparency.is_some() {
for l in &mut d.layers {
sanitize_container_transparency(Arc::make_mut(l));
}
}
return Ok(Some(d));
}
return Ok(None);
}
apply(&mut d, &mut vectorcraft_doc::Selection::default(), plan, o)?;
if o.no_transparency.is_some() {
for l in &mut d.layers {
sanitize_container_transparency(Arc::make_mut(l));
}
}
Ok(Some(d))
}
/// Flatten and normalize container-level transparency (on layers and sublayers) into groups
/// so that the flattener's plan includes them and leaves no container transparency behind.
fn normalize_layer_transparency(d: &mut Document, o: &FlattenOptions) -> bool {
if o.no_transparency.is_none() {
return false;
}
let mut changed = false;
let mut layers = std::mem::take(&mut d.layers);
for l in &mut layers {
changed |= normalize_node_transparency(d, Arc::make_mut(l));
}
d.layers = layers;
changed
}
fn clear_transparency(n: &mut Node) {
n.opacity = 1.0;
n.blend = BlendMode::Normal;
n.isolate = false;
n.knockout = Knockout::Neutral;
n.knockout_shape = false;
n.extras_mut().mask = None;
n.appearance = Appearance::default().into();
}
fn normalize_node_transparency(d: &mut Document, n: &mut Node) -> bool {
let mut changed = false;
let is_layer = n.is_layer();
let clips = n.clips();
if let Some(children) = n.children_mut() {
for c in children.iter_mut() {
if c.is_layer() {
changed |= normalize_node_transparency(d, Arc::make_mut(c));
}
}
}
let has_transparency = !n.has_default_transparency() || n.shows_own_transparency();
if is_layer && has_transparency {
let children = n.children().map_or(&[][..], Vec::as_slice);
let (guides, art): (Vec<_>, Vec<_>) = children.iter().cloned().partition(|c| c.is_ruler_guide());
if art.is_empty() {
clear_transparency(n);
n.set_clips(false);
changed = true;
} else {
let mut g = Node::group(d.alloc_id(), art);
if clips {
g.set_clips(true);
}
g.opacity = n.opacity;
g.blend = n.blend;
g.isolate = n.isolate;
g.knockout = n.knockout;
g.knockout_shape = n.knockout_shape;
g.appearance = n.appearance.clone();
g.extras_mut().mask = n.extras_mut().mask.take();
n.set_clips(false);
clear_transparency(n);
let mut new_children = vec![Arc::new(g)];
new_children.extend(guides);
if let Some(ch) = n.children_mut() {
*ch = new_children;
}
changed = true;
}
} else if is_layer && !n.visible {
clear_transparency(n);
}
changed
}
fn sanitize_container_transparency(n: &mut Node) {
if n.is_container() {
clear_transparency(n);
if let Some(children) = n.children_mut() {
for c in children.iter_mut() {
if c.is_container() {
sanitize_container_transparency(Arc::make_mut(c));
}
}
}
}
}
// ---------- apply ----------
pub(super) fn apply(d: &mut Document, sel: &mut vectorcraft_doc::Selection, plan: Plan, o: &FlattenOptions) -> Result<(Vec<NodeId>, usize, usize)> {
+91 -16
View File
@@ -26,7 +26,9 @@ use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_geom::{FillRule, PathData, Point, SubPath};
use vectorcraft_pathops as po;
use vectorcraft_tools::intertwine::{Face, drawn_order, face_at, faces_in, faces_of, is_intertwine, nonempty, painted_areas};
use vectorcraft_tools::intertwine::{
Face, drawn_order, face_at, faces_in, faces_of, in_intertwine, is_intertwine, nonempty, painted_areas, refused_member,
};
use super::edit::selected_roots;
use super::pathops::Beside;
@@ -106,17 +108,7 @@ fn refused(d: &Document, n: &Node) -> Option<&'static str> {
if around.iter().filter(|a| **a != n.id).filter_map(|a| d.node(*a)).any(is_intertwine) {
return Some("an object already in an Intertwine group");
}
let mut why = None;
n.walk(&mut |c| {
why = why.or(match &c.kind {
NodeKind::Intertwine { .. } => Some("an Intertwine group"),
NodeKind::Repeat(_) => Some("a Repeat"),
NodeKind::Group { .. } if c.extras().graph.is_some() => Some("a graph"),
NodeKind::Group { .. } if vectorcraft_tools::builder::is_live_paint(c) => Some("a Live Paint group"),
_ => None,
});
});
why
refused_member(n)
}
fn make(s: &mut Session, p: &Value) -> Result<Value> {
@@ -179,10 +171,7 @@ fn release(s: &mut Session, _: &Value) -> Result<Value> {
.flatten()
.map(|c| {
let mut c = (**c).clone();
let mut e = c.extras_mut();
e.intertwine = None;
e.intertwine_tiers = Vec::new();
drop(e);
without_areas(&mut c);
c
})
.collect();
@@ -196,6 +185,92 @@ fn release(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
}
// ---------- members that come and go ----------
/// Why `n` can't go into `parent`, an Intertwine group or a container inside one, if it can't
/// ([`refused_member`]). Other containers take it as they did.
pub(crate) fn refused_in(d: &Document, parent: Option<NodeId>, n: &Node) -> Option<&'static str> {
parent.filter(|p| in_intertwine(d, *p)).and_then(|_| refused_member(n))
}
/// The Intertwine groups that `ids` are members of, each once.
pub(crate) fn groups_of(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
let mut seen = std::collections::HashSet::new();
ids.iter().filter_map(|i| d.parent_of(*i)).filter(|g| d.node(*g).is_some_and(is_intertwine) && seen.insert(*g)).collect()
}
/// `n` without the areas it is drawn over other members in.
fn without_areas(n: &mut Node) {
if n.extras().intertwine.is_some() || !n.extras().intertwine_tiers.is_empty() {
let mut e = n.extras_mut();
e.intertwine = None;
e.intertwine_tiers = Vec::new();
}
}
/// Whether Intertwine group `g` has nothing of its own that changes how its members are drawn:
/// it is visible and unlocked, with full opacity, normal blending, no appearance and no extras
/// (an opacity mask among them).
fn bare(g: &Node) -> bool {
let plain = Node::new(g.id, NodeKind::Intertwine { children: vec![] });
(g.visible, g.locked, g.opacity, g.blend, g.isolate, g.knockout, g.knockout_shape)
== (plain.visible, plain.locked, plain.opacity, plain.blend, plain.isolate, plain.knockout, plain.knockout_shape)
&& g.appearance == plain.appearance
&& *g.extras() == *plain.extras()
}
/// After objects moved in the Layers panel: each of `placed` (the objects now in place, each with
/// the container it came from, None for a copy) that is not in the container it came from loses
/// the areas it was drawn over other members in, so it joins an Intertwine group at no tier and
/// leaves one as ordinary art. Then each of `left` (the Intertwine groups objects came from) that
/// has fewer than two members is taken apart: its one member goes in its place without areas, and
/// an empty one is removed. A group with one member and something of its own ([`bare`]) becomes a
/// plain group of that member instead, keeping its id and all it has. The other members keep their
/// areas.
pub(crate) fn settle_members(d: &mut Document, placed: &[(NodeId, Option<NodeId>)], left: &[NodeId]) -> Result<()> {
for (id, from) in placed {
if d.node(*id).is_some_and(|n| n.extras().intertwine.is_some() || !n.extras().intertwine_tiers.is_empty())
&& from.is_none_or(|f| d.parent_of(*id) != Some(f))
{
without_areas(d.node_mut(*id).ok_or(EngineError::NoNode(*id))?);
}
}
let lone: Vec<NodeId> =
left.iter().copied().filter(|g| d.node(*g).is_some_and(|n| is_intertwine(n) && n.children().is_none_or(|c| c.len() < 2))).collect();
let (kept, lone): (Vec<NodeId>, Vec<NodeId>) =
lone.into_iter().partition(|g| d.node(*g).is_some_and(|n| n.children().is_some_and(|c| c.len() == 1) && !bare(n)));
for g in &kept {
let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?;
if let NodeKind::Intertwine { children } = &mut n.kind {
let children = std::mem::take(children)
.into_iter()
.map(|c| {
let mut c = (*c).clone();
without_areas(&mut c);
Arc::new(c)
})
.collect();
n.kind = NodeKind::Group { children, clip: false };
}
}
let mut apart = Beside::replacing(d, &lone);
for g in &lone {
let Some(n) = d.node(*g) else { continue };
let members: Vec<Node> = n
.children()
.into_iter()
.flatten()
.map(|c| {
let mut c = (**c).clone();
without_areas(&mut c);
c
})
.collect();
apart.put(d, *g, members)?;
}
apart.finish(d)
}
// ---------- Expand ----------
/// Replace Intertwine group `id` by a plain group of the art it draws
+21 -4
View File
@@ -110,7 +110,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Rows",
[],
None,
"{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer or group (on top of its contents). Layers go only in layers or at the top level, objects in layers and groups; an object placed beside a top-level layer goes inside it. A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies. Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids}",
"{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer, group or Intertwine group (on top of its contents). Layers go only in layers or at the top level, objects in layers, groups and Intertwine groups; an object placed beside a top-level layer goes inside it. An object placed in an Intertwine group becomes a member drawn in its row's order, with no arranged areas, and one placed in a group that is a member becomes part of that member; one that is or holds an Intertwine group, a Repeat, a graph or a Live Paint group is refused. A member moved out of its Intertwine group drops its arranged areas, and a group left with one member is replaced by that member, or becomes a plain group of it when the group has an opacity, blending, appearance, mask, lock or hidden state of its own (with no member, it is removed). A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies. Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids}",
has_doc,
move_rows
),
@@ -119,7 +119,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reorder",
[],
None,
"{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers), deselecting every selected object left hidden or locked (the key object too)",
"{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too)",
has_doc,
move_node
),
@@ -242,14 +242,15 @@ pub(crate) fn row_roots(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
}
/// Whether `parent` (None: the top level) can hold `n`: layers go at the top level or in layers,
/// anything else in layers and groups.
/// anything else in layers, groups and Intertwine groups (which also check what the object holds:
/// [`super::intertwine::refused_in`]).
pub(crate) fn accepts(d: &Document, parent: Option<NodeId>, n: &Node) -> bool {
match parent {
None => n.is_layer(),
Some(p) => match d.node(p).map(|x| &x.kind) {
Some(NodeKind::Layer { .. }) => true,
// A ruler guide stays directly in a layer or sublayer.
Some(NodeKind::Group { .. }) => !n.is_layer() && !n.is_ruler_guide(),
Some(NodeKind::Group { .. } | NodeKind::Intertwine { .. }) => !n.is_layer() && !n.is_ruler_guide(),
_ => false,
},
}
@@ -791,10 +792,17 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> {
let into = parent.and_then(|p| d.node(p)).map_or("the top level", |p| if p.is_layer() { "a layer" } else { p.kind_label() });
return Err(bad(C, format!("{} can't go into {into}", n.display_name())));
}
if let Some(what) = nodes.iter().find_map(|n| super::intertwine::refused_in(d, parent, n)) {
return Err(bad(C, format!("{what} can't be intertwined")));
}
if parent.is_some_and(|p| locked_within(d, p)) {
return Err(EngineError::Other("the layer or group is locked".into()));
}
let label = if copy { "Duplicate Rows" } else { "Move Rows" };
// Where each moved row comes from (a copy has a new id, so it comes from nowhere), and the
// Intertwine groups it leaves.
let from: std::collections::HashMap<NodeId, Option<NodeId>> = ids.iter().map(|i| (*i, d.parent_of(*i))).collect();
let left = if copy { vec![] } else { super::intertwine::groups_of(d, &ids) };
let moved = s.edit(label, |d, sel| {
let nodes = if copy {
let mut nodes = vec![];
@@ -829,6 +837,8 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> {
if copy {
super::typecmd::refresh_bounds_of(d, &out);
}
let placed: Vec<(NodeId, Option<NodeId>)> = out.iter().map(|o| (*o, from.get(o).copied().flatten())).collect();
super::intertwine::settle_members(d, &placed, &left)?;
sel.prune(d);
sel.deselect_uneditable(d);
Ok(out)
@@ -848,8 +858,15 @@ fn move_node(s: &mut Session, p: &Value) -> Result<Value> {
if !accepts(d, parent, n) {
return Err(bad(C, "layers go only at the top level or in layers, objects in layers and groups"));
}
if let Some(what) = super::intertwine::refused_in(d, parent, n) {
return Err(bad(C, format!("{what} can't be intertwined")));
}
let from = d.parent_of(id);
let left = super::intertwine::groups_of(d, &[id]);
s.edit("Reorder", |d, sel| {
d.move_node(id, parent, index)?;
super::intertwine::settle_members(d, &[(id, from)], &left)?;
sel.prune(d);
sel.deselect_uneditable(d);
Ok(())
})?;
+73 -11
View File
@@ -92,7 +92,7 @@ pub(super) fn blend_make(s: &mut Session, p: &Value) -> Result<Value> {
_ => defaults,
};
let spacing = spacing_param(p, C, cur.spacing)?;
let orientation = orientation_param(p, cur.orientation);
let orientation = orientation_param(p, C, cur.orientation)?;
let (ease0, color0, no_spine) = match base.as_ref().map(|n| &n.kind) {
Some(NodeKind::Blend { spec, .. }) => (spec.ease, spec.color_shift, spec.no_spine),
_ => (Default::default(), 0.0, !create_spine.creates_spine()),
@@ -364,29 +364,91 @@ fn selected_spec(s: &Session) -> Option<(NodeId, BlendSpec, Vec<NodeId>)> {
pub(super) fn blend_options(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.blend.options";
let Some((_, cur, _)) = selected_spec(s) else {
let id = crate::cmd::object_param(p, "id", C)?;
let target = match id {
Some(id) => {
let doc = &s.doc()?.doc;
match doc.node(id).map(|n| &n.kind) {
Some(NodeKind::Blend { .. }) if !doc.is_editable(id) => return Err(bad(C, "the object is hidden or locked")),
Some(NodeKind::Blend { spec, children }) => Some((id, (**spec).clone(), children.iter().map(|c| c.id).collect())),
_ => return Err(bad(C, "not a blend")),
}
}
None => selected_spec(s),
};
let Some((_, cur, _)) = target else {
if ["easingType", "ramp", "colorShift"].iter().any(|key| p.get(*key).is_some_and(|v| !v.is_null())) {
return Err(bad(C, "select a blend to set easing or color shift"));
}
// Nothing to set them on: the options new blends start with (easing is per blend).
let d = s.prefs.blend_options.unwrap_or_default();
let spacing = spacing_param(p, C, d.spacing)?;
s.prefs.blend_options = Some(BlendDefaults { spacing, orientation: orientation_param(p, d.orientation), ..d });
let orientation = orientation_param(p, C, d.orientation)?;
s.prefs.blend_options = Some(BlendDefaults { spacing, orientation, ..d });
return Ok(json!({ "defaults": true }));
};
if gives_easing(p) && any_without_spine(s) {
let no_spine = if id.is_some() { cur.no_spine } else { any_without_spine(s) };
if gives_easing(p) && no_spine {
return Err(bad(C, "the blend has no spine"));
}
// Every value is checked before anything changes. Each blend then takes only the values that
// were given and keeps its own for the rest, so editing several blends does not copy the first
// one's options onto the others.
let given = |key: &str| p.get(key).is_some_and(|v| !v.is_null());
let has_count = given("value") || given("steps") || given("distance");
let has_spacing = given("spacing") || has_count || p.get("smooth").and_then(Value::as_bool) == Some(true);
let spacing = spacing_param(p, C, cur.spacing)?;
let orientation = orientation_param(p, cur.orientation);
let orientation = orientation_param(p, C, cur.orientation)?;
let ease = ease_param(p, C, cur.ease)?;
let color_shift = percent_param(p, C, "colorShift", cur.color_shift, -100.0)?;
edit_blends(s, "Blend Options", |_, spec| {
spec.spacing = spacing;
spec.orientation = orientation;
spec.ease = ease;
spec.color_shift = color_shift;
})
let (has_orientation, has_kind, has_ramp, has_shift) = (given("orientation"), given("easingType"), given("ramp"), given("colorShift"));
let set = |spec: &mut BlendSpec| {
// A spacing mode without a count keeps the count of a blend already in that mode.
let same_mode = std::mem::discriminant(&spacing) == std::mem::discriminant(&spec.spacing);
if has_spacing && (has_count || !same_mode) {
spec.spacing = spacing;
}
if has_orientation {
spec.orientation = orientation;
}
if has_kind {
spec.ease.kind = ease.kind;
}
if has_ramp {
spec.ease.ramp = ease.ramp;
}
if has_shift {
spec.color_shift = color_shift;
}
};
let targets = match id {
Some(id) => vec![id],
None => selected_of(s, is_blend),
};
let doc = &s.doc()?.doc;
let changes = |b: &NodeId| match doc.node(*b).map(|n| &n.kind) {
Some(NodeKind::Blend { spec, .. }) => {
let mut next = (**spec).clone();
set(&mut next);
next != **spec
}
_ => false,
};
if !targets.iter().any(changes) {
return ok();
}
match id {
Some(id) => {
s.edit("Blend Options", |d, _| {
if let Some(NodeKind::Blend { spec, .. }) = d.node_mut(id).map(|n| &mut n.kind) {
set(spec);
}
Ok(())
})?;
ok()
}
None => edit_blends(s, "Blend Options", |_, spec| set(spec)),
}
}
pub(super) fn blend_set_easing(s: &mut Session, p: &Value) -> Result<Value> {
+1 -1
View File
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Blend Options…",
["Object", "Blend"],
None,
"{spacing?: smooth|steps|distance, value?: n, steps?: n, distance?: pt, orientation?: page|path, smooth?: bool, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct, colorShift?: pct} set the options of the selected blends; easingType chooses the distribution, ramp sets its strength (0..100; 0 = even), colorShift (-100..100; 0 = even) shifts colours independently of shape/position easing (omitted ones keep their value; out of range is an error); with no blend selected, the options new blends start with (spacing and orientation only; a tool setting, not an undo step) → {defaults?: true}",
"{id?: id, spacing?: smooth|steps|distance, value?: n, steps?: n, distance?: pt, orientation?: page|path, smooth?: bool, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct, colorShift?: pct} set the options of the selected blends (or of the blend `id` alone; a hidden or locked one is an error); easingType chooses the distribution, ramp sets its strength (0..100; 0 = even), colorShift (-100..100; 0 = even) shifts colours independently of shape/position easing (each blend keeps its own value for every option omitted; out of range is an error and changes nothing; no undo step when nothing changes); with no blend selected and no `id`, the options new blends start with (spacing and orientation only; a tool setting, not an undo step) → {defaults?: true}",
always,
blend_options
),
+14 -7
View File
@@ -1,7 +1,7 @@
use super::mesh::whole;
use super::{
Arc, BlendEase, BlendEaseType, BlendOrientation, BlendSpacing, Document, EngineError, Node, NodeId, NodeKind, Result, Selection, Session, Value,
bad, check_numbers, has_selection, json, named_ids, selected_roots, str_param, switch_or,
bad, check_numbers, has_selection, json, named_ids, selected_roots, switch_or, text_param,
};
pub(super) fn ids_json(ids: &[NodeId]) -> Value {
@@ -128,8 +128,11 @@ pub(super) fn spacing_param(p: &Value, cmd: &str, current: BlendSpacing) -> Resu
let smooth = switch_or(p, "smooth", false, cmd)?;
let num = |k: &str| p.get(k).and_then(Value::as_f64);
let steps = |k: &str, n: f64| whole(n, k, cmd).map(|n| BlendSpacing::Steps(n as u32));
let mode = str_param(p, "spacing");
let mode = text_param(p, "spacing", cmd)?;
let value = num("value");
if mode.is_none() && value.is_some() {
return Err(bad(cmd, "`value` needs `spacing` (steps|distance)"));
}
let sp = match mode {
Some("smooth") | Some("smoothColor") => BlendSpacing::SmoothColor,
Some("steps") => match value {
@@ -157,11 +160,15 @@ pub(super) fn spacing_param(p: &Value, cmd: &str, current: BlendSpacing) -> Resu
}
}
pub(super) fn orientation_param(p: &Value, current: BlendOrientation) -> BlendOrientation {
match str_param(p, "orientation") {
Some("path") | Some("alignToPath") => BlendOrientation::AlignToPath,
Some("page") | Some("alignToPage") => BlendOrientation::AlignToPage,
_ => current,
/// `orientation`: `page` or `path`; missing or null keeps `current`, and any other value is an error.
pub(super) fn orientation_param(p: &Value, cmd: &str, current: BlendOrientation) -> Result<BlendOrientation> {
match p.get("orientation").filter(|v| !v.is_null()) {
None => Ok(current),
Some(v) => match v.as_str() {
Some("path") | Some("alignToPath") => Ok(BlendOrientation::AlignToPath),
Some("page") | Some("alignToPage") => Ok(BlendOrientation::AlignToPage),
_ => Err(bad(cmd, "orientation must be page or path")),
},
}
}
+6 -1
View File
@@ -80,11 +80,16 @@ pub(super) fn send_to_current_layer(s: &mut Session, _: &Value) -> Result<Value>
if st.doc.children(Some(layer)).is_some_and(|c| c.iter().rev().filter(art).map(|n| n.id).take(ids.len()).eq(ids.iter().rev().copied())) {
return ok();
}
s.edit("Send to Current Layer", |d, _| {
let placed: Vec<(NodeId, Option<NodeId>)> = ids.iter().map(|i| (*i, st.doc.parent_of(*i))).collect();
let left = crate::cmd::intertwine::groups_of(&st.doc, &ids);
s.edit("Send to Current Layer", |d, sel| {
let moved = d.remove_many(&ids)?;
let ch = d.children_mut(Some(layer))?;
let at = Node::guide_run_start(ch);
ch.splice(at..at, moved);
// Members sent out of an Intertwine group leave it as ordinary art.
crate::cmd::intertwine::settle_members(d, &placed, &left)?;
sel.prune(d);
Ok(())
})?;
ok()
+3 -3
View File
@@ -260,7 +260,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Align",
["Window", "Align"],
None,
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", to?: \"selection\"|\"artboard\"|\"key\" (default: the key object when the selection has one, select.key, else the selection; a key guide, select.key {guide}, stays put and the objects line up on its line: a vertical guide sets where left, center and right go and vertical alignment leaves them, a horizontal one the other way round; aligning to the key, the other selected ruler guides move too: a vertical guide to the key's left edge, center or right edge, a horizontal one to its top, center or bottom; aligning to the artboard moves selected guides to its edges too (#3463), and with only guides selected aligning to the selection moves them to their collective bounds), artboard?: index (0-based; with to: \"artboard\", the artboard to align to; the app passes the active one; default: the artboard under the center of the selection, else the first), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} With anchor points selected (Direct Selection), the points align instead: to their own bounds, to the artboard (#1180), or, aligning to the key with a key anchor (select.key {id, anchor}), to the key anchor, which stays put",
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", to?: \"selection\"|\"artboard\"|\"key\" (default: the key object when the selection has one, select.key, else the selection; a key guide, select.key {guide}, stays put and the objects line up on its line: a vertical guide sets where left, center and right go and vertical alignment leaves them, a horizontal one the other way round; aligning to the key, the other selected ruler guides move too: a vertical guide to the key's left edge, center or right edge, a horizontal one to its top, center or bottom; aligning to the artboard moves selected guides to its edges too (#3463), and with only guides selected aligning to the selection moves them to their collective bounds), artboard?: index (0-based; with to: \"artboard\", the artboard to align to; the app passes the active one; default: the artboard under the center of the selection, else the first), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes, geometry effects and projected 3D art), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} With anchor points selected (Direct Selection), the points align instead: to their own bounds, to the artboard (#1180), or, aligning to the key with a key anchor (select.key {id, anchor}), to the key anchor, which stays put",
has_selection_or_guides,
align
),
@@ -269,7 +269,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Distribute",
["Window", "Align"],
None,
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", spacing?: pt (used with a key, select.key: the key object, or the key guide, select.key {guide}, stays put and the lines are placed this far apart, outward from its line, in their order on that line; 0 puts them all on its line; a key guide along the axis leaves everything where it is; not used without a key, or with anchor points selected and no key anchor), to?: \"selection\"|\"artboard\"|\"key\" (default: the key while there is one, else the selection; \"key\" without spacing distributes as \"selection\" does; with anchor points selected, with \"selection\" or \"artboard\" the key anchor is not the key and all the points are spaced as without one; not used with spacing and a key object; with a key guide, \"selection\" or \"artboard\" distributes without it as the key), artboard?: index (0-based; with to: \"artboard\", the artboard to distribute across; the app passes the active one; default: as object.align's), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} space the selected objects' left edges, centers or right edges (top edges, centers or bottom edges) in their order on that line, with the selected ruler guides across the axis (vertical ones for horizontal; #1597): a guide has no size, so its edges and center are its line, and guides along the axis stay. Without spacing and a key they are spaced evenly, the first and last stay put, and fewer than three don't move; with spacing and a key, see spacing (two are enough); with to: \"artboard\", the first one's left (top) edge goes to the artboard's left (top) edge, the last one's right (bottom) edge goes to the artboard's right (bottom) edge, and two are enough. With anchor points selected (Direct Selection), the points are spaced evenly between the first and the last along the axis instead (#1636); with spacing and a key anchor (select.key {id, anchor}), the key anchor stays put and the others are placed spacing apart, outward from it, in their order along the axis",
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", spacing?: pt (used with a key, select.key: the key object, or the key guide, select.key {guide}, stays put and the lines are placed this far apart, outward from its line, in their order on that line; 0 puts them all on its line; a key guide along the axis leaves everything where it is; not used without a key, or with anchor points selected and no key anchor), to?: \"selection\"|\"artboard\"|\"key\" (default: the key while there is one, else the selection; \"key\" without spacing distributes as \"selection\" does; with anchor points selected, with \"selection\" or \"artboard\" the key anchor is not the key and all the points are spaced as without one; not used with spacing and a key object; with a key guide, \"selection\" or \"artboard\" distributes without it as the key), artboard?: index (0-based; with to: \"artboard\", the artboard to distribute across; the app passes the active one; default: as object.align's), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes, geometry effects and projected 3D art), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} space the selected objects' left edges, centers or right edges (top edges, centers or bottom edges) in their order on that line, with the selected ruler guides across the axis (vertical ones for horizontal; #1597): a guide has no size, so its edges and center are its line, and guides along the axis stay. Without spacing and a key they are spaced evenly, the first and last stay put, and fewer than three don't move; with spacing and a key, see spacing (two are enough); with to: \"artboard\", the first one's left (top) edge goes to the artboard's left (top) edge, the last one's right (bottom) edge goes to the artboard's right (bottom) edge, and two are enough. With anchor points selected (Direct Selection), the points are spaced evenly between the first and the last along the axis instead (#1636); with spacing and a key anchor (select.key {id, anchor}), the key anchor stays put and the others are placed spacing apart, outward from it, in their order along the axis",
can_distribute,
distribute
),
@@ -278,7 +278,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Distribute Spacing",
["Window", "Align"],
None,
"{axis?: \"horizontal\"|\"vertical\" (default: \"horizontal\"), spacing?: pt (the key object, select.key, or the key guide, select.key {guide}, stays put and the others are spaced from it; a key guide along the axis leaves everything where it is), to?: \"selection\"|\"artboard\"|\"key\" (used without spacing, and with a key guide; with anchor points selected, with \"selection\" or \"artboard\" the key anchor is not the key and all the points are spaced as without one; default: the key while there is one, else the selection; \"key\" without spacing spaces as \"selection\" does), artboard?: index (0-based; with to: \"artboard\", the artboard to space across; the app passes the active one; default: as object.align's), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} without spacing, make the gaps between the selected objects equal, in the order of their left (top) edges, with the selected ruler guides across the axis as items with no size (#1597; guides along the axis stay): the first item's left (top) edge and the last one's right (bottom) edge stay put, or with to: \"artboard\" go to the artboard's left (top) and right (bottom) edges. With anchor points selected (Direct Selection), the points are spaced evenly along the axis instead, or `spacing` apart from the first (#1636), or with a key anchor (select.key {id, anchor}) `spacing` apart outward from the key anchor, which stays put",
"{axis?: \"horizontal\"|\"vertical\" (default: \"horizontal\"), spacing?: pt (the key object, select.key, or the key guide, select.key {guide}, stays put and the others are spaced from it; a key guide along the axis leaves everything where it is), to?: \"selection\"|\"artboard\"|\"key\" (used without spacing, and with a key guide; with anchor points selected, with \"selection\" or \"artboard\" the key anchor is not the key and all the points are spaced as without one; default: the key while there is one, else the selection; \"key\" without spacing spaces as \"selection\" does), artboard?: index (0-based; with to: \"artboard\", the artboard to space across; the app passes the active one; default: as object.align's), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes, geometry effects and projected 3D art), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} without spacing, make the gaps between the selected objects equal, in the order of their left (top) edges, with the selected ruler guides across the axis as items with no size (#1597; guides along the axis stay): the first item's left (top) edge and the last one's right (bottom) edge stay put, or with to: \"artboard\" go to the artboard's left (top) and right (bottom) edges. With anchor points selected (Direct Selection), the points are spaced evenly along the axis instead, or `spacing` apart from the first (#1636), or with a key anchor (select.key {id, anchor}) `spacing` apart outward from the key anchor, which stays put",
can_distribute,
distribute_spacing
),
+21 -6
View File
@@ -153,6 +153,20 @@ fn page_fonts(name: &str, bytes: &[u8], path: &str, pages: &PlacedPages) -> BTre
fonts
}
/// The document whose links are copied beside the placed file `name` (`bytes`), which is copied
/// as it is: a `.ai` file's editing data ([`super::place::document::editing_data`]), or the native
/// document an EPS or PostScript file carries, which placing it reads. `None` for other files and
/// for data that can't be read.
fn editing_data(name: &str, bytes: &[u8]) -> Option<Document> {
if let Some(doc) = super::place::document::editing_data(name, bytes) {
return Some(doc);
}
if !super::place::document::is_postscript(bytes) {
return None;
}
vectorcraft_format::load(&vectorcraft_eps::native(bytes)?).ok()
}
/// Collect dependencies depth-first so nested VectorCraft files are rewritten before
/// their parents: each parent can record the final hash of the rewritten child.
/// Cycles, excessive nesting, and unreadable children are reported, not fatal.
@@ -200,7 +214,7 @@ impl<'a> Collector<'a> {
self.warnings.push(message);
}
/// Warns when a file that placed `.ai` file `source` links (`name`) was copied as `copy`: the
/// Warns when a file that placed `.ai` or EPS file `source` links (`name`) was copied as `copy`: the
/// copy of `source` finds it only by its name, beside it.
/// `path` is the link's path as the warning names it.
fn renamed(&mut self, lines: &mut Vec<String>, source: &str, path: &str, name: &str, copy: &str) {
@@ -213,8 +227,8 @@ impl<'a> Collector<'a> {
}
}
/// Collects the files `doc` links. `by_name`: `doc` is a placed `.ai` file's editing data,
/// whose links are not rewritten, so its copy finds them by name beside it. `lookup`: the
/// Collects the files `doc` links. `by_name`: `doc` is a placed `.ai` or EPS file's editing
/// data, whose links are not rewritten, so its copy finds them by name beside it. `lookup`: the
/// document whose links (with the same paths as `doc`'s) are looked for, and where from, when
/// not `doc` from `source`.
fn collect(
@@ -311,12 +325,13 @@ impl<'a> Collector<'a> {
if by_name {
self.renamed(&mut lines, source, &shown, &file.name, &destination_file);
}
// A placed PDF or .ai file is copied as it is, as an image is; the files a .ai file
// read from its editing data links are copied beside it.
// A placed PDF, .ai or EPS file is copied as it is, as an image is; the files a .ai
// file read from its editing data, or an EPS file read from the native document it
// carries, links are copied beside it.
let pages = placed.get(&file.path);
let placed_file = pages.is_some();
check_carried_scripts(&file.name, &bytes, found_path)?;
if placed_file && let Some(mut art) = super::place::document::editing_data(&file.name, &bytes) {
if placed_file && let Some(mut art) = editing_data(&file.name, &bytes) {
if depth >= vectorcraft_doc::placed_document::MAX_DEPTH {
self.warn(&mut lines, format!("{shown}: nesting limit reached; copied unchanged without collecting its own links"));
} else {
+70 -5
View File
@@ -1874,20 +1874,85 @@ fn cut_at_anchors(s: &mut Session, _: &Value) -> Result<Value> {
}
cut.finish(d)?;
// Each cut leaves one of its two coincident anchors selected, so a drag pulls the ends apart.
sel.clear();
for (id, a) in picked {
sel.add(id);
sel.anchors.entry(id).or_default().insert(a);
}
select_cut_ends(sel, &picked);
Ok(all)
})?;
Ok(super::draw2::ids_json(&ids))
}
/// Replaces the selection with the anchors in `picked`: each id once, in the order it first
/// appears, with every anchor listed for it. An empty `picked` clears the selection.
fn select_cut_ends(sel: &mut Selection, picked: &[(NodeId, (usize, usize))]) {
sel.set(picked.iter().map(|(id, _)| *id));
for (id, a) in picked {
sel.anchors.entry(*id).or_default().insert(*a);
}
}
#[cfg(test)]
mod tests {
use super::*;
/// `select_cut_ends` by clearing the selection and adding each id in turn, kept as the
/// reference the one-call version must match.
fn select_cut_ends_one_by_one(sel: &mut Selection, picked: &[(NodeId, (usize, usize))]) {
sel.clear();
for (id, a) in picked {
sel.add(*id);
sel.anchors.entry(*id).or_default().insert(*a);
}
}
/// A selection with every field set, the art made since the last deselect included.
fn busy_selection() -> Selection {
Selection {
objects: vec![NodeId(90), NodeId(91)],
anchors: [(NodeId(90), [(0, 3)].into())].into(),
segments: [(NodeId(91), [(0, 1)].into())].into(),
key: Some(NodeId(90)),
target: Some(NodeId(91)),
slices: vec![NodeId(92)],
guides: vec![NodeId(93)],
key_guide: Some(NodeId(93)),
key_anchor: Some((NodeId(90), (0, 3))),
symbol_part: Some(vectorcraft_doc::SymbolPart { instance: NodeId(94), path: vec![0, 2] }),
on_path_member: Some(NodeId(95)),
new_art: Arc::new([NodeId(90), NodeId(97)].into()),
}
}
/// The cut ends of open paths, of an opened closed path, of a path of several subpaths (one id
/// with several anchors, first seen before other ids), long lists and an empty one give the
/// same selection, every field, as clearing it and adding each id in turn.
#[test]
fn selecting_cut_ends_matches_adding_them_one_by_one() {
let n = NodeId;
let mut cases: Vec<Vec<(NodeId, (usize, usize))>> = vec![
vec![],
vec![(n(1), (0, 0)), (n(2), (0, 0))],
vec![(n(5), (0, 0))],
vec![(n(7), (0, 0)), (n(3), (1, 0)), (n(8), (0, 0)), (n(3), (2, 0)), (n(7), (0, 0)), (n(3), (0, 0))],
];
let mut rng = Lcg(11);
for len in [50, 2_000] {
cases.push((0..len).map(|_| (n(rng.below(300) + 1), (rng.below(4) as usize, 0))).collect());
}
for picked in &cases {
for start in [Selection::default(), busy_selection()] {
let (mut ours, mut theirs) = (start.clone(), start.clone());
select_cut_ends(&mut ours, picked);
select_cut_ends_one_by_one(&mut theirs, picked);
assert_eq!(ours, theirs, "{picked:?}");
assert_eq!(ours.new_art, start.new_art);
}
}
let mut sel = busy_selection();
select_cut_ends(&mut sel, &cases[3]);
assert_eq!(sel.objects, [n(7), n(3), n(8)]);
assert_eq!(sel.anchors[&n(3)].iter().collect::<Vec<_>>(), [&(0, 0), &(1, 0), &(2, 0)]);
assert_eq!((sel.anchors.len(), sel.key, sel.target, sel.symbol_part.is_some()), (3, None, None, false));
}
/// `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 {
@@ -548,6 +548,7 @@ pub(super) const ALLOWED: &[&str] = &[
"select.toggle",
"select.update",
"shape.arc",
"shape.circleThroughPoints",
"shape.ellipse",
"shape.flare",
"shape.line",
+28 -1
View File
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Print Setup",
[],
None,
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100} (% with custom and tiling), overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks are not marked, and paints already set to overprint keep it; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)",
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks are not marked, and paints already set to overprint keep it; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)",
has_doc,
setup
),
@@ -82,11 +82,38 @@ pub(crate) fn settings_over(cmd: &str, mut v: Value, p: &Value) -> Result<PrintS
Some(over @ Value::Object(_)) => merge(&mut v, over),
Some(_) => return Err(bad(cmd, "settings must be an object")),
}
link_scale(cmd, &mut v, p.get("settings").and_then(|s| s.get("scale")).filter(|s| s.is_object()))?;
let set = PrintSettings::deserialize(&v).map_err(|e| bad(cmd, format!("print settings: {e}")))?;
set.check().map_err(|e| pdf_error(cmd, e))?;
Ok(set)
}
/// Keep the custom scale's width and height equal in the merged settings `v` while `scale.linked`
/// is on, after `over` (the request's `scale`) was merged in: the one side the request gives sets
/// the other, and otherwise the height takes the width (as turning the link on does). A request
/// that gives a different width and height without a `linked` key turns the link off; with
/// `linked: true`, or with `linked: null` over a linked scale, it is refused.
fn link_scale(cmd: &str, v: &mut Value, over: Option<&Value>) -> Result<()> {
let given = |k: &str| over.and_then(|o| o.get(k)).filter(|x| !x.is_null());
let (width, height) = (given("width").cloned(), given("height").cloned());
let apart = matches!((&width, &height), (Some(w), Some(h)) if w.as_f64() != h.as_f64());
let Some(scale) = v.get_mut("scale").and_then(Value::as_object_mut) else { return Ok(()) };
if apart && over.and_then(|o| o.get("linked")).is_none() {
scale.insert("linked".into(), Value::Bool(false));
}
if scale.get("linked") != Some(&Value::Bool(true)) {
return Ok(());
}
if apart {
return Err(bad(cmd, "scale: give one percentage, or the same width and height, while scale.linked is on (linked: false scales them apart)"));
}
let (from, to) = if width.is_none() && height.is_some() { ("height", "width") } else { ("width", "height") };
if let Some(value) = scale.get(from).cloned() {
scale.insert(to.into(), value);
}
Ok(())
}
pub(crate) fn to_json(set: &PrintSettings) -> Result<Value> {
serde_json::to_value(set).map_err(|e| EngineError::Other(e.to_string()))
}
+61 -30
View File
@@ -378,11 +378,12 @@ pub(crate) fn raster_pixels(d: &Document, n: &Node, below: bool, members: bool)
/// The image Object › Rasterize makes of `n` with the options of `n`'s Effect › Rasterize, when
/// that is its only visible raster effect and is its own (not a fill's or a stroke's): made of `n`
/// without that effect and without its transparency, which stays on the object. When Transform
/// effects after the Rasterize effect move its image ([`vectorcraft_render::rasterize_stage`]),
/// the image is made of the art before them and moved by them, as the canvas draws it. `None`
/// otherwise, when those Transform effects flatten the image, or when the image can't be made.
/// effects after the Rasterize effect move or copy its image ([`vectorcraft_render::rasterize_stage`]),
/// the image is made of the art before them once and placed by each of their maps, as the canvas
/// draws it: with copies, a group of the placements with the lowest first. `None` otherwise, when
/// those Transform effects flatten every placement, or when the image can't be made.
fn rasterize_effect_image(d: &mut Document, n: &Node) -> Option<Node> {
let (whole, r, map) = rasterize_effect_art(d, n)?;
let (whole, r, maps) = rasterize_effect_art(d, n)?;
let p = json!({
"ppi": r.ppi.unwrap_or(d.raster_effects_ppi),
"colorModel": r.color_model.id(),
@@ -395,33 +396,58 @@ fn rasterize_effect_image(d: &mut Document, n: &Node) -> Option<Node> {
// image's transparency would need one too; upgrade when CMYK images carry alpha.
let image = super::menucmds::rasterize_art(d, vec![whole], &p, "object.rasterize", false).ok()?;
let mut image = image.into_node(d);
if let Some(map) = map {
image.transform(map, false);
match maps.as_deref() {
None => Some(image),
Some([map]) => {
image.transform(*map, false);
Some(image)
}
Some(maps) => {
// Each placement is an object of its own on the one image's pixels.
let placed: Vec<Arc<Node>> = maps
.iter()
.map(|map| {
let mut copy = d.reid(&image);
copy.transform(*map, false);
Arc::new(copy)
})
.collect();
Some(Node::group(d.alloc_id(), placed))
}
}
Some(image)
}
/// What [`rasterize_effect_image`] makes its image of: `n`, or the art before the Transform effects
/// that move the image, without the Rasterize effect and without its transparency; that effect's
/// options; and the map those Transform effects move the image by. `None` when `n` has another
/// raster effect, when the Rasterize effect is not its own, or when those Transform effects
/// flatten the image.
fn rasterize_effect_art(d: &Document, n: &Node) -> Option<(Node, effects::Rasterize, Option<Affine>)> {
/// that move or copy the image, without the Rasterize effect and without its transparency; that
/// effect's options; and the maps those Transform effects place the image by, the lowest first,
/// without those that flatten it. `None` when `n` has another raster effect, when the Rasterize
/// effect is not its own, or when those Transform effects flatten every placement.
fn rasterize_effect_art(d: &Document, n: &Node) -> Option<(Node, effects::Rasterize, Option<Vec<Affine>>)> {
let [RasterFx::Rasterize(r)] = raster_fx(n)[..] else { return None };
let staged = vectorcraft_render::rasterize_stage(d, n);
if let Some((_, map)) = &staged
&& !(map.determinant().is_finite() && map.determinant().abs() > 1e-12)
{
return None;
}
let (stage, map) = staged.map_or((None, None), |(stage, map)| (Some(stage), Some(map)));
let (stage, maps) = match vectorcraft_render::rasterize_stage(d, n) {
Some((stage, maps)) => {
let maps: Vec<Affine> = maps.into_iter().filter(|m| places(*m)).collect();
if maps.is_empty() {
return None;
}
(Some(stage), Some(maps))
}
None => (None, None),
};
let n = stage.as_ref().unwrap_or(n);
let at = n.appearance.effects.iter().position(|e| e.visible && e.id == effects::RASTERIZE)?;
let mut whole = n.clone();
whole.appearance.effects.remove(at);
(whole.opacity, whole.blend) = (1.0, Default::default());
whole.extras_mut().mask = None;
Some((whole, r, map))
Some((whole, r, maps))
}
/// Does `map`, one of those a Rasterize image is placed by ([`vectorcraft_render::rasterize_stage`]),
/// place it? Not when it flattens it to a line or a point: the canvas draws nothing there.
fn places(map: Affine) -> bool {
let det = map.determinant();
det.is_finite() && det.abs() > 1e-12
}
/// `v` (an object without its raster effects) replaced by `image` of the object with them: the
@@ -658,27 +684,32 @@ fn walk_all(out: &mut Document, nodes: &[Arc<Node>], report: &mut FlattenReport)
.then(|| nodes.iter().map(|n| walk(out, n, report).map(Arc::new).unwrap_or_else(|| n.clone())).collect())
}
/// `n` as an image when its Rasterize image moves with the Transform effects after it
/// ([`vectorcraft_render::rasterize_stage`]): the image is made of the art before those Transform
/// effects and moved by them, as the canvas draws it, which baking the geometry effects first would
/// lose. A map that flattens the image leaves an empty group, as the canvas draws nothing. Inside
/// groups, layers and opacity masks, the members are looked at the same way. `None` when nothing in
/// `n` changes; hidden objects and template layers stay as they are.
/// `n` as an image when its Rasterize image moves with the Transform effects after it, or as a
/// group of that image's placements when they copy it ([`vectorcraft_render::rasterize_stage`]):
/// the image is made of the art before those Transform effects and placed by them, as the canvas
/// draws it, which baking the geometry effects first would lose. Maps that flatten every placement
/// leave an empty group, as the canvas draws nothing. Inside groups, layers and opacity masks, the
/// members are looked at the same way. `None` when nothing in `n` changes; hidden objects and
/// template layers stay as they are.
fn staged(out: &mut Document, n: &Node, report: &mut FlattenReport) -> Option<Node> {
if !n.visible || matches!(n.kind, NodeKind::Layer { template: true, .. }) {
return None;
}
if let Some((_, map)) = vectorcraft_render::rasterize_stage(out, n) {
if let Some((_, maps)) = vectorcraft_render::rasterize_stage(out, n) {
let mut v = n.clone();
strip_raster(&mut v, false);
let det = map.determinant();
if !(det.is_finite() && det.abs() > 1e-12) {
if !maps.iter().any(|m| places(*m)) {
v.appearance = Default::default();
v.kind = NodeKind::Group { children: vec![], clip: false };
return Some(v);
}
let image = raster_image(out, n, false, false)?;
report.record(n, &image);
// The placements share one image: its resolution is the first one's.
let first = match &image.kind {
NodeKind::Group { children, clip: false } => children.first().map_or(&image, |c| &**c),
_ => &image,
};
report.record(n, first);
let mut m = replace_with_image(v, image);
staged_mask(out, &mut m, report);
return Some(m);
+56 -31
View File
@@ -308,24 +308,30 @@ pub(crate) fn selectable(d: &Document, iso: Option<NodeId>) -> Vec<NodeId> {
/// them, leaving out every hidden or locked object with what it holds. `f` returns whether to
/// visit the objects inside the one it is given.
pub(crate) fn walk_selectable(d: &Document, iso: Option<NodeId>, mut f: impl FnMut(&Node) -> bool) {
fn inside(n: &Node, f: &mut impl FnMut(&Node) -> bool) {
if n.visible && !n.locked && f(n) {
walk_selectable_in(d, iso, |n, _| f(n));
}
/// [`walk_selectable`], handing `f` each object with the node that holds it in the tree: its
/// layer, sublayer, group or other container, or `None` for a top-level layer.
fn walk_selectable_in(d: &Document, iso: Option<NodeId>, mut f: impl FnMut(&Node, Option<&Node>) -> bool) {
fn inside(n: &Node, parent: Option<&Node>, f: &mut impl FnMut(&Node, Option<&Node>) -> bool) {
if n.visible && !n.locked && f(n, parent) {
for c in n.children().into_iter().flatten() {
inside(c, f);
inside(c, Some(n), f);
}
}
}
fn find(n: &Node, tops: &BTreeSet<NodeId>, f: &mut impl FnMut(&Node) -> bool) {
fn find(n: &Node, parent: Option<&Node>, tops: &BTreeSet<NodeId>, f: &mut impl FnMut(&Node, Option<&Node>) -> bool) {
if tops.contains(&n.id) {
return inside(n, f);
return inside(n, parent, f);
}
for c in n.children().into_iter().flatten() {
find(c, tops, f);
find(c, Some(n), tops, f);
}
}
let tops: BTreeSet<NodeId> = selectable(d, iso).into_iter().collect();
for l in &d.layers {
find(l, &tops, &mut f);
find(l, None, &tops, &mut f);
}
}
@@ -1098,7 +1104,9 @@ fn select_color(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "give `fill`, `stroke` or both"));
}
let reads_as = |paint: Paint, hex: Option<&str>| hex.is_none_or(|h| paint.color().is_some_and(|c| c.to_hex() == h));
select_where(s, C, p, |d, n| paint_reported(d, n) && reads_as(fill_of(n), fill.as_deref()) && reads_as(stroke_of(n).0, stroke.as_deref()))
select_where(s, C, p, |_, n, parent| {
paint_reported(n, parent) && reads_as(fill_of(n), fill.as_deref()) && reads_as(stroke_of(n).0, stroke.as_deref())
})
}
/// The longest note, in bytes, that Select by Note searches for.
@@ -1219,11 +1227,11 @@ fn fold_case(c: char) -> impl Iterator<Item = char> {
c.to_lowercase().map(|l| if l == 'ς' { 'σ' } else { l })
}
/// Does `document.inspect` report a fill and stroke for `n`? A compound path's are its own, though
/// it holds its members, and its members report none.
fn paint_reported(d: &Document, n: &Node) -> bool {
/// Does `document.inspect` report a fill and stroke for `n`, held by `parent`? A compound path's
/// are its own, though it holds its members, and its members report none.
fn paint_reported(n: &Node, parent: Option<&Node>) -> bool {
let compound = |n: &Node| matches!(n.kind, NodeKind::Compound { .. });
compound(n) || (!n.is_container() && !d.parent_of(n.id).and_then(|p| d.node(p)).is_some_and(compound))
compound(n) || (!n.is_container() && !parent.is_some_and(compound))
}
/// The object Select > Same compares the others with, and whether isolation mode is inside a
@@ -1260,30 +1268,30 @@ fn same_fill(s: &mut Session, cmd: &str, eq: impl Fn(&Node, &Node) -> bool) -> R
fn same_in(s: &mut Session, cmd: &str, live_paint: bool, eq: impl Fn(&Node, &Node) -> bool) -> Result<Value> {
let st = s.doc()?;
let (refn, members) = same_reference(st, cmd)?;
let group = live_paint_group(&st.doc, refn.id);
let group = live_paint_group(st.doc.parent_of(refn.id).and_then(|p| st.doc.node(p)));
let refn = refn.clone();
select_where(s, cmd, &json!({}), |d, n| {
(!live_paint || live_paint_group(d, n.id) == group) && (if members { !n.is_container() } else { paint_reported(d, n) }) && eq(n, &refn)
})
select_where(s, cmd, &json!({}), |_, n, parent| same_candidate(n, parent, live_paint, group, members) && eq(n, &refn))
}
/// The Live Paint group `id` is a face or edge of.
fn live_paint_group(d: &Document, id: NodeId) -> Option<NodeId> {
d.parent_of(id).filter(|p| d.node(*p).is_some_and(is_live_paint))
/// Whether Select > Same compares `n`, held by `parent`, with its reference: with `live_paint`, only
/// when `n` is a face or edge of the Live Paint group `group` (or of none, for `None`); in
/// isolation mode inside a compound path (`members`), any object that is not a container;
/// otherwise one that [`paint_reported`] accepts.
fn same_candidate(n: &Node, parent: Option<&Node>, live_paint: bool, group: Option<NodeId>, members: bool) -> bool {
(!live_paint || live_paint_group(parent) == group) && (if members { !n.is_container() } else { paint_reported(n, parent) })
}
/// The Live Paint group an object held by `parent` is a face or edge of.
fn live_paint_group(parent: Option<&Node>) -> Option<NodeId> {
parent.filter(|p| is_live_paint(p)).map(|p| p.id)
}
/// Select the objects [`walk_selectable`] visits that `f` accepts (not looking inside accepted
/// ones); Select > Reselect repeats `cmd` with `p`.
pub(crate) fn select_where(s: &mut Session, cmd: &str, p: &Value, f: impl Fn(&Document, &Node) -> bool) -> Result<Value> {
/// ones); `f` is given each object with the node that holds it. Select > Reselect repeats `cmd`
/// with `p`.
pub(crate) fn select_where(s: &mut Session, cmd: &str, p: &Value, f: impl Fn(&Document, &Node, Option<&Node>) -> bool) -> Result<Value> {
let st = s.doc()?;
let mut ids = vec![];
walk_selectable(&st.doc, st.isolation, |n| {
if f(&st.doc, n) {
ids.push(n.id);
return false;
}
true
});
let ids = matching(&st.doc, st.isolation, |n, parent| f(&st.doc, n, parent));
let from = st.selection.objects.clone();
s.select(|_, sel| sel.set(ids.iter().copied()))?;
let st = s.doc_mut()?;
@@ -1292,12 +1300,26 @@ pub(crate) fn select_where(s: &mut Session, cmd: &str, p: &Value, f: impl Fn(&Do
Ok(json!({ "count": st.selection.objects.len() }))
}
/// The objects [`walk_selectable`] visits that `f` accepts, in paint order, not looking inside
/// accepted ones. `f` is given each object with the node that holds it.
fn matching(d: &Document, iso: Option<NodeId>, f: impl Fn(&Node, Option<&Node>) -> bool) -> Vec<NodeId> {
let mut ids = vec![];
walk_selectable_in(d, iso, |n, parent| {
if f(n, parent) {
ids.push(n.id);
return false;
}
true
});
ids
}
fn same_graphic_style(s: &mut Session, _: &Value) -> Result<Value> {
let cmd = "select.same.graphicStyle";
let st = s.doc()?;
let (refn, _) = same_reference(st, cmd)?;
let id = super::style::linked_style(&st.doc, refn).map(|g| g.id).ok_or_else(|| bad(cmd, "the selection has no graphic style"))?;
select_where(s, cmd, &json!({}), |d, n| n.extras().graphic_style == Some(id) && super::style::linked_style(d, n).is_some())
select_where(s, cmd, &json!({}), |d, n, _| n.extras().graphic_style == Some(id) && super::style::linked_style(d, n).is_some())
}
/// An appearance attribute Select > Same > Appearance Attribute matches.
@@ -1321,7 +1343,7 @@ fn same_attribute(s: &mut Session, p: &Value) -> Result<Value> {
Attribute::Item(ap.items.iter().rev().find(|i| i.is_fill()).cloned().ok_or_else(|| bad(cmd, "the object has no fill, stroke or effect"))?)
}
};
select_where(s, cmd, p, |_, n| match &attr {
select_where(s, cmd, p, |_, n, _| match &attr {
Attribute::Item(it) => n.appearance.items.contains(it),
Attribute::Effect(e) => n.appearance.effects.iter().any(|x| x.id == e.id && x.params == e.params),
})
@@ -1381,5 +1403,8 @@ fn not_pixel_aligned(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({ "count": s.doc()?.selection.objects.len() }))
}
#[cfg(test)]
mod same_tests;
#[cfg(test)]
mod tests;
+433
View File
@@ -0,0 +1,433 @@
//! Select > Same and Select by Color through [`walk_selectable_in`], which hands each object the
//! node that holds it, against copies of the walk and the tests that looked each object's parent up
//! by its id.
use std::collections::BTreeSet;
use std::sync::Arc;
use std::time::{Duration, Instant};
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use super::{fill_of, is_live_paint, matching, same_candidate, same_paint, same_reference, selectable, stroke_of, walk_selectable_in};
use crate::Session;
/// `walk_selectable` as it was before it handed each object its parent.
fn walk_by_id(d: &Document, iso: Option<NodeId>, mut f: impl FnMut(&Node) -> bool) {
fn inside(n: &Node, f: &mut impl FnMut(&Node) -> bool) {
if n.visible && !n.locked && f(n) {
for c in n.children().into_iter().flatten() {
inside(c, f);
}
}
}
fn find(n: &Node, tops: &BTreeSet<NodeId>, f: &mut impl FnMut(&Node) -> bool) {
if tops.contains(&n.id) {
return inside(n, f);
}
for c in n.children().into_iter().flatten() {
find(c, tops, f);
}
}
let tops: BTreeSet<NodeId> = selectable(d, iso).into_iter().collect();
for l in &d.layers {
find(l, &tops, &mut f);
}
}
/// `paint_reported` as it was, looking up `n`'s parent by its id.
fn paint_reported_by_id(d: &Document, n: &Node) -> bool {
let compound = |n: &Node| matches!(n.kind, NodeKind::Compound { .. });
compound(n) || (!n.is_container() && !d.parent_of(n.id).and_then(|p| d.node(p)).is_some_and(compound))
}
/// `live_paint_group` as it was, looking up the parent of `id`.
fn live_paint_group_by_id(d: &Document, id: NodeId) -> Option<NodeId> {
d.parent_of(id).filter(|p| d.node(*p).is_some_and(is_live_paint))
}
/// The objects `select_where`'s loop took before the walk handed each object its parent.
fn matching_by_id(d: &Document, iso: Option<NodeId>, f: impl Fn(&Document, &Node) -> bool) -> Vec<NodeId> {
let mut ids = vec![];
walk_by_id(d, iso, |n| {
if f(d, n) {
ids.push(n.id);
return false;
}
true
});
ids
}
/// The objects `same_in` took before the walk handed each object its parent.
fn same_by_id(d: &Document, iso: Option<NodeId>, refn: &Node, members: bool, live_paint: bool, eq: impl Fn(&Node, &Node) -> bool) -> Vec<NodeId> {
let group = live_paint_group_by_id(d, refn.id);
matching_by_id(d, iso, |d, n| {
(!live_paint || live_paint_group_by_id(d, n.id) == group)
&& (if members { !n.is_container() } else { paint_reported_by_id(d, n) })
&& eq(n, refn)
})
}
/// The objects `same_in` takes now.
fn same_now(d: &Document, iso: Option<NodeId>, refn: &Node, members: bool, live_paint: bool, eq: impl Fn(&Node, &Node) -> bool) -> Vec<NodeId> {
let group = super::live_paint_group(d.parent_of(refn.id).and_then(|p| d.node(p)));
matching(d, iso, |n, parent| same_candidate(n, parent, live_paint, group, members) && eq(n, refn))
}
#[track_caller]
fn run(s: &mut Session, cmd: &str, p: Value) -> Value {
s.execute(cmd, &p).unwrap_or_else(|e| panic!("`{cmd}` {p} failed: {e}"))
}
fn id(v: &Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap_or_else(|| panic!("no id in {v}")))
}
fn sel(s: &mut Session, ids: &[NodeId]) {
run(s, "select.set", json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}));
}
/// A 10 × 10 rectangle at (`x`, `y`) filled with `hex`.
fn rect(s: &mut Session, x: f64, y: f64, hex: &str) -> NodeId {
let r = id(&run(s, "shape.rectangle", json!({"x": x, "y": y, "width": 10.0, "height": 10.0})));
run(s, "paint.setFill", json!({"ids": [r.0], "color": hex}));
r
}
/// A compound path of three rectangles at `y`, filled with `hex` → the compound path and its
/// member paths.
fn compound(s: &mut Session, y: f64, hex: &str) -> (NodeId, Vec<NodeId>) {
let members: Vec<NodeId> = [0.0, 20.0, 40.0].map(|x| rect(s, 300.0 + x, y, hex)).into();
sel(s, &members);
let c = id(&run(s, "object.compoundPath.make", json!({})));
run(s, "paint.setFill", json!({"ids": [c.0], "color": hex}));
(c, members)
}
/// A Live Paint group of two overlapping squares at `y`, its left face red, its middle face blue and
/// its right face red → the group and its faces.
fn live_paint(s: &mut Session, y: f64) -> (NodeId, Vec<NodeId>) {
let a = id(&run(s, "shape.rectangle", json!({"x": 0.0, "y": y, "width": 100.0, "height": 100.0})));
let b = id(&run(s, "shape.rectangle", json!({"x": 50.0, "y": y, "width": 100.0, "height": 100.0})));
sel(s, &[a, b]);
let g = id(&run(s, "livePaint.make", json!({})));
let faces = [(25.0, "#ff0000"), (75.0, "#0000ff"), (125.0, "#ff0000")]
.map(|(x, hex)| NodeId(run(s, "livePaint.fill", json!({"group": g.0, "point": [x, y + 50.0], "color": hex}))["face"].as_u64().unwrap()))
.into();
(g, faces)
}
/// The objects of [`rich`] that tests pick from.
struct Rich {
plain: Vec<NodeId>,
compound: NodeId,
members: Vec<NodeId>,
group: NodeId,
live_paint: NodeId,
faces: Vec<NodeId>,
sublayer: NodeId,
}
/// A document with red and blue rectangles, a compound path, a group with a hidden and a locked
/// rectangle, a locked group, a Live Paint group, a sublayer holding a rectangle and a second
/// compound path, and a hidden and a locked layer with a red rectangle each.
fn rich() -> (Session, Rich) {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 800, "height": 600}));
let layer = s.doc().unwrap().doc.layers[0].id;
let mut plain = vec![rect(&mut s, 0.0, 0.0, "#ff0000"), rect(&mut s, 20.0, 0.0, "#ff0000"), rect(&mut s, 40.0, 0.0, "#0000ff")];
let (compound_id, members) = compound(&mut s, 0.0, "#ff0000");
let [in_group, hidden, locked] = [0.0, 20.0, 40.0].map(|x| rect(&mut s, x, 200.0, "#ff0000"));
let blue = rect(&mut s, 60.0, 200.0, "#0000ff");
sel(&mut s, &[in_group, hidden, locked, blue]);
let group = id(&run(&mut s, "object.group", json!({})));
run(&mut s, "layer.setProps", json!({"id": hidden.0, "visible": false}));
run(&mut s, "layer.setProps", json!({"id": locked.0, "locked": true}));
let in_locked = rect(&mut s, 100.0, 200.0, "#ff0000");
sel(&mut s, &[in_locked]);
let locked_group = id(&run(&mut s, "object.group", json!({})));
run(&mut s, "layer.setProps", json!({"id": locked_group.0, "locked": true}));
let (live_paint_id, faces) = live_paint(&mut s, 300.0);
plain.extend([in_group, blue]);
let sublayer = id(&run(&mut s, "layer.newSublayer", json!({"parent": layer.0})));
plain.push(rect(&mut s, 0.0, 500.0, "#ff0000"));
compound(&mut s, 500.0, "#0000ff");
for prop in ["visible", "locked"] {
let l = id(&run(&mut s, "layer.new", json!({"top": true})));
rect(&mut s, 200.0, 500.0, "#ff0000");
run(&mut s, "layer.setProps", json!({"id": l.0, prop: prop == "locked"}));
}
let rich = Rich { plain, compound: compound_id, members, group, live_paint: live_paint_id, faces, sublayer };
(s, rich)
}
/// The isolation scopes to try: none, the group, the compound path, and the Live Paint group.
fn scopes(r: &Rich) -> [Option<NodeId>; 4] {
[None, Some(r.group), Some(r.compound), Some(r.live_paint)]
}
/// Isolate `iso`, leaving isolation mode first.
fn isolate(s: &mut Session, iso: Option<NodeId>) {
if s.doc().unwrap().isolation.is_some() {
run(s, "object.exitIsolation", json!({}));
}
if let Some(i) = iso {
run(s, "object.isolate", json!({"id": i.0}));
assert_eq!(s.doc().unwrap().isolation, Some(i));
}
}
/// The walk visits the objects it visited before, in the same order and with the same objects left
/// out, and hands each the node that `Document::parent_of` names for it.
#[test]
fn the_walk_hands_each_object_the_node_that_holds_it() {
let (mut s, r) = rich();
// Look inside everything, and inside every other object only.
let deeper: [fn(&Node) -> bool; 2] = [|_| true, |n| n.id.0 % 2 == 0];
for iso in scopes(&r) {
isolate(&mut s, iso);
let st = s.doc().unwrap();
let d = &st.doc;
for f in deeper {
let mut before = vec![];
walk_by_id(d, st.isolation, |n| {
before.push((n.id, d.parent_of(n.id)));
f(n)
});
let mut now = vec![];
walk_selectable_in(d, st.isolation, |n, parent| {
now.push((n.id, parent.map(|p| p.id)));
f(n)
});
assert!(!now.is_empty(), "isolating {iso:?}");
assert_eq!(now, before, "isolating {iso:?}");
}
}
// Every face, member path and the sublayer's art were visited somewhere above.
let st = s.doc().unwrap();
assert!(r.faces.iter().chain(&r.members).all(|f| st.doc.node(*f).is_some()));
assert!(st.doc.node(r.sublayer).is_some_and(|n| n.is_layer()));
}
/// Select > Same and Select by Color select the objects they selected before, in the same order,
/// with the same reply and the same Select > Reselect state, from every kind of reference object
/// and in every isolation scope.
#[test]
fn select_same_takes_the_objects_it_took_when_it_looked_up_parents() {
type Eq = fn(&Node, &Node) -> bool;
let fill: Eq = |a, b| same_paint(&fill_of(a), &fill_of(b), false);
let stroke: Eq = |a, b| same_paint(&stroke_of(a).0, &stroke_of(b).0, false);
let commands: [(&str, bool, Eq); 6] = [
("select.same.fillColor", true, fill),
("select.same.fillAndStroke", true, |a, b| {
same_paint(&fill_of(a), &fill_of(b), false) && same_paint(&stroke_of(a).0, &stroke_of(b).0, false)
}),
("select.same.strokeColor", false, stroke),
("select.same.opacity", false, |a, b| (a.opacity - b.opacity).abs() < 1e-6),
("select.same.blendingMode", false, |a, b| a.blend == b.blend),
("select.same.shapeType", false, |a, b| a.kind_label() == b.kind_label()),
];
let (mut s, r) = rich();
assert!(!s.prefs.select_same_tint_percent);
let froms: Vec<NodeId> = r.plain.iter().chain(&r.members).chain(&r.faces).copied().chain([r.compound]).collect();
let mut checked = 0;
for iso in scopes(&r) {
isolate(&mut s, iso);
for from in &froms {
for (cmd, live_paint, eq) in commands {
// An object outside the isolated one may not be selectable; the selection then
// stays, and both sides compare with what it holds.
let _ = s.execute("select.set", &json!({"ids": [from.0]}));
let st = s.doc().unwrap();
let Ok((refn, members)) = same_reference(st, cmd) else {
assert!(s.execute(cmd, &json!({})).is_err(), "{cmd} from {from:?} isolating {iso:?}");
continue;
};
let refn = refn.clone();
let expected = same_by_id(&st.doc, st.isolation, &refn, members, live_paint, eq);
assert_eq!(same_now(&st.doc, st.isolation, &refn, members, live_paint, eq), expected, "{cmd} from {from:?} isolating {iso:?}");
let before = st.selection.objects.clone();
let reply = run(&mut s, cmd, json!({}));
let st = s.doc().unwrap();
assert_eq!(st.selection.objects, expected, "{cmd} from {from:?} isolating {iso:?}");
assert_eq!(reply, json!({"count": expected.len()}));
assert_eq!(st.last_selection_cmd, Some((cmd.to_string(), json!({}), before)));
checked += 1;
}
}
for hex in ["#ff0000", "#0000ff"] {
let st = s.doc().unwrap();
let reads_as = |n: &Node| fill_of(n).color().is_some_and(|c| c.to_hex() == hex);
let expected = matching_by_id(&st.doc, st.isolation, |d, n| paint_reported_by_id(d, n) && reads_as(n));
let p = json!({"fill": hex});
let reply = run(&mut s, "select.color", p.clone());
let st = s.doc().unwrap();
assert_eq!(st.selection.objects, expected, "select.color {hex} isolating {iso:?}");
assert_eq!(reply, json!({"count": expected.len()}));
assert_eq!(st.last_selection_cmd.as_ref().map(|(c, p, _)| (c.as_str(), p)), Some(("select.color", &p)));
}
}
// Most of the references can be selected in some scope.
assert!(checked > froms.len() * commands.len(), "{checked} checks");
}
/// In a damaged document that holds an id twice, the parent that decides whether an object is a
/// member of a compound path or a face of a Live Paint group is the one that holds the object the
/// walk is at, not the one that holds the id's first place in the tree.
#[test]
fn select_same_reads_the_parent_of_the_object_it_is_at() {
for in_live_paint in [false, true] {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 800, "height": 600}));
let layer = s.doc().unwrap().doc.layers[0].id;
let (_, inner) = if in_live_paint { live_paint(&mut s, 300.0) } else { compound(&mut s, 0.0, "#0000ff") };
let from = rect(&mut s, 0.0, 0.0, "#ff0000");
// A red rectangle above the others that has the id of a face or member path.
let mut copy = s.doc().unwrap().doc.node(from).unwrap().clone();
copy.id = inner[0];
Arc::make_mut(&mut s.doc_mut().unwrap().doc).insert(Some(layer), usize::MAX, copy).unwrap();
let mut commands = vec![("select.same.fillColor", json!({})), ("select.same.fillAndStroke", json!({}))];
// Select by Color takes the red faces of a Live Paint group too, so it is tried on the
// compound path only.
if !in_live_paint {
commands.push(("select.color", json!({"fill": "#ff0000"})));
}
for (cmd, p) in commands {
sel(&mut s, &[from]);
let reply = run(&mut s, cmd, p);
assert_eq!(reply["count"], 2, "{cmd}, Live Paint: {in_live_paint}");
}
}
}
/// A document of `n` objects on one layer: red and blue rectangles, one in 25 a compound path of
/// three, and two Live Paint groups that hold one in 25 each as faces → the session, with the first
/// rectangle selected.
fn big(n: usize) -> Session {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 800, "height": 600}));
let (c, _) = compound(&mut s, 0.0, "#ff0000");
let (g, _) = live_paint(&mut s, 300.0);
let [red, blue] = ["#ff0000", "#0000ff"].map(|hex| rect(&mut s, 0.0, 0.0, hex));
let mut d = Document::clone(&s.doc().unwrap().doc);
let layer = d.layers[0].id;
let template = |id: NodeId| d.node(id).unwrap().clone();
let (c, g, red, blue) = (template(c), template(g), template(red), template(blue));
fn renumber(n: &Node, d: &mut Document) -> Node {
let mut n = n.clone();
n.id = d.alloc_id();
for c in n.children_mut().into_iter().flatten() {
*c = Arc::new(renumber(c, d));
}
n
}
d.children_mut(Some(layer)).unwrap().clear();
let faces: Vec<Arc<Node>> = g.children().into_iter().flatten().cloned().collect();
for _ in 0..2 {
let mut g = renumber(&g, &mut d);
if let Some(ch) = g.children_mut() {
ch.clear();
for i in 0..n / 25 {
ch.push(Arc::new(renumber(&faces[i % faces.len()], &mut d)));
}
}
d.insert(Some(layer), usize::MAX, g).unwrap();
}
for i in 0..n - 2 * (n / 25) {
let node = match i % 25 {
0 => renumber(&c, &mut d),
k if k % 2 == 0 => renumber(&red, &mut d),
_ => renumber(&blue, &mut d),
};
d.insert(Some(layer), usize::MAX, node).unwrap();
}
let first = d.layers[0].children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Path { .. })).unwrap().id;
s.add_document(d, None);
sel(&mut s, &[first]);
s
}
/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere.
fn thread_cpu() -> Option<Duration> {
let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?;
stat.split_whitespace().next()?.parse().ok().map(Duration::from_nanos)
}
/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock.
fn time(f: impl FnOnce()) -> Duration {
match thread_cpu() {
Some(before) => {
f();
thread_cpu().map_or(Duration::ZERO, |after| after.saturating_sub(before))
}
None => {
let start = Instant::now();
f();
start.elapsed()
}
}
}
fn ms(d: Duration) -> f64 {
d.as_secs_f64() * 1000.0
}
/// Timings of Select > Same's search, by id lookups and with the walk's parents, on 5,000, 50,000
/// and 200,000 objects, run in turn on the same document, 7 runs each. Ignored by default; it
/// prints the median, fastest and slowest run and sets no bound on them:
/// `cargo test --release -p vectorcraft-engine --lib select_same_perf -- --ignored --nocapture`.
#[test]
#[ignore = "a benchmark: run with --ignored --nocapture"]
fn select_same_perf() {
const RUNS: usize = 7;
type Eq = fn(&Node, &Node) -> bool;
let fill: Eq = |a, b| same_paint(&fill_of(a), &fill_of(b), false);
let stroke: Eq = |a, b| same_paint(&stroke_of(a).0, &stroke_of(b).0, false);
eprintln!("select_same_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" });
eprintln!(
"select_same_perf: {:>7} {:<12} {:>8} {:>26} {:>26}",
"objects", "command", "selected", "by id ms (min-max)", "walk parents ms (min-max)"
);
for n in [5_000, 50_000, 200_000] {
let s = big(n);
let st = s.doc().unwrap();
let (d, iso) = (&st.doc, st.isolation);
let objects = {
let mut k = 0;
walk_selectable_in(d, iso, |_, _| {
k += 1;
true
});
k
};
for (cmd, live_paint, eq) in [("fillColor", true, fill), ("strokeColor", false, stroke)] {
let (refn, members) = same_reference(st, cmd).unwrap();
let (mut old, mut new) = (Vec::new(), Vec::new());
let (mut a, mut b) = (vec![], vec![]);
for run in 0..RUNS {
// The two take turns going first.
if run % 2 == 0 {
old.push(time(|| a = std::hint::black_box(same_by_id(d, iso, refn, members, live_paint, eq))));
new.push(time(|| b = std::hint::black_box(same_now(d, iso, refn, members, live_paint, eq))));
} else {
new.push(time(|| b = std::hint::black_box(same_now(d, iso, refn, members, live_paint, eq))));
old.push(time(|| a = std::hint::black_box(same_by_id(d, iso, refn, members, live_paint, eq))));
}
assert_eq!(a, b, "{n} objects, {cmd}");
}
old.sort();
new.sort();
eprintln!(
"select_same_perf: {objects:>7} {cmd:<12} {:>8} {:>10.3} ({:>6.3}-{:>7.3}) {:>10.3} ({:>6.3}-{:>7.3})",
b.len(),
ms(old[RUNS / 2]),
ms(old[0]),
ms(old[RUNS - 1]),
ms(new[RUNS / 2]),
ms(new[0]),
ms(new[RUNS - 1]),
);
}
}
}
+266 -5
View File
@@ -2,6 +2,8 @@
//! Magic Wand panel's (session state, kept across tool switches); the tool runs
//! `select.magicWand` on click.
use std::collections::HashSet;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use vectorcraft_color::Paint;
@@ -188,13 +190,14 @@ impl WandSettings {
}
}
/// Paintable leaves (paths, compounds, text, images) that are visible and editable.
/// Paintable leaves (paths, compounds, text, images) that are visible and editable, in the order
/// of the document walk.
fn paintable(doc: &Document) -> Vec<NodeId> {
let mut out = vec![];
let mut compounds: Vec<NodeId> = vec![];
let mut compounds: HashSet<NodeId> = HashSet::new();
doc.walk(|n| {
if matches!(n.kind, NodeKind::Compound { .. }) {
compounds.push(n.id);
compounds.insert(n.id);
out.push(n.id);
} else if !n.is_container() && !n.is_ruler_guide() {
out.push(n.id);
@@ -210,6 +213,18 @@ fn paintable(doc: &Document) -> Vec<NodeId> {
out
}
/// Shift-click: the selected objects in their order, then each hit that isn't selected yet.
fn added(selected: &[NodeId], hits: Vec<NodeId>) -> Vec<NodeId> {
let seen: HashSet<NodeId> = selected.iter().copied().collect();
selected.iter().copied().chain(hits.into_iter().filter(|h| !seen.contains(h))).collect()
}
/// Alt-click: the selected objects that aren't hits, in their order.
fn subtracted(selected: &[NodeId], hits: Vec<NodeId>) -> Vec<NodeId> {
let hits: HashSet<NodeId> = hits.into_iter().collect();
selected.iter().copied().filter(|i| !hits.contains(i)).collect()
}
fn magic_wand(s: &mut Session, p: &Value) -> Result<Value> {
let id = object_param(p, "id", "select.magicWand")?.ok_or_else(|| bad("select.magicWand", "missing id"))?;
let st = s.doc()?;
@@ -224,8 +239,8 @@ fn magic_wand(s: &mut Session, p: &Value) -> Result<Value> {
.filter(|i| st.doc.node(*i).is_some_and(|n| w.matches(&reference, n, mode)))
.collect();
let ids: Vec<NodeId> = match str_param(p, "mode").unwrap_or("set") {
"add" => st.selection.objects.iter().copied().chain(hits.iter().copied().filter(|h| !st.selection.objects.contains(h))).collect(),
"subtract" => st.selection.objects.iter().copied().filter(|i| !hits.contains(i)).collect(),
"add" => added(&st.selection.objects, hits),
"subtract" => subtracted(&st.selection.objects, hits),
"set" => hits,
other => return Err(bad("select.magicWand", format!("unknown mode `{other}` (set, add, subtract)"))),
};
@@ -423,6 +438,252 @@ mod tests {
assert_eq!((o["fillTolerance"].as_f64(), o["strokeTolerance"].as_f64()), (Some(32.0), Some(32.0)));
}
/// [`paintable`] with the compound paths kept in a list and searched for each object's parent.
fn paintable_by_search(doc: &Document) -> Vec<NodeId> {
let mut out = vec![];
let mut compounds: Vec<NodeId> = vec![];
doc.walk(|n| {
if matches!(n.kind, NodeKind::Compound { .. }) {
compounds.push(n.id);
out.push(n.id);
} else if !n.is_container() && !n.is_ruler_guide() {
out.push(n.id);
}
});
let editable = doc.editable();
out.retain(|id| {
!doc.parent_of(*id).is_some_and(|p| compounds.contains(&p))
&& editable(*id)
&& doc.is_visible(*id)
&& doc.node(*id).is_some_and(|n| n.visible)
});
out
}
/// [`added`] with the selection searched for each hit.
fn added_by_search(selected: &[NodeId], hits: &[NodeId]) -> Vec<NodeId> {
selected.iter().copied().chain(hits.iter().copied().filter(|h| !selected.contains(h))).collect()
}
/// [`subtracted`] with the hits searched for each selected object.
fn subtracted_by_search(selected: &[NodeId], hits: &[NodeId]) -> Vec<NodeId> {
selected.iter().copied().filter(|i| !hits.contains(i)).collect()
}
/// A red fill for an even `k` and a blue one for an odd `k`, with a 1 pt black stroke.
fn bench_paint(k: usize) -> vectorcraft_doc::Appearance {
use vectorcraft_color::Color;
let fill = if k.is_multiple_of(2) { Color::rgb(1.0, 0.0, 0.0) } else { Color::rgb(0.0, 0.0, 1.0) };
vectorcraft_doc::Appearance::basic(Paint::solid(fill), Paint::solid(Color::BLACK), 1.0)
}
/// Path `k`: a 10 × 10 rectangle painted as [`bench_paint`]. Every 97th path is locked and
/// every 89th hidden.
fn bench_path(d: &mut Document, k: usize) -> Node {
use vectorcraft_geom::{Rect, shapes};
let (x, y) = ((k % 200) as f64 * 20.0, (k / 200) as f64 * 20.0);
let mut n = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 10.0, y + 10.0)), bench_paint(k));
n.locked = k % 97 == 5;
n.visible = k % 89 != 7;
n
}
/// A session whose document holds `blocks` × 200 paths on one layer. Each block has a group of
/// 10 paths, 25 compound paths of 2 paths each and 140 loose paths, with the group and the
/// compound paths among the loose paths. The compound paths alternate red and blue fills, and
/// a few are locked or hidden.
fn wand_session(blocks: usize) -> Session {
use std::sync::Arc;
use vectorcraft_geom::FillRule;
let mut d = Document::new(4000.0, 4000.0);
let mut k = 0;
let mut next = |d: &mut Document| {
k += 1;
bench_path(d, k - 1)
};
let mut art = vec![];
for slot in 0..blocks * 166 {
let node = match slot % 166 {
0 => {
let members = (0..10).map(|_| Arc::new(next(&mut d))).collect();
Node::group(d.alloc_id(), members)
}
c @ 1..=25 => {
let members = (0..2).map(|_| Arc::new(next(&mut d))).collect();
let mut n = Node::new(d.alloc_id(), NodeKind::Compound { children: members, rule: FillRule::NonZero });
n.appearance = bench_paint(c).into();
n.locked = slot % 1001 == 3;
n.visible = slot % 1003 != 5;
n
}
_ => next(&mut d),
};
art.push(Arc::new(node));
}
if let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() {
*ch = art;
}
let mut s = Session::new();
s.add_document(d, None);
s
}
/// The objects the wand picks when `reference` is clicked, found as before membership sets.
fn hits_by_search(s: &Session, reference: NodeId) -> Vec<NodeId> {
let st = s.doc().unwrap();
let r = st.doc.node(reference).unwrap();
let w = s.menu.wand.clone();
paintable_by_search(&st.doc).into_iter().filter(|i| w.matches(r, st.doc.node(*i).unwrap(), st.doc.color_mode)).collect()
}
#[test]
fn membership_sets_give_the_same_objects_in_the_same_order_as_searches() {
// 20,000 paths: 5,000 in 2,500 compound paths and 1,000 in 100 groups.
let mut s = wand_session(100);
let doc = &s.doc().unwrap().doc;
let all = paintable(doc);
assert!(all == paintable_by_search(doc), "paintable objects differ");
// Compound paths stay pickable unless locked or hidden, and their members never are.
let pickable: HashSet<NodeId> = all.iter().copied().collect();
let (mut compounds, mut skipped) = (0, 0);
doc.walk(|n| {
if let NodeKind::Compound { children, .. } = &n.kind {
compounds += 1;
skipped += usize::from(n.locked || !n.visible);
assert_eq!(pickable.contains(&n.id), n.visible && !n.locked, "compound path {}", n.id.0);
assert!(children.iter().all(|m| !pickable.contains(&m.id)), "a member of compound path {} is pickable", n.id.0);
}
});
assert_eq!(compounds, 2_500);
assert!(skipped > 0 && skipped < 100, "{skipped} locked or hidden compound paths");
let reference = all[0];
let hits = hits_by_search(&s, reference);
assert!(hits.len() > 5_000 && hits.len() < all.len() / 2 + 1_000, "{} hits", hits.len());
// A selection in another order than the document's: every third object from the end, both
// hits and objects that aren't hits.
let selected: Vec<NodeId> = all.iter().rev().step_by(3).copied().collect();
assert!(selected.iter().any(|i| hits.contains(i)) && selected.iter().any(|i| !hits.contains(i)));
assert!(added(&selected, hits.clone()) == added_by_search(&selected, &hits), "Shift-click differs");
assert!(subtracted(&selected, hits.clone()) == subtracted_by_search(&selected, &hits), "Alt-click differs");
// And through the command, in each mode.
let ids: Vec<u64> = selected.iter().map(|i| i.0).collect();
for (mode, want) in [("set", hits.clone()), ("add", added_by_search(&selected, &hits)), ("subtract", subtracted_by_search(&selected, &hits))]
{
s.execute("select.set", &json!({ "ids": ids })).unwrap();
assert!(s.doc().unwrap().selection.objects == selected, "select.set kept the order");
let r = s.execute("select.magicWand", &json!({"id": reference.0, "mode": mode})).unwrap();
assert_eq!(r["count"], json!(want.len()), "{mode}");
assert!(s.doc().unwrap().selection.objects == want, "{mode} selects other objects or another order");
}
}
/// Time the Magic Wand's paintable walk, Shift-click and Alt-click lists and a whole Shift-click
/// on documents of 2,000, 20,000 and 50,000 paths, with membership sets and with the searches
/// they replace, alternating 7 runs of each and giving the medians in ms. On Linux the times are
/// the thread's CPU time.
/// Run with `cargo test --release -p vectorcraft-engine --lib magic_wand_membership_timing -- --ignored --nocapture`.
#[test]
#[ignore = "manual timing probe; performance depends on machine load"]
fn magic_wand_membership_timing() {
fn cpu_ns() -> Option<u64> {
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
}
/// The time of one call of `f`, averaged over `reps` calls.
fn time(reps: u32, f: &mut dyn FnMut()) -> f64 {
let start = (cpu_ns(), std::time::Instant::now());
for _ in 0..reps {
f();
}
let ms = match (start.0, cpu_ns()) {
(Some(a), Some(b)) => b.saturating_sub(a) as f64 / 1e6,
_ => start.1.elapsed().as_secs_f64() * 1000.0,
};
ms / f64::from(reps)
}
fn median(v: &mut [f64]) -> f64 {
v.sort_by(f64::total_cmp);
v[v.len() / 2]
}
/// Alternate `old` and `new` 7 times each and print their medians and every run. Each run
/// takes the mean of enough calls for about 100 ms.
fn compare(paths: usize, what: &str, old: &mut dyn FnMut(), new: &mut dyn FnMut()) {
let reps = (100.0 / time(1, old).max(0.1)).clamp(1.0, 200.0) as u32;
let (mut o, mut n) = (vec![], vec![]);
for _ in 0..7 {
o.push(time(reps, old));
n.push(time(reps, new));
}
let runs = format!("calls per run {reps}: {o:.3?} / {n:.3?}");
println!("| {paths} | {what} | {:.3} | {:.3} | {runs}", median(&mut o), median(&mut n));
}
println!("clock: {}", if cpu_ns().is_some() { "thread CPU time" } else { "wall clock" });
println!("| paths | step | searches (ms) | sets (ms) | runs");
for blocks in [10, 100, 250] {
let mut s = wand_session(blocks);
let paths = blocks * 200;
let st = s.doc().unwrap();
let all = paintable(&st.doc);
assert!(all == paintable_by_search(&st.doc));
let reference = all[0];
let hits = hits_by_search(&s, reference);
let selected: Vec<NodeId> = all.iter().rev().step_by(2).copied().collect();
assert!(added(&selected, hits.clone()) == added_by_search(&selected, &hits));
assert!(subtracted(&selected, hits.clone()) == subtracted_by_search(&selected, &hits));
let doc = &st.doc;
compare(
paths,
"paintable",
&mut || {
std::hint::black_box(paintable_by_search(doc));
},
&mut || {
std::hint::black_box(paintable(doc));
},
);
compare(
paths,
"Shift-click list",
&mut || {
std::hint::black_box(added_by_search(&selected, &hits));
},
&mut || {
std::hint::black_box(added(&selected, hits.clone()));
},
);
compare(
paths,
"Alt-click list",
&mut || {
std::hint::black_box(subtracted_by_search(&selected, &hits));
},
&mut || {
std::hint::black_box(subtracted(&selected, hits.clone()));
},
);
// A whole Shift-click after the selection is set: [`magic_wand`], and its steps with
// the searches.
let ids = json!({ "ids": selected.iter().map(|i| i.0).collect::<Vec<u64>>() });
let click = json!({"id": reference.0, "mode": "add"});
let s = std::cell::RefCell::new(&mut s);
compare(
paths,
"select.set, then Shift-click",
&mut || {
let s = &mut **s.borrow_mut();
s.execute("select.set", &ids).unwrap();
let before = s.doc().unwrap().selection.objects.clone();
let picked = added_by_search(&before, &hits_by_search(s, reference));
s.select(|_, sel| sel.set(picked)).unwrap();
},
&mut || {
let s = &mut **s.borrow_mut();
s.execute("select.set", &ids).unwrap();
magic_wand(s, &click).unwrap();
},
);
}
}
#[test]
fn isolation_mode_limits_the_wand_to_the_isolated_group() {
let mut s = Session::new();
+1
View File
@@ -24,6 +24,7 @@ mod build;
mod cancel;
mod caret_kerning;
mod charstroke;
mod circle_through;
pub(super) mod clip;
mod clipboard;
mod clipflavours;
+139
View File
@@ -772,3 +772,142 @@ fn whether_a_blend_has_a_spine_is_saved_and_old_blends_have_one() {
assert!(!v.no_spine, "{odd}");
}
}
fn undo_len(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
/// Two blends with different options, both selected: the first (Steps 3, along the path, Ease
/// Out at 20%, Shift 10%) and the second (Distance 12 pt, along the page, Ease In Out at 60%,
/// Shift -40%).
fn two_different_blends(s: &mut Session) -> (NodeId, NodeId) {
let b1 = make(s, 0.0, json!({"spacing": "steps", "orientation": "path"}));
let b2 = make(s, 100.0, json!({"spacing": "distance", "value": 12, "orientation": "path"}));
s.execute("object.blend.setEasing", &json!({"id": b1.0, "easingType": "easeOut", "ramp": 20, "colorShift": 10})).unwrap();
s.execute("object.blend.setEasing", &json!({"id": b2.0, "easingType": "easeInOut", "ramp": 60, "colorShift": -40})).unwrap();
sel(s, &[b2]);
s.execute("object.blend.options", &json!({"orientation": "page"})).unwrap();
sel(s, &[b1, b2]);
(b1, b2)
}
#[test]
fn options_on_several_blends_set_only_the_values_given() {
let mut s = session();
let (b1, b2) = two_different_blends(&mut s);
let (before1, before2) = (spec(&s, b1).1, spec(&s, b2).1);
assert_ne!(before1.spacing, before2.spacing);
// Each value given goes to every selected blend; each keeps its own for the others.
for (p, apply) in [
(json!({"colorShift": 30}), (|sp: &mut BlendSpec| sp.color_shift = 30.0) as fn(&mut BlendSpec)),
(json!({"ramp": 45}), |sp| sp.ease.ramp = 0.45),
(json!({"easingType": "easeOutIn"}), |sp| sp.ease.kind = vectorcraft_doc::BlendEaseType::OutIn),
(json!({"orientation": "path"}), |sp| sp.orientation = BlendOrientation::AlignToPath),
(json!({"spacing": "steps", "value": 7}), |sp| sp.spacing = BlendSpacing::Steps(7)),
] {
let (mut want1, mut want2) = (spec(&s, b1).1, spec(&s, b2).1);
apply(&mut want1);
apply(&mut want2);
s.execute("object.blend.options", &p).unwrap();
assert_eq!((spec(&s, b1).1, spec(&s, b2).1), (want1, want2), "{p}");
}
// A spacing mode without a count keeps the count of a blend already in that mode; a blend in
// another mode takes the mode's starting count.
s.execute("object.blend.options", &json!({"id": b2.0, "spacing": "distance", "value": 12})).unwrap();
s.execute("object.blend.options", &json!({"spacing": "steps"})).unwrap();
assert_eq!((spec(&s, b1).1.spacing, spec(&s, b2).1.spacing), (BlendSpacing::Steps(7), BlendSpacing::Steps(5)));
s.execute("object.blend.options", &json!({"id": b2.0, "spacing": "steps", "value": 12})).unwrap();
s.execute("object.blend.options", &json!({"spacing": "steps"})).unwrap();
assert_eq!((spec(&s, b1).1.spacing, spec(&s, b2).1.spacing), (BlendSpacing::Steps(7), BlendSpacing::Steps(12)));
// The whole edit of both blends is one undo step.
let depth = undo_len(&s);
s.execute("object.blend.options", &json!({"colorShift": -5, "ramp": 5})).unwrap();
assert_eq!(undo_len(&s), depth + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((spec(&s, b1).1.color_shift, spec(&s, b2).1.color_shift), (30.0, 30.0));
}
#[test]
fn options_with_an_id_edit_that_blend_alone() {
let mut s = session();
let (b1, b2) = two_different_blends(&mut s);
let before2 = spec(&s, b2).1;
let mut want1 = spec(&s, b1).1;
s.execute("object.blend.options", &json!({"id": b1.0, "spacing": "distance", "value": 15, "ramp": 50, "colorShift": -20})).unwrap();
want1.spacing = BlendSpacing::Distance(15.0);
want1.ease.ramp = 0.5;
want1.color_shift = -20.0;
assert_eq!(spec(&s, b1).1, want1, "only the values given change");
assert_eq!(spec(&s, b2).1, before2, "a selected blend that is not `id` stays as it was");
// `id` works with nothing selected, and does not set the options new blends start with.
s.execute("select.none", &json!({})).unwrap();
let defaults = s.execute("object.blend.info", &json!({})).unwrap();
s.execute("object.blend.options", &json!({"id": b2.0, "orientation": "path"})).unwrap();
assert_eq!(spec(&s, b2).1.orientation, BlendOrientation::AlignToPath);
assert_eq!(s.execute("object.blend.info", &json!({})).unwrap(), defaults);
// A hidden or locked blend and an object that is not a blend are errors that change nothing.
for (visible, locked) in [(false, false), (true, true)] {
s.edit("state", |d, _| {
let n = d.node_mut(b1).unwrap();
(n.visible, n.locked) = (visible, locked);
Ok(())
})
.unwrap();
let (before, depth) = (spec(&s, b1).1, undo_len(&s));
let error = s.execute("object.blend.options", &json!({"id": b1.0, "colorShift": 25})).unwrap_err().to_string();
assert!(error.contains("the object is hidden or locked"), "{error}");
assert_eq!((spec(&s, b1).1, undo_len(&s)), (before, depth));
}
let other = rect(&mut s, 300.0, 0.0, 10.0);
for id in [json!(other.0), json!(999_999)] {
let error = s.execute("object.blend.options", &json!({"id": id, "colorShift": 25})).unwrap_err().to_string();
assert!(error.contains("not a blend"), "{error}");
}
// The blend's own spine decides whether easing is allowed, whatever is selected.
s.execute("object.blend.createSpine", &json!({"mode": "never"})).unwrap();
let bare = make(&mut s, 300.0, json!({}));
sel(&mut s, &[b2]);
let error = s.execute("object.blend.options", &json!({"id": bare.0, "ramp": 30})).unwrap_err().to_string();
assert!(error.contains("the blend has no spine"), "{error}");
s.execute("object.blend.options", &json!({"id": b2.0, "ramp": 30})).unwrap();
assert_eq!(spec(&s, b2).1.ease.ramp, 0.3);
}
#[test]
fn options_that_change_nothing_or_are_refused_record_no_undo_step() {
let mut s = session();
let (b1, b2) = two_different_blends(&mut s);
let before = (spec(&s, b1).1, spec(&s, b2).1);
let depth = undo_len(&s);
// Values the blends already have, and no values at all.
for p in [json!({}), json!({"smooth": false}), json!({"orientation": "page", "id": b2.0}), json!({"colorShift": 10, "id": b1.0})] {
s.execute("object.blend.options", &p).unwrap();
assert_eq!(undo_len(&s), depth, "{p}");
}
// An invalid value anywhere stops the whole call before anything changes.
for p in [
json!({"colorShift": 50, "ramp": 101}),
json!({"colorShift": 50, "ramp": -1}),
json!({"colorShift": 50, "ramp": "half"}),
json!({"ramp": 50, "colorShift": -101}),
json!({"ramp": 50, "easingType": "linear"}),
json!({"ramp": 50, "spacing": "steps", "value": 0}),
json!({"ramp": 50, "spacing": "distance", "value": -3}),
json!({"ramp": 50, "id": "b1"}),
json!({"ramp": 50, "orientation": "sideways"}),
json!({"ramp": 50, "orientation": 1}),
json!({"ramp": 50, "value": 3}),
json!({"ramp": 50, "spacing": 123}),
] {
assert!(s.execute("object.blend.options", &p).is_err(), "{p}");
assert_eq!((spec(&s, b1).1, spec(&s, b2).1, undo_len(&s)), (before.0.clone(), before.1.clone(), depth), "{p}");
}
// Make and the options new blends start with refuse an unknown orientation too.
let error = s.execute("object.blend.make", &json!({"orientation": "sideways"})).unwrap_err().to_string();
assert!(error.contains("orientation must be page or path"), "{error}");
assert_eq!(undo_len(&s), depth);
s.execute("select.none", &json!({})).unwrap();
let defaults = s.execute("object.blend.info", &json!({})).unwrap();
assert!(s.execute("object.blend.options", &json!({"orientation": "sideways"})).is_err());
assert_eq!(s.execute("object.blend.info", &json!({})).unwrap(), defaults);
}
+209
View File
@@ -0,0 +1,209 @@
//! `shape.circleThroughPoints`: a circle through three given points, or through the three anchor
//! points selected with Direct Selection, and the Ellipse tool's three Shift-clicks that run it.
use serde_json::{Value, json};
use vectorcraft_doc::{LiveShape, Node, NodeKind};
use vectorcraft_geom::Point;
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
use crate::*;
const C: &str = "shape.circleThroughPoints";
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s
}
fn node(s: &Session, id: NodeId) -> Node {
s.doc().unwrap().doc.node(id).unwrap().clone()
}
fn undo_len(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn object_count(s: &Session) -> usize {
let mut n = 0;
s.doc().unwrap().doc.walk(|_| n += 1);
n
}
fn id_of(v: &Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
/// Whether the geometric bounds of `id` are `want` to within 10⁻⁹ pt.
fn bounds_are(s: &Session, id: NodeId, want: vectorcraft_geom::Rect) -> bool {
let b = s.doc().unwrap().doc.bounds_of(&[id], false).unwrap();
[(b.x0, want.x0), (b.y0, want.y0), (b.x1, want.x1), (b.y1, want.y1)].iter().all(|(a, w)| (a - w).abs() < 1e-9)
}
/// The largest distance of `points` from the path of `id`.
fn farthest_from_path(s: &Session, id: NodeId, points: &[Point]) -> f64 {
let n = node(s, id);
let path = n.path_data().unwrap();
points.iter().map(|p| path.nearest(*p).unwrap().4).fold(0.0, f64::max)
}
/// (0, 0), (80, 0) and (0, 60) lie on the circle centered at (40, 30) with radius 50 (their
/// right angle stands on the diameter). The circle is a live ellipse with the current paint, is
/// selected, passes through the points to within the four-curve circle's error (about 0.03% of the
/// radius), and one undo removes it.
#[test]
fn the_circle_through_three_given_points_is_exact_and_one_undo_step() {
let mut s = session();
let reference = id_of(&s.execute("shape.ellipse", &json!({"x": 200, "y": 200, "width": 10, "height": 10})).unwrap());
let undo = undo_len(&s);
let points = [Point::new(0.0, 0.0), Point::new(80.0, 0.0), Point::new(0.0, 60.0)];
let out = s.execute(C, &json!({"points": [[0, 0], [80, 0], [0, 60]]})).unwrap();
assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(40.0), Some(30.0), Some(50.0)), "{out}");
let id = id_of(&out);
let n = node(&s, id);
match &n.kind {
NodeKind::Path { live: Some(live), .. } => match live.as_ref() {
LiveShape::Ellipse { w, h, pie, .. } => assert_eq!((*w, *h, *pie), (100.0, 100.0, (0.0, 360.0))),
other => panic!("not a live ellipse: {other:?}"),
},
other => panic!("not a live shape: {other:?}"),
}
assert!(bounds_are(&s, id, vectorcraft_geom::Rect::new(-10.0, -20.0, 90.0, 80.0)));
assert!(farthest_from_path(&s, id, &points) < 50.0 * 3e-4, "{}", farthest_from_path(&s, id, &points));
assert_eq!(n.appearance, node(&s, reference).appearance, "the current paint, as the Ellipse tool draws");
assert_eq!(s.doc().unwrap().selection.objects, [id]);
assert_eq!(undo_len(&s), undo + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.node(id).is_none());
}
/// Two points that are the same, or three on one line, are refused with a message; nothing is
/// drawn and no undo step is recorded. Points nearly on one line still give their circle.
#[test]
fn coincident_or_collinear_points_are_refused() {
let mut s = session();
let (undo, count) = (undo_len(&s), object_count(&s));
for points in [json!([[10, 10], [10, 10], [50, 80]]), json!([[0, 0], [50, 50], [100, 100]]), json!([[5, 5], [5, 5], [5, 5]])] {
let e = s.execute(C, &json!({ "points": points })).unwrap_err().to_string();
assert!(e.contains("no circle passes through these points"), "{points}: {e}");
assert_eq!((undo_len(&s), object_count(&s)), (undo, count), "{points}");
}
// 0.01 pt off a chord 200 pt long: the sagitta formula r = (h² + (L/2)²) / 2h.
let out = s.execute(C, &json!({"points": [[100, 200], [300, 200], [200, 199.99]]})).unwrap();
let want = (0.01f64 * 0.01 + 100.0 * 100.0) / 0.02;
let (cx, cy, r) = (out["cx"].as_f64().unwrap(), out["cy"].as_f64().unwrap(), out["radius"].as_f64().unwrap());
assert!((r - want).abs() / want < 1e-9 && (cx - 200.0).abs() < 1e-6 && (cy - (199.99 + want)).abs() / want < 1e-9, "{out}");
}
/// Points that are not three pairs of finite numbers are an error, not a fallback.
#[test]
fn malformed_points_are_refused() {
let mut s = session();
let undo = undo_len(&s);
for points in [
json!([[0, 0], [10, 0]]),
json!([[0, 0], [10, 0], [0, 10], [5, 5]]),
json!([[0, 0], [10, 0], [0]]),
json!([[0, 0], [10, 0], ["0", 10]]),
json!("0,0 10,0 0,10"),
json!([[0, 0], [10, 0], [0, 10, 3]]),
] {
let e = s.execute(C, &json!({ "points": points })).unwrap_err().to_string();
assert!(e.contains("`points` must be three [x, y] pairs of numbers"), "{points}: {e}");
}
assert_eq!(undo_len(&s), undo);
}
/// With `points` left out, the three anchor points selected with Direct Selection give the
/// circle, from one path or several; any other number of them is an error.
#[test]
fn three_direct_selected_anchor_points_give_the_circle() {
let mut s = session();
let anchors: Vec<Value> = [(0, 0), (80, 0), (0, 60), (50, 120)].iter().map(|(x, y)| json!({"x": x, "y": y})).collect();
let path = id_of(&s.execute("path.create", &json!({ "anchors": anchors })).unwrap());
s.execute("select.anchors", &json!({"id": path.0, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": "set"})).unwrap();
let out = s.execute(C, &json!({})).unwrap();
assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(40.0), Some(30.0), Some(50.0)), "{out}");
// Anchors of two paths.
let other = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 60}, {"x": 0, "y": 200}]})).unwrap());
s.execute("select.anchors", &json!({"id": path.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap();
s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 0]], "mode": "add"})).unwrap();
let out = s.execute(C, &json!({"points": null})).unwrap();
assert_eq!((out["cx"].as_f64(), out["cy"].as_f64()), (Some(40.0), Some(30.0)), "{out}");
// Two or four anchors, or a path of four anchors selected whole.
for picked in [json!([[0, 0], [0, 1]]), json!([[0, 0], [0, 1], [0, 2], [0, 3]])] {
s.execute("select.anchors", &json!({"id": path.0, "anchors": picked, "mode": "set"})).unwrap();
let e = s.execute(C, &json!({})).unwrap_err().to_string();
assert!(e.contains("direct-select three anchor points, or give `points`"), "{picked}: {e}");
}
s.execute("select.set", &json!({"ids": [path.0]})).unwrap();
assert!(s.execute(C, &json!({})).is_err());
// A path of three anchors selected whole counts all three, as the other anchor commands count
// them; with an object that is not a path also selected, there is no circle.
let triangle = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 80, "y": 0}, {"x": 0, "y": 60}]})).unwrap());
s.execute("select.set", &json!({"ids": [triangle.0]})).unwrap();
let out = s.execute(C, &json!({})).unwrap();
assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(40.0), Some(30.0), Some(50.0)), "{out}");
s.execute("edit.undo", &json!({})).unwrap();
let text = id_of(&s.execute("text.create", &json!({"x": 300, "y": 300, "text": "A"})).unwrap());
s.execute("select.set", &json!({"ids": [triangle.0, text.0]})).unwrap();
assert!(s.execute(C, &json!({})).is_err());
let undo = undo_len(&s);
// Two selected segments hold three ends, which are not selected anchor points.
s.execute("select.segments", &json!({"id": path.0, "segments": [[0, 0], [0, 1]], "mode": "set"})).unwrap();
assert_eq!(s.doc().unwrap().selection.anchors.get(&path).map(|a| a.len()), Some(3));
let e = s.execute(C, &json!({})).unwrap_err().to_string();
assert!(e.contains("direct-select three anchor points, or give `points`"), "{e}");
assert_eq!(undo_len(&s), undo);
}
/// With Align New Objects to Pixel Grid on, the circle is still drawn through the points: it is
/// not pixel-aligned, so the grid does not move it.
#[test]
fn the_circle_is_not_moved_onto_the_pixel_grid() {
let mut s = session();
s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap();
let points = [Point::new(0.3, 0.2), Point::new(80.6, 0.1), Point::new(0.4, 60.7)];
let pairs: Vec<Value> = points.iter().map(|p| json!([p.x, p.y])).collect();
let id = id_of(&s.execute(C, &json!({ "points": pairs })).unwrap());
assert!(farthest_from_path(&s, id, &points) < 51.0 * 3e-4, "{}", farthest_from_path(&s, id, &points));
assert!(!node(&s, id).extras().pixel_aligned);
}
fn view() -> ViewInfo {
ViewInfo { smart_guides: false, ..ViewInfo::default() }
}
fn click(s: &mut Session, mods: Mods, x: f64, y: f64) {
for k in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(k, x, y).with_mods(mods), view()).unwrap();
}
}
/// With the Ellipse tool, three Shift-clicks draw the circle through the three points, in one
/// undo step; Escape drops the points placed so far.
#[test]
fn three_shift_clicks_with_the_ellipse_tool_draw_the_circle_through_them() {
let mut s = session();
s.select_tool("ellipse", view()).unwrap();
let shift = Mods { shift: true, ..Mods::default() };
let (undo, count) = (undo_len(&s), object_count(&s));
click(&mut s, shift, 100.0, 100.0);
click(&mut s, shift, 180.0, 100.0);
assert_eq!((undo_len(&s), object_count(&s)), (undo, count), "two points draw nothing yet");
click(&mut s, shift, 100.0, 160.0);
assert_eq!(undo_len(&s), undo + 1);
let id = *s.doc().unwrap().selection.objects.first().unwrap();
assert!(bounds_are(&s, id, vectorcraft_geom::Rect::new(90.0, 80.0, 190.0, 180.0)));
// Escape after two points: the next three clicks start afresh.
click(&mut s, shift, 0.0, 0.0);
click(&mut s, shift, 10.0, 300.0);
s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap();
click(&mut s, shift, 200.0, 200.0);
click(&mut s, shift, 280.0, 200.0);
let undo = undo_len(&s);
click(&mut s, shift, 200.0, 260.0);
assert_eq!(undo_len(&s), undo + 1);
let id = *s.doc().unwrap().selection.objects.first().unwrap();
assert!(bounds_are(&s, id, vectorcraft_geom::Rect::new(190.0, 180.0, 290.0, 280.0)));
}
+231
View File
@@ -452,6 +452,237 @@ fn what_cannot_be_intertwined_is_refused_with_a_reason() {
assert!(e.to_string().contains("not an Intertwine group"), "{e}");
}
// ---------- members dragged in and out in the Layers panel ----------
/// A green rectangle (84..96 × 46..54) that crosses ring B's stroke at (90, 50) and no part of A.
fn green_bar(s: &mut Session) -> NodeId {
let id = id_of(&s.execute("shape.rectangle", &json!({"x": 84, "y": 46, "width": 12, "height": 8})).unwrap());
s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#00ff00"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [id.0], "none": true})).unwrap();
id
}
fn kids(s: &Session, g: NodeId) -> Vec<NodeId> {
s.doc().unwrap().doc.node(g).and_then(vectorcraft_doc::Node::children).map(|c| c.iter().map(|n| n.id).collect()).unwrap_or_default()
}
fn rows(s: &mut Session, ids: &[NodeId], target: NodeId, place: &str, copy: bool) -> Result<Value> {
s.execute("layer.move", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "target": target.0, "place": place, "copy": copy}))
}
fn undo_len(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn has_areas(s: &Session, id: NodeId) -> bool {
let n = s.doc().unwrap().doc.node(id).unwrap();
n.extras().intertwine.is_some() || !n.extras().intertwine_tiers.is_empty()
}
fn parent(s: &Session, id: NodeId) -> Option<NodeId> {
s.doc().unwrap().doc.parent_of(id)
}
/// The help page: "You can drag additional objects into the group later."
#[test]
fn layer_move_adds_a_member_without_losing_existing_weave() {
let mut s = session();
let (g, a, b) = intertwined(&mut s);
arrange(&mut s, json!({"at": [50, 30]}));
let c = green_bar(&mut s);
let undo = undo_len(&s);
rows(&mut s, &[c], g, "inside", false).unwrap();
assert_eq!(kids(&s, g), [a, b, c], "on top of the group's objects");
assert_eq!(undo_len(&s), undo + 1, "one undo step");
assert!(area(&s, a).is_some(), "the arranged overlap is kept");
let r = render(&s);
assert!(red(&r, 50, 30) && blue(&r, 50, 70), "the rings are woven as before");
assert!(green(&r, 90, 50), "the new member is drawn in its own order");
// A live member: its overlap with B can be arranged.
assert_eq!(arrange(&mut s, json!({"id": g.0, "at": [90, 50]}))["count"], 1);
assert!(blue(&render(&s), 90, 50));
for format in ["vectorcraft", "svg"] {
let data = s.execute("document.export", &json!({"format": format})).unwrap()["dataBase64"].clone();
let mut o = Session::new();
o.execute("document.open", &json!({"name": format!("woven.{format}"), "dataBase64": data})).unwrap();
let r = render(&o);
assert!(red(&r, 50, 30) && blue(&r, 50, 70) && blue(&r, 90, 50), "{format}");
}
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(kids(&s, g), [a, b]);
assert_eq!(parent(&s, c), parent(&s, g));
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(kids(&s, g), [a, b, c]);
}
/// An object that overlaps no member still joins the group, beside a member's row too; Alt-drag
/// adds a copy, which starts drawn in its own order everywhere.
#[test]
fn layer_move_accepts_nonoverlapping_member() {
let mut s = session();
let (g, a, b) = intertwined(&mut s);
arrange(&mut s, json!({"at": [50, 30]}));
let c = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap());
rows(&mut s, &[c], a, "above", false).unwrap();
assert_eq!(kids(&s, g), [a, c, b], "above member A");
let v = rows(&mut s, &[a], g, "inside", true).unwrap();
let copy = NodeId(v["ids"][0].as_u64().unwrap());
assert_eq!(kids(&s, g), [a, c, b, copy]);
assert!(has_areas(&s, a) && !has_areas(&s, copy), "the copy has no arranged areas");
let r = render(&s);
assert!(red(&r, 50, 30) && red(&r, 50, 70), "the copy of A is drawn over B at both crossings");
}
#[test]
fn layer_move_rejects_unsupported_intertwine_members_atomically() {
let mut s = session();
let (a, b) = rings(&mut s);
let p = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap());
select(&mut s, &[p]);
let pg = id_of(&s.execute("object.group", &json!({})).unwrap());
select(&mut s, &[a, b, pg]);
let g = id_of(&s.execute("object.intertwine.make", &json!({})).unwrap());
let d = id_of(&s.execute("shape.rectangle", &json!({"x": 150, "y": 150, "width": 10, "height": 10})).unwrap());
let e = id_of(&s.execute("shape.rectangle", &json!({"x": 155, "y": 150, "width": 10, "height": 10})).unwrap());
select(&mut s, &[d, e]);
let g2 = id_of(&s.execute("object.intertwine.make", &json!({})).unwrap());
let f = id_of(&s.execute("shape.rectangle", &json!({"x": 180, "y": 180, "width": 5, "height": 5})).unwrap());
select(&mut s, &[g2, f]);
let holder = id_of(&s.execute("object.group", &json!({})).unwrap());
let layer = s.doc().unwrap().doc.layer_of(g).unwrap();
let before = s.doc().unwrap().doc.clone();
let undo = undo_len(&s);
// No nested Intertwine groups: not as a member, inside a member's group, beside a member's
// row, nor held in a group.
for (ids, target, place) in [(g2, g, "inside"), (g2, pg, "inside"), (g2, a, "above"), (holder, g, "inside"), (holder, b, "below")] {
let err = rows(&mut s, &[ids], target, place, false).unwrap_err();
assert!(err.to_string().contains("an Intertwine group can't be intertwined"), "{place} {}: {err}", target.0);
let err = rows(&mut s, &[ids], target, place, true).unwrap_err();
assert!(err.to_string().contains("can't be intertwined"), "copy: {err}");
}
let err = s.execute("node.move", &json!({"id": holder.0, "parent": g.0, "index": 0})).unwrap_err();
assert!(err.to_string().contains("an Intertwine group can't be intertwined"), "{err}");
let err = rows(&mut s, &[layer], g, "inside", false).unwrap_err();
assert!(err.to_string().contains("can't go into"), "{err}");
assert_eq!(undo_len(&s), undo, "no undo step");
assert!(s.doc().unwrap().doc == before, "the document is as it was");
// A plain object goes into the group inside the Intertwine group.
rows(&mut s, &[f], pg, "inside", false).unwrap();
assert_eq!(kids(&s, pg), [p, f]);
}
#[test]
fn layer_move_clears_areas_when_member_leaves() {
let mut s = session();
let (a, b) = rings(&mut s);
let c = green_bar(&mut s);
select(&mut s, &[a, b, c]);
let g = id_of(&s.execute("object.intertwine.make", &json!({})).unwrap());
arrange(&mut s, json!({"at": [50, 30]}));
assert!(has_areas(&s, a));
rows(&mut s, &[a], g, "above", false).unwrap();
assert_eq!(parent(&s, a), parent(&s, g));
assert!(!has_areas(&s, a), "ordinary art again");
assert_eq!(kids(&s, g), [b, c], "two members stay an Intertwine group");
assert!(matches!(s.doc().unwrap().doc.node(g).unwrap().kind, NodeKind::Intertwine { .. }));
let r = render(&s);
assert!(red(&r, 50, 30) && red(&r, 50, 70) && green(&r, 90, 50), "A is above the group at both crossings");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(kids(&s, g), [a, b, c]);
assert!(has_areas(&s, a));
assert!(red(&render(&s), 50, 30));
}
#[test]
fn layer_move_between_intertwines_drops_old_areas() {
let mut s = session();
let (g, a, b) = intertwined(&mut s);
arrange(&mut s, json!({"at": [50, 30]}));
let d = id_of(&s.execute("shape.rectangle", &json!({"x": 150, "y": 150, "width": 10, "height": 10})).unwrap());
let e = id_of(&s.execute("shape.rectangle", &json!({"x": 155, "y": 150, "width": 10, "height": 10})).unwrap());
select(&mut s, &[d, e]);
let g2 = id_of(&s.execute("object.intertwine.make", &json!({})).unwrap());
rows(&mut s, &[a], g2, "inside", false).unwrap();
assert_eq!(kids(&s, g2), [d, e, a]);
assert!(!has_areas(&s, a), "the areas of the group it left do not come along");
assert!(s.doc().unwrap().doc.node(g).is_none(), "the group A left has one member and is taken apart");
assert_eq!(parent(&s, b), parent(&s, g2));
}
#[test]
fn layer_move_dissolves_a_group_left_with_one_member() {
let mut s = session();
let (g, a, b) = intertwined(&mut s);
arrange(&mut s, json!({"at": [50, 30]}));
let layer = parent(&s, g).unwrap();
let top = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap());
select(&mut s, &[g]);
let undo = undo_len(&s);
rows(&mut s, &[b], top, "above", false).unwrap();
assert_eq!(undo_len(&s), undo + 1, "one undo step");
assert!(s.doc().unwrap().doc.node(g).is_none());
assert_eq!(kids(&s, layer), [a, top, b], "the one member left is in the group's place");
assert!(!has_areas(&s, a), "with no other member it has no areas");
assert!(!s.doc().unwrap().selection.contains(g));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(kids(&s, layer), [g, top]);
assert_eq!(kids(&s, g), [a, b]);
let r = render(&s);
assert!(red(&r, 50, 30) && blue(&r, 50, 70), "woven as before");
// Both members out: the empty group is removed.
rows(&mut s, &[a, b], g, "above", false).unwrap();
assert!(s.doc().unwrap().doc.node(g).is_none());
assert_eq!(kids(&s, layer), [a, b, top]);
assert!(!has_areas(&s, a) && !has_areas(&s, b));
}
/// A group left with one member that has an opacity of its own stays, as a plain group of that
/// member, so the member is drawn as before.
#[test]
fn layer_move_keeps_a_lone_members_group_with_its_own_opacity() {
let mut s = session();
let (g, a, b) = intertwined(&mut s);
arrange(&mut s, json!({"at": [50, 30]}));
s.execute("object.setProps", &json!({"ids": [g.0], "opacity": 40})).unwrap();
let layer = parent(&s, g).unwrap();
rows(&mut s, &[b], g, "above", false).unwrap();
assert_eq!(kids(&s, layer), [g, b]);
assert_eq!(kids(&s, g), [a]);
let n = s.doc().unwrap().doc.node(g).unwrap().clone();
assert!(matches!(n.kind, NodeKind::Group { clip: false, .. }), "a plain group");
assert!((n.opacity - 0.4).abs() < 1e-6, "{}", n.opacity);
assert!(!has_areas(&s, a));
s.execute("edit.undo", &json!({})).unwrap();
assert!(matches!(s.doc().unwrap().doc.node(g).unwrap().kind, NodeKind::Intertwine { .. }));
assert_eq!(kids(&s, g), [a, b]);
}
#[test]
fn node_move_and_send_to_current_layer_clean_up_membership() {
let mut s = session();
let (g, a, b) = intertwined(&mut s);
arrange(&mut s, json!({"at": [50, 30]}));
let layer = parent(&s, g).unwrap();
s.execute("node.move", &json!({"id": b.0, "parent": layer.0, "index": 0})).unwrap();
assert!(s.doc().unwrap().doc.node(g).is_none());
assert_eq!(kids(&s, layer), [b, a]);
assert!(!has_areas(&s, a));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(kids(&s, g), [a, b]);
// A member sent to the current layer leaves the group the same way.
select(&mut s, &[a]);
s.execute("object.arrange.sendToCurrentLayer", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.node(g).is_none());
assert_eq!(kids(&s, layer), [b, a]);
assert!(!has_areas(&s, a));
s.execute("edit.undo", &json!({})).unwrap();
// node.move puts an object into an Intertwine group.
let c = green_bar(&mut s);
s.execute("node.move", &json!({"id": c.0, "parent": g.0, "index": 1})).unwrap();
assert_eq!(kids(&s, g), [a, c, b]);
}
// ---------- on the canvas ----------
fn press(s: &mut Session, pts: &[(f64, f64)], shift: bool) -> Vec<UiRequest> {
+21
View File
@@ -3160,6 +3160,27 @@ fn direction_handles_leave_out_hidden_and_locked_paths() {
assert_eq!(selected(&s), vec![a]);
}
#[test]
fn direction_handles_select_many_paths_in_groups_and_layers_in_paint_order() {
let mut s = session();
let mut paths: Vec<NodeId> = (0..60).map(|i| rect(&mut s, (i % 20) as f64 * 12.0, (i / 20) as f64 * 12.0, 10.0, 10.0)).collect();
sel(&mut s, &paths[10..40]);
s.execute("object.group", &json!({})).unwrap();
s.execute("layer.new", &json!({})).unwrap();
paths.extend((0..60).map(|i| rect(&mut s, (i % 20) as f64 * 12.0, 100.0 + (i / 20) as f64 * 12.0, 10.0, 10.0)));
s.execute("select.all", &json!({})).unwrap();
assert_eq!(s.execute("select.object.directionHandles", &json!({})).unwrap()["anchors"], 4 * paths.len());
let st = s.doc().unwrap();
let mut want = vectorcraft_doc::Selection::default();
for id in st.doc.paint_order(paths.iter().copied()) {
want.add(id);
want.anchors.insert(id, (0..4).map(|i| (0, i)).collect());
}
want.new_art = st.selection.new_art.clone();
assert_eq!(st.selection.objects.len(), paths.len());
assert_eq!(st.selection, want);
}
#[test]
fn select_point_and_area_text() {
let mut s = session();
+32
View File
@@ -767,6 +767,38 @@ fn package_copies_a_linked_eps_file_as_it_is() {
assert!(s.doc().unwrap().doc.has_placed());
}
#[test]
fn package_copies_the_files_a_linked_eps_files_native_document_places_beside_it() {
let dir = Folder::new("package-placed-eps-links");
let pic = dir.file("pics/photo.png");
write(&pic, &png(600, 300, RED));
let mut art = session();
place(&mut art, &pic);
std::fs::create_dir_all(dir.0.join("art")).unwrap();
let src = dir.file("art/seal.eps");
run(&mut art, "document.export", json!({"path": src, "format": "eps"}));
let mut s = session();
let placed = run(&mut s, "file.place", json!({"path": src}));
assert_eq!(placed["linked"], true, "{placed}");
save(&mut s, &dir.file("poster.vectorcraft"));
let r = run(&mut s, "file.package", json!({"folder": dir.file("out")}));
assert_eq!((r["links"].as_u64(), r["missingLinks"].clone(), r["warnings"].clone()), (Some(2), json!([]), json!([])), "{r}");
let root = dir.0.join("out/poster Folder");
assert_eq!(std::fs::read(root.join("Links/photo.png")).unwrap(), png(600, 300, RED));
// The copy of the EPS file finds the picture beside it, not its preview.
std::fs::remove_dir_all(dir.0.join("art")).unwrap();
std::fs::remove_dir_all(dir.0.join("pics")).unwrap();
let copy = root.join("Links/seal.eps").to_string_lossy().into_owned();
let shows_the_file = || {
let bytes = std::fs::read(&copy).unwrap();
let a = cmd::place::document::document_art("seal.eps", &bytes, Some(&copy), 1, false, vectorcraft_doc::PageBox::Crop, "t").unwrap();
a.doc.images.values().any(|b| !b.is_proxy())
};
assert!(shows_the_file());
std::fs::remove_file(root.join("Links/photo.png")).unwrap();
assert!(!shows_the_file(), "the preview only");
}
#[test]
fn package_copies_a_linked_postscript_ai_file_the_document_holds_after_it_is_gone() {
let dir = Folder::new("package-placed-ps-ai");
+54
View File
@@ -378,6 +378,60 @@ fn flare_spiral_and_polar_grid_draw_in_perspective() {
assert_eq!(attached(&s, NodeId(r["id"].as_u64().unwrap())).map(|a| a.0), Some(Plane::Left));
}
/// Alt-click (Option-click on macOS) with the Flare tool draws one flare with the tool's options as
/// one undo step, without a dialog. On the active plane it is the flare the click-opened Flare Tool
/// Options draw there; without the grid it is drawn flat. A plain click opens the dialog.
#[test]
fn an_alt_click_with_the_flare_tool_draws_the_flare_the_click_dialog_draws() {
use vectorcraft_tools::{PointerEvent, PointerKind};
let (mut s, _) = persp_session();
s.execute("perspective.grid.show", &json!({"visible": true})).unwrap();
s.execute("perspective.plane.set", &json!({"plane": "left"})).unwrap();
let v = ViewInfo::default();
s.select_tool("flare", v).unwrap();
s.set_tool_option_cmd(&json!({"tool": "flare", "values": {"diameter": 40, "rays": 6, "ringsOn": false}})).unwrap();
let options = s.tool_options_of("flare");
let at = Point::new(300.0, 380.0);
let alt = Mods { alt: true, ..Default::default() };
let alt_click = |s: &mut Session| {
s.pointer(&PointerEvent::new(PointerKind::Down, at.x, at.y).with_mods(alt), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, at.x, at.y).with_mods(alt), v).unwrap()
};
let n = undo_len(&s);
assert_eq!(alt_click(&mut s), vec![], "no dialog");
assert_eq!(undo_len(&s), n + 1);
assert_eq!(s.journal.last().unwrap().0, "perspective.draw");
let id = *s.doc().unwrap().selection.objects.first().unwrap();
assert_eq!(attached(&s, id).map(|a| a.0), Some(Plane::Left));
let drawn = node(&s, id).geometric_bounds().unwrap();
assert_eq!(s.tool_options_of("flare"), options, "the click leaves the options as they are");
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.node(id).is_none());
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(node(&s, id).geometric_bounds(), Some(drawn));
s.execute("edit.undo", &json!({})).unwrap();
let params = vectorcraft_tools::extra::flare_params(&options, at);
let (cmd, p) = crate::perspective_click(&s, "shape.flare", &params, at).unwrap();
let dialog = NodeId(s.execute(&cmd, &p).unwrap()["id"].as_u64().unwrap());
assert_eq!(node(&s, dialog).geometric_bounds(), Some(drawn), "the flare the dialog's OK draws");
// A click above the ground plane's horizon draws nothing and reports the error.
s.execute("perspective.plane.set", &json!({"plane": "ground"})).unwrap();
let above = grid(&s).horizon - 50.0;
let n = undo_len(&s);
s.pointer(&PointerEvent::new(PointerKind::Down, at.x, above).with_mods(alt), v).unwrap();
assert!(s.pointer(&PointerEvent::new(PointerKind::Up, at.x, above).with_mods(alt), v).is_err());
assert_eq!(undo_len(&s), n);
// Without the grid the flare is drawn flat; a plain click opens the dialog.
s.execute("perspective.grid.show", &json!({"visible": false})).unwrap();
assert_eq!(alt_click(&mut s), vec![]);
assert_eq!(s.journal.last().unwrap().0, "shape.flare");
let flat = *s.doc().unwrap().selection.objects.first().unwrap();
assert_eq!(attached(&s, flat), None);
s.pointer(&PointerEvent::new(PointerKind::Down, at.x, at.y), v).unwrap();
let ui = s.pointer(&PointerEvent::new(PointerKind::Up, at.x, at.y), v).unwrap();
assert_eq!(ui, vec![UiRequest::Dialog("flare".into(), json!({"x": at.x, "y": at.y}))]);
}
#[test]
fn click_to_size_dialogs_draw_on_the_active_plane_in_plane_units() {
let (mut s, _) = persp_session();
+24
View File
@@ -1212,6 +1212,30 @@ fn a_click_of_the_place_cursor_asks_the_frontend_to_place_the_file_when_asked_to
assert_eq!(s.journal.last(), at_once.journal.last());
}
/// A Shift-click of the place cursor asks the frontend for the file's import options
/// (`showImportOptions: true`); headless, with no frontend to ask, it places the file as a click
/// does.
#[test]
fn a_shift_click_of_the_place_cursor_places_headless_as_a_click_does() {
let view = ViewInfo::default();
let files: Vec<Value> = ["a.png", "b.png"].iter().map(|n| file(n, &png(40, 20, [9, 9, 9, 255], None))).collect();
let shift = Mods { shift: true, ..Mods::default() };
let (mut headless, mut app) = (session(), session());
app.place_cursor_requests = true;
let mut reqs = vec![];
for s in [&mut headless, &mut app] {
s.execute("file.place.queue", &json!({"files": files})).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 10.0, 10.0).with_mods(shift), view).unwrap();
reqs = s.pointer(&PointerEvent::new(PointerKind::Up, 10.0, 10.0).with_mods(shift), view).unwrap();
}
let [UiRequest::Place(p)] = &reqs[..] else { panic!("{reqs:?}") };
assert_eq!(p["showImportOptions"], true);
let [img] = &top_children(&headless)[..] else { panic!("one image placed") };
let b = img.geometric_bounds().unwrap();
assert_eq!([b.x0, b.y0, b.width(), b.height()], [10.0, 10.0, 40.0, 20.0]);
assert_eq!(headless.tool_options()["names"], json!(["b.png"]));
}
/// Files read for the place cursor apart from the session ([`Session::prepare_place_queue`], then
/// [`cmd::place::QueueJob::read`] on another thread and [`Session::place_queue_read`]) load it as
/// `file.place.queue` loads it: the same reply, with the files that can't be read skipped, and the
+279 -1
View File
@@ -1,5 +1,5 @@
//! Use Preview Bounds: the Transform panel values, the bounding box, Align and Distribute measure
//! visual bounds (strokes and geometry effects included) when it is on.
//! visual bounds (strokes, geometry and projected 3D effects included) when it is on.
use std::sync::Arc;
@@ -103,6 +103,284 @@ fn near(a: Rect, b: Rect, tolerance: f64) -> bool {
[(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(x, y)| (x - y).abs() <= tolerance)
}
const PREVIEW_3D: [&str; 4] = ["threeD.extrude", "threeD.revolve", "threeD.inflate", "threeD.rotate"];
/// A live projected rectangle, with the effect on the object or its painted fill.
fn projected_rect(s: &mut Session, effect: &str, item: bool) -> NodeId {
let id = rect(s, 100.0, 80.0, 0.0);
run(s, "effect.apply", json!({"ids": [id.0], "effect": effect, "params": params_3d(effect), "item": if item { json!(0) } else { Value::Null }}));
id
}
/// Settings for `effect` that turn the art and give it depth.
fn params_3d(effect: &str) -> Value {
let mut params = json!({"rotationX": -20, "rotationY": 35, "rotationZ": 15, "perspectiveAngle": 0, "shade": false});
match effect {
"threeD.revolve" => {
params["segments"] = json!(8);
params["angle"] = json!(240);
params["offset"] = json!(12);
}
"threeD.extrude" => {
params["depth"] = json!(40);
params["bevel"] = json!("rounded");
}
"threeD.inflate" => params["depth"] = json!(20),
_ => {}
}
params
}
/// Measure the renderer's projected vector art, including any geometry effects left after 3D.
fn projected(s: &Session, id: NodeId) -> Rect {
let d = &s.doc().unwrap().doc;
let n = d.node(id).unwrap();
let art = vectorcraft_render::effects::revolve_art(n).or_else(|| vectorcraft_render::effects::solid_art(n)).unwrap();
vectorcraft_render::effects::preview::visual_bounds(&d.symbol_boxes(), &art).unwrap()
}
/// All four projected effects contribute at object and item scope; off and hidden keep source bounds.
#[test]
fn preview_3d_measures_the_projected_art_at_object_and_item_scope() {
for effect in PREVIEW_3D {
for item in [false, true] {
let mut s = session();
let id = projected_rect(&mut s, effect, item);
let expected = projected(&s, id);
let source = geometric(&s, id);
assert!(!near(expected, source, 1e-3), "the fixture must change its bounds: {effect}");
preview(&mut s, true);
assert!(near(s.transform_bounds(&[id]).unwrap(), expected, 1e-6), "{effect}, item={item}");
preview(&mut s, false);
assert_eq!(s.transform_bounds(&[id]), Some(source));
preview(&mut s, true);
run(&mut s, "effect.setParams", json!({"ids": [id.0], "index": 0, "item": if item { json!(0) } else { Value::Null }, "visible": false}));
assert_eq!(s.transform_bounds(&[id]), Some(source), "hidden {effect}, item={item}");
}
}
}
/// Align and spacing use projected edges, with one undo step and no repeat-alignment edit.
#[test]
fn preview_3d_align_and_spacing_measure_projected_edges() {
for effect in PREVIEW_3D {
let mut s = session();
let a = projected_rect(&mut s, effect, false);
let b = rect(&mut s, 20.0, 30.0, 0.0);
preview(&mut s, true);
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
let before = s.doc().unwrap().doc.clone();
let history = s.doc().unwrap().history.undo.len();
run(&mut s, "object.align", json!({"horizontal": "left"}));
assert!((projected(&s, a).x0 - geometric(&s, b).x0).abs() < 1e-6, "{effect}");
assert_eq!(s.doc().unwrap().history.undo.len(), history + 1);
let aligned = s.doc().unwrap().doc.clone();
run(&mut s, "object.align", json!({"horizontal": "left"}));
assert_eq!(s.doc().unwrap().history.undo.len(), history + 1, "already aligned {effect}");
assert_eq!(s.doc().unwrap().doc, aligned);
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.doc().unwrap().doc, before);
run(&mut s, "edit.redo", json!({}));
assert_eq!(s.doc().unwrap().doc, aligned);
let mut s = session();
let a = projected_rect(&mut s, effect, false);
let b = rect(&mut s, 350.0, 30.0, 0.0);
preview(&mut s, true);
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
let before = s.doc().unwrap().doc.clone();
run(&mut s, "object.distributeSpacing", json!({"axis": "horizontal", "spacing": 0}));
assert!((projected(&s, a).x1 - geometric(&s, b).x0).abs() < 1e-6, "{effect}");
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.doc().unwrap().doc, before);
}
}
/// A group's and a symbol's projected members are measured as art rather than flat source paths.
#[test]
fn preview_3d_measures_projected_group_and_symbol_members() {
for effect in PREVIEW_3D {
let mut source = session();
let source_id = projected_rect(&mut source, effect, false);
let expected = projected(&source, source_id);
let mut d = Document::new(600.0, 400.0);
let mut shape = source.doc().unwrap().doc.node(source_id).unwrap().clone();
shape.id = d.alloc_id();
let group = Node::group(d.alloc_id(), vec![Arc::new(shape.clone())]);
let group_id = group.id;
let layer = d.layers[0].id;
d.insert(Some(layer), 0, group).unwrap();
shape.id = d.alloc_id();
d.symbols.push(Symbol { dynamic: false, name: "3D / Bounds".into(), art: Arc::new(shape) });
let shift = Affine::translate((250.0, 0.0));
let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "3D / Bounds".into(), xf: shift });
let instance_id = instance.id;
d.insert(Some(layer), 1, instance).unwrap();
let mut s = Session::new();
s.add_document(d, None);
preview(&mut s, true);
assert!(near(s.transform_bounds(&[group_id]).unwrap(), expected, 1e-6), "group {effect}");
assert!(near(s.transform_bounds(&[instance_id]).unwrap(), shift.transform_rect_bbox(expected), 1e-6), "symbol {effect}");
}
}
/// A symbol instance with a 3D effect of its own is measured by the art the renderer projects from its symbol.
#[test]
fn preview_3d_measures_an_instance_with_its_own_effect() {
for effect in PREVIEW_3D {
let mut d = Document::new(600.0, 400.0);
let square = Node::path(
d.alloc_id(),
shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 80.0)),
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
);
d.symbols.push(Symbol { dynamic: false, name: "3D / Own".into(), art: Arc::new(square) });
let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "3D / Own".into(), xf: Affine::translate((50.0, 40.0)) });
let (layer, id) = (d.layers[0].id, instance.id);
d.insert(Some(layer), 0, instance).unwrap();
let mut s = Session::new();
s.add_document(d, None);
run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": effect, "params": params_3d(effect)}));
let d = &s.doc().unwrap().doc;
let n = d.node(id).unwrap();
let art = vectorcraft_render::effects::revolve_art_in(Some(d), n).or_else(|| vectorcraft_render::effects::solid_art_in(Some(d), n)).unwrap();
let expected = vectorcraft_render::effects::preview::visual_bounds(&d.symbol_boxes(), &art).unwrap();
let source = geometric(&s, id);
assert!(!near(expected, source, 1e-3), "the fixture must change its bounds: {effect}");
preview(&mut s, true);
assert!(near(s.transform_bounds(&[id]).unwrap(), expected, 1e-6), "{effect}");
}
}
/// Dynamic instance overrides are applied before deciding which painted 3D surfaces remain.
#[test]
fn preview_3d_dynamic_symbol_overrides_precede_projection() {
for effect in PREVIEW_3D {
let mut source = session();
let source_id = projected_rect(&mut source, effect, false);
let full = projected(&source, source_id);
let mut d = Document::new(600.0, 400.0);
let mut art = source.doc().unwrap().doc.node(source_id).unwrap().clone();
art.id = d.alloc_id();
d.symbols.push(Symbol { dynamic: true, name: "3D / Dynamic".into(), art: Arc::new(art) });
let mut instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "3D / Dynamic".into(), xf: Affine::IDENTITY });
instance
.extras_mut()
.symbol_overrides
.push(vectorcraft_doc::symbol_overrides::SymbolOverride { fill: Some(Paint::None), ..Default::default() });
let id = instance.id;
let changed = vectorcraft_doc::symbol_overrides::dynamic_art(&d.symbols[0].art, &instance);
let expected = vectorcraft_render::effects::preview::visual_bounds(&d.symbol_boxes(), &changed);
if effect == "threeD.extrude" {
assert!(expected.is_some(), "the Extrude fixture must retain its source bounds");
}
assert!(expected.is_none_or(|b| !near(b, full, 1e-3)), "the override must remove the projected surface: {effect}");
let layer = d.layers[0].id;
d.insert(Some(layer), 0, instance).unwrap();
let mut s = Session::new();
s.add_document(d, None);
preview(&mut s, true);
let actual = s.transform_bounds(&[id]);
assert!(
match (actual, expected) {
(Some(a), Some(b)) => near(a, b, 1e-6),
(None, None) => true,
_ => false,
},
"overridden {effect}: {actual:?}, expected {expected:?}"
);
run(&mut s, "symbol.instance.reset", json!({"ids": [id.0]}));
assert!(near(s.transform_bounds(&[id]).unwrap(), full, 1e-6), "reset {effect}");
}
}
/// Geometry after projection remains part of the measured stack at object and item scope.
#[test]
fn preview_3d_applies_geometry_after_the_projected_surface() {
for effect in PREVIEW_3D {
for item in [false, true] {
let mut s = session();
let id = projected_rect(&mut s, effect, item);
run(
&mut s,
"effect.apply",
json!({"ids": [id.0], "effect": "path.offsetPath", "params": {"offset": 5}, "item": if item { json!(0) } else { Value::Null }}),
);
let expected = projected(&s, id);
preview(&mut s, true);
assert!(near(s.transform_bounds(&[id]).unwrap(), expected, 1e-6), "{effect}, item={item}");
}
}
}
/// Typed width sizes the projected art and remains one undoable edit.
#[test]
fn preview_3d_set_bounds_sizes_the_projected_width() {
for effect in PREVIEW_3D {
let mut s = session();
let id = projected_rect(&mut s, effect, false);
let target = projected(&s, id).width() * 1.25;
preview(&mut s, true);
let before = s.doc().unwrap().doc.clone();
let history = s.doc().unwrap().history.undo.len();
run(&mut s, "object.setBounds", json!({"width": target, "reference": 0, "proportional": true, "strokes": false}));
assert!((projected(&s, id).width() - target).abs() < 1e-4, "{effect}: {:?}, target {target}", projected(&s, id));
assert_eq!(s.doc().unwrap().history.undo.len(), history + 1);
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.doc().unwrap().doc, before);
}
}
/// A rotated selection measures the projected surface in its own bounding-box frame.
#[test]
fn preview_3d_oriented_box_follows_projected_art() {
for effect in PREVIEW_3D {
let mut s = session();
let id = projected_rect(&mut s, effect, false);
run(&mut s, "object.rotate", json!({"angle": 30}));
let d = &s.doc().unwrap().doc;
let angle = d.bbox_angle(&[id]);
assert!(angle.abs() > 0.1);
let n = d.node(id).unwrap();
let art = vectorcraft_render::effects::revolve_art(n).or_else(|| vectorcraft_render::effects::solid_art(n)).unwrap();
let frame = vectorcraft_doc::OrientedBox { angle, rect: Rect::ZERO }.to_doc().inverse();
let expected = vectorcraft_render::effects::preview::bounds_in(&d.symbol_boxes(), &art, frame).unwrap();
preview(&mut s, true);
let measured = s.transform_box(&[id]).unwrap();
assert_eq!(measured.angle, angle);
assert!(near(measured.rect, expected, 1e-6), "{effect}: {measured:?} vs {expected:?}");
}
}
/// A click on a member of a layer with a 3D effect selects that member, with Use Preview Bounds on
/// or off, and the layer is still measured by its projected art.
#[test]
fn a_click_selects_the_member_of_a_layer_with_a_3d_effect() {
for effect in PREVIEW_3D {
for on in [false, true] {
let mut s = session();
let id = rect(&mut s, 100.0, 80.0, 0.0);
run(&mut s, "paint.setFill", json!({"color": "#0000ff"}));
let layer = s.doc().unwrap().doc.layers[0].id;
run(&mut s, "effect.apply", json!({"ids": [layer.0], "effect": effect, "params": params_3d(effect), "item": null}));
preview(&mut s, on);
run(&mut s, "select.none", json!({}));
let v = ViewInfo::default();
s.select_tool("selection", v).unwrap();
for k in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(k, 140.0, 125.0), v).unwrap();
}
assert_eq!(s.active().unwrap().selection.objects, [id], "{effect}, preview={on}");
let d = &s.doc().unwrap().doc;
let art =
vectorcraft_render::effects::revolve_art(&d.layers[0]).or_else(|| vectorcraft_render::effects::solid_art(&d.layers[0])).unwrap();
let expected = vectorcraft_render::effects::preview::visual_bounds(&d.symbol_boxes(), &art).unwrap();
let measured = vectorcraft_render::effects::preview::bounds_of(d, &[layer], true).unwrap();
assert!(near(measured, expected, 1e-6), "{effect}: {measured:?} vs {expected:?}");
}
}
}
#[test]
fn a_square_with_offset_path_is_measured_by_the_offset_shape() {
let mut s = session();
+53
View File
@@ -69,6 +69,59 @@ fn overprint_black_is_saved_with_the_setup_and_in_presets() {
assert_eq!(changed, ["output.overprintBlack"]);
}
#[test]
fn the_scale_link_keeps_width_and_height_equal() {
let (mut s, _) = session();
let scale = |s: &mut Session, p: Value| s.execute("print.setup", &json!({ "settings": p })).unwrap()["settings"]["scale"].clone();
assert_eq!(scale(&mut s, json!({})), json!({"width": 100.0, "height": 100.0, "linked": true}), "on for a new job");
// Linked, one percentage sets the other, whichever it is.
assert_eq!(scale(&mut s, json!({"scaling": "custom", "scale": {"width": 40}})), json!({"width": 40.0, "height": 40.0, "linked": true}));
assert_eq!(scale(&mut s, json!({"scale": {"height": 250}})), json!({"width": 250.0, "height": 250.0, "linked": true}));
assert_eq!(scale(&mut s, json!({"scale": {"width": 60, "height": 60.0}})), json!({"width": 60.0, "height": 60.0, "linked": true}));
// Two different percentages with linked: true are refused and keep what was saved.
let apart = s.execute("print.setup", &json!({"settings": {"scale": {"width": 50, "height": 200, "linked": true}}}));
assert!(matches!(apart, Err(EngineError::BadParams { .. })), "{apart:?}");
assert!(s.execute("print.preview", &json!({"settings": {"scale": {"width": 50, "height": 200, "linked": true}}})).is_err());
// `linked: null` keeps the saved link, as null keeps any saved setting.
let kept = s.execute("print.setup", &json!({"settings": {"scale": {"width": 50, "height": 200, "linked": null}}}));
assert!(matches!(kept, Err(EngineError::BadParams { .. })), "{kept:?}");
assert_eq!(scale(&mut s, json!({}))["width"], 60.0);
// Without linked, two different percentages turn the link off and print as given.
assert_eq!(scale(&mut s, json!({"scale": {"width": 50, "height": 200}})), json!({"width": 50.0, "height": 200.0, "linked": false}));
assert_eq!(s.execute("print.preview", &json!({})).unwrap()["sheets"][0]["scale"], json!([50.0, 200.0]));
// Unlinked, each changes alone; turning the link on sets the height to the width.
assert_eq!(scale(&mut s, json!({"scale": {"height": 120}})), json!({"width": 50.0, "height": 120.0, "linked": false}));
assert_eq!(scale(&mut s, json!({"scale": {"linked": true}})), json!({"width": 50.0, "height": 50.0, "linked": true}));
assert_eq!(s.execute("print.preview", &json!({})).unwrap()["sheets"][0]["scale"], json!([50.0, 50.0]));
// Kept in the native file and in print presets.
let doc = &s.doc().unwrap().doc;
let back = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap();
assert_eq!(back.print_setup.as_ref().map(|p| p["scale"].clone()), Some(json!({"width": 50.0, "height": 50.0, "linked": true})));
s.execute("print.presets.save", &json!({"name": "Apart", "settings": {"scaling": "custom", "scale": {"width": 30, "height": 90}}})).unwrap();
let preset = s.prefs.print_presets.iter().find(|p| p.name == "Apart").map(|p| p.settings.scale.clone());
assert_eq!(preset.map(|p| (p.width, p.height, p.linked)), Some((30.0, 90.0, false)));
assert_eq!(scale(&mut s, json!({}))["linked"], true, "saving a preset leaves the document's settings");
let v = s.execute("print.setup", &json!({"preset": "Apart"})).unwrap();
assert_eq!(v["settings"]["scale"], json!({"width": 30.0, "height": 90.0, "linked": false}));
}
#[test]
fn a_scale_saved_without_the_link_keeps_its_width_and_height() {
let (mut s, _) = session();
// Settings saved before the link had no `linked`: they print as they did, unlinked.
let mut old = serde_json::to_value(vectorcraft_pdf::PrintSettings::default()).unwrap();
old["scaling"] = json!("custom");
old["scale"] = json!({"width": 50, "height": 200});
let mut doc = (*s.doc().unwrap().doc).clone();
doc.print_setup = Some(old);
s.doc_mut().unwrap().doc = std::sync::Arc::new(doc);
let pv = s.execute("print.preview", &json!({})).unwrap();
assert_eq!(pv["sheets"][0]["scale"], json!([50.0, 200.0]));
assert_eq!(pv["settings"]["scale"]["linked"], false);
// One percentage changes alone until the link is turned on.
assert_eq!(s.execute("print.preview", &json!({"settings": {"scale": {"width": 80}}})).unwrap()["sheets"][0]["scale"], json!([80.0, 200.0]));
}
#[test]
fn print_writes_the_saved_setup_with_overrides() {
let (mut s, _) = session();
+50
View File
@@ -395,6 +395,56 @@ fn expand_rasterize_then_transform_matches_canvas() {
assert!(matches!(&n.kind, vectorcraft_doc::NodeKind::Group { children, .. } if children.is_empty()), "{:?}", n.kind);
}
/// With copies, the Transform effect after Rasterize places the one image on the original and on
/// each copy: Expand Appearance and PDF export make a group of the image placed by each copy's
/// map, the last copy lowest and the original on top, as the canvas draws it, all on the pixels
/// Object › Rasterize makes of the art.
#[test]
fn expand_rasterize_then_copying_transform_places_the_image_on_each_copy() {
let mut o = session();
red_rectangle(&mut o);
let made = id(&o.execute("object.rasterize", &json!({"ppi": 72, "background": "white", "addAround": 2})).unwrap());
let od = &o.doc().unwrap().doc;
let (w, h, xf, png, _) = rasterized(od, od.node(made).unwrap());
let about =
|m: vectorcraft_geom::Affine| vectorcraft_geom::Affine::translate((70.5, 65.25)) * m * vectorcraft_geom::Affine::translate((-70.5, -65.25));
let turn = |deg: f64| about(vectorcraft_geom::Affine::rotate(-deg.to_radians()));
let cases = [
(json!({"moveH": 50, "copies": 2}), [vectorcraft_geom::Affine::translate((100.0, 0.0)), vectorcraft_geom::Affine::translate((50.0, 0.0))]),
(json!({"rotate": 30, "copies": 2}), [turn(60.0), turn(30.0)]),
];
for (params, [lowest, middle]) in cases {
let mut s = session();
let r = red_rectangle(&mut s);
let raster = json!({"useDocumentResolution": false, "resolution": 72, "background": "white", "addAround": 2});
s.execute("effect.apply", &json!({"effect": "rasterize", "params": raster, "ids": [r.0]})).unwrap();
s.execute("effect.apply", &json!({"effect": "distort.transform", "params": params.clone(), "ids": [r.0]})).unwrap();
let check = |d: &Document, n: &vectorcraft_doc::Node, what: &str| {
let NodeKind::Group { children, clip: false } = &n.kind else { panic!("{what} {params}: a group, {:?}", n.kind_label()) };
assert_eq!(children.len(), 3, "{what} {params}");
let mut keys = std::collections::HashSet::new();
for (c, map) in children.iter().zip([lowest, middle, vectorcraft_geom::Affine::IDENTITY]) {
let (w2, h2, xf2, png2, _) = rasterized(d, c);
assert_eq!((w2, h2), (w, h), "{what} {params}");
assert!(png2 == png, "{what} {params}: the same pixels");
let want = map * xf;
assert!(xf2.as_coeffs().iter().zip(want.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-6), "{what} {params}: {xf2:?} {want:?}");
if let NodeKind::Image(im) = &c.kind {
keys.insert(im.key.clone());
}
}
assert_eq!(keys.len(), 1, "{what} {params}: one image for the three placements");
let mut ids = std::collections::HashSet::new();
n.walk(&mut |c| assert!(ids.insert(c.id), "{what} {params}: id {:?} twice", c.id));
};
let flat = crate::flatten_raster_effects(&s.doc().unwrap().doc).unwrap();
check(&flat, &flat.layers[0].children().unwrap()[0], "PDF export");
s.execute("effect.expandAppearance", &json!({"ids": [r.0]})).unwrap();
let d = &s.doc().unwrap().doc;
check(d, d.node(r).unwrap(), "Expand Appearance");
}
}
#[test]
fn the_clipping_mask_follows_the_art_its_geometry_effects_draw() {
let clip = |s: &Session, n: NodeId| match &s.doc().unwrap().doc.node(n).unwrap().kind {
+128
View File
@@ -1805,6 +1805,134 @@ fn linear_picks_show_and_snap_to_smart_guides() {
assert_eq!(text(&s, id), "60.02 pt");
}
/// A shape with a curve at each top corner, for the tests of where Linear picks land.
const CURVED_TOP: &str = "M130 358 C185 358 230 315 230 260 L425 260 C490 260 541 305 541 358 L541 440 L130 440 Z";
/// Where the next Linear click lands (the last marker the overlays draw, and its size) and the
/// labels shown, with the pointer at (`x`, `y`).
fn linear_marker(s: &mut Session, view: ViewInfo, x: f64, y: f64) -> (Option<(vectorcraft_geom::Point, f32)>, Vec<String>) {
use vectorcraft_engine::tools::Overlay;
s.pointer(&PointerEvent::new(PointerKind::Move, x, y), view).unwrap();
let o = s.overlays(view);
let at = o.iter().filter_map(|o| if let Overlay::Anchor { p, size, .. } = o { Some((*p, *size)) } else { None }).next_back();
let labels = o.iter().filter_map(|o| if let Overlay::Label { text, .. } = o { Some(text.clone()) } else { None }).collect();
(at, labels)
}
/// A plain click at (`x`, `y`): the pointer moves there, then presses and releases.
fn linear_click(s: &mut Session, view: ViewInfo, x: f64, y: f64) {
for kind in [PointerKind::Move, PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, x, y), view).unwrap();
}
}
/// Linear picks land on the anchors and paths of the art with an "anchor" or "path" label, and on
/// the ends and lines of dimensions already drawn, from as far as on the art's anchors: zoomed in,
/// a dimension started a few pixels from the end of another starts exactly at that end.
#[test]
fn linear_picks_land_on_anchors_paths_and_drawn_dimensions() {
let (plain, zoomed) = (ViewInfo::default(), ViewInfo { zoom: 8.0, ..ViewInfo::default() });
let mut s = session();
run(&mut s, "path.create", json!({"d": CURVED_TOP}));
run(&mut s, "select.none", json!({}));
s.select_tool("dimension", plain).unwrap();
let pt = vectorcraft_geom::Point::new;
let hover = |s: &mut Session, view: ViewInfo, x: f64, y: f64| {
let (at, labels) = linear_marker(s, view, x, y);
(at.map(|(p, _)| p), labels)
};
// Beside the end of the curve: on the anchor, labeled.
assert_eq!(hover(&mut s, plain, 231.0, 262.0), (Some(pt(230.0, 260.0)), vec!["anchor".to_string()]));
// Beside the curve: on its closest point, labeled.
let (at, labels) = hover(&mut s, plain, 200.0, 337.0);
assert!(at.is_some_and(|q| q.distance(pt(200.0, 337.0)) < 6.0 && q != pt(200.0, 337.0)), "{at:?}");
assert_eq!(labels, ["path"]);
// A first dimension from the bottom of the curve to its top, placed above the art.
linear_click(&mut s, plain, 130.0, 358.0);
linear_click(&mut s, plain, 230.0, 260.0);
linear_click(&mut s, plain, 180.0, 207.0);
let first = s.doc().unwrap().selection.objects[0].0;
assert_eq!((recipe(&s, first).a, recipe(&s, first).b), (pt(130.0, 358.0), pt(230.0, 260.0)));
run(&mut s, "select.none", json!({}));
s.select_tool("dimension", zoomed).unwrap();
// Zoomed in, 5.8 pixels from the end of its dimension line: on that end, marked as an anchor.
assert_eq!(linear_marker(&mut s, zoomed, 230.6, 207.4), (Some((pt(230.0, 207.0), 10.0)), vec!["anchor".to_string()]));
// 6.4 pixels beside its extension line: on the line.
let (at, labels) = hover(&mut s, zoomed, 230.8, 230.0);
assert!(at.is_some_and(|q| (q.x - 230.0).abs() < 1e-6 && (q.y - 230.0).abs() < 1e-6), "{at:?}");
assert_eq!(labels, ["path"]);
// The next dimension starts where the first one's line ends.
linear_click(&mut s, zoomed, 230.6, 207.4);
linear_click(&mut s, zoomed, 425.0, 260.0);
linear_click(&mut s, zoomed, 330.0, 207.0);
let second = s.doc().unwrap().selection.objects[0].0;
assert_ne!(second, first);
let d = recipe(&s, second);
assert!(near(d.a, pt(230.0, 207.0)) && near(d.b, pt(425.0, 260.0)), "{:?} {:?}", d.a, d.b);
}
/// An anchor of the art that a dimension already measures takes a point picked beside it, not the
/// end of the extension line a few points off it. A locked dimension pulls no point, and with
/// Smart Guides and Snap to Point off no dimension pulls a point and no label shows. A press on
/// the end of a dimension's line over a segment of the art that moves a few pixels before the
/// release picks that end, as a press on an anchor does.
#[test]
fn an_anchor_beside_a_drawn_dimension_takes_the_point() {
let (plain, zoomed) = (ViewInfo::default(), ViewInfo { zoom: 8.0, ..ViewInfo::default() });
let off = ViewInfo { smart_guides: false, snap_to_point: false, ..zoomed };
let mut s = session();
run(&mut s, "path.create", json!({"d": CURVED_TOP}));
run(&mut s, "select.none", json!({}));
s.select_tool("dimension", plain).unwrap();
let pt = vectorcraft_geom::Point::new;
linear_click(&mut s, plain, 130.0, 358.0);
linear_click(&mut s, plain, 230.0, 260.0);
linear_click(&mut s, plain, 180.0, 207.0);
let first = s.doc().unwrap().selection.objects[0].0;
// Locked, the first dimension's line end does not pull a point 5.8 pixels away.
run(&mut s, "object.lock", json!({}));
let (at, _) = linear_marker(&mut s, zoomed, 230.6, 207.4);
assert!(at.is_none_or(|(p, _)| p != pt(230.0, 207.0)), "a locked dimension: {at:?}");
run(&mut s, "object.unlockAll", json!({}));
run(&mut s, "select.none", json!({}));
// 2.5 pixels above the curve's top anchor and 1.5 pixels below the end of the extension line
// that starts 4 points above it: on the anchor, linked to the art.
assert_eq!(linear_marker(&mut s, plain, 230.0, 257.5), (Some((pt(230.0, 260.0), 10.0)), vec!["anchor".to_string()]));
// Smart Guides and Snap to Point off: no pull to the dimension's line end, and no labels.
let (at, labels) = linear_marker(&mut s, off, 230.6, 207.4);
assert!(at.is_none_or(|(p, _)| p != pt(230.0, 207.0)) && labels.is_empty(), "{at:?} {labels:?}");
let (at, labels) = linear_marker(&mut s, off, 230.1, 260.1);
assert!(at.is_some_and(|(p, _)| p == pt(230.0, 260.0)) && labels.is_empty(), "{at:?} {labels:?}");
// Snap to Point on and Smart Guides off: the line end takes the point, and no label shows.
assert_eq!(linear_marker(&mut s, ViewInfo { snap_to_point: true, ..off }, 230.6, 207.4), (Some((pt(230.0, 207.0), 10.0)), vec![]));
// A second dimension whose line lies on the bottom edge, from x 425 to x 541.
linear_click(&mut s, plain, 425.0, 260.0);
linear_click(&mut s, plain, 541.0, 358.0);
linear_click(&mut s, plain, 480.0, 440.0);
let second = s.doc().unwrap().selection.objects[0].0;
assert_ne!(second, first);
run(&mut s, "select.none", json!({}));
// A press 1.4 pixels from its line's left end, on the bottom edge, moved 5 pixels: the end is
// picked, and no dimension of the edge is dragged out.
for (kind, x) in [(PointerKind::Move, 426.0), (PointerKind::Down, 426.0), (PointerKind::Drag, 431.0), (PointerKind::Up, 431.0)] {
s.pointer(&PointerEvent::new(kind, x, 441.0), plain).unwrap();
}
linear_click(&mut s, plain, 541.0, 440.0);
linear_click(&mut s, plain, 480.0, 470.0);
let third = s.doc().unwrap().selection.objects[0].0;
assert_ne!(third, second);
let d = recipe(&s, third);
assert!(near(d.a, pt(425.0, 440.0)) && near(d.b, pt(541.0, 440.0)), "{:?} {:?}", d.a, d.b);
// A dimension of the left edge whose line lies 4 points off it, where its extension lines
// start: zoomed in, the end of its line still takes a point 4.7 pixels away.
run(&mut s, "select.none", json!({}));
linear_click(&mut s, plain, 130.0, 358.0);
linear_click(&mut s, plain, 130.0, 440.0);
linear_click(&mut s, plain, 126.0, 400.0);
run(&mut s, "select.none", json!({}));
assert_eq!(linear_marker(&mut s, zoomed, 125.5, 358.3), (Some((pt(126.0, 358.0), 10.0)), vec!["anchor".to_string()]));
}
/// The page content streams of exported PDF `v`, inflated.
fn pdf_content(v: &Value) -> String {
let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap();