Merge main into perf/layer-highlight-set

This commit is contained in:
dotCooCoo
2026-11-18 07:39:22 -08:00
680 changed files with 65906 additions and 4204 deletions
+6 -2
View File
@@ -59,6 +59,9 @@ chrono = { workspace = true }
craft-xml = { workspace = true }
# The compound file that holds a Word 97-2003 document placed as type (place/doc.rs).
cfb = "0.15"
# The Text Import Options character sets other than Unicode and ANSI (place/text.rs). Already in
# Cargo.lock (vectorcraft-eps), so this adds no new crate.
encoding_rs = { workspace = true }
kurbo = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
@@ -70,8 +73,9 @@ log = { workspace = true }
[target.'cfg(unix)'.dependencies]
rustix = { workspace = true, features = ["std", "process"] }
# Whether a recovery area's lock file is still the one that was opened (`FolderStore::still_named`).
# Already in Cargo.lock (walkdir), so this adds no new crate.
# Whether a recovery area's lock file is still the one that was opened (`FolderStore::still_named`),
# and whether two paths a script names are one file (`script::files`). Already in Cargo.lock
# (walkdir), so this adds no new crate.
[target.'cfg(windows)'.dependencies]
same-file = "1.0.6"
@@ -0,0 +1,154 @@
//! `cargo run --release -p vectorcraft-engine --example layer_select_bench` prints the time of a
//! Shift-click in the Layers panel's selection column (`layer.selectAll {id, add: true}`) on a layer of
//! 2,000, 20,000 and 50,000 rectangles, with all of its art selected (the click removes it) and with
//! every other object selected (the click adds the rest). Each case is timed one id at a time (`old`,
//! the loop the command used before, copied here) and in one pass (`new`), side by side in one
//! process: first the whole command, then the selection step alone. Each case checks that both give
//! the same selection and reply before it is timed.
//! `ITERS` sets the runs per case (default 7); each row is the median wall time in ms, followed by
//! every run of `old` and of `new`.
// 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::HashSet;
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};
fn iters() -> usize {
std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1)
}
fn median(ms: &[f64]) -> f64 {
let mut ms = ms.to_vec();
ms.sort_by(f64::total_cmp);
ms[ms.len() / 2]
}
/// A document whose first layer holds `n` 10 pt squares in a row → (document, layer, squares).
fn squares(n: usize) -> (Document, NodeId, Vec<NodeId>) {
let mut doc = Document::new(1600.0, 1200.0);
let layer = doc.layers[0].id;
let ids = (0..n)
.map(|i| {
let (x, y) = ((i % 100) as f64 * 12.0, (i / 100) as f64 * 12.0);
let corners = [(x, y), (x + 10.0, y), (x + 10.0, y + 10.0), (x, y + 10.0)];
let path = PathData::single(SubPath::new(corners.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), true));
let id = doc.alloc_id();
doc.insert(Some(layer), usize::MAX, Node::path(id, path, Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 1.0))).unwrap();
id
})
.collect();
(doc, layer, ids)
}
/// `layer.selectAll {id: layer, add: true}` before the change: the layer's art checked, removed or
/// added one id at a time with [`Selection::contains`], [`Selection::remove`] and [`Selection::add`].
fn old_command(s: &mut Session, layer: NodeId) -> Value {
let st = s.doc().unwrap();
let ids = st.doc.node(layer).unwrap().layer_art(true);
let all_selected = !ids.is_empty() && ids.iter().all(|i| st.selection.contains(*i));
let rows = st.layer_rows.clone();
s.select(|_, sel| old_step(sel, &ids, all_selected)).unwrap();
let st = s.doc_mut().unwrap();
st.layer_rows = rows;
json!({ "selected": st.selection.objects.iter().map(|i| i.0).collect::<Vec<_>>() })
}
fn old_step(sel: &mut Selection, ids: &[NodeId], all_selected: bool) {
for i in ids {
if all_selected { sel.remove(*i) } else { sel.add(*i) }
}
}
fn new_command(s: &mut Session, layer: NodeId) -> Value {
s.execute("layer.selectAll", &json!({"id": layer.0, "add": true})).unwrap()
}
/// Every run of `old` and of `new`, run in turn, each from `prepare`'s state.
fn time<S>(mut prepare: impl FnMut() -> S, old: impl Fn(&mut S), new: impl Fn(&mut S)) -> (Vec<f64>, Vec<f64>) {
let run = |s: &mut S, f: &dyn Fn(&mut S)| {
let t = Instant::now();
f(s);
t.elapsed().as_secs_f64() * 1000.0
};
let (mut olds, mut news) = (Vec::new(), Vec::new());
for _ in 0..iters() {
let mut s = prepare();
olds.push(run(&mut s, &old));
black_box(&s);
let mut s = prepare();
news.push(run(&mut s, &new));
black_box(&s);
}
(olds, news)
}
fn row(name: &str, (old, new): (Vec<f64>, Vec<f64>)) {
let (o, n) = (median(&old), median(&new));
let list = |ms: &[f64]| ms.iter().map(|m| format!("{m:.2}")).collect::<Vec<_>>().join(" ");
println!(" {name:<40} {o:>12.3} ms {n:>12.3} ms {:>9.1}x", o / n.max(1e-9));
println!(" old runs: {}", list(&old));
println!(" new runs: {}", list(&new));
}
fn main() {
println!(" {:<40} {:>15} {:>15} {:>10}", "case", "old", "new", "speedup");
for n in [2_000usize, 20_000, 50_000] {
println!("{n} objects");
let (doc, layer, ids) = squares(n);
let mut s = Session::new();
s.add_document(doc, None);
let mut all = Selection::default();
all.set(ids.iter().copied());
let mut half = Selection::default();
half.set(ids.iter().copied().step_by(2));
for (name, start) in [("all selected (removes)", &all), ("half selected (adds)", &half)] {
let reset = |s: &mut Session| {
let st = s.doc_mut().unwrap();
st.selection = start.clone();
st.layer_rows.clear();
};
// Both ways give the same selection and reply.
reset(&mut s);
let old_reply = old_command(&mut s, layer);
let old_sel = s.doc().unwrap().selection.clone();
reset(&mut s);
let new_reply = new_command(&mut s, layer);
assert_eq!(s.doc().unwrap().selection, old_sel, "{name}: the same selection");
assert_eq!(new_reply, old_reply, "{name}: the same reply");
let (mut olds, mut news) = (Vec::new(), Vec::new());
for _ in 0..iters() {
for (f, ms) in [(old_command as fn(&mut Session, NodeId) -> Value, &mut olds), (new_command, &mut news)] {
reset(&mut s);
let t = Instant::now();
black_box(f(&mut s, layer));
ms.push(t.elapsed().as_secs_f64() * 1000.0);
}
}
row(&format!("command, {name}"), (olds, news));
// The selection step alone, on a copy of the starting selection.
let art = s.doc().unwrap().doc.node(layer).unwrap().layer_art(true);
let selected: HashSet<NodeId> = start.objects.iter().copied().collect();
let all_selected = art.iter().all(|i| selected.contains(i));
let new_step = |sel: &mut Selection| {
if all_selected {
sel.remove_all(art.iter().copied());
} else {
sel.add_all(art.iter().copied());
}
};
let (mut a, mut b) = (start.clone(), start.clone());
old_step(&mut a, &art, all_selected);
new_step(&mut b);
assert_eq!(a, b, "{name}: the same selection step");
row(&format!("selection step, {name}"), time(|| start.clone(), |sel| old_step(sel, &art, all_selected), new_step));
}
}
}
+217
View File
@@ -0,0 +1,217 @@
//! `cargo run --release -p vectorcraft-engine --example link_colors_bench` prints the time
//! `Document::map_solid_paints_in` takes to link the paints of selected objects to swatches, as Add Used
//! Colors and New Color Group do for the selection with global swatches, on synthetic documents: 2,000 and
//! 20,000 rectangles in one layer, and 5,000 rectangles in 1,000 groups of groups, selected with and
//! without the groups that hold them. The fills and strokes use 50 colors, each with a swatch to link to.
//! For each it times two ways of finding the selected objects that no other selected object holds: a
//! search of the id list for each ancestor of each id, and a lookup of each ancestor in a set of the ids
//! (as `map_solid_paints_in` does). Both then link the same paints in the same loop. It checks that both
//! give the same count, visit the same paints in the same order and leave the same document as
//! `map_solid_paints_in` before it times them.
//! `ITERS` sets the runs per row (default 7); the two ways run in alternating order, each run links 10
//! fresh copies of the document, and each row is the median time of one call. 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::collections::{HashMap, HashSet};
use std::hint::black_box;
use std::sync::Arc;
use std::time::Instant;
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::swatches::{LinkFn, map_node_solid_paints};
use vectorcraft_doc::{Appearance, Document, Node, NodeId};
use vectorcraft_geom::{Rect, shapes};
/// The colors the rectangles use, each with a swatch to link to.
const COLORS: usize = 50;
/// The calls in each timed run; a row gives the time of one call.
const REPS: usize = 10;
/// A way of finding the ids that no other listed id holds.
type Roots = fn(&Document, &[NodeId]) -> Vec<NodeId>;
/// A way of applying a link function to the paints of the listed ids, returning the count changed.
type Map<'a> = dyn FnMut(&mut Document, &[NodeId], &mut LinkFn) -> usize + 'a;
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
}
}
}
/// Color `i` of [`COLORS`]: each has its own red value.
fn color(i: usize) -> Color {
Color::rgb(i as f32 / COLORS as f32, 0.5, 0.25)
}
/// The bits of a color's red value, which tell the colors of [`color`] apart; `u32::MAX` for other color models.
fn red_bits(c: &Color) -> u32 {
match c {
Color::Rgb { r, .. } => r.to_bits(),
_ => u32::MAX,
}
}
/// The ids in the order given, less those with an ancestor in the list: a search of the list for each ancestor.
fn roots_by_search(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect()
}
/// [`roots_by_search`] with each ancestor looked up in a set of the ids.
fn roots_by_set(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
let listed: HashSet<NodeId> = ids.iter().copied().collect();
ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| listed.contains(p)))).collect()
}
/// `f` applied to the paints of the subtrees of the ids `roots` finds, each node holding a changed
/// paint put in place: the work of `map_solid_paints_in`.
fn map_in(d: &mut Document, ids: &[NodeId], roots: Roots, f: &mut LinkFn) -> usize {
let mut n = 0;
for id in roots(d, ids) {
let Some(mut node) = d.node(id).cloned() else { continue };
let count = map_node_solid_paints(&mut node, f);
if count > 0
&& let Some(slot) = d.node_mut(id)
{
*slot = node;
n += count;
}
}
n
}
/// Link every paint whose color has a swatch to that swatch, as Add Used Colors does for global
/// swatches, recording each paint visited. Returns the count and the visits.
fn link(d: &mut Document, ids: &[NodeId], map: &mut Map) -> (usize, Vec<(Color, Option<String>)>) {
let names: HashMap<u32, String> = (0..COLORS).map(|i| (red_bits(&color(i)), format!("Swatch {i}"))).collect();
let mut visits = vec![];
let n = map(d, ids, &mut |c, s, _| {
visits.push((*c, s.clone()));
match names.get(&red_bits(c)) {
Some(name) if s.is_none() => {
*s = Some(name.clone());
true
}
_ => false,
}
});
(n, visits)
}
fn rect(d: &mut Document, i: usize) -> Arc<Node> {
let id = d.alloc_id();
let (x, y) = ((i % 100) as f64 * 12.0, (i / 100) as f64 * 12.0);
let r = shapes::rectangle(Rect::new(x, y, x + 10.0, y + 10.0));
let a = Appearance::basic(Paint::solid(color(i % COLORS)), Paint::solid(color((i + 7) % COLORS)), 1.0);
Arc::new(Node::path(id, r, a))
}
/// `n` rectangles in the first layer, all selected.
fn flat(n: usize) -> (Document, Vec<NodeId>) {
let mut d = Document::new(1600.0, 1200.0);
let l = d.layers[0].id;
let mut ids = vec![];
for i in 0..n {
let node = rect(&mut d, i);
ids.push(node.id);
d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(node)).unwrap();
}
(d, ids)
}
/// 1,000 groups in the first layer, each holding a group of 5 rectangles: the rectangles, and with
/// `groups` the two groups above each of them too, listed first.
fn nested(groups: bool) -> (Document, Vec<NodeId>) {
let mut d = Document::new(1600.0, 1200.0);
let l = d.layers[0].id;
let (mut outer_ids, mut leaves) = (vec![], vec![]);
for g in 0..1_000 {
let rects: Vec<Arc<Node>> = (0..5).map(|i| rect(&mut d, g * 5 + i)).collect();
leaves.extend(rects.iter().map(|r| r.id));
let inner = Node::group(d.alloc_id(), rects);
let outer = Node::group(d.alloc_id(), vec![Arc::new(inner.clone())]);
if groups {
outer_ids.extend([outer.id, inner.id]);
}
d.insert(Some(l), usize::MAX, outer).unwrap();
}
outer_ids.extend(leaves);
(d, outer_ids)
}
fn bench(name: &str, (doc, ids): (Document, Vec<NodeId>)) {
let mut shipped = doc.clone();
let want = link(&mut shipped, &ids, &mut |d, ids, f| d.map_solid_paints_in(ids, f));
for roots in [roots_by_search as Roots, roots_by_set] {
let mut d = doc.clone();
let got = link(&mut d, &ids, &mut |d, ids, f| map_in(d, ids, roots, f));
assert_eq!(got, want, "{name}: the same count and visits");
assert_eq!(d.layers, shipped.layers, "{name}: the same document");
}
let (mut old, mut new, mut real) = (vec![], vec![], vec![]);
let timed = |map: &mut Map| {
let mut docs = vec![doc.clone(); REPS];
measure(|| {
for d in &mut docs {
black_box(link(d, black_box(&ids), &mut *map));
}
}) / REPS as f64
};
for i in 0..iters() {
let run = |roots: Roots, out: &mut Vec<f64>| out.push(timed(&mut |d, ids, f| map_in(d, ids, roots, f)));
if i % 2 == 0 {
run(roots_by_search, &mut old);
run(roots_by_set, &mut new);
} else {
run(roots_by_set, &mut new);
run(roots_by_search, &mut old);
}
real.push(timed(&mut |d, ids, f| d.map_solid_paints_in(ids, f)));
}
let (old, new, real) = (median(old), median(new), median(real));
println!(" {name:<46} {:>7} {:>7} {old:>12.3} {new:>12.3} {real:>12.3} {:>8.1}x", ids.len(), want.0, old / new);
}
fn main() {
let unit = if thread_cpu_ns().is_some() { "CPU ms" } else { "wall ms" };
println!(
" {:<46} {:>7} {:>7} {:>12} {:>12} {:>12} {:>9}",
"document",
"ids",
"linked",
format!("search, {unit}"),
format!("set, {unit}"),
format!("shipped, {unit}"),
"speedup"
);
bench("2,000 rectangles in one layer", flat(2_000));
bench("20,000 rectangles in one layer", flat(20_000));
bench("5,000 rectangles in 1,000 groups of groups", nested(false));
bench("the same with the 2,000 groups listed first", nested(true));
}
@@ -0,0 +1,146 @@
//! `cargo run --release -p vectorcraft-engine --example stroke_targets_bench` prints the time `stroke.set`
//! takes to list its targets on documents of 2,000, 10,000 and 20,000 rectangles, all in one group. For
//! each size it times, on the same leaves, the merge that checks each leaf against the growing list and
//! the merge that checks it against a set, checks that the two lists are equal, and then times the whole
//! `stroke.set {weight: 3}` command twice: once with the group named and once with every rectangle named.
//! The whole-command rows include the document copy the command makes for undo; each run is undone
//! before the next, outside the timed part.
//! 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 merge rows repeats the merge 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::HashSet;
use std::hint::black_box;
use std::time::Instant;
use serde_json::{Value, json};
use vectorcraft_color::Color;
use vectorcraft_doc::{Document, NodeId};
use vectorcraft_engine::Session;
use vectorcraft_geom::Rect;
use vectorcraft_testkit::fixtures::DocBuilder;
fn iters() -> usize {
std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1)
}
/// 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 in one group, and the squares' ids in stacking order.
fn document(n: usize) -> (Document, NodeId, Vec<NodeId>) {
let mut b = DocBuilder::new(4000.0, 4000.0);
let kids: Vec<_> = (0..n)
.map(|i| {
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))
})
.collect();
let leaves = kids.iter().map(|k| k.id).collect();
let group = b.group(kids, false);
(b.build(), group, leaves)
}
/// The merge that checks each leaf against the growing list.
fn listed(mut out: Vec<NodeId>, leaves: Vec<NodeId>) -> Vec<NodeId> {
for id in leaves {
if !out.contains(&id) {
out.push(id);
}
}
out
}
/// The merge that checks each leaf against a set seeded with `out`.
fn with_set(mut out: Vec<NodeId>, leaves: Vec<NodeId>) -> Vec<NodeId> {
let mut seen: HashSet<NodeId> = out.iter().copied().collect();
for id in leaves {
if seen.insert(id) {
out.push(id);
}
}
out
}
fn row(name: &str, ms: f64) {
println!(" {name:<52} {ms:>10.3} ms");
}
/// The median time of `stroke.set {weight: 3}` on `ids`, each run undone outside the timed part.
fn whole_command(s: &mut Session, ids: &[NodeId], n: usize) -> f64 {
let p: Value = json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>(), "weight": 3});
let runs = (0..iters())
.map(|_| {
let mut r = Value::Null;
let t = ms(|| r = black_box(s.execute("stroke.set", &p).unwrap()));
assert_eq!(r["objects"], n, "{r}");
s.execute("edit.undo", &json!({})).unwrap();
t
})
.collect();
median(runs)
}
fn bench(n: usize) {
println!("{n} paths in one group");
let (doc, group, leaves) = document(n);
// Each run merges `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(Vec<NodeId>, Vec<NodeId>) -> Vec<NodeId>| -> (f64, Vec<NodeId>) {
let mut last = Vec::new();
let runs = (0..iters())
.map(|_| {
let mut work: Vec<Vec<NodeId>> = (0..reps).map(|_| leaves.clone()).collect();
let mut done = Vec::with_capacity(reps);
let t = ms(|| {
for input in &mut work {
done.push(f(Vec::new(), black_box(std::mem::take(input))));
}
});
last = done.pop().unwrap();
t / reps as f64
})
.collect();
(median(runs), last)
};
let (old, a) = time(listed);
let (new, b) = time(with_set);
assert_eq!(a, b, "both merges give the same list");
assert_eq!(a, leaves);
row("target merge, list search", old);
row("target merge, set", new);
println!(" {:<52} {:>10.1}x", "ratio", old / new);
let mut s = Session::new();
s.add_document(doc, None);
row("stroke.set, whole command, the group named", whole_command(&mut s, &[group], n));
row("stroke.set, whole command, every path named", whole_command(&mut s, &leaves, n));
}
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);
}
}
+26 -3
View File
@@ -74,6 +74,7 @@ pub mod perspgrid;
pub mod place;
pub mod plugin;
pub(crate) mod plugin_call;
mod preflight;
pub mod prefscmds;
pub mod print;
pub(crate) mod printadvanced;
@@ -98,7 +99,6 @@ pub(crate) mod symboledit;
pub mod symbollib;
pub(crate) mod tabs;
mod textedit;
mod xmlattrs;
pub use textedit::effective_kerning;
pub mod textstyles;
@@ -382,6 +382,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(package::specs());
v.extend(slices::specs());
v.extend(print::specs());
v.extend(preflight::specs());
v.extend(recovery::specs());
v.extend(fileio::dxfimport::specs());
v.extend(webexport::specs());
@@ -407,7 +408,18 @@ pub fn command_specs() -> &'static [CommandSpec] {
/// The command `id`: a built-in one, or a command an installed plug-in adds
/// ([`plugin::command_specs`]).
pub fn find_command(id: &str) -> Option<&'static CommandSpec> {
command_specs().iter().find(|c| c.id == id).or_else(|| plugin::find_spec(id))
static INDEX: std::sync::OnceLock<std::collections::HashMap<&'static str, &'static CommandSpec>> = std::sync::OnceLock::new();
INDEX.get_or_init(|| index_by_id(command_specs())).get(id).copied().or_else(|| plugin::find_spec(id))
}
/// `specs` by id. An id that more than one spec has names the first of them, as a search of
/// `specs` in order finds.
pub(crate) fn index_by_id(specs: &[CommandSpec]) -> std::collections::HashMap<&'static str, &CommandSpec> {
let mut index = std::collections::HashMap::with_capacity(specs.len());
for spec in specs {
index.entry(spec.id).or_insert(spec);
}
index
}
/// Runs command `spec`'s implementation with `p`. A plug-in command's runs the plug-in
@@ -821,12 +833,16 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap<
pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
pub(crate) use addons::{DecodedImages, refresh_color_masks};
/// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window.
pub use addons::{fold_source, print_hidden};
/// Document Info's category titles and the Objects category's count labels.
pub use docinfo::{CATEGORIES, OBJECT_LABELS};
pub use docmenu::guide_indexes;
pub(crate) use edit::{settle_interaction, typing_in_progress};
pub(crate) use edit::{Unrecorded, settle_interaction, typing_in_progress};
pub(crate) use object::bounds_rewrite;
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
/// The rules `object.scale`, `object.reflect` and `object.shear` check their params with.
pub use object::{reflect_axis, scale_factors, shear_tangent};
pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys};
pub use select::SIMILAR;
pub(crate) use vectorcraft_doc::range::parse_range;
@@ -886,6 +902,9 @@ pub(crate) use buildcmds::TracePresetChanges;
/// The shapes a group selected alone gives the Pathfinder panel.
pub use pathops::shape_count;
/// The Shape Mode commands' warning when a selected open path encloses no area.
pub use pathops::SHAPE_MODE_OPEN_PATH_NO_AREA;
/// The gaps View › Show Live Paint Gaps shows on a Live Paint group.
pub use buildcmds::live_paint_gaps;
@@ -901,6 +920,10 @@ pub use brushsym::current_symbol;
/// Data window reads files by it too).
pub use variablecmds::utf16_order_without_mark;
/// How the Graph Data window's Import Data and Import Data Sets' `%` columns read a graph data
/// file: its size limit, its text, its cells and the data `graph.setData` takes from them.
pub use graph::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text};
/// The Variables panel's sort (`variable.sort`) and its rows in that order.
pub use variablecmds::{VariableSort, VariableSortKey, variable_order};
+3
View File
@@ -14,8 +14,10 @@ mod pen;
mod select;
mod shapes;
mod typetools;
mod units;
pub(crate) use image::{DecodedImages, refresh_color_masks};
pub use packaging::{fold_source, print_hidden};
pub(crate) use packaging::{role_swatch_edited, role_swatches_merged};
use super::CommandSpec;
@@ -35,5 +37,6 @@ pub fn specs() -> Vec<CommandSpec> {
v.extend(select::specs());
v.extend(shapes::specs());
v.extend(typetools::specs());
v.extend(units::specs());
v
}
@@ -6,8 +6,10 @@
//! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's.
mod check;
mod fold;
mod roles;
pub use fold::{fold_source, print_hidden};
pub(crate) use roles::{role_swatch_edited, role_swatches_merged};
use super::super::CommandSpec;
@@ -15,6 +17,7 @@ use super::super::CommandSpec;
pub fn specs() -> Vec<CommandSpec> {
let mut v = roles::specs();
v.extend(check::specs());
v.extend(fold::specs());
v
}
+63 -22
View File
@@ -4,7 +4,7 @@
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_geom::PathData;
use vectorcraft_three_d::fold::{FoldLine, IssueCode, LineKind, MAX_SEGMENTS, blanks};
use vectorcraft_three_d::fold::{Blank, FoldLine, Issue, IssueCode, LineKind, MAX_SEGMENTS, blanks};
use super::super::super::pathops::length_given;
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or};
@@ -14,7 +14,7 @@ use crate::{Result, Session};
const CHECK: &str = "addon.packaging.check";
/// How far apart the ends of two lines may be and still be joined, in points.
const TOLERANCE: (f64, f64, f64) = (0.01, 0.1, 10.0);
pub(super) const TOLERANCE: (f64, f64, f64) = (0.01, 0.1, 10.0);
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
@@ -101,23 +101,44 @@ fn kind(role: Role) -> LineKind {
}
}
fn check(s: &mut Session, p: &Value) -> Result<Value> {
let select = switch_or(p, "select", false, CHECK)?;
let tolerance = match length_given(p, "tolerance", CHECK)? {
None => TOLERANCE.1,
Some(t) if (TOLERANCE.0..=TOLERANCE.2).contains(&t) => t,
Some(_) => return Err(bad(CHECK, format!("`tolerance` must be from {} to {} pt", TOLERANCE.0, TOLERANCE.2))),
};
/// The fold lines a check or a fold reads: where they came from (`ids`, `selection` or
/// `document`), the lines, and the ids of those on a non-printing layer.
pub(super) struct Lines {
pub scope: &'static str,
pub lines: Vec<FoldLine>,
pub non_printing: Vec<u64>,
}
/// The tolerance `p` gives for `cmd`, or the default.
pub(super) fn tolerance(p: &Value, cmd: &str) -> Result<f64> {
match length_given(p, "tolerance", cmd)? {
None => Ok(TOLERANCE.1),
Some(t) if (TOLERANCE.0..=TOLERANCE.2).contains(&t) => Ok(t),
Some(_) => Err(bad(cmd, format!("`tolerance` must be from {} to {} pt", TOLERANCE.0, TOLERANCE.2))),
}
}
/// The fold lines among the objects `p` names for `cmd` (`ids`, else the selection), or, while
/// nothing is selected and `ids` is left out, every shown fold line of the document. Hidden lines
/// are left out in every scope, members of a selected group included.
pub(super) fn lines(s: &Session, p: &Value, cmd: &str) -> Result<Lines> {
let given = p.get("ids").is_some_and(|v| !v.is_null());
let roots = checked_ids_or_selection(s, p, CHECK)?;
let roots = checked_ids_or_selection(s, p, cmd)?;
let d = &s.doc()?.doc;
// Hidden lines are left out in every scope, members of a selected group included.
let shown = |ids: Vec<NodeId>| ids.into_iter().filter(|id| d.is_visible(*id)).collect::<Vec<_>>();
let (scope, targets) = match (given, roots.is_empty()) {
(true, _) => ("ids", shown(role_targets(d, &roots, false).0)),
(false, false) => ("selection", shown(role_targets(d, &roots, false).0)),
(false, true) => ("document", shown_targets(d)),
};
Ok(match (given, roots.is_empty()) {
(true, _) => lines_of(d, "ids", shown(role_targets(d, &roots, false).0)),
(false, false) => lines_of(d, "selection", shown(role_targets(d, &roots, false).0)),
(false, true) => document_lines(d),
})
}
/// Every shown fold line of `d`.
pub(super) fn document_lines(d: &Document) -> Lines {
lines_of(d, "document", shown_targets(d))
}
fn lines_of(d: &Document, scope: &'static str, targets: Vec<NodeId>) -> Lines {
let table = RoleTable::of(d);
let mut lines = vec![];
let mut non_printing = vec![];
@@ -136,12 +157,21 @@ fn check(s: &mut Session, p: &Value) -> Result<Value> {
segments = segments.saturating_add(path.subpaths.iter().map(|sp| sp.segment_count()).sum());
lines.push(FoldLine { path, kind: kind(role), key: id.0 });
}
let (found, mut issues) = blanks(&lines, tolerance);
if !non_printing.is_empty() {
issues.push(vectorcraft_three_d::fold::Issue { code: IssueCode::NonPrinting, keys: non_printing, at: None });
Lines { scope, lines, non_printing }
}
/// The blanks `lines` make and their issues, the non-printing one last.
pub(super) fn found(lines: &Lines, tolerance: f64) -> (Vec<Blank>, Vec<Issue>) {
let (found, mut issues) = blanks(&lines.lines, tolerance);
if !lines.non_printing.is_empty() {
issues.push(Issue { code: IssueCode::NonPrinting, keys: lines.non_printing.clone(), at: None });
}
let ok = !issues.iter().any(|i| i.code.is_error());
let rows: Vec<Value> = issues
(found, issues)
}
/// `issues` as the rows `addon.packaging.check` and `addon.packaging.fold` answer with.
pub(super) fn issue_rows(issues: &[Issue], scope: &str) -> Vec<Value> {
issues
.iter()
.map(|i| {
let mut row = json!({
@@ -155,7 +185,18 @@ fn check(s: &mut Session, p: &Value) -> Result<Value> {
}
row
})
.collect();
.collect()
}
fn check(s: &mut Session, p: &Value) -> Result<Value> {
let select = switch_or(p, "select", false, CHECK)?;
let tolerance = tolerance(p, CHECK)?;
let lines = lines(s, p, CHECK)?;
let scope = lines.scope;
let (found, issues) = found(&lines, tolerance);
let d = &s.doc()?.doc;
let ok = !issues.iter().any(|i| i.code.is_error());
let rows = issue_rows(&issues, scope);
if select {
let mut ids: Vec<NodeId> = issues.iter().flat_map(|i| i.keys.iter().map(|k| NodeId(*k))).filter(|id| d.node(*id).is_some()).collect();
ids.sort_unstable_by_key(|id| id.0);
@@ -0,0 +1,110 @@
//! Fold Preview's model (`addon.packaging.fold`): a blank folded into its 3D shape by
//! [`vectorcraft_three_d::fold::fold`], and what the Fold Preview window needs to draw it: the
//! document's blanks ([`fold_source`]) and the objects its print leaves out ([`print_hidden`]).
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_three_d::fold::{Blank, Issue, fold, pick};
use super::super::super::{CommandSpec, bad, cmd, finite_numbers, has_doc, number_or};
use super::check::{TOLERANCE, document_lines, found, issue_rows, lines, tolerance};
use super::roles::{RoleTable, can_carry};
use crate::{Result, Session};
const FOLD: &str = "addon.packaging.fold";
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
query "addon.packaging.fold",
"Fold",
[],
None,
"{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: a Crease or a Perforation by 90° away from the printed side, a Partial Cut by 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true within tolerance or 0.5% of the hinge's length. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel",
has_doc,
fold_command
)]
}
/// The blanks the shown fold lines of `d` make, and their issues (`addon.packaging.check` on the
/// whole document): what the Fold Preview window folds.
pub fn fold_source(d: &Document) -> (Vec<Blank>, Vec<Issue>) {
found(&document_lines(d), TOLERANCE.1)
}
/// The objects the print on a folded blank leaves out: the layers that do not print and, unless
/// `fold_lines`, every object with a line role.
pub fn print_hidden(d: &Document, fold_lines: bool) -> Vec<NodeId> {
fn walk(n: &Node, table: &RoleTable, fold_lines: bool, out: &mut Vec<NodeId>) {
match &n.kind {
NodeKind::Layer { printable: false, .. } => out.push(n.id),
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, table, fold_lines, out)),
_ if !fold_lines && can_carry(n) && table.role_of(n).is_some() => out.push(n.id),
_ => {}
}
}
let table = RoleTable::of(d);
let mut out = vec![];
d.layers.iter().for_each(|l| walk(l, &table, fold_lines, &mut out));
out
}
fn fold_command(s: &mut Session, p: &Value) -> Result<Value> {
let tolerance = tolerance(p, FOLD)?;
let amount = number_or(p, "amount", 1.0, FOLD)?;
if !(0.0..=1.0).contains(&amount) {
return Err(bad(FOLD, "`amount` must be from 0 to 1"));
}
let base = match p.get("base") {
None | Some(Value::Null) => None,
Some(v) => {
let [x, y] = finite_numbers::<2>(v).ok_or_else(|| bad(FOLD, "`base` must be a point: [x, y]"))?;
Some(vectorcraft_geom::Point::new(x, y))
}
};
let lines = lines(s, p, FOLD)?;
let (blanks, issues) = found(&lines, tolerance);
let ok = !issues.iter().any(|i| i.code.is_error());
let picked = pick(&blanks, base);
if base.is_some() && picked.is_none() {
return Err(bad(FOLD, "`base` is in no panel"));
}
let folded = picked.and_then(|(b, panel)| Some((b, blanks.get(b)?, fold(blanks.get(b)?, Some(panel), amount, tolerance)?)));
let Some((index, blank, f)) = folded else {
return Ok(json!({
"ok": ok, "blank": null, "blanks": blanks.len(), "base": null, "panels": [], "hinges": [], "collisions": [],
"issues": issue_rows(&issues, lines.scope),
}));
};
let column = |m: &[[f64; 3]; 3], k: usize| json!([m[0][k], m[1][k], m[2][k]]);
let panels: Vec<Value> = blank
.panels
.iter()
.zip(&f.panels)
.map(|(panel, placed)| {
json!({
"outline": panel.outline.to_bezpath().to_svg(),
"frame": {"x": column(&placed.pose.m, 0), "y": column(&placed.pose.m, 1), "z": column(&placed.pose.m, 2), "origin": placed.pose.t},
"parent": placed.parent,
"depth": placed.depth,
})
})
.collect();
let hinges: Vec<Value> = f
.hinges
.iter()
.map(|h| json!({"a": h.a, "b": h.b, "angle": h.angle, "kind": if h.tree { "tree" } else { "closing" }, "closes": h.closes, "gap": h.gap}))
.collect();
Ok(json!({
"ok": ok,
"blank": index,
"blanks": blanks.len(),
"base": f.base,
"panels": panels,
"hinges": hinges,
"collisions": f.collisions.iter().map(|(a, b)| [a, b]).collect::<Vec<_>>(),
"issues": issue_rows(&issues, lines.scope),
}))
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,157 @@
//! Tests for the Fold Preview's model: a blank drawn in a document folded into its 3D shape.
use serde_json::{Value, json};
use crate::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
s
}
fn path(s: &mut Session, d: &str) -> u64 {
s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap()
}
fn role(s: &mut Session, role: &str, ids: &[u64]) {
s.execute("addon.packaging.setRole", &json!({ "role": role, "ids": ids })).unwrap();
}
fn fold(s: &mut Session, p: Value) -> Value {
s.execute("addon.packaging.fold", &p).unwrap()
}
/// A tray blank: a 100 pt base (x 140 to 240, y 140 to 240) with a 40 pt wall on each side →
/// (outline, creases).
fn tray(s: &mut Session) -> (u64, Vec<u64>) {
let outline = path(s, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z");
let creases = vec![path(s, "M140 140 L240 140"), path(s, "M240 140 L240 240"), path(s, "M240 240 L140 240"), path(s, "M140 240 L140 140")];
role(s, "cut", &[outline]);
role(s, "crease", &creases);
s.execute("select.none", &json!({})).unwrap();
(outline, creases)
}
fn vector(v: &Value) -> [f64; 3] {
let a = v.as_array().unwrap();
[a[0].as_f64().unwrap(), a[1].as_f64().unwrap(), a[2].as_f64().unwrap()]
}
/// The middle of the bounds of the points of SVG path data `d` (absolute moves and lines only).
fn middle(d: &str) -> [f64; 2] {
let n: Vec<f64> = d.split(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-')).filter_map(|t| t.parse().ok()).collect();
let span = |k: usize| n.iter().skip(k).step_by(2).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &t| (lo.min(t), hi.max(t)));
let ((x0, x1), (y0, y1)) = (span(0), span(1));
[(x0 + x1) / 2.0, (y0 + y1) / 2.0]
}
fn near(a: [f64; 3], b: [f64; 3]) -> bool {
a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9)
}
#[test]
fn a_tray_folds_its_walls_up_round_the_base() {
let mut s = session();
tray(&mut s);
let steps = s.doc().unwrap().history.undo.len();
let r = fold(&mut s, json!({}));
assert_eq!((r["ok"].as_bool(), r["blank"].as_u64(), r["blanks"].as_u64()), (Some(true), Some(0), Some(1)), "{r}");
let panels = r["panels"].as_array().unwrap();
assert_eq!(panels.len(), 5);
let base = r["base"].as_u64().unwrap() as usize;
let frame = &panels[base]["frame"];
assert!(
near(vector(&frame["x"]), [1.0, 0.0, 0.0]) && near(vector(&frame["z"]), [0.0, 0.0, 1.0]) && near(vector(&frame["origin"]), [0.0; 3]),
"{frame}"
);
assert!(panels[base]["parent"].is_null());
assert!(panels[base]["outline"].as_str().unwrap().starts_with('M'), "SVG path data");
for (i, p) in panels.iter().enumerate().filter(|(i, _)| *i != base) {
assert_eq!((p["parent"].as_u64(), p["depth"].as_u64()), (Some(base as u64), Some(1)), "{p}");
// Each wall stands square to the base, below it (away from the print), its print facing out:
// away from the base's middle (190, 190), toward the side the wall lies on.
let [cx, cy] = middle(p["outline"].as_str().unwrap());
let (x, y, o) = (vector(&p["frame"]["x"]), vector(&p["frame"]["y"]), vector(&p["frame"]["origin"]));
let placed: [f64; 3] = std::array::from_fn(|k| o[k] + x[k] * cx - y[k] * cy);
let (dx, dy) = (cx - 190.0, 190.0 - cy);
let out = if dx.abs() > dy.abs() { [dx.signum(), 0.0, 0.0] } else { [0.0, dy.signum(), 0.0] };
assert!(near(vector(&p["frame"]["z"]), out), "wall {i}: {p}");
assert!((placed[2] + 20.0).abs() < 1e-9, "wall {i}'s middle is 20 pt below the base: {placed:?}");
}
let hinges = r["hinges"].as_array().unwrap();
assert_eq!(hinges.len(), 4);
assert!(hinges.iter().all(|h| h["kind"] == "tree" && h["angle"] == 90.0 && h["closes"] == true), "{r}");
assert_eq!(r["collisions"], json!([]));
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "a fold records no undo step");
// Flat, every frame is the flat blank's own.
let r = fold(&mut s, json!({ "amount": 0 }));
for p in r["panels"].as_array().unwrap() {
assert!(near(vector(&p["frame"]["z"]), [0.0, 0.0, 1.0]) && near(vector(&p["frame"]["origin"]), [0.0; 3]), "{p}");
}
}
#[test]
fn the_base_is_the_panel_under_a_point() {
let mut s = session();
tray(&mut s);
// The left wall: x 100 to 140, y 140 to 240.
let r = fold(&mut s, json!({ "base": [120, 190] }));
let base = r["base"].as_u64().unwrap() as usize;
let panels = r["panels"].as_array().unwrap();
assert!(near(vector(&panels[base]["frame"]["z"]), [0.0, 0.0, 1.0]));
// The tray's base is now a child of the wall, and the other walls its children.
let depths: Vec<u64> = panels.iter().map(|p| p["depth"].as_u64().unwrap()).collect();
let mut sorted = depths.clone();
sorted.sort_unstable();
assert_eq!(sorted, [0, 1, 2, 2, 2], "{depths:?}");
let e = s.execute("addon.packaging.fold", &json!({ "base": [10, 10] })).unwrap_err().to_string();
assert!(e.contains("`base` is in no panel"), "{e}");
}
#[test]
fn bad_values_are_refused() {
let mut s = session();
tray(&mut s);
for (p, want) in [
(json!({ "amount": 1.5 }), "`amount` must be from 0 to 1"),
(json!({ "amount": -0.1 }), "`amount` must be from 0 to 1"),
(json!({ "amount": "1" }), "`amount` must be a number"),
(json!({ "base": [1] }), "`base` must be a point"),
(json!({ "base": "middle" }), "`base` must be a point"),
(json!({ "tolerance": 50 }), "`tolerance` must be from"),
] {
let e = s.execute("addon.packaging.fold", &p).unwrap_err().to_string();
assert!(e.contains(want), "{p}: {e}");
}
}
#[test]
fn without_a_blank_nothing_is_folded_and_the_issues_say_why() {
let mut s = session();
let r = fold(&mut s, json!({}));
assert_eq!((r["ok"].as_bool(), r["blank"].is_null(), r["blanks"].as_u64()), (Some(false), true, Some(0)), "{r}");
assert_eq!(r["panels"], json!([]));
assert_eq!(r["issues"][0]["code"], "noCut");
}
#[test]
fn the_print_leaves_out_fold_lines_and_layers_that_do_not_print() {
let mut s = session();
let (outline, creases) = tray(&mut s);
let art = path(&mut s, "M150 150 L200 150 L200 200 Z");
let notes = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("layer.setProps", &json!({"id": notes, "printable": false})).unwrap();
let d = &s.doc().unwrap().doc;
let hidden: Vec<u64> = cmd::print_hidden(d, false).into_iter().map(|id| id.0).collect();
for id in creases.iter().chain([&outline, &notes]) {
assert!(hidden.contains(id), "{id} in {hidden:?}");
}
assert!(!hidden.contains(&art));
let shown: Vec<u64> = cmd::print_hidden(d, true).into_iter().map(|id| id.0).collect();
assert_eq!(shown, vec![notes], "with the fold lines shown, only the layer is left out");
let (blanks, issues) = cmd::fold_source(d);
assert_eq!((blanks.len(), blanks[0].panels.len()), (1, 5));
assert!(issues.is_empty(), "{issues:?}");
}
+4 -1
View File
@@ -3,11 +3,13 @@
//! anchor edits, Split / Add Points at Crossings, Slide Anchor Along Path, the Corner Tool's corners
//! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), the Shared Edge Merge Tool's
//! merges with Keep Shared Points Together ([`shared_edge`]), Divide into Dashes, Expand Dashes
//! into Paths, Trim at Crossings ([`trim`]), Common Tangents ([`tangents`]) and Tangent Circle
//! into Paths, Trim at Crossings ([`trim`]), Smooth Bridge ([`bridge`]), Common Tangents
//! ([`tangents`]) and Tangent Circle
//! ([`tangent_circle`]).
//! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's
//! and the UI's.
mod bridge;
mod corners;
#[cfg(test)]
mod effect_tests;
@@ -183,6 +185,7 @@ pub fn specs() -> Vec<CommandSpec> {
v.extend(corners::specs());
v.extend(shared_edge::specs());
v.extend(trim::specs());
v.extend(bridge::specs());
v.extend(tangent_circle::specs());
v.extend(tangents::specs());
v
@@ -0,0 +1,95 @@
//! Smooth Bridge: two selected circles joined into one outline by two concave arcs that touch both
//! circles, replacing the circles or added above them.
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_geom::PathData;
use vectorcraft_pathops::addons::pathtools as pt;
use super::super::super::pathops::{Beside, remove_each};
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_selection, switch_or};
use super::given;
use crate::{EngineError, Result, Session};
#[cfg(test)]
mod tests;
/// The command, and its undo step's name.
const C: &str = "addon.pathtools.bridge";
const LABEL: &str = "Smooth Bridge";
/// The arcs' radius as a percentage of the smaller circle's radius: by default, and the range.
const RADIUS: f64 = 100.0;
const RADII: (f64, f64) = (1.0, 1000.0);
pub(super) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.pathtools.bridge",
"Smooth Bridge",
["Object", "Plug-ins", "Path Precision Tools"],
None,
"{radius?: % 1..1000 (100; the radius of the bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), keepOriginals?: bool (false: the outline replaces the two circles, painted as the upper one; true: it goes directly above the upper one and the circles stay), ids?: [id, id] (default: the selection)} join two circles (paths whose outline is a circle, not hidden or locked) into one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. Overlapping and touching circles are joined too; one circle inside the other, or circles too far apart for the radius (the arcs would not reach both, or would cross), is an error, which suggests a larger radius when one up to 1000% would bridge them. One undo step; the outline is selected → {id}",
has_selection,
bridge
)]
}
fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
let percent = given(p, "radius", Some(RADII), C)?.unwrap_or(RADIUS);
let keep = switch_or(p, "keepOriginals", false, C)?;
let roots = checked_ids_or_selection(s, p, C)?;
let circles: Vec<(NodeId, pt::Circle)> = {
let d = &s.doc()?.doc;
let editable = d.editable();
d.paint_order(roots.iter().copied())
.into_iter()
.filter_map(|id| match &d.node(id)?.kind {
NodeKind::Path { path, guide: false, clipping: false, .. } if editable(id) => Some((id, pt::circle_of(path)?)),
_ => None,
})
.collect()
};
let ([(below, a), (above, b)], 2) = (circles.as_slice(), roots.len()) else {
return Err(bad(C, "select two circles to bridge"));
};
let (below, above) = (*below, *above);
let at = |percent: f64| pt::smooth_bridge(*a, *b, a.radius.min(b.radius) * percent / 100.0);
let outline = match at(percent) {
Ok(sp) => PathData::single(sp),
Err(pt::BridgeError::Inside) => return Err(bad(C, "one circle is inside the other")),
// A larger radius bridges circles a smaller one cannot, so only suggest one that is allowed.
Err(pt::BridgeError::TooFar) if at(RADII.1).is_ok() => {
return Err(bad(C, "the circles are too far apart for this radius: raise the radius"));
}
Err(pt::BridgeError::TooFar) => return Err(bad(C, "the circles are too far apart for this radius")),
Err(pt::BridgeError::Bad) => return Err(bad(C, "select two circles to bridge")),
};
let id = s.edit(LABEL, |d, sel| {
let id = if keep {
// A copy of the upper circle (its appearance) with the outline as its path, right above
// it; the circles stay as they are, live shapes included.
// Fresh ids throughout, its opacity mask's art included.
let upper = d.node(above).cloned().ok_or(EngineError::NoNode(above))?;
let mut n = d.reid(&upper);
if let NodeKind::Path { path, live, .. } = &mut n.kind {
*path = outline;
*live = None;
}
let id = n.id;
let mut beside = Beside::above(d, &[above]);
beside.put(d, above, vec![n])?;
beside.finish(d)?;
id
} else {
// The upper circle becomes the outline (a plain path now) and the lower one goes.
if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(above).map(|n| &mut n.kind) {
*path = outline;
*live = None;
}
remove_each(d, &[below])?;
above
};
sel.set([id]);
Ok(id)
})?;
Ok(json!({ "id": id.0 }))
}
@@ -0,0 +1,184 @@
//! Smooth Bridge: the outline in place of the circles or above them, one undo step, the radius,
//! and what it refuses.
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_geom::kurbo::Shape;
use crate::Session;
const BRIDGE: &str = "addon.pathtools.bridge";
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s
}
/// A circle about (`x`, `y`) with radius `r`.
fn circle(s: &mut Session, x: f64, y: f64, r: f64) -> NodeId {
let id = s.execute("shape.ellipse", &json!({"x": x - r, "y": y - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap();
NodeId(id)
}
fn select(s: &mut Session, ids: &[NodeId]) {
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
}
fn top_level(s: &Session) -> Vec<NodeId> {
s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect()
}
fn area(s: &Session, id: NodeId) -> f64 {
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().to_bezpath().area().abs()
}
fn err(s: &mut Session, p: Value) -> String {
s.execute(BRIDGE, &p).unwrap_err().to_string()
}
#[test]
fn two_circles_become_one_outline_in_the_upper_ones_place() {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 20.0);
let b = circle(&mut s, 160.0, 100.0, 20.0);
select(&mut s, &[a, b]);
let steps = s.doc().unwrap().history.undo.len();
let r = s.execute(BRIDGE, &json!({})).unwrap();
assert_eq!(r["id"], json!(b.0));
assert_eq!(top_level(&s), [b]);
let d = &s.doc().unwrap().doc;
let NodeKind::Path { path, live, .. } = &d.node(b).unwrap().kind else { panic!("a path") };
assert!(live.is_none(), "a plain path now");
assert!(path.subpaths.len() == 1 && path.subpaths[0].closed);
let bounds = path.bounds().unwrap();
assert!((bounds.x0 - 80.0).abs() < 1e-2 && (bounds.x1 - 180.0).abs() < 1e-2 && (bounds.height() - 40.0).abs() < 1e-2, "{bounds:?}");
// Both circles and the bridge between them: more than the two circles' area.
assert!(area(&s, b) > 2.0 * std::f64::consts::PI * 400.0);
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [b]);
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(top_level(&s), [a, b]);
assert!(matches!(&s.doc().unwrap().doc.node(b).unwrap().kind, NodeKind::Path { live: Some(_), .. }), "the circle is back as it was");
}
#[test]
fn keep_originals_adds_the_outline_above_the_upper_circle() {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 30.0);
let b = circle(&mut s, 170.0, 100.0, 10.0);
let c = circle(&mut s, 300.0, 250.0, 5.0);
s.execute("paint.setFill", &json!({"ids": [b.0], "color": "#00ff00"})).unwrap();
let steps = s.doc().unwrap().history.undo.len();
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [b.0, a.0], "keepOriginals": true, "radius": 400})).unwrap()["id"].as_u64().unwrap());
assert_eq!(top_level(&s), [a, b, id, c]);
let d = &s.doc().unwrap().doc;
assert_eq!(d.node(id).unwrap().appearance, d.node(b).unwrap().appearance, "painted as the upper circle");
assert!(matches!(&d.node(a).unwrap().kind, NodeKind::Path { live: Some(_), .. }), "the circles stay as they are");
assert!(matches!(&d.node(b).unwrap().kind, NodeKind::Path { live: Some(_), .. }));
let bounds = d.node(id).unwrap().path_data().unwrap().bounds().unwrap();
assert!((bounds.x0 - 70.0).abs() < 1e-2 && (bounds.x1 - 180.0).abs() < 1e-2 && (bounds.y0 - 70.0).abs() < 1e-2, "{bounds:?}");
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [id]);
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
}
#[test]
fn a_kept_outline_gets_its_own_mask_art() {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 20.0);
let b = circle(&mut s, 150.0, 100.0, 20.0);
let m = NodeId(s.execute("shape.rectangle", &json!({"x": 130, "y": 80, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap());
s.execute("transparency.makeOpacityMask", &json!({"ids": [b.0, m.0]})).unwrap();
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "keepOriginals": true})).unwrap()["id"].as_u64().unwrap());
let d = &s.doc().unwrap().doc;
let art = |n: NodeId| d.node(n).unwrap().extras().mask.as_deref().map(|m| m.art.id);
let (kept, copied) = (art(b).unwrap(), art(id).unwrap());
assert_ne!(kept, copied, "the outline's mask art has ids of its own");
}
#[test]
fn a_larger_radius_makes_a_wider_bridge() {
let area_at = |radius: f64| {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 20.0);
let b = circle(&mut s, 150.0, 100.0, 15.0);
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": radius})).unwrap()["id"].as_u64().unwrap());
area(&s, id)
};
let (default, wider, widest) = (area_at(100.0), area_at(200.0), area_at(400.0));
assert!(default < wider && wider < widest, "{default} {wider} {widest}");
let (narrow, default, wide) = (area_at(65.0), default, area_at(300.0));
assert!(narrow < default && default < wide, "{narrow} {default} {wide}");
// The default is 100%: the smaller circle's radius.
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 20.0);
let b = circle(&mut s, 150.0, 100.0, 15.0);
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap());
assert!((area(&s, id) - default).abs() < 1e-9);
}
#[test]
fn overlapping_and_touching_circles_are_joined() {
for (gap, radius) in [(-15.0, 50.0), (0.0, 50.0), (0.0, 1.0)] {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 20.0);
let b = circle(&mut s, 140.0 + gap, 100.0, 20.0);
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": radius})).unwrap()["id"].as_u64().unwrap());
assert_eq!(top_level(&s), [id], "gap {gap}");
}
// Unequal overlapping circles at every radius, the largest included.
for radius in [1.0, 100.0, 300.0, 1000.0] {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 10.0);
let b = circle(&mut s, 125.0, 100.0, 30.0);
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": radius})).unwrap()["id"].as_u64().unwrap());
assert_eq!(top_level(&s), [id], "radius {radius}");
}
}
#[test]
fn far_apart_nested_and_other_objects_are_refused() {
let mut s = session();
let a = circle(&mut s, 50.0, 100.0, 10.0);
let far = circle(&mut s, 250.0, 100.0, 10.0);
let near = circle(&mut s, 110.0, 100.0, 10.0);
let inner = circle(&mut s, 52.0, 100.0, 4.0);
let square = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap());
let oval = NodeId(s.execute("shape.ellipse", &json!({"x": 300, "y": 0, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap());
let before = top_level(&s);
let steps = s.doc().unwrap().history.undo.len();
// 60 pt apart: the default radius (10 pt) cannot reach, the largest (100 pt) can.
assert!(err(&mut s, json!({"ids": [a.0, near.0]})).ends_with("too far apart for this radius: raise the radius"));
assert!(s.execute(BRIDGE, &json!({"ids": [a.0, near.0], "radius": 1000})).is_ok());
s.execute("edit.undo", &json!({})).unwrap();
// 200 pt apart even the largest radius (1000%, 100 pt) closes the neck: it stays open only above
// ((200 / 2)² − 10²) / (2 × 10) = 495 pt. No larger radius is suggested.
for radius in [100, 1000] {
let e = err(&mut s, json!({"ids": [a.0, far.0], "radius": radius}));
assert!(e.ends_with("the circles are too far apart for this radius"), "{e}");
}
assert!(err(&mut s, json!({"ids": [a.0, inner.0]})).contains("one circle is inside the other"));
for ids in [json!([a.0, square.0]), json!([a.0, oval.0]), json!([a.0]), json!([a.0, far.0, inner.0])] {
assert!(err(&mut s, json!({ "ids": ids })).contains("select two circles to bridge"), "{ids}");
}
assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": 0.5})).contains("`radius` must be from 1 to 1000"));
assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": 1001})).contains("`radius`"));
assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": "big"})).contains("`radius` must be a number"));
assert!(err(&mut s, json!({"ids": [a.0, far.0], "keepOriginals": "yes"})).contains("`keepOriginals` must be true or false"));
assert_eq!(top_level(&s), before);
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "nothing changed, no undo step");
}
#[test]
fn locked_and_hidden_circles_are_not_bridged() {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 20.0);
let b = circle(&mut s, 150.0, 100.0, 20.0);
select(&mut s, &[b]);
s.execute("object.lock", &json!({})).unwrap();
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two circles to bridge"));
s.execute("object.unlockAll", &json!({})).unwrap();
select(&mut s, &[a]);
s.execute("object.hide", &json!({})).unwrap();
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two circles to bridge"));
}
@@ -1,7 +1,8 @@
//! Common Tangents (`addon.pathtools.commonTangents`): the straight lines that touch two selected
//! convex closed paths (ellipses at any rotation and scale, and convex Bézier paths) without
//! crossing into either, added as separate open paths, with the line joining their centers if
//! asked. The geometry is `vectorcraft_pathops::addons::pathtools::common_tangents`.
//! asked. One of the two may be a point (a path of one anchor) instead: the lines then run from it
//! to where they touch the path. The geometry is `vectorcraft_pathops::addons::pathtools::common_tangents`.
#[cfg(test)]
mod tests;
@@ -30,19 +31,24 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Common Tangents",
["Object", "Plug-ins", "Path Precision Tools"],
None,
"{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is less than a billionth of the larger of their sizes and the distance between their centers. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}",
"{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is less than a billionth of the larger of their sizes and the distance between their centers. One of the two may be a point (a path of one anchor): the lines then run from the point to where they touch the path, two when the point lies outside it (one that lies along a straight side covers the whole side), one when the point lies on its outline, that is, less than the touching tolerance from it, with the point's distance from the path's center in place of the distance between centers (centered on the point and as long as the path is wide along it, or the whole straight side the point lies on), none when it lies inside; every `tangents` value gives the same lines, counted as internal when `tangents` is \"internal\" and as external otherwise, and the centerline runs from the point to the path's center; two points are refused. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}",
has_selection,
common_tangents
)]
}
/// The outline of path `id` as the geometry takes it: an exact ellipse for a whole live ellipse,
/// else the path's one closed convex subpath.
/// The outline of path `id` as the geometry takes it: a point for a path of one anchor, an exact
/// ellipse for a whole live ellipse, else the path's one closed convex subpath.
fn outline_of(d: &Document, id: NodeId) -> Result<pt::Outline> {
const C: &str = COMMON_TANGENTS;
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
let NodeKind::Path { path, live, .. } = &n.kind else { return Err(bad(C, "select two closed paths")) };
let [sp] = path.subpaths.as_slice() else { return Err(bad(C, "select two closed paths")) };
if sp.anchors.len() == 1
&& let Some(only) = sp.anchors.first()
{
return pt::Outline::point(only.p).map_err(refusal);
}
if let Some(LiveShape::Ellipse { w, h, pie, xf }) = live.as_deref() {
let span = (pie.1 - pie.0).rem_euclid(360.0);
if span < 1e-9 || 360.0 - span < 1e-9 {
@@ -74,17 +80,36 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result<Value> {
let ordered = d.paint_order(roots.iter().copied());
let [first, second] = ordered.as_slice() else { return Err(bad(C, "select two closed paths")) };
let (a, b) = (outline_of(d, *first)?, outline_of(d, *second)?);
if a.is_point() && b.is_point() {
return Err(bad(C, "select two closed paths"));
}
// A point goes first, so that each line runs from it to where it touches the path.
let point = a.is_point() || b.is_point();
let (a, b) = if b.is_point() { (b, a) } else { (a, b) };
let all = pt::common_tangents(&a, &b).map_err(|_| bad(C, "the two paths have the same outline"))?;
let external = all.iter().filter(|t| t.kind == pt::TangentKind::External).count();
let keep = |t: &&pt::Tangent| match kinds {
"external" => t.kind == pt::TangentKind::External,
"internal" => t.kind == pt::TangentKind::Internal,
_ => true,
// A point's external and internal tangents are the same lines: every kind keeps them.
let keep = |t: &&pt::Tangent| {
point
|| match kinds {
"external" => t.kind == pt::TangentKind::External,
"internal" => t.kind == pt::TangentKind::Internal,
_ => true,
}
};
let kept: Vec<&pt::Tangent> = all.iter().filter(keep).collect();
let count = |kind: pt::TangentKind| kept.iter().filter(|t| t.kind == kind).count();
let (external_kept, internal_kept) = (count(pt::TangentKind::External), count(pt::TangentKind::Internal));
let (external_kept, internal_kept) = match (point, kinds) {
(true, "internal") => (0, kept.len()),
(true, _) => (kept.len(), 0),
_ => (count(pt::TangentKind::External), count(pt::TangentKind::Internal)),
};
let lines: Vec<(Point, Point)> = kept.iter().map(|t| (t.from, t.to)).collect();
if lines.is_empty() && point {
// Written as `EngineError::Other` so that the i18n message scan finds it.
let warning = EngineError::Other("The point lies inside the path, so it has no tangents".into());
return Ok(json!({ "ids": [], "external": 0, "internal": 0, "centerline": null, "warning": warning.to_string() }));
}
if lines.is_empty() {
// Written as `EngineError::Other` so that the i18n message scan finds them. Exactly one
// external tangent means one path lies inside the other and touches it there; paths that
@@ -248,6 +248,84 @@ fn nested_and_overlapping_paths_change_nothing_and_say_why() {
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(1), Some(0)), "{r}");
}
fn point(s: &mut Session, x: f64, y: f64) -> NodeId {
id_of(&s.execute("path.create", &json!({"anchors": [{"x": x, "y": y}]})).unwrap())
}
#[test]
fn a_point_and_an_ellipse_get_the_two_lines_from_the_point_and_the_centerline() {
let mut s = session();
// The point is drawn after the oval, so it is the upper object; the lines still start at it.
let oval = id_of(&s.execute("shape.ellipse", &json!({"x": 260, "y": 170, "width": 80, "height": 60})).unwrap());
let dot = point(&mut s, 100.0, 200.0);
select(&mut s, &[oval, dot]);
let before = steps(&s);
let r = s.execute(C, &json!({"centerline": true})).unwrap();
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}");
assert_eq!(steps(&s), before + 1);
let found = lines(&s, &r);
assert_eq!(found.len(), 3, "two tangents and the centerline");
let (p, c) = (Point::new(100.0, 200.0), Point::new(300.0, 200.0));
// From (-200, 0) to an ellipse with semi-axes 40 and 30 about the origin: the touching points
// are x = -a²/200 = -8, y = ±b √(1 - x²/a²).
let y = 30.0 * (1.0f64 - (8.0f64 / 40.0).powi(2)).sqrt();
for sy in [1.0, -1.0] {
let touch = c + Vec2::new(-8.0, sy * y);
assert!(found[..2].iter().any(|(a, b)| near(*a, p) && near(*b, touch)), "{touch:?} in {found:?}");
}
assert_eq!(r["centerline"], r["ids"][2]);
assert!(near(found[2].0, p) && near(found[2].1, c), "{:?}", found[2]);
// Every `tangents` value gives the same two lines.
for (kind, external, internal) in [("external", 2, 0), ("internal", 0, 2)] {
let r = s.execute(C, &json!({"ids": [oval.0, dot.0], "tangents": kind})).unwrap();
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(external), Some(internal)), "{kind}: {r}");
assert_eq!(lines(&s, &r).len(), 2, "{kind}");
}
}
#[test]
fn a_point_below_the_path_still_starts_the_lines() {
let mut s = session();
// The point is drawn first, so it is the lower object and needs no swap.
let dot = point(&mut s, 100.0, 200.0);
let round = circle(&mut s, 300.0, 200.0, 50.0);
let r = s.execute(C, &json!({"ids": [round.0, dot.0], "centerline": true})).unwrap();
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}");
let found = lines(&s, &r);
assert_eq!(found.len(), 3, "two tangents and the centerline");
let p = Point::new(100.0, 200.0);
assert!(found.iter().all(|(a, _)| near(*a, p)), "every line starts at the point: {found:?}");
// From 200 away to a circle of radius 50, each tangent is √(200² - 50²) long.
let length = (200.0f64 * 200.0 - 50.0 * 50.0).sqrt();
assert!(found[..2].iter().all(|(a, b)| (a.distance(*b) - length).abs() < 1e-6), "{found:?}");
assert!(near(found[2].1, Point::new(300.0, 200.0)), "{:?}", found[2]);
}
#[test]
fn a_point_on_or_inside_a_path_and_two_points() {
let mut s = session();
let round = circle(&mut s, 200.0, 200.0, 50.0);
// On the circle: one line, centered on the point and as long as the circle is wide.
let on = point(&mut s, 250.0, 200.0);
let r = s.execute(C, &json!({"ids": [round.0, on.0]})).unwrap();
assert_eq!(r["external"].as_u64(), Some(1), "{r}");
let (p, q) = lines(&s, &r)[0];
assert!((p.x - 250.0).abs() < 1e-5 && (q.x - 250.0).abs() < 1e-5 && (p.distance(q) - 100.0).abs() < 1e-5, "{p:?} {q:?}");
// Inside: nothing changes, and the warning says why.
let inside = point(&mut s, 210.0, 190.0);
let before = (steps(&s), s.doc().unwrap().doc.node_count());
let r = s.execute(C, &json!({"ids": [round.0, inside.0], "centerline": true})).unwrap();
assert_eq!(r["ids"], json!([]));
assert!(r["warning"].as_str().unwrap().contains("point lies inside the path"), "{r}");
assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes");
// Two points, or a point and an open path, are refused.
let err = |s: &mut Session, p: Value| s.execute(C, &p).unwrap_err().to_string();
assert!(err(&mut s, json!({"ids": [on.0, inside.0]})).contains("select two closed paths"));
let open = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 50, "y": 0}, {"x": 50, "y": 50}]})).unwrap());
assert!(err(&mut s, json!({"ids": [open.0, on.0]})).contains("open"));
assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), (before.0 + 1, before.1 + 1), "only the open path was added");
}
#[test]
fn bad_selections_and_params_are_refused() {
let mut s = session();
+124
View File
@@ -0,0 +1,124 @@
//! Unit Converter (`addon.units.*`), a built-in add-on that shows one length in every unit at once.
//! `addon.units.convert` reads a length as a number field reads it ([`Unit::parse`]: units and
//! arithmetic) and gives it in each unit of Preferences › Units › East Asian Type
//! ([`Unit::EAST_ASIAN`]), written as the fields write it ([`Unit::number`], [`Unit::format`]).
//! `addon.units.selectionSize` gives the selection's width and height, measured as the Transform
//! panel measures them, in the same units. Its panel and its place in Object › Plug-ins are the
//! UI's; the panel applies a length to the selection with `object.setBounds`.
#[cfg(test)]
mod tests;
use serde_json::{Value, json};
use vectorcraft_doc::{OrientedBox, Unit, decimal_point, finite_in_every_unit};
use vectorcraft_render::effects;
use super::super::{CommandSpec, always, bad, cmd, has_selection};
use crate::{Result, Session};
const CONVERT: &str = "addon.units.convert";
const SELECTION_SIZE: &str = "addon.units.selectionSize";
/// The most characters of a refused value an error message shows.
const SHOWN_CHARS: usize = 64;
/// The longest `value` or `unit` text `addon.units.convert` reads, in bytes.
const MAX_TEXT_LEN: usize = 1024;
/// The most `+ - * /` signs `addon.units.convert` reads in one `value`: [`Unit::parse`] takes one
/// level of recursion per sign.
const MAX_OPERATORS: usize = 128;
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
query "addon.units.convert",
"Convert Units",
[],
None,
"{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}",
always,
convert
),
cmd!(
query "addon.units.selectionSize",
"Selection Size in Units",
[],
None,
"{} the selection's width and height as the Transform panel shows them (its bounding box, rotated with rotated objects; with Use Preview Bounds, the visual bounds; with anchor points selected (Direct Selection), the box around those points), each as addon.units.convert gives it → {width: {points, units}, height: {points, units}}",
has_selection,
selection_size
),
]
}
/// The length `pt` (points) in every unit of [`Unit::EAST_ASIAN`]: `{points, units: [{unit,
/// label, number, text}]}`.
pub fn in_every_unit(pt: f64) -> Value {
let units: Vec<Value> =
Unit::EAST_ASIAN.iter().map(|u| json!({"unit": u.key(), "label": u.label(), "number": u.number(pt), "text": u.format(pt)})).collect();
json!({ "points": pt, "units": units })
}
/// The unit `p` gives for a number without a suffix (points when left out; null is an error).
fn unit_param(p: &Value) -> Result<Unit> {
let Some(given) = p.get("unit") else { return Ok(Unit::Points) };
let named = given.as_str().filter(|name| name.len() <= MAX_TEXT_LEN).and_then(Unit::named_east_asian);
named.ok_or_else(|| {
let u = match given {
Value::String(s) => clipped(s).escape_debug().to_string(),
other => shown(other),
};
bad(CONVERT, format!("unknown units `{u}`"))
})
}
fn convert(_: &mut Session, p: &Value) -> Result<Value> {
let unit = unit_param(p)?;
let Some(v) = p.get("value").filter(|v| !v.is_null()) else {
return Err(bad(CONVERT, "missing `value`"));
};
let pt = match v {
Value::String(s) if readable(s) => unit.parse(&decimal_point(s)),
Value::Number(n) => n.as_f64().map(|n| unit.to_pt(n)),
_ => None,
};
let pt = pt.filter(|&pt| finite_in_every_unit(pt));
pt.map(in_every_unit).ok_or_else(|| {
let v = shown(v);
bad(CONVERT, format!("`value` must be a number, not {v}"))
})
}
/// Is `s` short enough to read: at most [`MAX_TEXT_LEN`] bytes and [`MAX_OPERATORS`] `+ - * /`
/// signs?
fn readable(s: &str) -> bool {
s.len() <= MAX_TEXT_LEN && s.chars().filter(|c| matches!(c, '+' | '-' | '*' | '/')).count() <= MAX_OPERATORS
}
/// `v` as an error message shows it: text cut at [`SHOWN_CHARS`] characters with "…", as JSON,
/// an array as `[…]` and an object as `{…}`.
fn shown(v: &Value) -> String {
match v {
Value::String(s) => Value::String(clipped(s)).to_string(),
Value::Array(_) => "[…]".into(),
Value::Object(_) => "{…}".into(),
other => other.to_string(),
}
}
/// `s` cut at [`SHOWN_CHARS`] characters, with "…" when it is longer.
fn clipped(s: &str) -> String {
match s.char_indices().nth(SHOWN_CHARS) {
Some((at, _)) => format!("{}…", s.get(..at).unwrap_or_default()),
None => s.to_string(),
}
}
fn selection_size(s: &mut Session, _: &Value) -> Result<Value> {
let st = s.doc()?;
let measure = s.bounds_measure();
let b = match effects::preview::anchor_bounds_with(&st.selection, &st.doc, measure) {
Some(r) => Some(OrientedBox::aligned(r)),
None => s.transform_box(&st.selection.objects),
};
let b = b.ok_or_else(|| bad(SELECTION_SIZE, "nothing selected"))?;
Ok(json!({ "width": in_every_unit(b.rect.width()), "height": in_every_unit(b.rect.height()) }))
}
+209
View File
@@ -0,0 +1,209 @@
//! Unit Converter's commands: a length in every unit, read as number fields read it, the selection's
//! size as the Transform panel measures it, bad params refused, and nothing in the document changed.
use serde_json::{Value, json};
use vectorcraft_doc::Unit;
use crate::{EngineError, Session};
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s
}
fn convert(s: &mut Session, p: Value) -> Value {
s.execute("addon.units.convert", &p).unwrap()
}
/// The row of `r` for the unit with key `key`.
fn row<'a>(r: &'a Value, key: &str) -> &'a Value {
r["units"].as_array().unwrap().iter().find(|u| u["unit"] == key).unwrap_or_else(|| panic!("{key} in {r}"))
}
fn near(a: f64, b: f64) -> bool {
(a - b).abs() < 1e-9
}
#[test]
fn a_length_comes_back_in_every_unit_in_order() {
let mut s = session();
let r = convert(&mut s, json!({"value": "10mm"}));
assert!(near(r["points"].as_f64().unwrap(), 720.0 / 25.4));
let keys: Vec<&str> = r["units"].as_array().unwrap().iter().map(|u| u["unit"].as_str().unwrap()).collect();
assert_eq!(keys, Unit::EAST_ASIAN.map(Unit::key));
assert_eq!(row(&r, "millimeters")["number"], "10");
assert_eq!(row(&r, "millimeters")["text"], "10 mm");
assert_eq!(row(&r, "centimeters")["text"], "1 cm");
assert_eq!(row(&r, "inches")["text"], "0.3937 in");
assert_eq!(row(&r, "points")["text"], "28.346 pt");
assert_eq!(row(&r, "q")["text"], "40 Q");
assert_eq!(row(&r, "ha")["text"], "40 H");
assert_eq!(row(&r, "pixels")["number"], row(&r, "points")["number"], "pixels are points");
assert_eq!(row(&r, "feetInches")["label"], "Feet & Inches");
// Each row is what a field of that unit shows for the length.
for u in Unit::EAST_ASIAN {
let pt = 720.0 / 25.4;
assert_eq!(row(&r, u.key())["text"], u.format(pt), "{u:?}");
assert_eq!(row(&r, u.key())["number"], u.number(pt), "{u:?}");
}
}
#[test]
fn values_read_as_number_fields_read_them() {
let mut s = session();
let pt = |s: &mut Session, p: Value| convert(s, p)["points"].as_f64().unwrap();
assert!(near(pt(&mut s, json!({"value": "1in/2"})), 36.0));
assert!(near(pt(&mut s, json!({"value": "2p6"})), 30.0));
assert!(near(pt(&mut s, json!({"value": "1080/2 px"})), 540.0));
assert!(near(pt(&mut s, json!({"value": "3cm*50%"})), 1.5 * 72.0 / 2.54));
assert!(near(pt(&mut s, json!({"value": "13q"})), 13.0 * 72.0 / 101.6));
// A number without a unit is in `unit`, points by default.
assert!(near(pt(&mut s, json!({"value": 12})), 12.0));
assert!(near(pt(&mut s, json!({"value": 2, "unit": "in"})), 144.0));
assert!(near(pt(&mut s, json!({"value": "2", "unit": "Inches"})), 144.0));
assert!(near(pt(&mut s, json!({"value": "3+1", "unit": "cm"})), 4.0 * 72.0 / 2.54));
assert!(near(pt(&mut s, json!({"value": 6, "unit": "ha"})), 6.0 * 72.0 / 101.6));
assert!(near(pt(&mut s, json!({"value": 1, "unit": "feetInches"})), 864.0));
// A suffix wins over `unit`.
assert!(near(pt(&mut s, json!({"value": "1in", "unit": "mm"})), 72.0));
// A decimal comma reads as a point, as in the number fields.
assert!(near(pt(&mut s, json!({"value": "0,5 in"})), 36.0));
assert!(near(pt(&mut s, json!({"value": "1,5", "unit": "in"})), 108.0));
// Each number of a sum reads its own separator.
assert!(near(pt(&mut s, json!({"value": "100.5 mm-0,5", "unit": "mm"})), 100.0 * 72.0 / 25.4));
// A comma in a sum is a decimal comma, as in the number fields: 1,500+2 is 3.5.
assert!(near(pt(&mut s, json!({"value": "1,500+2", "unit": "mm"})), 3.5 * 72.0 / 25.4));
// A sum of 128 signs still reads.
assert!(near(pt(&mut s, json!({"value": format!("1{}", "+1".repeat(128))})), 129.0));
}
#[test]
fn keys_the_commands_do_not_take_are_refused() {
let s = session();
s.check_params("addon.units.convert", &json!({"value": 1, "unit": "mm"})).unwrap();
s.check_params("addon.units.selectionSize", &json!({})).unwrap();
for (id, p) in [
("addon.units.convert", json!({"value": 1, "units": "mm"})),
("addon.units.convert", json!({"value": 1, "ids": [1]})),
("addon.units.selectionSize", json!({"ids": [1]})),
("addon.units.selectionSize", json!({"value": 1})),
] {
match s.check_params(id, &p) {
Err(EngineError::BadParams { cmd, .. }) => assert_eq!(cmd, id, "{p}"),
other => panic!("{id} {p}: expected BadParams, got {other:?}"),
}
}
}
#[test]
fn the_selection_size_follows_preview_bounds_and_selected_anchors() {
let mut s = session();
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 72, "height": 36})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [id], "color": "#000000"})).unwrap();
s.execute("stroke.set", &json!({"ids": [id], "weight": 10})).unwrap();
let wh = |s: &mut Session| {
let r = s.execute("addon.units.selectionSize", &json!({})).unwrap();
(r["width"]["points"].as_f64().unwrap(), r["height"]["points"].as_f64().unwrap())
};
assert_eq!(wh(&mut s), (72.0, 36.0), "geometric bounds");
// Use Preview Bounds: the stroke's outer half on every side.
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap();
let (w, h) = wh(&mut s);
assert!(near(w, 82.0) && near(h, 46.0), "{w} × {h}");
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": false})).unwrap();
// Two neighboring anchors selected (Direct Selection): the box around them, one edge of the
// rectangle.
s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap();
let (w, h) = wh(&mut s);
assert!((near(w, 72.0) && near(h, 0.0)) || (near(w, 0.0) && near(h, 36.0)), "{w} × {h}");
}
#[test]
fn it_needs_no_document_and_changes_nothing() {
let mut s = Session::new();
assert!(near(convert(&mut s, json!({"value": "1in"}))["points"].as_f64().unwrap(), 72.0));
let mut s = session();
let (before, steps) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
convert(&mut s, json!({"value": "5mm"}));
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
assert!(*s.doc().unwrap().doc == *before);
}
#[test]
fn bad_values_and_units_are_refused() {
let mut s = session();
for p in [
json!({}),
json!({"value": null}),
json!({"value": "abc"}),
json!({"value": "10 furlongs"}),
json!({"value": "1in/0"}),
json!({"value": "1e400"}),
// Finite in points, too large in Q and Ha.
json!({"value": 1.5e308}),
json!({"value": "1.5e308"}),
// A thousands comma is refused, as the number fields refuse it.
json!({"value": "1,000 mm"}),
json!({"value": "1,000.5"}),
json!({"value": "+1,000"}),
json!({"value": "1,000\""}),
json!({"value": "1,000'"}),
// A long expression is refused instead of exhausting the stack.
json!({"value": format!("1{}", "+1".repeat(200_000))}),
json!({"value": format!("1{}", "+1".repeat(129))}),
json!({"value": true}),
json!({"value": [1]}),
json!({"value": 1, "unit": "furlongs"}),
json!({"value": 1, "unit": 5}),
json!({"value": 1, "unit": ["mm"]}),
// Only an omitted `unit` is points.
json!({"value": 1, "unit": null}),
] {
match s.execute("addon.units.convert", &p) {
Err(EngineError::BadParams { cmd, .. }) => assert_eq!(cmd, "addon.units.convert", "{p}"),
other => panic!("{p}: expected BadParams, got {other:?}"),
}
}
}
#[test]
fn a_long_value_or_unit_is_refused_with_a_short_message() {
let mut s = session();
let long = "9".repeat(100_000);
for (p, says) in [
(json!({"value": long.clone()}), format!("`value` must be a number, not \"{}…\"", "9".repeat(64))),
(json!({"value": [long.clone()]}), "`value` must be a number, not […]".to_string()),
(json!({"value": 1, "unit": long.clone()}), format!("unknown units `{}…`", "9".repeat(64))),
(json!({"value": 1, "unit": "furlongs"}), "unknown units `furlongs`".to_string()),
(json!({"value": "a\"b\nc"}), "`value` must be a number, not \"a\\\"b\\nc\"".to_string()),
] {
match s.execute("addon.units.convert", &p) {
Err(e @ EngineError::BadParams { .. }) => assert!(e.to_string().ends_with(&says), "{e}"),
other => panic!("expected BadParams, got {other:?}"),
}
}
}
#[test]
fn the_selection_size_is_the_transform_panels() {
let mut s = session();
assert!(s.execute("addon.units.selectionSize", &json!({})).is_err(), "nothing selected");
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 72, "height": 36})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let steps = s.doc().unwrap().history.undo.len();
let r = s.execute("addon.units.selectionSize", &json!({})).unwrap();
assert!(near(r["width"]["points"].as_f64().unwrap(), 72.0));
assert!(near(r["height"]["points"].as_f64().unwrap(), 36.0));
assert_eq!(row(&r["width"], "inches")["text"], "1 in");
assert_eq!(row(&r["height"], "picas")["text"], "3 p");
// A turned object keeps its own sides, as the Transform panel's W and H show them.
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
let r = s.execute("addon.units.selectionSize", &json!({})).unwrap();
let b = s.transform_box(&s.doc().unwrap().selection.objects).unwrap();
assert!(near(r["width"]["points"].as_f64().unwrap(), b.rect.width()));
assert!(near(r["width"]["points"].as_f64().unwrap(), 72.0));
assert!(near(r["height"]["points"].as_f64().unwrap(), 36.0));
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "only the rotation is a step");
}
+42
View File
@@ -172,6 +172,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
BuiltinBrushLibrary { id: "art-ribbons", name: "Art Ribbons", make: art_ribbons },
BuiltinBrushLibrary { id: "ink-and-wash", name: "Ink and Wash", make: ink_and_wash },
BuiltinBrushLibrary { id: "calligraphic-nibs", name: "Calligraphic Nibs", make: calligraphic_nibs },
BuiltinBrushLibrary { id: "pressure-sensitive", name: "Pressure Sensitive", make: pressure_sensitive },
BuiltinBrushLibrary { id: "bristle-brushes", name: "Bristle Brushes", make: bristle_brushes },
BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders },
BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes },
@@ -374,6 +375,47 @@ fn bristle(name: &str, shape: BristleShape, [size, length, density, thickness, o
Brush { name: name.into(), kind: BrushKind::Bristle(Bristle { shape, size, length, density, thickness, opacity, stiffness }) }
}
/// Pressure Sensitive: four original marks whose art width or nib size responds to recorded pen
/// pressure. Mouse paths keep the engine's neutral middle-pressure rendering.
fn pressure_sensitive() -> BrushLibrary {
let flex = black(band(100.0, 5.0, 48, |x| 0.5 * (x / 100.0 * std::f64::consts::TAU).sin()));
let pulse = group(vec![
black(band(100.0, 2.8, 64, |x| 1.4 * (x / 100.0 * 2.0 * std::f64::consts::TAU).sin())),
black(shapes::ellipse(Rect::new(46.0, -2.2, 54.0, 2.2))),
]);
let art_pressure = |name: &str, art: Node, light: f64, heavy: f64| Brush {
name: name.into(),
kind: BrushKind::Art(ArtBrush {
art,
width: light,
width_mode: Some(Variation::Pressure),
width_max: Some(heavy),
colorization: Colorization::Tints,
..Default::default()
}),
};
let nib_pressure = |name: &str, angle: f64, roundness: f64, size: f64, variation: f64| Brush {
name: name.into(),
kind: BrushKind::Calligraphic(Calligraphic {
angle,
roundness,
size,
variation: [0.0, 0.0, variation],
modes: Some([Variation::Fixed, Variation::Fixed, Variation::Pressure]),
}),
};
built(
"Pressure Sensitive",
Document::new(100.0, 100.0),
vec![
art_pressure("Flex Ribbon", flex, 35.0, 250.0),
art_pressure("Pulse Stroke", pulse, 45.0, 280.0),
nib_pressure("Round Flow", 0.0, 100.0, 7.0, 5.0),
nib_pressure("Chisel Flow", 35.0, 25.0, 9.0, 7.0),
],
)
}
/// Bristle Brushes: one bristle brush for each tip shape, from a fine liner to wide fans for
/// blending and texture.
fn bristle_brushes() -> BrushLibrary {
+14 -5
View File
@@ -36,8 +36,8 @@ mod symbols;
pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint};
use brushes::{
brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_options, brush_place_art,
brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush,
brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_object_options, brush_options,
brush_place_art, brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush,
};
pub(crate) use dynamic::{edit_part, fit_parts, part_only, selected_part};
use dynamic::{symbol_instance_reset, symbol_instance_select_part, symbol_instance_set_appearance};
@@ -165,10 +165,19 @@ pub fn specs() -> Vec<CommandSpec> {
"Brush Options…",
[],
None,
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
has_doc,
brush_options
),
cmd!(
"brush.objectOptions",
"Options of Selected Object…",
[],
None,
"{ids?|id?, params?: {…the fields brush.options takes that a path can set for itself: calligraphic angle (counter-clockwise from level), roundness, size, variation, modes; scatter size, spacing, scatter, rotation (counter-clockwise), modes, rotation_relative_to_path, colorization; art width, width_mode, width_max, flip_along, flip_across, overlap, colorization; pattern scale, spacing, fit, flip_along, flip_across, colorization (values outside their ranges are clamped; a colorization object changes only the fields it gives; a null item of an array such as size: [40, null] keeps each stroke's own item, else the brush's)}, reset?: bool} set the brush settings of the brushed strokes of the selected paths on those strokes only, leaving the brush and its other strokes as they are (the Brushes panel's Options of Selected Object); params add to each stroke's own settings, a mode params does not set (no modes, or a null item) stays the one each stroke draws with when a changed variation or range would change it, a setting equal to the brush's own value is dropped, and reset: true clears them so the strokes draw the brush again; without params or reset nothing changes; one undo step, none when nothing changes. The brushes' own edits (brush.options) still reach the settings a stroke does not set, applying a brush (brush.apply, stroke.setAdvanced or a brush.freehand extend with another brush) or removing it clears them, and a renamed brush keeps them. Refused with nothing painted with a brush selected, for paths painted with brushes of different types, for a bristle brush, for a field the type does not take and for a value of the wrong kind → {ids: the brushed paths, changed: the paths whose settings changed, options: the first stroke's own settings}",
has_doc,
brush_object_options
),
cmd!(
"object.expandBrush",
"Expand Brush Strokes",
@@ -202,7 +211,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New Symbol…",
[],
None,
"{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}",
"{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid), keepArt?: false} make a symbol from the selection and replace it with an instance, or with keepArt: true leave the selection as ordinary art where it is, still selected, with id null; a frame of threaded text in the selection that becomes an instance leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}",
has_selection,
symbol_new
),
@@ -256,7 +265,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Redefine Symbol",
[],
None,
"{name, ids?|id?} replace the symbol's art with the selection (instances update, keeping their appearance changes to the objects at paths the new art still has; the selection becomes an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds) → {name, id}",
"{name, ids?|id?, keepArt?: false} replace the symbol's art with the selection (instances update, keeping their appearance changes to the objects at paths the new art still has; the selection becomes an instance, or with keepArt: true stays ordinary art where it is, still selected, and id is null; a frame of threaded text in the selection that becomes an instance leaves its thread with the text it shows, which the symbol's art holds; art that holds an instance of the symbol (opacity masks included), directly or through the symbols it nests, is refused) → {name, id}",
has_selection,
symbol_update
),
+175 -2
View File
@@ -1,6 +1,7 @@
use super::{
AppearanceItem, Arc, BTreeSet, Bristle, Brush, BrushKind, Color, Document, EngineError, Node, NodeId, NodeKind, Paint, Result, Session, Value,
anchor, bad, brush, check_numbers, find_command, ids_json, json, name_param, names_param, ok, roots, selection_art, set_unknown, str_param,
switch_or,
};
// ---------- brushes ----------
@@ -31,7 +32,12 @@ pub(super) fn brush_list(s: &mut Session, _: &Value) -> Result<Value> {
pub(super) fn brush_get(s: &mut Session, p: &Value) -> Result<Value> {
let name = name_param(p, "brush.get")?;
let b = brush::find(&s.doc()?.doc, name).ok_or_else(|| EngineError::Other(format!("no brush named `{name}`")))?;
Ok(serde_json::to_value(b).unwrap_or_default())
let mut v = serde_json::to_value(&b).unwrap_or_default();
// A scatter brush saves its hue jitter only when it is not 0; brush.get shows it either way.
if let (BrushKind::Scatter(sc), Some(o)) = (&b.kind, v.as_object_mut()) {
o.entry("hue_jitter").or_insert(json!(sc.hue_jitter));
}
Ok(v)
}
/// The art `brush.new` takes from `ids` or `id`, else from the selection ([`selection_art`]).
@@ -57,6 +63,8 @@ pub(crate) fn apply_brush(d: &mut Document, ids: &[NodeId], name: &str, stroke:
st.width = 1.0;
}
st.brush = Some(name.to_string());
// The path's own brush settings (Options of Selected Object) go with the brush they set.
st.brush_options.clear();
}
}
}
@@ -85,6 +93,7 @@ pub(super) fn brush_remove(s: &mut Session, p: &Value) -> Result<Value> {
for it in &mut n.appearance.items {
if let AppearanceItem::Stroke(st) = it {
st.brush = None;
st.brush_options.clear();
}
}
}
@@ -129,13 +138,17 @@ fn merge(base: &mut Value, patch: &Value) {
}
}
/// Sets brush `to` on the strokes in `items` that paint with brush `from`.
/// Sets brush `to` on the strokes in `items` that paint with brush `from`. A renamed brush keeps
/// each stroke's own settings for it; a stroke left without a brush loses them.
fn set_stroke_brush(items: &mut [AppearanceItem], from: &str, to: Option<&str>) {
for it in items {
if let AppearanceItem::Stroke(st) = it
&& st.brush.as_deref() == Some(from)
{
st.brush = to.map(str::to_string);
if to.is_none() {
st.brush_options.clear();
}
}
}
}
@@ -494,6 +507,166 @@ pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "name": out }))
}
/// Options of Selected Object: set the brush settings of the brushed strokes of the selected paths
/// (or `ids`) on those strokes only, leaving the brush as it is. `params` adds to each stroke's
/// own settings, `reset` clears them; without either, nothing changes and the settings are given.
pub(super) fn brush_object_options(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "brush.objectOptions";
let params = match p.get("params") {
None | Some(Value::Null) => serde_json::Map::new(),
Some(Value::Object(o)) => o.clone(),
Some(_) => {
let key = "params";
return Err(bad(C, format!("`{key}` must be an object")));
}
};
let reset = switch_or(p, "reset", false, C)?;
if reset && !params.is_empty() {
return Err(bad(C, "give `params` or `reset`, not both"));
}
let d = &s.doc()?.doc;
let lib = brush::library(d);
let ids = brush_targets(d, &roots(s, p)?);
// Each brushed stroke: its path, its place in the appearance, its brush and its settings now.
let mut strokes = vec![];
for id in &ids {
let Some(n) = d.node(*id) else { continue };
for (i, it) in n.appearance.items.iter().enumerate() {
let AppearanceItem::Stroke(st) = it else { continue };
if let Some(b) = st.brush.as_deref().and_then(|name| lib.iter().find(|b| b.name == name)) {
strokes.push((*id, i, b, &st.brush_options));
}
}
}
let Some(&(_, _, first, _)) = strokes.first() else { return Err(bad(C, "no path painted with a brush is selected")) };
if strokes.iter().any(|(_, _, b, _)| b.kind.type_id() != first.kind.type_id()) {
return Err(bad(C, "the selected paths are painted with brushes of different types"));
}
// Only a bristle brush has none.
if first.kind.stroke_option_keys().is_empty() {
return Err(bad(C, "a bristle brush has no options of its own on a path"));
}
let out: Vec<NodeId> = ids.iter().copied().filter(|id| strokes.iter().any(|(s, ..)| s == id)).collect();
// Without params or reset the settings are only given: nothing is normalized or changed.
if !reset && params.is_empty() {
let keys = first.kind.stroke_option_keys();
let own: serde_json::Map<String, Value> =
strokes[0].3.iter().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect();
return Ok(json!({ "ids": ids_json(&out), "changed": [], "options": own }));
}
let mut changes = vec![];
let mut options = None;
for (id, i, b, own) in &strokes {
let next = if reset {
serde_json::Map::new()
} else {
// Settings saved for another type of brush are left out.
let keys = b.kind.stroke_option_keys();
let mut merged: serde_json::Map<String, Value> =
own.iter().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect();
let was = merged.clone();
// A colorization object changes only the fields it gives, and a null item of an
// array keeps the stroke's own item (else the brush's).
for (k, v) in &params {
let next = match (merged.get(k), v) {
(Some(Value::Object(mine)), Value::Object(fields)) if k == "colorization" => {
let mut c = mine.clone();
c.extend(fields.clone());
Value::Object(c)
}
(Some(mine), _) => brush::keep_items(v, mine),
(None, _) => v.clone(),
};
merged.insert(k.clone(), next);
}
keep_drawn_modes(b, &was, &params, &mut merged);
keep_largest_width(b, &was, &params, &mut merged);
b.stroke_options_that_differ(&merged).map_err(|e| bad(C, e))?
};
options.get_or_insert_with(|| next.clone());
if &next != *own {
changes.push((*id, *i, next));
}
}
let changed: Vec<NodeId> = ids.iter().copied().filter(|id| changes.iter().any(|(c, ..)| c == id)).collect();
if !changes.is_empty() {
s.edit("Options of Selected Object", |d, _| {
for (id, i, next) in changes {
if let Some(AppearanceItem::Stroke(st)) = d.node_mut(id).and_then(|n| n.appearance.items.get_mut(i)) {
st.brush_options = next;
}
}
Ok(())
})?;
}
Ok(json!({ "ids": ids_json(&out), "changed": ids_json(&changed), "options": options.unwrap_or_default() }))
}
/// The modes brush `b` draws with, for a Calligraphic or a Scatter brush.
fn drawn_modes(b: &Brush) -> Option<Vec<Value>> {
let modes = match &b.kind {
BrushKind::Calligraphic(c) => serde_json::to_value(c.modes()),
BrushKind::Scatter(s) => serde_json::to_value(s.modes()),
_ => return None,
};
match modes {
Ok(Value::Array(m)) => Some(m),
_ => None,
}
}
/// Keep each mode a stroke of brush `b` draws with (with its own settings `was`) that `params`
/// does not set (no `modes`, or a `null` item) and that `merged`, its settings with `params`,
/// would change. A mode the stroke leaves to its values follows them, so without this a changed
/// variation or range would also change the mode.
fn keep_drawn_modes(
b: &Brush,
was: &serde_json::Map<String, Value>,
params: &serde_json::Map<String, Value>,
merged: &mut serde_json::Map<String, Value>,
) {
let given = match params.get("modes") {
None | Some(Value::Null) => vec![],
Some(Value::Array(m)) => m.clone(),
// A value of the wrong kind is refused when the settings are checked.
Some(_) => return,
};
let (Some(before), Some(after)) =
(b.with_stroke_options(was).ok().as_ref().and_then(drawn_modes), b.with_stroke_options(merged).ok().as_ref().and_then(drawn_modes))
else {
return;
};
if before == after {
return;
}
let kept = before.into_iter().zip(after).enumerate().map(|(j, (w, a))| if given.get(j).is_some_and(|g| !g.is_null()) { a } else { w }).collect();
merged.insert("modes".into(), Value::Array(kept));
}
/// Keep the largest width a stroke of art brush `b` draws with (with its own settings `was`) when
/// `params` sets `width` and no `width_max`. Without a `width_max` of its own the largest width is
/// the width, so without this a changed width would also change the largest width.
fn keep_largest_width(
b: &Brush,
was: &serde_json::Map<String, Value>,
params: &serde_json::Map<String, Value>,
merged: &mut serde_json::Map<String, Value>,
) {
if params.get("width").is_none_or(Value::is_null) || params.get("width_max").is_some_and(|m| !m.is_null()) {
return;
}
let art = |o: &serde_json::Map<String, Value>| match b.with_stroke_options(o).ok().map(|b| b.kind) {
Some(BrushKind::Art(a)) => Some(a),
_ => None,
};
let (Some(before), Some(after)) = (art(was), art(merged)) else { return };
let follows_pen = |a: &brush::ArtBrush| a.width_mode.is_some_and(|m| m.follows_pen());
// Only a width that followed the pen has a largest width, and only one that still does uses it.
if before.width_max.is_none() && follows_pen(&before) && follows_pen(&after) && after.width != before.width {
merged.insert("width_max".into(), json!(before.width));
}
}
/// The name `brush.placeArt` gives each pattern brush tile it places, by tile, in the order it
/// places them; `brush.replaceArt` reads a group of that name as that tile.
const TILE_NAMES: [&str; 5] = ["Side Tile", "Outer Corner Tile", "Inner Corner Tile", "Start Tile", "End Tile"];
+33 -4
View File
@@ -253,6 +253,9 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
let nine = nine_slice_param(p, C, None)?.flatten();
let dynamic = type_param(p, C)?.unwrap_or(false);
let pixel = pixel_grid_param(p, C)?.unwrap_or(false);
// `keepArt` leaves the art as ordinary art instead of replacing it with an instance.
let keep_art = switch_or(p, "keepArt", false, C)?;
let iso = s.doc()?.isolation;
// Keep the art where it was: the geometric centre stays at `c`, whatever the registration is.
let place = place_xf(c + reg.offset_from_center(size.0, size.1), size, reg);
let id = s.edit("New Symbol", |d, sel| {
@@ -264,13 +267,20 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
d.set_symbol_export_type(&name, export);
d.set_symbol_nine_slice(&name, nine);
d.set_symbol_pixel_aligned(&name, pixel);
if keep_art {
// The art stays where it is and stays selected, apart from art that is hidden or
// locked, in a hidden or locked group or layer, or on a locked artboard.
let locks = d.locked_artboards();
sel.set(ids.iter().copied().filter(|i| crate::cmd::select::is_selectable(d, iso, &locks, *i)));
return Ok(None);
}
let id = instance_in_place(d, &ids, &name, place)?;
sel.set([id]);
Ok(id)
Ok(Some(id))
})?;
Ok(json!({
"name": name,
"id": id.0,
"id": id.map(|i| i.0),
"registration": reg.0,
"exportType": export.id(),
"nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value),
@@ -612,6 +622,8 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result<Value> {
}
// Redefining the symbol being edited leaves symbol editing mode in the same step.
let session = s.doc()?.doc.symbol_edit.clone().filter(|e| e.symbol == name);
// `keepArt` leaves the art as ordinary art instead of replacing it with an instance.
let keep_art = switch_or(p, "keepArt", false, C)?;
if session.is_some() {
crate::cmd::settle_interaction(s)?;
s.end_text_edit();
@@ -625,10 +637,20 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result<Value> {
}
}
let mut art = selection_art(s, p)?.ok_or_else(|| EngineError::Other("nothing selected".into()))?;
// Nor can art that holds an instance of it, directly or through the symbols it nests.
if crate::cmd::symboledit::holds_symbol(&s.doc()?.doc, &art, &name, &mut Default::default()) {
return Err(EngineError::Other("a symbol can't hold an instance of itself".into()));
}
crate::cmd::threads::keep_shown_text(&s.doc()?.doc, &mut art);
let (art, size, c) = normalize(art)?;
let old = natural_size(&s.doc()?.doc, &name);
let editing = session.is_some();
// The isolation the kept art is selected in: the one from before symbol editing mode when
// the step leaves it.
let iso = match &session {
Some(se) => se.back_isolation,
None => s.doc()?.isolation,
};
let id = s.edit("Redefine Symbol", |d, sel| {
if editing {
crate::cmd::symboledit::finish(d, sel);
@@ -647,15 +669,22 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result<Value> {
}
// Each instance keeps its appearance changes to the objects the new art still has.
fit_overrides(d, &instances);
if keep_art {
// The art stays where it is and stays selected, apart from art that is hidden or
// locked, in a hidden or locked group or layer, or on a locked artboard.
let locks = d.locked_artboards();
sel.set(ids.iter().copied().filter(|i| crate::cmd::select::is_selectable(d, iso, &locks, *i)));
return Ok(None);
}
let reg = d.symbol_registration(&name);
let id = instance_in_place(d, &ids, &name, place_xf(c + reg.offset_from_center(size.0, size.1), size, reg))?;
sel.set([id]);
Ok(id)
Ok(Some(id))
})?;
if let Some(se) = &session {
crate::cmd::symboledit::leave_editing(s, se)?;
}
Ok(json!({ "name": name, "id": id.0 }))
Ok(json!({ "name": name, "id": id.map(|i| i.0) }))
}
/// How many levels of nested instances Delete Symbol expands before it gives up.
+1
View File
@@ -659,6 +659,7 @@ fn fit_to_edge(row: &mut AppearanceItem, run: Option<(f64, bool, bool, bool)>) {
}
s.profile = None;
s.brush = None;
s.brush_options.clear();
}
if !starts {
s.start_arrow = None;
@@ -579,6 +579,11 @@ impl SwatchChoices {
Some(v) => Ok(Self { all: one(v)?, by_name: BTreeMap::new() }),
}
}
/// Add for every conflict: each pasted swatch whose name the document gives another color
/// comes in renamed.
pub(crate) fn add_all() -> Self {
Self { all: SwatchChoice::Add, by_name: BTreeMap::new() }
}
fn of(&self, name: &str) -> SwatchChoice {
self.by_name.get(name).copied().unwrap_or(self.all)
}
+28 -2
View File
@@ -121,7 +121,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Separations Preview",
[],
None,
"{on?: bool, plates?: [names], toggle?: plate, only?: plate} Separations Preview: show the chosen plates (one plate = greyscale ink coverage) → {on, plates: [{name, spot, visible, rgb}]}",
"{on?: bool, plates?: [names], toggle?: plate, only?: plate, soloToggle?: plate (only that plate, or every plate when it is the only one shown)} Separations Preview: show the chosen plates (one plate = grayscale ink coverage) → {on, plates: [{name, spot, visible, rgb}]}",
always,
separations
),
@@ -754,10 +754,12 @@ fn map_art_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof
}
/// `f` applied to the colors in `n`'s subtree that [`proof::map_node_colors`] does not visit: the
/// effect colors ([`map_effect_colors`]), the series paints and label styles a graph keeps
/// effect colors ([`map_effect_colors`]), the Hue Shift key colors of strokes' own brush settings
/// ([`map_stroke_brush_keys`]), the series paints and label styles a graph keeps
/// ([`map_graph_colors`]) and the art of every opacity mask.
fn map_more_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
map_effect_colors(&mut n.appearance, f);
map_stroke_brush_keys(&mut n.appearance, f);
if let Some(e) = n.extras_if_any() {
if let Some(g) = e.graph.as_deref_mut() {
map_graph_colors(g, f);
@@ -773,6 +775,23 @@ fn map_more_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proo
}
}
/// `f` applied to the Hue Shift key color of each stroke's own brush settings in appearance `a`
/// (Options of Selected Object, `colorization.key` of [`StrokeLayer::brush_options`]); a key
/// that does not read is left as it is.
///
/// [`StrokeLayer::brush_options`]: vectorcraft_doc::StrokeLayer::brush_options
fn map_stroke_brush_keys(a: &mut vectorcraft_doc::Appearance, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
for it in &mut a.items {
let vectorcraft_doc::AppearanceItem::Stroke(st) = it else { continue };
let Some(c) = st.brush_options.get_mut("colorization").and_then(Value::as_object_mut) else { continue };
let Some(key) = c.get("key").and_then(|k| serde_json::from_value::<Color>(k.clone()).ok()) else { continue };
let n = f(&key, None);
if n != key {
c.insert("key".into(), json!(n));
}
}
}
/// Whether art color `c` is the Hue Shift key color `key`, with the tolerance the brush's
/// colorization matches it with.
fn matches_key(c: &Color, key: &Color) -> bool {
@@ -1036,6 +1055,13 @@ fn separations(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(n) = text_param(p, "only", C)? {
v.separations = Some(vec![check(n)?]);
}
// The panel's Alt-click on a plate's eye: that plate alone, or every plate when it already
// shows alone among the active document's plates.
if let Some(n) = text_param(p, "soloToggle", C)? {
let n = check(n)?;
let alone = v.separations.as_ref().is_some_and(|vis| all.iter().filter(|a| vis.contains(a)).eq([&n]));
v.separations = Some(if alone { all.clone() } else { vec![n] });
}
if let Some(n) = text_param(p, "toggle", C)? {
let n = check(n)?;
let vis = v.separations.get_or_insert_with(|| all.clone());
+56 -33
View File
@@ -62,7 +62,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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",
"{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or 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 points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn",
has_doc,
circle_through_points
),
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Create Text",
[],
None,
"{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
"{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
has_doc,
text_create
),
@@ -413,16 +413,16 @@ 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.
/// A live ellipse whose edge passes through two or three points: `points`, or the two or three
/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. 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`"))?,
Some(v) => two_or_three_points(v).ok_or_else(|| bad(C, "`points` must be two or three [x, y] pairs of numbers"))?,
None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select two or three anchor points, or give `points`"))?,
};
let [a, b, c] = points;
let (center, radius) = shapes::circle_through(a, b, c)
let (center, radius) = shapes::circle_through_points(&points)
.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()) };
@@ -434,24 +434,25 @@ fn circle_through_points(s: &mut Session, p: &Value) -> Result<Value> {
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]> {
/// The two or three points `[[x, y], [x, y]]` or `[[x, y], [x, y], [x, y]]` holds, each pair two
/// finite numbers.
fn two_or_three_points(v: &Value) -> Option<Vec<Point>> {
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)?]),
match v.as_array() {
Some(pairs) if matches!(pairs.len(), 2 | 3) => pairs.iter().map(pair).collect(),
_ => None,
}
}
/// The positions of the selected anchor points, when there are exactly three. They are counted as
/// The positions of the selected anchor points, when there are two or 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]>> {
fn selected_anchor_points(s: &Session) -> Result<Option<Vec<Point>>> {
let st = s.doc()?;
if st.selection.segments.values().any(|set| !set.is_empty()) {
return Ok(None);
@@ -472,10 +473,7 @@ fn selected_anchor_points(s: &Session) -> Result<Option<[Point; 3]>> {
return Ok(None);
}
}
Ok(match points.as_slice() {
&[a, b, c] => Some([a, b, c]),
_ => None,
})
Ok(matches!(points.len(), 2 | 3).then_some(points))
}
/// The whole-number count `p` gives for `key` (`5` or `5.0`), or `default` when it is left out or
@@ -942,7 +940,13 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
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);
if p.get("font").is_some() || p.get("style").is_some() {
// A face from a redefined [Normal Character Style] is checked too, as one given here is.
let normal_face = s
.doc()
.ok()
.and_then(|d| super::textstyles::style_attrs(&d.doc, false, super::textstyles::NORMAL_CHAR))
.is_some_and(|m| m.contains_key("font_family") || m.contains_key("font_style"));
if p.get("font").is_some() || p.get("style").is_some() || normal_face {
let runs = match id.and_then(|i| s.doc().ok()?.doc.node(i)).map(|n| &n.kind) {
Some(NodeKind::Text(t)) => t.runs.iter().flat_map(super::fonts::run_fonts).collect(),
_ => Default::default(),
@@ -970,8 +974,9 @@ pub(crate) fn new_type_para() -> vectorcraft_doc::ParaStyle {
/// The paragraph alignment, leading model and character alignment new type starts with (`t`'s
/// paragraph and runs): `justify` from `p` (else as [`new_type_para`] left it), `leadingModel`
/// and `charAlign` from `p`, else em box top to top and em box centre while the
/// interface is in Japanese (#432), else the Roman baseline for both. Noted in the journal, so a
/// and `charAlign` from `p` (`charAlign` else from a redefined `[Normal Character Style]` that
/// sets it), else em box top to top and em box centre while the interface is in Japanese (#432),
/// else the Roman baseline for both. Noted in the journal, so a
/// replay sets the same whatever the interface.
pub(crate) fn new_type_alignment(s: &mut Session, p: &Value, cmd: &str, t: &mut TextObject) -> Result<()> {
use vectorcraft_doc::{CharAlign, LeadingModel};
@@ -991,7 +996,14 @@ pub(crate) fn new_type_alignment(s: &mut Session, p: &Value, cmd: &str, t: &mut
l
}
};
let align = match super::textedit::char_align_param(p, cmd)? {
// A redefined [Normal Character Style] that sets Character Alignment gives it to new type.
let normal_align = s
.doc()
.ok()
.and_then(|d| super::textstyles::style_attrs(&d.doc, false, super::textstyles::NORMAL_CHAR))
.filter(|m| m.contains_key("charAlign"))
.and(t.runs.first().map(|r| r.style.char_align));
let align = match super::textedit::char_align_param(p, cmd)?.or(normal_align) {
Some(a) => a,
None => {
let a = if japanese { CharAlign::EmBoxCenter } else { CharAlign::RomanBaseline };
@@ -1019,17 +1031,25 @@ pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str, t: &mut TextObject)
}
/// The character style new type gets: `size`, `font`, `style` and `color` from `p` (an RGB
/// `color` in a CMYK document as [`super::paint::new_color`] stores it), else the defaults,
/// filled as `[Normal Character Style]` is (black unless redefined; never the current fill,
/// #7975), in the document's
/// language. A `size` outside [`super::typecmd::TYPE_SIZES`] is an error.
/// `color` in a CMYK document as [`super::paint::new_color`] stores it), else
/// `[Normal Character Style]`'s (the default font, size and black fill unless redefined;
/// never the current fill, #7975), in the style's language, else the document's. A `size` outside
/// [`super::typecmd::TYPE_SIZES`] is an error.
pub(crate) fn new_type_style(s: &Session, p: &Value, cmd: &str) -> Result<CharStyle> {
let mut style = CharStyle::default();
let mut style = s.doc().map_or_else(|_| CharStyle::default(), |d| super::textstyles::normal_char_style(&d.doc));
if let Some(sz) = p.get("size").and_then(Value::as_f64) {
style.size = super::typecmd::given_type_size(sz, cmd)?;
}
if str_param(p, "font").is_some() || str_param(p, "style").is_some() {
// A face given to the command takes its own version and axis settings, as a font change
// does, not those [Normal Character Style] gave another face.
style.font_version = None;
style.font_axes.clear();
}
if let Some(f) = str_param(p, "font") {
style.font_family = f.to_string();
// A family alone starts in Regular, whatever style [Normal Character Style] has.
style.font_style = CharStyle::default().font_style;
}
if let Some(f) = str_param(p, "style") {
style.font_style = f.to_string();
@@ -1039,12 +1059,15 @@ pub(crate) fn new_type_style(s: &Session, p: &Value, cmd: &str) -> Result<CharSt
}
style.fill = match p.get("color").and_then(color_value) {
Some(c) => vectorcraft_color::Paint::solid(super::paint::new_color(s, p, c)),
None => s.doc().map_or_else(|_| CharStyle::default().fill, |d| super::textstyles::normal_char_fill(&d.doc)),
None => style.fill,
};
// In the language Document Setup chose, else Preferences › Hyphenation › Default Language; none
// for the default. Type already in a document keeps its own.
let chosen = |name: &str| vectorcraft_doc::setup::char_language(name).ok().flatten();
let document = s.doc().ok().and_then(|d| chosen(&d.doc.setup.language));
style.language = document.or_else(|| chosen(&s.prefs.hyphenation_language)).map(str::to_string);
// In the language a redefined [Normal Character Style] gives, else the one Document Setup chose,
// else Preferences › Hyphenation › Default Language; none for the default. Type already in a
// document keeps its own.
if style.language.is_none() {
let chosen = |name: &str| vectorcraft_doc::setup::char_language(name).ok().flatten();
let document = s.doc().ok().and_then(|d| chosen(&d.doc.setup.language));
style.language = document.or_else(|| chosen(&s.prefs.hyphenation_language)).map(str::to_string);
}
Ok(style)
}
+3 -10
View File
@@ -3,10 +3,8 @@ use super::{CommandSpec, EngineError, Result, Session, cmd, has_doc};
use serde_json::{Value, json};
use std::sync::Arc;
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::dimension::{
ArrowStyle, Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, Orientation, TextAlignment, TextPosition,
};
use vectorcraft_doc::{Appearance, Arrowhead, CharStyle, ColorMode, Dash, Document, Node, NodeId, NodeKind, TextObject};
use vectorcraft_doc::dimension::{Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, Orientation, TextAlignment, TextPosition};
use vectorcraft_doc::{Appearance, CharStyle, ColorMode, Dash, Document, Node, NodeId, NodeKind, TextObject};
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Vec2};
pub fn specs() -> Vec<CommandSpec> {
@@ -567,12 +565,7 @@ fn appearance(o: &DimensionOptions, mode: ColorMode, ext: bool, arrows: bool) ->
LineType::Solid => None,
};
if arrows {
let head = match o.arrow_style {
ArrowStyle::Filled => Some(Arrowhead::Triangle),
ArrowStyle::Open => Some(Arrowhead::TriangleOpen),
ArrowStyle::Tick => Some(Arrowhead::Slash),
ArrowStyle::None => None,
};
let head = o.arrow_style.arrowhead();
st.start_arrow = head.clone();
st.end_arrow = head;
st.arrow_scale = (o.arrow_scale, o.arrow_scale);
+88 -12
View File
@@ -16,7 +16,7 @@ use vectorcraft_tools::distort::{PinSet, arap, collect_points, mesh_for, project
use super::edit::{duplicate_in, outermost, refuse_symbol_part, selected_roots};
use super::{
CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_doc, has_selection, matrix_param,
named_id, named_ids, number_or, object_param, ok, point_indices, point_param, str_param, switch_or, targets,
named_id, named_ids, number_or, object_param, ok, point_indices, point_param, str_param, switch_or, targets, text_param, u64_req,
};
use crate::EngineError;
@@ -35,7 +35,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Width Point",
[],
None,
"{id, t: 0..1 (fraction of the path length), left, right: side widths in pt, index?: width point to edit or move, adjustAdjoining?: bool (the nearest points either side change their widths in proportion, using the sampled widths for a new point)} → {index}. Without index a point already at t is replaced; a point moved onto another one's t joins it as a discontinuous point (on the side it came from), so the width steps there. Creates a uniform profile first if needed",
"{id, t: 0..1 (fraction of the path length), left, right: side widths in pt, index?: width point to edit or move, adjustAdjoining?: bool (the nearest points either side change their widths in proportion, using the sampled widths for a new point), outIndex?, outLeft, outRight: the outgoing half of the discontinuous point whose incoming half is index, single?: \"incoming\" | \"outgoing\"} → {index}. Without index a point already at t is replaced; a point moved onto another one's t joins it as a discontinuous point (on the side it came from), so the width steps there. With outIndex both halves change in one step and keep their place (t must be theirs); adjustAdjoining then changes the nearest point before from the incoming half and the nearest point after from the outgoing half. single keeps only that half's widths, leaving one continuous point. Creates a uniform profile first if needed",
has_doc,
width_point_set
),
@@ -214,6 +214,15 @@ fn uniform() -> WidthProfile {
/// Width points closer than this (in t) are at the same place: a discontinuous point.
const SAME_T: f64 = 1e-6;
/// The outgoing half of the discontinuous width point whose incoming half is point `a`: point `a`
/// and the next one are the two halves when they are the only points within 1e-6 (in t) of `a`'s
/// place. None when `a` is out of range or not such an incoming half.
pub fn width_point_pair(points: &[(f64, f64, f64)], a: usize) -> Option<usize> {
let t = points.get(a)?.0;
let at: Vec<usize> = (0..points.len()).filter(|i| (points[*i].0 - t).abs() <= SAME_T).collect();
(at == [a, a + 1]).then_some(a + 1)
}
/// The stroke of `id` that width point commands edit (a compound path's for its members).
fn stroke_mut(d: &mut Document, id: NodeId) -> Result<&mut vectorcraft_doc::StrokeLayer> {
let id = stroke_owner(d, id);
@@ -265,9 +274,9 @@ fn place(points: &mut Vec<(f64, f64, f64)>, mut pt: (f64, f64, f64), from_below:
}
/// Adjust Adjoining Width Points: point `i` changes from `old` to `new` widths, and the nearest
/// points at other positions either side change in proportion (by the same amount from zero).
fn adjust_adjoining(points: &mut [(f64, f64, f64)], i: usize, old: (f64, f64, f64), new: (f64, f64, f64)) {
let t = points[i].0;
/// points farther than [`SAME_T`] from place `t` on the sides `sides` names (before, after)
/// change in proportion (by the same amount from zero).
fn adjust_adjoining(points: &mut [(f64, f64, f64)], i: usize, t: f64, old: (f64, f64, f64), new: (f64, f64, f64), sides: [bool; 2]) {
let scale = |v: f64, o: f64, n: f64| {
let width = if o > 1e-9 {
let product = v * n;
@@ -284,8 +293,8 @@ fn adjust_adjoining(points: &mut [(f64, f64, f64)], i: usize, old: (f64, f64, f6
};
width.max(0.0)
};
let before = (0..i).rev().find(|j| (points[*j].0 - t).abs() > SAME_T);
let after = (i + 1..points.len()).find(|j| (points[*j].0 - t).abs() > SAME_T);
let before = (0..i).rev().find(|j| (points[*j].0 - t).abs() > SAME_T).filter(|_| sides[0]);
let after = (i + 1..points.len()).find(|j| (points[*j].0 - t).abs() > SAME_T).filter(|_| sides[1]);
for j in before.into_iter().chain(after) {
let q = &mut points[j];
(q.1, q.2) = (scale(q.1, old.1, new.1), scale(q.2, old.2, new.2));
@@ -303,6 +312,46 @@ fn same_points(a: Option<&WidthProfile>, b: Option<&WidthProfile>) -> bool {
}
}
/// Set both halves of the discontinuous point whose incoming half is `i` and outgoing half `j` to
/// the widths of `inc` and `out` (their places are ignored: the point keeps its place). With
/// `single` (`true` for the outgoing half) only that half's widths remain, as one continuous point.
/// With `adjust`, the nearest point before changes with the incoming half and the nearest point after
/// with the outgoing half, once each. → the index of the point (its incoming half).
fn set_pair(
points: &mut Vec<(f64, f64, f64)>,
(i, inc): (usize, (f64, f64, f64)),
(j, out): (usize, (f64, f64, f64)),
adjust: bool,
single: Option<bool>,
) -> Result<usize> {
const C: &str = "stroke.widthPoint.set";
if width_point_pair(points, i) != Some(j) {
return Err(bad(C, "`index` and `outIndex` must be the two halves of one discontinuous width point"));
}
let at = points[i].0;
let (old_in, old_out) = (points[i], points[j]);
if (old_in.0 - inc.0).abs() > SAME_T {
return Err(bad(C, "a discontinuous width point keeps its place"));
}
let (new_in, new_out) = match single {
None => ((old_in.0, inc.1, inc.2), (old_out.0, out.1, out.2)),
Some(false) => ((old_in.0, inc.1, inc.2), (old_in.0, inc.1, inc.2)),
Some(true) => ((old_in.0, out.1, out.2), (old_in.0, out.1, out.2)),
};
// Both halves measure their neighbors from the point's place, so a point within SAME_T of the
// outgoing half but not of that place is the point after the pair.
if adjust {
adjust_adjoining(points, i, at, old_in, new_in, [true, false]);
adjust_adjoining(points, j, at, old_out, new_out, [false, true]);
}
points[i] = new_in;
points[j] = new_out;
if single.is_some() {
points.remove(j);
}
Ok(i)
}
fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "stroke.widthPoint.set";
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
@@ -312,6 +361,25 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "left/right must be non-negative widths"));
}
let adjust = switch_or(p, "adjustAdjoining", false, C)?;
let single = match text_param(p, "single", C)? {
None => None,
Some(side @ ("incoming" | "outgoing")) => Some(side == "outgoing"),
Some(_) => return Err(bad(C, "`single` must be `incoming` or `outgoing`")),
};
// The outgoing half of a discontinuous point: its index and side widths (points).
// `single`, `outLeft` or `outRight` without `outIndex` is refused as a missing `outIndex`.
let out_widths = ["outLeft", "outRight"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null()));
let out = match p.get("outIndex") {
None | Some(Value::Null) if single.is_none() && !out_widths => None,
_ => {
let j = usize::try_from(u64_req(p, "outIndex", C)?).map_err(|_| bad(C, "no such width point"))?;
let (l, r) = (f64_req(p, "outLeft", C)?, f64_req(p, "outRight", C)?);
if !(l.is_finite() && r.is_finite()) || l < 0.0 || r < 0.0 || l.max(r) > 1.0e5 {
return Err(bad(C, "left/right must be non-negative widths"));
}
Some((j, l, r))
}
};
// When the profile comes out as it was, within a rounding error (1e-9), the document and its undo
// history stay as they are.
let mut pos = 0;
@@ -324,11 +392,19 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "width factors must be finite"));
}
let mut prof = st.profile.take().unwrap_or_else(uniform);
pos = match point_index(p, &prof, C)? {
Some(i) => {
pos = match (point_index(p, &prof, C)?, out) {
(None, Some(_)) => return Err(bad(C, "missing index")),
(Some(i), Some((j, l, r))) => {
let out = (t, l / half, r / half);
if !out.1.is_finite() || !out.2.is_finite() {
return Err(bad(C, "width factors must be finite"));
}
set_pair(&mut prof.points, (i, pt), (j, out), adjust, single)?
}
(Some(i), None) => {
let old = prof.points[i];
if adjust {
adjust_adjoining(&mut prof.points, i, old, pt);
adjust_adjoining(&mut prof.points, i, old.0, old, pt, [true, true]);
}
if (old.0 - t).abs() <= SAME_T {
// Widths only: it keeps its place (and its side of a discontinuous point).
@@ -339,12 +415,12 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> {
place(&mut prof.points, pt, old.0 < t)
}
}
None => {
(None, None) => {
let old = adjust.then(|| prof.at(t));
prof.points.retain(|q| (q.0 - t).abs() > SAME_T);
let i = place(&mut prof.points, pt, true);
if let Some((left, right)) = old {
adjust_adjoining(&mut prof.points, i, (t, left, right), pt);
adjust_adjoining(&mut prof.points, i, pt.0, (t, left, right), pt, [true, true]);
}
i
}
+179 -5
View File
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Document Info",
["Window", "Document Info"],
None,
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds",
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds",
has_doc,
info
),
@@ -178,14 +178,58 @@ fn repeat_entry(d: &Document, n: &Node, spec: &RepeatSpec) -> (Value, (String, S
(entry, (name, format!("{}, {detail}", kind.label())))
}
/// The artboards the Artboard tool has selected while it is the current tool, in artboard order,
/// with the index of its active artboard; none with another tool or when it has none of the
/// document's artboards selected. Indices the document does not have are left out.
fn artboard_tool_selection(s: &Session) -> Option<(Vec<usize>, usize)> {
if s.tool_id() != "artboard" {
return None;
}
let n = s.active().map_or(0, |d| d.doc.artboards.len());
let t = s.tool_options_of("artboard");
let index = |v: &Value| v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < n);
let mut picked: Vec<usize> = t["selected"].as_array().into_iter().flatten().filter_map(index).collect();
picked.sort_unstable();
picked.dedup();
let first = *picked.first()?;
let active = index(&t["active"]).filter(|a| picked.contains(a)).unwrap_or(first);
Some((picked, active))
}
/// The artboards `picked` as Document Info › Document lists them while the Artboard tool is the
/// current tool: their `selectedArtboards` entries (in the document's units), and for each its
/// rows: its name, width, height and the X and Y of its top-left corner from the ruler origin of
/// artboard `active`.
fn selected_artboard_rows(d: &Document, picked: &[usize], active: usize) -> (Vec<Value>, Vec<(String, String)>) {
let (u, per) = (d.units, d.units.points());
let origin = d.ruler_origin_for(active);
let mut entries = vec![];
let mut rows = vec![];
for &i in picked {
let Some(a) = d.artboards.get(i) else { continue };
let (w, h, x, y) = (a.rect.width(), a.rect.height(), a.rect.x0 - origin.x, a.rect.y0 - origin.y);
entries.push(json!({ "index": i, "name": a.name, "width": w / per, "height": h / per, "x": x / per, "y": y / per }));
rows.extend([
("Artboard".to_string(), a.name.clone()),
("Width".into(), u.format(w)),
("Height".into(), u.format(h)),
("X".into(), u.format(x)),
("Y".into(), u.format(y)),
]);
}
(entries, rows)
}
/// The Document Info categories of `d` (only `category` when given) from `info` (what
/// `document.info` reports), its fonts and their Font Details rows, its image objects, the rows of
/// the brushes its art uses, the rows of its Repeat objects and the rows of its objects filled or
/// stroked with a spot color, with a pattern and with a gradient.
/// `document.info` reports), the rows of the artboards the Artboard tool has selected, its fonts
/// and their Font Details rows, its image objects, the rows of the brushes its art uses, the rows
/// of its Repeat objects and the rows of its objects filled or stroked with a spot color, with a
/// pattern and with a gradient.
#[allow(clippy::too_many_arguments)]
fn sections(
d: &Document,
info: &Value,
selected_artboards: &[(String, String)],
fonts: &BTreeSet<super::fonts::UsedFont>,
font_details: &[(String, String)],
images: &[ImageRow],
@@ -215,7 +259,19 @@ fn sections(
rows.extend(
d.artboards.iter().map(|a| (a.name.clone(), format!("{} × {}", u.format(a.rect.width()), u.format(a.rect.height())))),
);
rows.extend(selected_artboards.iter().cloned());
rows.push(("Raster Effects".into(), format!("{} ppi", d.raster_effects_ppi)));
let setup = &d.setup;
let colors = match setup.grid_colors_name() {
"Custom" => setup.grid_colors.map(|c| c.to_hex()).join(", "),
name => name.to_string(),
};
rows.extend([
("Grid Size".to_string(), setup.grid_size.label().to_string()),
("Grid Colors".into(), colors),
("Simulate Colored Paper".into(), if setup.simulate_paper { "On" } else { "Off" }.into()),
("Flattener Preset".into(), setup.flattener().to_string()),
]);
let counts = [
("Swatches", "swatches"),
("Character Styles", "characterStyles"),
@@ -556,6 +612,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
Some("text") => true,
Some(f) => return Err(bad(C, format!("format `{f}`: text or json"))),
};
let artboard_tool = artboard_tool_selection(s);
let st = s.doc()?;
let d = &st.doc;
let selection_only = bool_or(p, "selectionOnly", false);
@@ -787,7 +844,22 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
});
// The document's name: its file's, else its title.
out["document"]["name"] = json!(st.title());
let sections = sections(d, &out, &fonts, &font_rows, &image_rows, &brush_rows, &repeat_rows, &spot_rows, &pattern_rows, &gradient_rows, category);
let (selected_entries, selected_rows) = artboard_tool.map(|(picked, active)| selected_artboard_rows(d, &picked, active)).unwrap_or_default();
out["document"]["selectedArtboards"] = json!(selected_entries);
let sections = sections(
d,
&out,
&selected_rows,
&fonts,
&font_rows,
&image_rows,
&brush_rows,
&repeat_rows,
&spot_rows,
&pattern_rows,
&gradient_rows,
category,
);
if text {
return Ok(json!({ "text": report_text(&st.title(), selection_only, &sections) }));
}
@@ -804,6 +876,13 @@ fn document_summary(d: &Document) -> Value {
"unitId": d.units.key(),
"artboards": d.artboards.iter().map(|a| json!({ "name": a.name, "width": a.rect.width() / u, "height": a.rect.height() / u })).collect::<Vec<_>>(),
"rasterEffectsPpi": d.raster_effects_ppi,
"transparency": {
"gridSize": d.setup.grid_size.id(),
"gridColors": d.setup.grid_colors.map(|c| c.to_hex()),
"gridColorsName": d.setup.grid_colors_name(),
"simulatePaper": d.setup.simulate_paper,
"flattenerPreset": d.setup.flattener(),
},
})
}
@@ -875,6 +954,101 @@ mod tests {
assert!(i["objects"]["textObjects"].is_null() && i["objects"]["paths"] == 1);
}
/// The Document category's rows from `info`, as (label, value) pairs.
fn document_rows(i: &Value) -> Vec<(String, String)> {
let doc = i["sections"].as_array().unwrap().iter().find(|s| s["id"] == "document").unwrap();
doc["rows"].as_array().unwrap().iter().map(|r| (r[0].as_str().unwrap().to_string(), r[1].as_str().unwrap().to_string())).collect()
}
/// Document lists File › Document Setup's transparency settings: the grid's size and colors
/// (a preset's name, else both colors), Simulate Colored Paper and the flattener preset.
#[test]
fn info_lists_the_transparency_settings() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
let i = s.execute("document.info", &json!({})).unwrap();
let t = &i["document"]["transparency"];
assert_eq!(
(t["gridSize"].clone(), t["gridColorsName"].clone(), t["simulatePaper"].clone(), t["flattenerPreset"].clone()),
(json!("medium"), json!("Light"), json!(false), json!("Medium Resolution"))
);
let rows = document_rows(&i);
let at = rows.iter().position(|(l, _)| l == "Raster Effects").unwrap();
let expected =
[("Grid Size", "Medium"), ("Grid Colors", "Light"), ("Simulate Colored Paper", "Off"), ("Flattener Preset", "Medium Resolution")];
assert_eq!(rows[at + 1..at + 5], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}");
s.execute(
"document.setup",
&json!({"gridSize": "large", "gridColors": ["#ff0000", "#00ff00"], "simulatePaper": true, "flattenerPreset": "High Resolution"}),
)
.unwrap();
let i = s.execute("document.info", &json!({})).unwrap();
assert_eq!(i["document"]["transparency"]["gridColors"], json!(["#ff0000", "#00ff00"]));
assert_eq!(i["document"]["transparency"]["gridColorsName"], "Custom");
let rows = document_rows(&i);
let expected =
[("Grid Size", "Large"), ("Grid Colors", "#ff0000, #00ff00"), ("Simulate Colored Paper", "On"), ("Flattener Preset", "High Resolution")];
assert_eq!(rows[at + 1..at + 5], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}");
let report = s.execute("document.info", &json!({"category": "document", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
assert!(report.contains("Grid Colors: #ff0000, #00ff00\nSimulate Colored Paper: On\nFlattener Preset: High Resolution\n"), "{report}");
}
/// While the Artboard tool is the current tool, Document lists each artboard it has selected
/// after the artboards: its name, width, height and the X and Y of its top-left corner from the
/// ruler origin of the tool's active artboard. With another tool it lists none.
#[test]
fn info_lists_the_artboards_the_artboard_tool_selected() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("artboard.new", &json!({"x": 150, "y": 40, "width": 60, "height": 80})).unwrap();
s.execute("artboard.new", &json!({"x": 400, "y": 10, "width": 100, "height": 50})).unwrap();
s.execute("artboard.setProps", &json!({"index": 2, "name": "Back"})).unwrap();
let before = s.execute("document.info", &json!({})).unwrap();
assert_eq!(before["document"]["selectedArtboards"], json!([]));
s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
s.set_tool_option("selected", &json!([2, 1, 7]));
let i = s.execute("document.info", &json!({})).unwrap();
// Artboard 2 is active: positions are measured from its top-left corner.
assert_eq!(
i["document"]["selectedArtboards"],
json!([
{"index": 1, "name": "Artboard 2", "width": 60.0, "height": 80.0, "x": -250.0, "y": 30.0},
{"index": 2, "name": "Back", "width": 100.0, "height": 50.0, "x": 0.0, "y": 0.0},
])
);
let rows = document_rows(&i);
let at = rows.iter().position(|(l, _)| l == "Artboards").unwrap() + 4;
let expected = [
("Artboard", "Artboard 2"),
("Width", "60 pt"),
("Height", "80 pt"),
("X", "-250 pt"),
("Y", "30 pt"),
("Artboard", "Back"),
("Width", "100 pt"),
("Height", "50 pt"),
("X", "0 pt"),
("Y", "0 pt"),
("Raster Effects", "72 ppi"),
];
assert_eq!(rows[at..at + 11], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}");
// The rows follow the document's units and its ruler origin.
s.execute("document.setup", &json!({"units": "Millimeters"})).unwrap();
s.execute("document.setRulerOrigin", &json!({"x": 390, "y": 0, "artboard": 2})).unwrap();
s.set_tool_option("selected", &json!([2]));
let i = s.execute("document.info", &json!({"category": "document"})).unwrap();
let entry = &i["document"]["selectedArtboards"];
assert_eq!((entry.as_array().unwrap().len(), entry[0]["index"].clone()), (1, json!(2)));
assert!((entry[0]["x"].as_f64().unwrap() - 10.0 * 25.4 / 72.0).abs() < 1e-9, "{entry}");
let rows = document_rows(&i);
assert!(rows.contains(&("X".into(), "3.5278 mm".into())) && rows.contains(&("Y".into(), "3.5278 mm".into())), "{rows:?}");
// Another tool: no artboard rows.
s.select_tool("selection", crate::tooling::ViewInfo::default()).unwrap();
let i = s.execute("document.info", &json!({})).unwrap();
assert_eq!(i["document"]["selectedArtboards"], json!([]));
assert!(!document_rows(&i).iter().any(|(l, _)| l == "X"), "{:?}", document_rows(&i));
}
/// Document Info's fonts include the type in an opacity mask, in a symbol's art and in a
/// pattern swatch that nothing paints with; with `selectionOnly`, only the selected type's.
#[test]
+2 -1
View File
@@ -238,7 +238,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Guide",
[],
None,
"{index, pos: pt} | {dx?, dy?: pt, copy?: bool} put ruler guide `index` at `pos`, or move the selected guides (vertical ones by dx, horizontal ones by dy); copy leaves them and selects the moved copies",
"{index, pos: pt} | {dx?, dy?: pt, copy?: bool, interpolate?: bool (with art selected too: as object.move's)} put ruler guide `index` at `pos`, or move the selected guides (vertical ones by dx, horizontal ones by dy); copy leaves them and selects the moved copies",
guides_unlocked,
guide_move
),
@@ -990,6 +990,7 @@ pub(crate) fn guide_move(s: &mut Session, p: &Value) -> Result<Value> {
let dx = number_or(p, "dx", 0.0, "guide.move")?;
let dy = number_or(p, "dy", 0.0, "guide.move")?;
let copy = switch_or(p, "copy", false, "guide.move")?;
switch_or(p, "interpolate", false, "guide.move")?;
if !s.doc()?.selection.is_empty() {
let ids = super::edit::selected_roots(s)?;
return super::object::apply_transform(
+3 -3
View File
@@ -11,7 +11,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Pencil",
[],
None,
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end is an error, and nothing changes",
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes",
has_doc,
freehand
),
@@ -92,7 +92,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Eraser",
[],
None,
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation 0..360° clockwise; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from level), roundness?: % (100, 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0–1000, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An angle or roundness outside its range, an unknown mode, or a variation below 0 or past its range is refused with an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths lose its area, and open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added",
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation 0..360° clockwise; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from level), roundness?: % (100, 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0–1000, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An angle or roundness outside its range, an unknown mode, or a variation below 0 or past its range is refused with an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths and filled open paths without a visible painted stroke lose its area, and other open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added",
has_doc,
erase_region
),
@@ -101,7 +101,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Path Eraser",
[],
None,
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change what is erased), width?: pt (8)} erase the parts of selected paths under the drag → {ids}",
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change what is erased), width?: pt (8; from 0.001 to 1000)} erase the parts of selected paths under the drag → {ids}. A width outside 0.001 to 1000 is refused with an error, and nothing changes",
has_selection,
erase_segments
),
+32 -4
View File
@@ -345,18 +345,46 @@ pub(super) fn target_paths(doc: &Document, sel: &Selection, area: Rect) -> Vec<N
out
}
/// Any visible non-None fill, including one below a topmost None.
pub(super) fn has_fill(n: &Node) -> bool {
n.appearance.items.iter().any(|item| item.is_fill() && item.visible() && !item.paint().is_none())
}
/// A visible painted stroke keeps open paths on the existing outline-erasure route.
pub(super) fn has_painted_stroke(n: &Node) -> bool {
n.appearance.items.iter().any(
|item| matches!(item, vectorcraft_doc::AppearanceItem::Stroke(stroke) if stroke.visible && !stroke.paint.is_none() && stroke.width > 0.0),
)
}
/// A container stroke that paints this target's open geometry. A clipping container's own
/// paint follows its clipping outline, and a compound shape paints its combined area instead.
/// Neither makes its descendants' implicit fill-closing edges into new stroked edges.
pub(super) fn has_painted_ancestor_stroke(doc: &Document, id: NodeId) -> bool {
doc.ancestry(id)
.unwrap_or_default()
.into_iter()
.rev()
.skip(1)
.filter_map(|id| doc.node(id))
.take_while(|node| !node.clips() && !node.is_compound_shape())
.any(|node| matches!(node.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && has_painted_stroke(node))
}
/// [`target_paths`] for the tools that cut fills, with each target's geometry and fill rule: the
/// members of a compound path whose members are all closed paths give the compound path itself,
/// once, so its fill (holes included) is cut as one shape under its own fill rule.
pub(super) fn fill_targets(doc: &Document, sel: &Selection, area: Rect) -> Result<Vec<(NodeId, PathData, FillRule)>> {
let closed_compound = |n: &Node| {
/// With `open_fills`, an open compound with a visible fill and no painted visible stroke does too.
pub(super) fn fill_targets(doc: &Document, sel: &Selection, area: Rect, open_fills: bool) -> Result<Vec<(NodeId, PathData, FillRule)>> {
let area_compound = |n: &Node| {
let filled = open_fills && has_fill(n) && !has_painted_stroke(n) && !has_painted_ancestor_stroke(doc, n.id);
matches!(&n.kind, NodeKind::Compound { children, .. }
if children.iter().all(|c| matches!(&c.kind, NodeKind::Path { path, .. } if path.is_closed())))
if children.iter().all(|c| matches!(&c.kind, NodeKind::Path { path, .. } if path.is_closed() || filled)))
};
let editable = doc.editable();
let mut out: Vec<(NodeId, PathData, FillRule)> = vec![];
for id in target_paths(doc, sel, area) {
let compound = doc.parent_of(id).and_then(|p| doc.node(p)).filter(|p| closed_compound(p) && editable(p.id));
let compound = doc.parent_of(id).and_then(|p| doc.node(p)).filter(|p| area_compound(p) && editable(p.id));
let target = compound.map_or(id, |c| c.id);
if out.iter().any(|t| t.0 == target) {
continue;
+75 -17
View File
@@ -1,10 +1,11 @@
use super::common::{
PenRecord, SIZE_VARIATIONS, SIZES, Sample, center_strokes, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param,
poly_bounds, pressure_region, ranged, replace_with_pieces, samples_param, sibling_with, size_pressure, target_paths, usize_opt,
PenRecord, SIZE_VARIATIONS, SIZES, Sample, center_strokes, dist_to_polyline, fill_targets, has_fill, has_painted_ancestor_stroke,
has_painted_stroke, ids_json, path_mut, path_of, points_param, poly_bounds, pressure_region, ranged, replace_with_pieces, samples_param,
set_geometry, sibling_with, size_pressure, target_paths, usize_opt,
};
use super::{
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Rect, Result, Session,
SubPath, Value, Vec2, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po,
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, Document, EngineError, FillRule, Join, NodeId, NodeKind, Paint, ParamCurve, PathData, Point,
Rect, Result, Session, SubPath, Value, Vec2, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po,
};
use kurbo::{CubicBez, Line, PathSeg};
use vectorcraft_brush::{Brush, BrushKind, Calligraphic, Variation};
@@ -266,7 +267,7 @@ pub(super) fn knife(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let strip = po::outline_stroke(&PathData::single(SubPath::polyline(&pts, false)), KNIFE_GAP, Cap::Butt, Join::Round, 4.0);
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, 1.0))? {
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, 1.0), false)? {
if !pd.is_closed() {
continue;
}
@@ -340,8 +341,9 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
None => dist_to_polyline(&round, squash * q) <= r,
};
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach))? {
if pd.is_closed() {
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach), true)? {
if erase_as_area(&st.doc, id, &pd) {
let pd = eraser_fill_operand(pd);
if po::area(&po::boolean(&pd, rule, &region, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 {
continue;
}
@@ -353,6 +355,34 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
apply_plan(s, "Eraser", plan)
}
/// Whether the target is erased as filled area rather than as an open outline.
fn erase_as_area(doc: &Document, id: NodeId, pd: &PathData) -> bool {
// An unaggregated compound member keeps the outline route: its own appearance does not
// paint it. Eligible fill-only compounds were collected as one parent target above.
let compound_member =
doc.parent_of(id).and_then(|parent| doc.node(parent)).is_some_and(|parent| matches!(parent.kind, NodeKind::Compound { .. }));
let filled_open =
!compound_member && !has_painted_ancestor_stroke(doc, id) && doc.node(id).is_some_and(|node| has_fill(node) && !has_painted_stroke(node));
pd.is_closed() || filled_open
}
/// Close only Eraser's temporary fill operand, preserving an open path's straight closing edge.
fn eraser_fill_operand(mut pd: PathData) -> PathData {
for sp in &mut pd.subpaths {
if !sp.closed {
// These endpoint handles are unused by an open path. Closing it must not activate them.
if let Some(first) = sp.anchors.first_mut() {
first.h_in = first.p;
}
if let Some(last) = sp.anchors.last_mut() {
last.h_out = last.p;
}
sp.closed = true;
}
}
pd
}
/// `path.eraseRegion`'s `rect: [x, y, width, height]`: four finite numbers, with a width and a
/// height above 0.
fn marquee_param(v: &Value, cmd: &str) -> Result<Rect> {
@@ -369,7 +399,7 @@ fn marquee_param(v: &Value, cmd: &str) -> Result<Rect> {
}
/// `path.eraseRegion` with a marquee: everything inside `r` is erased from the paths (selected, or
/// all). Closed paths lose the rectangle's area, and open paths are cut where they cross its edges.
/// all). Closed paths and fill-only open paths lose the rectangle's area; other open paths are cut where they cross its edges.
fn erase_rect(s: &mut Session, r: Rect) -> Result<Value> {
let region =
PathData::single(SubPath::polyline(&[Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)], true));
@@ -392,8 +422,9 @@ fn erase_rect(s: &mut Session, r: Rect) -> Result<Value> {
};
let st = s.doc()?;
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, r)? {
if pd.is_closed() {
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, r, true)? {
if erase_as_area(&st.doc, id, &pd) {
let pd = eraser_fill_operand(pd);
if po::area(&po::boolean(&pd, rule, &region, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 {
continue;
}
@@ -492,8 +523,9 @@ fn erase_varied(s: &mut Session, samples: &[Sample], tip: [f64; 3], vary: [(Vari
let short = low(2).max(MIN_BRUSH_SIZE) * low(1).clamp(1.0, 100.0) / 100.0;
let reach = (size + sv) / 2.0;
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach))? {
if pd.is_closed() {
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach), true)? {
if erase_as_area(&st.doc, id, &pd) {
let pd = eraser_fill_operand(pd);
if po::area(&po::boolean(&pd, rule, &region, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 {
continue;
}
@@ -510,10 +542,36 @@ fn apply_plan(s: &mut Session, label: &str, plan: Vec<(NodeId, Vec<PathData>)>)
return Ok(json!({ "ids": [] }));
}
let ids = s.edit(label, |d, sel| {
// Measure every original painting owner before any geometry or appearance changes.
// This includes a Compound above a Path Eraser target and containers above live art.
let owners: std::collections::BTreeSet<_> = plan.iter().flat_map(|(id, _)| d.ancestry(*id).unwrap_or_default()).collect();
let pinned: Vec<_> = owners
.into_iter()
.filter_map(|id| {
let node = d.node(id)?;
if !node.appearance.has_unplaced_gradient() {
return None;
}
vectorcraft_render::pinned_appearance_for_geometry_edit(d, node).map(|appearance| (id, appearance))
})
.collect();
for (id, appearance) in pinned {
if let Some(node) = d.node_mut(id) {
node.appearance = appearance.into();
}
}
let mut all = vec![];
let mut cut = Beside::replacing(d, &plan.iter().map(|(id, _)| *id).collect::<Vec<_>>());
for (id, pieces) in plan {
all.extend(replace_with_pieces(d, &mut cut, id, pieces)?);
let clipping_path = d.position(id).is_some_and(|(parent, i, _)| i == 0 && parent.and_then(|p| d.node(p)).is_some_and(|p| p.clips()));
if clipping_path {
// Keep every clipping contour in its original first child slot. An empty mask
// must also stay there so the clipped artwork cannot become the new mask.
set_geometry(d, id, PathData::new(pieces.into_iter().flat_map(|p| p.subpaths).collect()))?;
all.push(id);
} else {
all.extend(replace_with_pieces(d, &mut cut, id, pieces)?);
}
}
cut.finish(d)?;
sel.set(all.iter().copied());
@@ -522,13 +580,13 @@ fn apply_plan(s: &mut Session, label: &str, plan: Vec<(NodeId, Vec<PathData>)>)
Ok(ids_json(&ids))
}
/// The Path Eraser's band width, in points (VectorCraft's own range).
const PATH_ERASER_WIDTHS: (f64, f64) = (0.001, 1000.0);
pub(super) fn erase_segments(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "path.eraseSegments";
let pts = points_param(p, "points", C)?;
let w = number_or(p, "width", 8.0, C)?;
if !(w.is_finite() && w > 0.0) {
return Err(bad(C, "width must be positive"));
}
let w = ranged(p, "width", 8.0, PATH_ERASER_WIDTHS, C)?;
let st = s.doc()?;
let mut plan = vec![];
for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, w)) {
+29 -20
View File
@@ -174,9 +174,13 @@ fn no_stroke(name: &str) -> EngineError {
bad("brush.freehand", format!("cannot apply brush `{name}`: path has no stroke"))
}
/// Sets brush `name` on the stroke of object `id` of `d`.
/// Sets brush `name` on the stroke of object `id` of `d`. The stroke's own settings for another
/// brush (Options of Selected Object) are cleared.
fn set_brush(d: &mut Document, id: NodeId, name: &str) {
if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) {
if st.brush.as_deref() != Some(name) {
st.brush_options.clear();
}
st.brush = Some(name.to_string());
}
}
@@ -209,7 +213,11 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
let label = if brush || brush_name.is_some() { "Paintbrush" } else { "Pencil" };
let keep_selected = switch_or(p, "keepSelected", true, C)?;
let filled = switch_or(p, "fill", false, C)?;
if let Some(ext) = p.get("extend").filter(|v| !v.is_null()) {
let extend = p.get("extend").filter(|v| !v.is_null());
if extend.is_none() && p.get("connect").is_some_and(|v| !v.is_null()) {
return Err(bad(C, "connect needs extend"));
}
if let Some(ext) = extend {
let id = object_param(ext, "id", C)?.ok_or_else(|| bad(C, "extend needs id"))?;
let at_start = match ext.get("end").filter(|v| !v.is_null()).map(Value::as_str) {
None | Some(Some("end")) => false,
@@ -234,26 +242,9 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
};
let Some(p0) = pts.first_mut() else { return Err(bad(C, "needs points")) };
*p0 = end;
if pts.len() < 2 {
// No stroke to add: the brush alone changes, when it is not the path's already, and the
// path is selected or deselected as a longer continuation leaves it.
if let Some(name) = brush_name
&& s.doc()?.doc.node(target).and_then(|n| n.appearance.stroke()).is_some_and(|st| st.brush.as_deref() != Some(name))
{
s.edit("Paintbrush", |d, sel| {
set_brush(d, target, name);
if keep_selected {
sel.set([id]);
} else {
sel.remove(id);
}
Ok(())
})?;
}
return Ok(json!({ "id": id.0 }));
}
// A stroke that ends on an open end of another path connects the two: (that path, its last
// open subpath, that subpath starting at the end the stroke ends on, it ends at its end).
// It is checked before a stroke of one point returns, so a bad `connect` is refused there too.
let connect = match p.get("connect").filter(|v| !v.is_null()) {
Some(cn) => {
let other = object_param(cn, "id", C)?.ok_or_else(|| bad(C, "connect needs id"))?;
@@ -276,6 +267,24 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
}
None => None,
};
if pts.len() < 2 {
// No stroke to add: the brush alone changes, when it is not the path's already, and the
// path is selected or deselected as a longer continuation leaves it.
if let Some(name) = brush_name
&& s.doc()?.doc.node(target).and_then(|n| n.appearance.stroke()).is_some_and(|st| st.brush.as_deref() != Some(name))
{
s.edit("Paintbrush", |d, sel| {
set_brush(d, target, name);
if keep_selected {
sel.set([id]);
} else {
sel.remove(id);
}
Ok(())
})?;
}
return Ok(json!({ "id": id.0 }));
}
// `closed`, when given, says whether the stroke closes the path: the Pencil and the
// Paintbrush send it, by their Close Paths When Ends Are Within and Alt at the release.
// Left out, an extending stroke that ends within four Fidelities of the path's other end
+98 -17
View File
@@ -6,6 +6,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, RulerMode, Unit};
use vectorcraft_geom::{Affine, Point, Vec2};
use vectorcraft_tools::distort::perspective::{PerspectiveGrid, Plane};
use super::clipboard::SwatchChoices;
use super::{
@@ -713,6 +714,85 @@ pub(crate) fn settle_interaction(s: &mut Session) -> Result<()> {
Ok(())
}
/// The document state that commands also change without an undo step: the perspective grid's view
/// options (whether it shows, Lock Grid, Lock Station Point, Snap to Grid and Show Rulers), its
/// active plane, the grid preferences, the export settings, and the current brush and symbol. Each
/// undo and redo step keeps it as the document on its other side had it
/// ([`crate::HistoryEntry::unrecorded`]).
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Unrecorded {
grid: vectorcraft_doc::GridPrefs,
export_settings: serde_json::Map<String, Value>,
brush: Option<Value>,
symbol: Option<Value>,
options: [bool; 5],
plane: Plane,
}
impl Unrecorded {
pub(crate) fn of(d: &Document) -> Self {
let g = PerspectiveGrid::current(d);
Unrecorded {
grid: d.grid.clone(),
export_settings: d.export_settings.clone(),
brush: d.unknown.get(vectorcraft_brush::CURRENT_KEY).cloned(),
symbol: d.unknown.get(super::brushsym::CURRENT_SYMBOL).cloned(),
options: [g.visible, g.locked, g.lock_station, g.snap, g.rulers],
plane: g.plane,
}
}
}
/// Undo and redo bring back `d`; `step` is that state as the document on the step's other side had
/// it. A part the step did not change (`d` has it as `step` does) stays as it is in `now`, the
/// document before the undo or redo, since it changed after the step without an undo step. A part
/// the step changed comes back with `d`. A current brush or symbol that `d` does not hold also
/// comes back with `d`. The point Automatic Plane Positioning holds comes back with `d`, and is let go when the
/// active plane kept is not the one it holds.
fn keep_unrecorded(now: &Document, step: &Unrecorded, d: &mut Arc<Document>) {
fn pick<T: Clone + PartialEq>(back: &T, step: &T, now: &T) -> T {
if back == step { now.clone() } else { back.clone() }
}
let back = Unrecorded::of(d);
let cur = Unrecorded::of(now);
let mut want = Unrecorded {
grid: pick(&back.grid, &step.grid, &cur.grid),
export_settings: pick(&back.export_settings, &step.export_settings, &cur.export_settings),
brush: pick(&back.brush, &step.brush, &cur.brush),
symbol: pick(&back.symbol, &step.symbol, &cur.symbol),
options: std::array::from_fn(|i| pick(&back.options[i], &step.options[i], &cur.options[i])),
plane: pick(&back.plane, &step.plane, &cur.plane),
};
if want.brush != back.brush && want.brush.as_ref().and_then(Value::as_str).is_some_and(|n| vectorcraft_brush::find(d, n).is_none()) {
want.brush = back.brush.clone();
}
if want.symbol != back.symbol && want.symbol.as_ref().and_then(Value::as_str).is_some_and(|n| !d.symbols.iter().any(|s| s.name == n)) {
want.symbol = back.symbol.clone();
}
if want == back {
return;
}
let m = Arc::make_mut(d);
for (key, v) in [(vectorcraft_brush::CURRENT_KEY, &want.brush), (super::brushsym::CURRENT_SYMBOL, &want.symbol)] {
match v {
Some(v) => m.unknown.insert(key.into(), v.clone()),
None => m.unknown.remove(key),
};
}
if (want.options, want.plane) != (back.options, back.plane) {
let mut g = PerspectiveGrid::current(m);
[g.visible, g.locked, g.lock_station, g.snap, g.rulers] = want.options;
if g.plane != want.plane {
g.plane = want.plane;
g.inferred = None;
}
g.keep_positioning_valid();
super::distortcmds::store_grid(m, &g);
}
m.grid = want.grid;
m.export_settings = want.export_settings;
}
fn undo(s: &mut Session, _: &Value) -> Result<Value> {
settle_interaction(s)?;
let menu = s.menu.clone();
@@ -723,6 +803,7 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> {
let editing = st.doc.mask_edit.map(|m| m.layer);
let editing_symbol = st.doc.symbol_edit.clone();
let doc = std::mem::replace(&mut st.doc, e.doc);
keep_unrecorded(&doc, &e.unrecorded, &mut st.doc);
let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection));
let selection = shared_selection(selection, st.history.redo.last());
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
@@ -758,6 +839,7 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> {
let editing = st.doc.mask_edit.map(|m| m.layer);
let editing_symbol = st.doc.symbol_edit.clone();
let doc = std::mem::replace(&mut st.doc, e.doc);
keep_unrecorded(&doc, &e.unrecorded, &mut st.doc);
let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection));
let selection = shared_selection(selection, st.history.undo.last());
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
@@ -1076,8 +1158,10 @@ fn cut(s: &mut Session, p: &Value) -> Result<Value> {
/// Select every surviving piece while retaining intentional compound-path structure.
/// `roots` contains the copied targets: whole-object roots are removed in full, while partial paths
/// lose only the copied geometry. An exhausted partial path is removed, along with its compound
/// parent if now empty; layers remain. Returns JSON `null` on success, replacing direct-selection
/// references with surviving object IDs.
/// parent if now empty; a compound left with one member stays a compound path, as after Clear;
/// layers remain. Removed and replaced roots go through one [`super::pathops::Beside`], which
/// rebuilds each parent's children once when the roots are separate. Returns JSON `null` on
/// success, replacing direct-selection references with surviving object IDs.
fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
let st = s.doc()?;
let sel = st.selection.clone();
@@ -1085,13 +1169,18 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
// The selected ruler guides were copied too (#3226): they go in the same undo step.
let gone = selection.guides.clone();
d.retain_guides(selection, |g| !g.id.is_some_and(|id| gone.contains(&id)));
// The compound paths that hold a root; one left with no members goes too.
let compounds: BTreeSet<NodeId> = roots
.iter()
.filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))))
.collect();
let mut survivors = vec![];
let mut pieces = super::pathops::Beside::replacing(d, roots);
for id in roots {
let Some(node) = d.node(*id) else { continue };
let has_direct = sel.anchors.contains_key(id) || sel.segments.contains_key(id);
if !has_direct || node.path_data().is_none() {
remove_leaving_no_empty_compound(d, *id)?;
pieces.put(d, *id, vec![])?;
continue;
}
let original = super::path::deletion_source(d, *id)?;
@@ -1114,12 +1203,14 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
}
subpaths.retain(|sp| sp.anchors.len() >= 2);
if subpaths.is_empty() {
remove_leaving_no_empty_compound(d, *id)?;
pieces.put(d, *id, vec![])?;
} else {
survivors.extend(super::path::replace_deleted_pieces(d, &mut pieces, original, subpaths)?);
}
}
pieces.finish(d)?;
let emptied: Vec<NodeId> = compounds.into_iter().filter(|p| d.node(*p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty()))).collect();
super::pathops::remove_each(d, &emptied)?;
selection.set(survivors);
selection.anchors.clear();
selection.segments.clear();
@@ -1128,19 +1219,6 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
ok()
}
/// Remove object `id`, and the compound path that held it when it was the compound's last member.
/// A compound left with one member stays a compound path, as after Clear.
fn remove_leaving_no_empty_compound(d: &mut Document, id: NodeId) -> Result<()> {
let parent = d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
d.remove(id)?;
if let Some(p) = parent
&& d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty()))
{
d.remove(p)?;
}
Ok(())
}
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
let guides = switch_or(p, "guides", false, "edit.clear")?;
let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None };
@@ -1751,3 +1829,6 @@ pub(crate) fn copy_above(d: &mut Document, roots: &[NodeId], mut change: impl Fn
pub(crate) fn arc_nodes(v: Vec<Node>) -> Vec<Arc<Node>> {
v.into_iter().map(Arc::new).collect()
}
#[cfg(test)]
mod tests;
+343
View File
@@ -0,0 +1,343 @@
//! Cut with direct-selected anchors removes the objects selected whole and the paths it empties
//! through one [`Beside`](super::super::pathops::Beside), and leaves the document, the selection,
//! the clipboard and the undo history exactly as removing each of them on its own does.
use std::collections::BTreeSet;
use std::time::{Duration, Instant};
use serde_json::{Value, json};
use vectorcraft_doc::{Document, NodeId, NodeKind, tree_walks};
use super::*;
use crate::tests_large_edits::{session, square};
/// Cut's removal with every root selected whole or emptied taken out by its own
/// [`Document::remove`], and its compound path removed right after when that left it empty. The
/// tests compare [`cut_direct_selection`] with it.
fn cut_one_at_a_time(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
let st = s.doc()?;
let sel = st.selection.clone();
s.edit("Cut", |d, selection| {
let gone = selection.guides.clone();
d.retain_guides(selection, |g| !g.id.is_some_and(|id| gone.contains(&id)));
let mut survivors = vec![];
let mut pieces = super::super::pathops::Beside::replacing(d, roots);
for id in roots {
let Some(node) = d.node(*id) else { continue };
let has_direct = sel.anchors.contains_key(id) || sel.segments.contains_key(id);
if !has_direct || node.path_data().is_none() {
remove_one(d, *id)?;
continue;
}
let original = super::super::path::deletion_source(d, *id)?;
let seg_refs = sel.segments.get(id);
let anchor_refs = sel.anchors.get(id);
let mut subpaths = Vec::new();
let owned = std::mem::take(&mut super::super::path::path_mut(d, *id)?.subpaths);
for (si, sp) in owned.into_iter().enumerate() {
let cuts = super::super::clipboard::subpath_selected_segments(&sp, si, seg_refs, anchor_refs);
if cuts.is_empty() {
subpaths.push(sp);
} else if seg_refs.is_some_and(|segments| !segments.is_empty()) {
subpaths.extend(super::super::path::without_segments(sp, &cuts));
} else {
let gone: BTreeSet<usize> = anchor_refs.into_iter().flat_map(|refs| super::super::path::subpath_refs(refs, si)).collect();
subpaths.extend(super::super::path::without_anchors(sp, &gone));
}
}
subpaths.retain(|sp| sp.anchors.len() >= 2);
if subpaths.is_empty() {
remove_one(d, *id)?;
} else {
survivors.extend(super::super::path::replace_deleted_pieces(d, &mut pieces, original, subpaths)?);
}
}
pieces.finish(d)?;
selection.set(survivors);
selection.anchors.clear();
selection.segments.clear();
Ok(())
})?;
ok()
}
/// Removes object `id`, and the compound path that held it when it was the compound's last member.
fn remove_one(d: &mut Document, id: NodeId) -> Result<()> {
let parent = d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
d.remove(id)?;
if let Some(p) = parent
&& d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty()))
{
d.remove(p)?;
}
Ok(())
}
/// Cut as `edit.cut` runs it for a direct selection, with [`cut_one_at_a_time`] in place of
/// [`cut_direct_selection`].
fn reference_cut(s: &mut Session) {
let (direct, roots) = copy_cut_targets(s).unwrap();
assert!(direct, "the selection is a direct selection");
copy(s, &json!({})).unwrap();
cut_one_at_a_time(s, &roots).unwrap();
}
fn run(s: &mut Session, cmd: &str, p: Value) -> Value {
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
}
/// Selects `whole` as objects, then anchors `anchors` of each path in `partial`.
fn select_direct(s: &mut Session, whole: &[NodeId], partial: &[(NodeId, Value)]) {
run(s, "select.set", json!({"ids": whole.iter().map(|id| id.0).collect::<Vec<_>>()}));
for (id, anchors) in partial {
run(s, "select.anchors", json!({"id": id.0, "anchors": anchors, "mode": "add"}));
}
}
/// The ids of every node of the document, depth first, with the depth of each.
fn tree(d: &Document) -> Vec<(usize, NodeId)> {
fn walk(n: &vectorcraft_doc::Node, depth: usize, out: &mut Vec<(usize, NodeId)>) {
out.push((depth, n.id));
for c in n.children().into_iter().flatten() {
walk(c, depth + 1, out);
}
}
let mut out = vec![];
for l in &d.layers {
walk(l, 0, &mut out);
}
out
}
/// Whether `a` and `b` hold the same document, selection, clipboard and number of undo and redo
/// steps.
fn assert_same(a: &Session, b: &Session, when: &str) {
let (x, y) = (a.doc().unwrap(), b.doc().unwrap());
assert_eq!(tree(&x.doc), tree(&y.doc), "{when}: the tree");
assert!(*x.doc == *y.doc, "{when}: the document");
assert_eq!(x.selection, y.selection, "{when}: the selection");
// Each session's document has its own uid; the clipboard names the one it came from.
assert_eq!(a.clipboard.source_doc.is_some(), b.clipboard.source_doc.is_some(), "{when}: the clipboard's source");
let unsourced = |c: &Clipboard| Clipboard { source_doc: None, ..c.clone() };
assert!(unsourced(&a.clipboard) == unsourced(&b.clipboard), "{when}: the clipboard");
assert_eq!(x.history.undo.len(), y.history.undo.len(), "{when}: the undo steps");
assert_eq!(x.history.redo.len(), y.history.redo.len(), "{when}: the redo steps");
}
/// Runs `edit.cut` on one session that `make` builds and [`reference_cut`] on another, and checks
/// that both hold the same after the Cut, after Undo and after Redo. Returns the first session after
/// the Cut.
fn same_as_one_at_a_time(make: impl Fn() -> Session) -> Session {
let (mut a, mut b) = (make(), make());
let before = a.doc().unwrap().doc.clone();
assert_same(&a, &b, "before");
run(&mut a, "edit.cut", json!({}));
reference_cut(&mut b);
assert_same(&a, &b, "Cut");
let after = a.doc().unwrap().doc.clone();
run(&mut a, "edit.undo", json!({}));
run(&mut b, "edit.undo", json!({}));
assert_same(&a, &b, "Undo");
assert!(*a.doc().unwrap().doc == *before, "Undo gives back the document");
run(&mut a, "edit.redo", json!({}));
run(&mut b, "edit.redo", json!({}));
assert_same(&a, &b, "Redo");
assert!(*a.doc().unwrap().doc == *after, "Redo gives back the Cut");
run(&mut a, "edit.undo", json!({}));
run(&mut a, "edit.redo", json!({}));
a
}
/// A new document; [`rect`] adds squares to it.
fn new_doc() -> Session {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 800, "height": 600}));
s
}
/// Adds a 10 pt square to the current layer, 20 pt right of the last one.
fn rect(s: &mut Session) -> NodeId {
let x = 20.0 * s.doc().unwrap().doc.node_count() as f64;
NodeId(run(s, "shape.rectangle", json!({"x": x, "y": 10, "width": 10, "height": 10}))["id"].as_u64().unwrap())
}
/// Makes a compound path of `ids` and returns it with its members in order.
fn compound(s: &mut Session, ids: &[NodeId]) -> (NodeId, Vec<NodeId>) {
run(s, "select.set", json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()}));
let c = NodeId(run(s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap());
let members = s.doc().unwrap().doc.node(c).unwrap().children().unwrap().iter().map(|m| m.id).collect();
(c, members)
}
/// Anchors 0 to 2 of a square: Cut leaves it no segment, so it is removed.
fn three_anchors() -> Value {
json!([[0, 0], [0, 1], [0, 2]])
}
/// Anchors 0 and 1 of a square: Cut keeps its other three sides.
fn two_anchors() -> Value {
json!([[0, 0], [0, 1]])
}
/// The compound path whose members are cut one whole and one emptied goes with them; the other
/// compound path keeps its one member left, as a compound path.
#[test]
fn cut_removes_a_compound_whose_members_all_go_and_keeps_one_with_one_member_left() {
let make = || {
let mut s = new_doc();
let first = [(); 2].map(|()| rect(&mut s));
let (gone, gone_members) = compound(&mut s, &first);
let second = [(); 3].map(|()| rect(&mut s));
let (kept, kept_members) = compound(&mut s, &second);
let other = rect(&mut s);
select_direct(
&mut s,
&[gone_members[0], kept_members[0]],
&[(gone_members[1], three_anchors()), (kept_members[1], three_anchors()), (other, two_anchors())],
);
(s, gone, kept, kept_members[2], other)
};
let s = same_as_one_at_a_time(|| make().0);
let (_, gone, kept, left, other) = make();
let d = &s.doc().unwrap().doc;
assert!(d.node(gone).is_none(), "the compound path whose members all went is removed");
let kept = d.node(kept).expect("the compound path with a member left stays");
assert!(matches!(kept.kind, NodeKind::Compound { .. }));
assert_eq!(kept.children().unwrap().iter().map(|m| m.id).collect::<Vec<_>>(), [left]);
assert_eq!(s.doc().unwrap().selection.objects, [other], "the cut square's other sides stay selected");
}
/// Objects inside two groups and on the layer, removed whole, emptied or cut apart between kept
/// siblings, keep the order and ids that removing them one at a time leaves.
#[test]
fn cut_inside_groups_keeps_the_order_and_ids_of_removing_one_at_a_time() {
let make = || {
let mut s = new_doc();
let a = [(); 4].map(|()| rect(&mut s));
run(&mut s, "select.set", json!({"ids": a.iter().map(|id| id.0).collect::<Vec<_>>()}));
run(&mut s, "object.group", json!({}));
let b = [(); 4].map(|()| rect(&mut s));
run(&mut s, "select.set", json!({"ids": b.iter().map(|id| id.0).collect::<Vec<_>>()}));
run(&mut s, "object.group", json!({}));
let c = [(); 4].map(|()| rect(&mut s));
select_direct(
&mut s,
&[a[0], a[2], b[3], c[1]],
&[(a[1], two_anchors()), (b[0], three_anchors()), (b[2], two_anchors()), (c[3], three_anchors())],
);
s
};
let s = same_as_one_at_a_time(make);
assert_eq!(s.doc().unwrap().selection.objects.len(), 2, "the two squares cut apart stay selected");
}
/// Selected ruler guides go with the objects, in the Cut's undo step.
#[test]
fn cut_removes_the_selected_guides_with_the_objects() {
let make = || {
let mut s = new_doc();
let [a, b, c] = [(); 3].map(|()| rect(&mut s));
run(&mut s, "guide.add", json!({"vertical": true, "pos": 30}));
run(&mut s, "guide.add", json!({"vertical": false, "pos": 40}));
select_direct(&mut s, &[a, c], &[(b, two_anchors())]);
run(&mut s, "guide.select", json!({"indexes": [1], "toggle": true}));
s
};
let s = same_as_one_at_a_time(make);
assert_eq!(s.doc().unwrap().doc.ruler_guides().len(), 1, "the selected guide is removed");
assert_eq!(s.clipboard.guides.len(), 1, "the selected guide is on the clipboard");
}
/// Roots that are not separate (one inside another) are removed one at a time, as before.
#[test]
fn cut_of_roots_inside_another_root_matches_removing_one_at_a_time() {
let make = || {
let mut s = new_doc();
let a = [(); 3].map(|()| rect(&mut s));
run(&mut s, "select.set", json!({"ids": a.iter().map(|id| id.0).collect::<Vec<_>>()}));
let group = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap());
let b = rect(&mut s);
select_direct(&mut s, &[group, b], &[(a[1], two_anchors())]);
(s, vec![a[1], group, b])
};
let (mut x, roots) = make();
let (mut y, _) = make();
copy(&mut x, &json!({})).unwrap();
copy(&mut y, &json!({})).unwrap();
cut_direct_selection(&mut x, &roots).unwrap();
cut_one_at_a_time(&mut y, &roots).unwrap();
assert_same(&x, &y, "Cut");
}
/// One layer of 10,000 squares with every fifth of the first 10,000 selected whole (2,000) and
/// anchors 0 and 1 of the square after them picked.
fn many() -> Session {
let mut s = session(10_001, square);
let ids = crate::tests_large_edits::layer(&s, 0);
let whole: Vec<NodeId> = ids.iter().take(10_000).step_by(5).copied().collect();
select_direct(&mut s, &whole, &[(ids[10_000], two_anchors())]);
s
}
/// The tree walks [`tree_walks`] counts while `f` runs on `s`.
fn walks(s: &mut Session, f: impl FnOnce(&mut Session)) -> u64 {
let before = tree_walks();
f(s);
tree_walks() - before
}
/// Cut of 2,000 objects selected whole among 10,000, with a direct selection, walks the document's
/// tree a few times, where removing them one at a time walks it several times for each object.
#[test]
fn direct_selection_cut_of_2000_of_10000_objects_takes_few_tree_walks() {
let s = same_as_one_at_a_time(many);
assert_eq!(crate::tests_large_edits::layer(&s, 0).len(), 8_001);
let (mut a, mut b) = (many(), many());
let batched = walks(&mut a, |s| {
run(s, "edit.cut", json!({}));
});
let one_at_a_time = walks(&mut b, reference_cut);
println!("tree walks: Cut {batched}, one at a time {one_at_a_time}");
assert!(batched <= 64, "Cut walked the document's tree {batched} times");
assert!(one_at_a_time >= 4 * batched.max(1), "one at a time walked it {one_at_a_time} times, Cut {batched}");
}
/// This thread's CPU time, where the system reports it (`/proc/thread-self/schedstat` on Linux).
fn cpu_time() -> 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 middle of `v`.
fn median(mut v: Vec<Duration>) -> Duration {
v.sort_unstable();
v[v.len() / 2]
}
/// Times Cut of [`many`] and [`reference_cut`] seven times each, in turn, and prints every run's
/// CPU and wall-clock time with the medians. Run it with
/// `cargo test --release -p vectorcraft-engine --lib -- --ignored --nocapture direct_selection_cut_timing`.
#[test]
#[ignore = "timing; prints the numbers"]
fn direct_selection_cut_timing() {
let mut runs: [(Vec<Duration>, Vec<Duration>); 2] = Default::default();
for round in 0..7 {
for (k, (cpu, wall)) in runs.iter_mut().enumerate() {
let mut s = many();
let (c0, w0) = (cpu_time(), Instant::now());
if k == 0 {
reference_cut(&mut s);
} else {
run(&mut s, "edit.cut", json!({}));
}
let w = w0.elapsed();
let c = c0.zip(cpu_time()).map(|(a, b)| b.saturating_sub(a)).unwrap_or(w);
println!("round {round} {}: cpu {c:?}, wall {w:?}", ["one at a time", "Cut"][k]);
cpu.push(c);
wall.push(w);
}
}
for (k, (cpu, wall)) in runs.into_iter().enumerate() {
println!("median {}: cpu {:?}, wall {:?}", ["one at a time", "Cut"][k], median(cpu), median(wall));
}
}
+17 -7
View File
@@ -28,7 +28,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Map Graphic",
[],
None,
"{symbol: name of a document symbol, face?: front|back (front; Plane has only a front; the back reads left to right as seen from behind; on Revolve the front is its swept side, which is the only face), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on Revolve from the middle of the side unrolled flat, x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on Revolve wrapped around the side, and drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap), Rotate (the Plane type) or Revolve; one undo step → {ids, graphic}",
"{symbol: name of a document symbol, face?: front|back|side (front; Plane has only a front; the back reads left to right as seen from behind; side is Extrude & Bevel's walls and bevels; on Revolve the front is its swept side, which is the only face), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on a side from the middle of the side unrolled flat: on Extrude & Bevel x along the outline, clockwise from its top, and y from the front toward the back; on Revolve x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Extrude & Bevel's side inside the side unrolled about x = 0, short of its cut, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on a side wrapped around it, and drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap, or on the side, hollow or not), Rotate (the Plane type) or Revolve; one undo step → {ids, graphic}",
has_doc,
map_graphic
),
@@ -113,22 +113,32 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result<Value> {
if !effects::takes_graphics(&effect.id) {
return Err(bad(C, format!("object {}: {}", id.0, effects::GRAPHICS_NOT_TAKEN)));
}
// A hollow Extrude & Bevel keeps the graphics it has, to show when Cap is turned on again,
// but has no cap to show a new one on.
// A hollow Extrude & Bevel keeps the graphics it has on its caps, to show when Cap is turned
// on again, but has no cap to show a new one on. Its side takes graphics.
let merged = effects::merged_params(&effect.id, &effect.params);
let extrude = (effect.id == effects::EXTRUDE).then(|| effects::extrude_options(&merged));
if extrude.is_some_and(|o| o.depth > 0.0 && !o.cap) {
let side = base.face == effects::PlanarFace::Side;
if !side && extrude.is_some_and(|o| o.depth > 0.0 && !o.cap) {
return Err(bad(C, format!("object {}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic", id.0)));
}
// With a depth of 0 the art is a plane, which has only a front.
if base.face == effects::PlanarFace::Back && extrude.is_some_and(|o| o.depth <= 0.0) {
if base.face != effects::PlanarFace::Front && extrude.is_some_and(|o| o.depth <= 0.0) {
return Err(bad(C, format!("object {}: with a depth of 0 the object has one face: map its graphics onto the front", id.0)));
}
let mut graphic = base.clone();
if p.get("scale").is_none()
&& let (Some(frame), Some(art)) = (effects::graphic_frame_at(Some(d), n, item, index), effects::graphic_bounds(d, &graphic.symbol))
&& let Some(art) = effects::graphic_bounds(d, &graphic.symbol)
{
graphic.scale = frame.fitting_scale(art);
// A graphic on the side starts fitting inside the side unrolled about x = 0, short of
// its cut; one on a cap inside the object's bounds.
let fit = if side {
effects::graphic_side_size(Some(d), n, item, index).map(|(w, h)| effects::graphic_fitting_scale(w, h, art))
} else {
effects::graphic_frame_at(Some(d), n, item, index).map(|frame| frame.fitting_scale(art))
};
if let Some(fit) = fit {
graphic.scale = fit;
}
}
let params = effects::with_graphic(&effects::merged_params(&effect.id, &effect.params), &graphic);
effects::validate_three_d_at_in(Some(d), n, &effect.id, &params, (item, index)).map_err(|e| bad(C, e))?;
@@ -135,6 +135,47 @@ fn map_graphic_refuses_what_cannot_take_it_and_changes_nothing() {
assert!(s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).is_ok());
}
#[test]
fn map_graphic_puts_a_graphic_on_the_side_of_an_extrude() {
let (mut s, id) = setup("threeD.extrude");
// A hollow Extrude & Bevel takes a graphic on its side.
s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"cap": false}})).unwrap();
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "y": 4.0, "ids": [id.0]})).unwrap();
assert_eq!(graphics(&s, id), json!([{"symbol": "Mark", "face": "side", "x": 0.0, "y": 4.0, "scale": 100.0, "rotation": 0.0}]));
// A plane, and a depth of 0, have no side.
let (mut s, plane) = setup("threeD.rotate");
let history = undo_len(&s);
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "ids": [plane.0]})).unwrap_err().to_string();
assert!(e.contains("one face"), "{e}");
assert_eq!(undo_len(&s), history);
let (mut s, flat) = setup("threeD.extrude");
s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"depth": 0.0}})).unwrap();
let history = undo_len(&s);
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "ids": [flat.0]})).unwrap_err().to_string();
assert!(e.contains("one face"), "{e}");
assert_eq!(undo_len(&s), history);
// A graphic taller than the side starts scaled to fit it: the side of the 100 × 100 square is
// about 300 pt wide short of its cut and 10 pt deep here, and the graphic with its stroke is
// 11 × 21.
let (mut s, id) = setup("threeD.extrude");
s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"depth": 10.0}})).unwrap();
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "ids": [id.0]})).unwrap();
let scale = graphics(&s, id)[0]["scale"].as_f64().unwrap();
assert!((scale - 1000.0 / 21.0).abs() < 1e-9, "{scale}");
// A graphic wider than the side is kept short of the cut, at a bottom corner of the square: the
// part about x = 0 is three quarters of the outline.
let (mut s, id) = setup("threeD.extrude");
let wide = s.execute("path.create", &json!({"d":"M0 380L400 380L400 390L0 390Z"})).unwrap()["id"].clone();
s.execute("threeD.addGraphic", &json!({"name": "Wide", "ids": [wide]})).unwrap();
s.execute("threeD.mapGraphic", &json!({"symbol": "Wide", "face": "side", "ids": [id.0]})).unwrap();
let d = &s.doc().unwrap().doc;
let (span, _) = vectorcraft_render::effects::graphic_side_size(Some(d), d.node(id).unwrap(), None, 0).unwrap();
let art = vectorcraft_render::effects::graphic_bounds(d, "Wide").unwrap();
assert!((span - 300.0).abs() < 1e-6 || (span - 303.0).abs() < 1e-6, "{span}");
let scale = graphics(&s, id)[0]["scale"].as_f64().unwrap();
assert!((scale - 100.0 * span / art.width()).abs() < 1e-9, "{scale}");
}
#[test]
fn set_params_edits_graphics_and_checks_them() {
let (mut s, id) = setup("threeD.extrude");
+12 -6
View File
@@ -1150,21 +1150,27 @@ fn random_brushes_baked<'a>(
std::borrow::Cow::Owned(def)
}
/// Does brush `name` of `brushes` draw different art for different points: a calligraphic or
/// scatter brush with Random variation, or a bristle brush?
fn draws_random_art(brushes: &[vectorcraft_brush::Brush], name: &str) -> bool {
/// Does brush `name` of `brushes`, with the stroke's own brush settings `options`, draw different
/// art for different points: a calligraphic or scatter brush with Random variation, or a bristle
/// brush?
fn draws_random_art(brushes: &[vectorcraft_brush::Brush], name: &str, options: &serde_json::Map<String, Value>) -> bool {
use vectorcraft_brush::{BrushKind, Variation};
brushes.iter().find(|b| b.name == name).is_some_and(|b| match &b.kind {
let Some(brush) = brushes.iter().find(|b| b.name == name) else { return false };
let edited = if options.is_empty() { None } else { brush.with_stroke_options(options).ok() };
let b = edited.as_ref().unwrap_or(brush);
match &b.kind {
BrushKind::Calligraphic(c) => c.modes().contains(&Variation::Random),
BrushKind::Scatter(s) => s.modes().contains(&Variation::Random),
BrushKind::Bristle(_) => true,
BrushKind::Art(_) | BrushKind::Pattern(_) => false,
})
}
}
/// Is `n` a path with a visible stroke whose brush varies at random ([`draws_random_art`])?
fn random_brushed(brushes: &[vectorcraft_brush::Brush], n: &Node) -> bool {
let random = |st: &vectorcraft_doc::appearance::StrokeLayer| st.visible && st.brush.as_deref().is_some_and(|b| draws_random_art(brushes, b));
let random = |st: &vectorcraft_doc::appearance::StrokeLayer| {
st.visible && st.brush.as_deref().is_some_and(|b| draws_random_art(brushes, b, &st.brush_options))
};
matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
&& n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(st) if random(st)))
}
+3 -2
View File
@@ -65,6 +65,7 @@ pub mod zip;
use serde_json::{Value, json};
pub(crate) use action_batch::action_step;
pub use action_batch::batch_overwrites_one_file;
pub use dxf::{UNSUPPORTED, Unsupported, unsupported};
pub use encode::{
@@ -95,7 +96,7 @@ pub use naming::{NameParts as FileNameParts, parse_date as parse_file_date, rend
pub(crate) use native::preview_png;
pub use native::with_compression_pref;
pub(crate) use pdfimport::opened_page_document;
pub use pdfimport::{LoadOptions, page_document};
pub use pdfimport::{LoadOptions, page_document, pages_can_link};
pub(crate) use psdlayers::import_active as psd_layers;
pub use psdlayers::{PsdInfo, info as psd_info};
pub(crate) use psdslices::over as psd_slices;
@@ -133,7 +134,7 @@ mod formats;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) use access::list_dir;
pub(crate) use access::{check_images_in, check_scripts_of};
pub(crate) use access::{check_images_in, check_scripts_of, with_readable_settings_folder};
pub use access::{check_linked_images, check_linked_scripts, write_file_with, write_save_file, write_save_file_with};
#[cfg(all(test, not(target_arch = "wasm32")))]
+46 -7
View File
@@ -144,8 +144,9 @@ pub(crate) fn check_scripts_of(cmd: &str, doc: &vectorcraft_doc::Document, doc_p
}
/// Does a file of a document with `artboards` artboards, written in format `format` with options
/// `p`, name the JavaScript files the document links? SVG, SVGZ, native files, native templates and
/// EPS files always do. A `.ai` or `.ait` file does unless it is a legacy version 7 `.ai` file or `p`
/// `p`, name the JavaScript files the document links? SVG, SVGZ, native files, native templates,
/// EPS files and the files of an exporter plug-in's format (`plugin.<id>`, whose plug-in is given
/// the native document's JSON) always do. A `.ai` or `.ait` file does unless it is a legacy version 7 `.ai` file or `p`
/// picks only some of the artboards; a PDF does with Preserve Editing on (as its preset, standard and
/// options leave it) unless `p` picks only some of the artboards. Neither a `.ai` file nor a PDF
/// does when `useArtboards` is false in `p` (one page, the bounds of the art). Options the encoder
@@ -159,6 +160,7 @@ pub(crate) fn names_linked_scripts(cmd: &str, format: &str, p: &Value, artboards
let art_page = || super::encode::use_artboards(cmd, p).is_ok_and(|u| u == Some(false));
match format {
"svg" | "svgz" | "vectorcraft" | "template" | "eps" => true,
_ if vectorcraft_plugins::export::plugin_id(format).is_some() => true,
"ai" | "ait" => {
let legacy = super::format(format).is_some_and(|f| super::legacy_ai::wanted(cmd, f, p).unwrap_or(false));
!legacy && !(format == "ai" && art_page()) && every_artboard()
@@ -171,13 +173,14 @@ pub(crate) fn names_linked_scripts(cmd: &str, format: &str, p: &Value, artboards
}
}
/// The error for an SVG that would name a linked image's file outside the read roots.
/// The error for a file that would name a linked image's file outside the read roots.
pub(crate) const IMAGE_OUTSIDE: &str = "a linked image file is outside the read roots";
/// `cmd` may write `d`, the document an output of `st` writes (all of it, or the objects it
/// exports), in format `format` (a format id) with options `p`: any format but SVG and SVGZ, and
/// those too unless read roots are in force and the file would name a linked image's file outside
/// them (a relative path taken from `st`'s folder; a URL is not checked). An `<image>` names the
/// exports), in format `format` (a format id) with options `p`: always, unless read roots are in
/// force and the file would name a linked image's file outside them (a relative path taken from
/// `st`'s folder; a URL is not checked). In any format but SVG and SVGZ, the file names them when it
/// carries the native document ([`check_native_images`]). An `<image>` names the
/// file with SVG Options › Images set to Link, and with Embed when the document holds no pixels for
/// the image, for the images of the art each file draws (with chosen artboards, the art over each
/// one; hidden layers and objects only with `hiddenLayers`, template layers and the opacity-mask
@@ -193,9 +196,12 @@ pub fn check_linked_images(cmd: &str, format: &str, st: &crate::DocState, d: &ve
/// [`check_linked_images`] for `d`, a document whose links are looked for from `base` (the
/// objects on the clipboard, looked for from the document they came from).
pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Document, base: crate::cmd::links::LinkBase, p: &Value) -> Result<()> {
if !matches!(format, "svg" | "svgz") || crate::file_access::current().is_none() {
if crate::file_access::current().is_none() {
return Ok(());
}
if !matches!(format, "svg" | "svgz") {
return check_native_images(cmd, format, d, base, p);
}
// Options that don't read as the encoder's choices count as Link, Preserve Editing, hidden
// layers kept and SVG 1.1: the encoder refuses them anyway.
let (link, preserve, hidden, tiny) = match super::svg::options_map(p) {
@@ -222,6 +228,39 @@ pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Docu
Ok(())
}
/// `cmd` may write `d` in format `format` (a format id other than SVG and SVGZ) with options `p`:
/// always, unless read roots are in force, the file carries the native document (a native file or
/// template, an EPS file, a `.ai` or `.ait` file, a PDF with Preserve Editing or an exporter
/// plug-in's file, as
/// [`names_linked_scripts`] counts them with `d`'s artboards) and that document names a file
/// outside them ([`crate::cmd::links::names_hidden_file`]: a linked image or placed file, the
/// relative path kept of one taken from `base`, a data set's image, or stored brushes that can't be
/// read). The error names no file or folder.
pub(crate) fn check_native_images(
cmd: &str,
format: &str,
d: &vectorcraft_doc::Document,
base: crate::cmd::links::LinkBase,
p: &Value,
) -> Result<()> {
let carried =
crate::file_access::current().is_some() && !matches!(format, "svg" | "svgz") && names_linked_scripts(cmd, format, p, d.artboards.len());
if carried && crate::cmd::links::names_hidden_file(d, base) { Err(bad(cmd, IMAGE_OUTSIDE)) } else { Ok(()) }
}
/// `doc` as a file written for the request being served carries it: without an Export for Screens
/// `folder` outside the read roots ([`super::screens::leave_out_unreadable_settings_folder`]). The
/// open document keeps it.
pub(crate) fn with_readable_settings_folder(doc: &vectorcraft_doc::Document) -> std::borrow::Cow<'_, vectorcraft_doc::Document> {
let settings = super::screens::leave_out_unreadable_settings_folder(doc.export_settings.clone());
if settings.len() == doc.export_settings.len() {
return std::borrow::Cow::Borrowed(doc);
}
let mut kept = doc.clone();
kept.export_settings = settings;
std::borrow::Cow::Owned(kept)
}
/// `path` checked for writing against the automation roots in force.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn may_write(path: &str) -> Result<()> {
+117 -32
View File
@@ -54,24 +54,19 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result<Value> {
}
for (i, c) in cmds.iter().enumerate() {
let id = c.get("command").and_then(Value::as_str).unwrap_or("");
let refuse = |reason: &str| bad(C, action_step(i, id, reason));
if id.is_empty() {
return Err(bad(C, format!("commands[{i}]: missing `command`")));
return Err(refuse("missing `command`"));
}
if id == "command.batch" || id == "action.batch" {
return Err(bad(C, "batches cannot nest"));
return Err(refuse("batches cannot nest"));
}
// `command.batch` refuses the batch when it reaches this step, which would fail every file or data set it plays.
if id == "prefs.import" {
return Err(bad(C, format!("commands[{i}]: `prefs.import` runs on its own, not as a batch step")));
return Err(refuse("`prefs.import` runs on its own, not as a batch step"));
}
if find_command(id).is_none() {
return Err(bad(
C,
match super::super::params::nearest_command(id) {
Some(near) => format!("commands[{i}]: unknown command `{id}`; did you mean `{near}`?"),
None => format!("commands[{i}]: unknown command `{id}`"),
},
));
return Err(refuse(&super::super::params::unknown_command(id).to_string()));
}
}
// Every option is checked before the destination folder is made.
@@ -160,7 +155,7 @@ pub fn batch_overwrites_one_file(s: &Session, p: &Value) -> bool {
Some(f) => own_format.is_some_and(|own| super::format(f).is_some_and(|f| f.id == own)),
};
match c.get("command").and_then(Value::as_str).unwrap_or("") {
"document.save" | "file.save" => !save && (path || own_file()),
"document.save" => !save && (path || own_file()),
"file.saveAs" => !save && path,
"file.saveCopy" | "file.saveAsTemplate" => path,
"document.export" | "document.exportSelection" => !export && path,
@@ -184,7 +179,7 @@ fn saves_move_to_each_file(steps: &[Value], redirected: bool) -> bool {
/// in the destination folder when `redirected`) and makes that file the document's own: a save in
/// the native template format writes a copy and leaves the document's file as it was.
fn retargeting_save(c: &Value, redirected: bool) -> bool {
if !matches!(c.get("command").and_then(Value::as_str), Some("document.save" | "file.save" | "file.saveAs")) {
if !matches!(c.get("command").and_then(Value::as_str), Some("document.save" | "file.saveAs")) {
return false;
}
let params = c.get("params");
@@ -219,7 +214,7 @@ fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run:
// open, so its artboard files count ([`dataset_output_paths`]). No output takes the name of a
// source file in the destination folder, other than that file's own output, or of a subfolder
// of the destination folder that holds source files.
let (steps, places) = filter_steps(run.steps, override_open, false);
let (steps, places) = filter_steps(run.steps, override_open);
let run = Run { steps: &steps, ..*run };
let in_dest: Vec<Option<(String, bool)>> = files.iter().map(|path| name_in_folder(path, run.dest_folder)).collect();
let mut picker =
@@ -272,7 +267,7 @@ fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result<Value> {
}
let doc_stem = st.path.as_deref().and_then(|p| std::path::Path::new(p).file_stem().and_then(|s| s.to_str())).unwrap_or("Untitled").to_string();
let stems = dataset_stems(&names, &doc_stem, run.dataset_file_naming, run, &st.doc)?;
let (steps, places) = filter_steps(run.steps, true, false);
let (steps, places) = filter_steps(run.steps, true);
let run = Run { steps: &steps, ..*run };
let mut processed = Vec::new();
let mut failed = 0usize;
@@ -353,22 +348,13 @@ impl StemPicker {
}
}
/// Drop Open (and optionally Close) steps when the batch supplies the file itself → the steps that
/// stay, and the index of each in `cmds`.
/// Drop the `document.open` steps when `drop_open` (the batch opens each source file itself) → the
/// steps that stay, and the index of each in `cmds`.
#[cfg(not(target_arch = "wasm32"))]
fn filter_steps(cmds: &[Value], drop_open: bool, drop_close: bool) -> (Vec<Value>, Vec<usize>) {
fn filter_steps(cmds: &[Value], drop_open: bool) -> (Vec<Value>, Vec<usize>) {
cmds.iter()
.enumerate()
.filter(|(_, c)| {
let id = c.get("command").and_then(Value::as_str).unwrap_or("");
if drop_open && matches!(id, "document.open" | "file.open") {
return false;
}
if drop_close && matches!(id, "file.close" | "document.close") {
return false;
}
true
})
.filter(|(_, c)| !(drop_open && c.get("command").and_then(Value::as_str) == Some("document.open")))
.map(|(i, c)| (c.clone(), i))
.unzip()
}
@@ -385,12 +371,24 @@ fn play_steps(s: &mut Session, run: &Run<'_>, places: &[usize], commands: Vec<Va
let Some((n, id, reason)) = batch_step_failure(&text) else { return e };
let same = run.steps.get(n).and_then(|c| c.get("command")).and_then(Value::as_str) == Some(id);
match places.get(n) {
Some(place) if same => EngineError::Other(format!("action step {} (`{id}`) failed: {reason}", place + 1)),
Some(&place) if same => EngineError::Other(action_step(place, id, reason)),
_ => e,
}
})
}
/// The text naming the member at `index` of an `action.batch`'s `commands`, counted from 1, with
/// its command id when it has one, and `reason`: ``action step 2 (`object.move`) failed: …``. The
/// checks before a batch runs and the errors of its steps as they run give the same text.
pub(crate) fn action_step(index: usize, id: &str, reason: &str) -> String {
let n = index.saturating_add(1);
if id.is_empty() {
format!("action step {n} failed: {reason}")
} else {
format!("action step {n} (`{}`) failed: {reason}", vectorcraft_apischema::shown_key(id))
}
}
/// The step number, command id and reason in the error `command.batch` gives when one of its steps
/// fails (``batch step 2 (`object.move`) failed: …``); none for any other error.
#[cfg(not(target_arch = "wasm32"))]
@@ -540,7 +538,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, def
outputs.push(DatasetOutput { ext: String::new(), artboards: false, joiner: "-", folder: true });
continue;
}
let writes = (run.override_save && matches!(id, "document.save" | "file.save" | "file.saveAs"))
let writes = (run.override_save && matches!(id, "document.save" | "file.saveAs"))
|| (run.override_export && matches!(id, "document.export" | "document.exportSelection"));
if writes {
let format = step.get("params").and_then(|p| p.get("format")).and_then(Value::as_str).filter(|f| !f.is_empty());
@@ -551,7 +549,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, def
};
if safe_extension(&ext) {
let format_id = super::format(format.unwrap_or(default_ext)).map(|f| f.id).unwrap_or("vectorcraft");
let is_save = matches!(id, "document.save" | "file.save" | "file.saveAs");
let is_save = matches!(id, "document.save" | "file.saveAs");
let artboards = if is_save {
!doc.artboards.is_empty() && matches!(format_id, "vectorcraft" | "template" | "ai" | "ait")
} else {
@@ -693,7 +691,7 @@ fn rewrite_paths(
.map(|c| {
let id = c.get("command").and_then(Value::as_str).unwrap_or("");
let mut c = c.clone();
let rewrite = (override_save && matches!(id, "document.save" | "file.save" | "file.saveAs"))
let rewrite = (override_save && matches!(id, "document.save" | "file.saveAs"))
|| (override_export && matches!(id, "document.export" | "document.exportForScreens" | "document.exportSelection" | "assets.export"));
if !rewrite {
return c;
@@ -2385,10 +2383,97 @@ mod tests {
let mut s = Session::new();
let p = json!({"folder": src.to_string_lossy(), "commands": [{"command": "object.unlockAll"}, {"command": "prefs.import", "params": {}}]});
let e = s.execute("action.batch", &p).unwrap_err().to_string();
assert!(e.contains("commands[1]: `prefs.import` runs on its own, not as a batch step"), "{e}");
assert!(e.contains("action step 2 (`prefs.import`) failed: `prefs.import` runs on its own, not as a batch step"), "{e}");
assert!(s.active().is_none(), "no file was opened");
}
/// Each step the checks before the batch refuse is named by its place in `commands`, from 1,
/// as a step that fails as it runs is, and no source file is opened.
#[test]
fn a_refused_step_is_named_by_its_place_from_1() {
let src = tmp("step-number-refused-src");
write_svg(&src, "a.svg", "#f00");
let prefix = "invalid parameters for `action.batch`: ";
let cases = [
(json!({"params": {}}), "action step 2 failed: missing `command`"),
(json!({"command": "select.al"}), "action step 2 (`select.al`) failed: unknown command `select.al`; did you mean `select.all`?"),
(json!({"command": "command.batch", "params": {"commands": []}}), "action step 2 (`command.batch`) failed: batches cannot nest"),
(json!({"command": "action.batch", "params": {}}), "action step 2 (`action.batch`) failed: batches cannot nest"),
(
json!({"command": "view.saved.new", "params": {"center": [0, 0], "zoom": 0}}),
"action step 2 (`view.saved.new`) failed: invalid parameters for `view.saved.new`: `zoom` must be a number > 0, not 0",
),
];
for (step, want) in cases {
let mut s = Session::new();
let p = json!({"folder": src.to_string_lossy(), "commands": [{"command": "object.unlockAll"}, step]});
let e = s.execute("action.batch", &p).unwrap_err().to_string();
assert_eq!(e, format!("{prefix}{want}"), "{step}");
assert!(s.active().is_none(), "{step}: a file was opened");
assert!(s.journal.is_empty(), "{step}: a step ran");
}
}
/// The parameter check of an `action.batch` names the step whose params it refuses, from 1;
/// that of a `command.batch` passes the step's error on as it is.
#[test]
fn the_parameter_check_names_the_refused_step() {
let bad_view = json!({"command": "view.saved.new", "params": {"center": [0, 0], "zoom": 0}});
let commands = json!([{"command": "object.unlockAll"}, {"command": "select.all"}, bad_view]);
let own = "invalid parameters for `view.saved.new`: `zoom` must be a number > 0, not 0";
let e = crate::cmd::params::check_params("action.batch", &json!({"commands": commands})).unwrap_err().to_string();
assert_eq!(e, format!("invalid parameters for `action.batch`: action step 3 (`view.saved.new`) failed: {own}"));
let e = crate::cmd::params::check_params("command.batch", &json!({"commands": commands})).unwrap_err().to_string();
assert_eq!(e, own);
}
/// The ids of the File menu's Open… and Save in the app (`file.open`, `file.save`) and
/// `document.close` are not engine commands, so a step with one is refused before the batch
/// starts, with Override Open and Override Save on or off.
#[test]
fn steps_with_ids_that_are_not_engine_commands_are_refused() {
let src = tmp("step-number-aliases-src");
write_svg(&src, "a.svg", "#f00");
for id in ["file.open", "file.save", "document.close"] {
for overrides in [true, false] {
let mut s = Session::new();
let p = json!({
"folder": src.to_string_lossy(),
"overrideOpen": overrides,
"overrideSave": overrides,
"commands": [{"command": "object.unlockAll"}, {"command": id, "params": {}}],
});
let e = s.execute("action.batch", &p).unwrap_err().to_string();
assert!(
e.starts_with(&format!("invalid parameters for `action.batch`: action step 2 (`{id}`) failed: unknown command `{id}`")),
"{e}"
);
assert!(s.active().is_none(), "{id}: a file was opened");
}
}
}
/// `command.batch` keeps its own numbering, from 0, for a step that fails.
#[test]
fn command_batch_keeps_its_own_step_numbers() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let e = s
.execute("command.batch", &json!({"commands": [{"command": "object.unlockAll"}, {"command": "object.align", "params": {}}]}))
.unwrap_err();
assert!(e.to_string().starts_with("batch step 1 (`object.align`) failed: "), "{e}");
}
/// A step's id in the error is cut short, as an unknown key's is.
#[test]
fn a_long_step_id_is_cut_short() {
let id = "x".repeat(10_000);
let shown = action_step(0, &id, "why");
assert!(shown.len() < 1_000, "{}", shown.len());
assert!(shown.starts_with("action step 1 (`xxx") && shown.ends_with("…`) failed: why"), "{shown}");
assert_eq!(action_step(usize::MAX, "", "why"), format!("action step {} failed: why", usize::MAX));
}
/// Only the error `command.batch` gives for a failed step is read as one.
#[test]
fn batch_step_failure_reads_only_a_step_error() {
+1 -1
View File
@@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Batch…",
[],
None,
"{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest, and a prefs.import step is refused (commands[i], from 0) before any file is opened. A switch (includeSubdirs, overrideOpen, overrideSave, overrideExport, stopOnError) that is not true or false, or a source, folder, destination, destinationFolder, datasetFileNaming or label that is not a string, is an error before any folder is made or file opened; null reads as left out. A step that fails is named in the error by its place in commands, from 1, counting the Open steps the batch skips (action step 3 (`object.align`) failed: …); the batch's own opening of a file, choosing of a data set and destination save, export or close give their errors without a step number. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)",
"{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. A step without a command, with a command the engine doesn't have, with params its command refuses, or with command.batch, action.batch or prefs.import (batches cannot nest) is refused before any file is opened, named by its place in commands, from 1 (action step 2 (`select.al`) failed: unknown command `select.al`; did you mean `select.all`?). A switch (includeSubdirs, overrideOpen, overrideSave, overrideExport, stopOnError) that is not true or false, or a source, folder, destination, destinationFolder, datasetFileNaming or label that is not a string, is an error before any folder is made or file opened; null reads as left out. A step that fails as it runs is named the same way, counting the Open steps the batch skips (action step 3 (`object.align`) failed: …); the batch's own opening of a file, choosing of a data set and destination save, export or close give their errors without a step number. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)",
always,
action_batch::action_batch
),
+3 -2
View File
@@ -226,9 +226,10 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) ->
vec![(Some(b), rect(b)?, false)]
}
};
let regions: Vec<(Rect, bool)> = drawings.iter().map(|&(_, region, crop)| (region, crop)).collect();
let outs = vectorcraft_cad::export_drawings(doc, &opts, &regions).map_err(|e| bad(C, e))?;
let mut enc = Encoded::default();
for (board, region, crop) in drawings {
let out = vectorcraft_cad::export(doc, &DxfOptions { region, crop, ..opts.clone() }).map_err(|e| bad(C, e))?;
for ((board, _, _), out) in drawings.into_iter().zip(outs) {
enc.files.push((board, out.bytes));
for w in out.warnings {
if !enc.warnings.contains(&w) {
+6 -4
View File
@@ -1053,12 +1053,14 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result<Encoded> {
/// The file exporter plug-in `plugin` writes of `doc` in its format `f`
/// ([`vectorcraft_plugins::export`]). The plug-in is given the native file's JSON
/// ([`vectorcraft_format::json_part`]) and `p`'s `params`, for the file `p`'s `path` names (else
/// one named after the document) with that path's extension when the plug-in lists it, else its
/// first. Its warnings come back with the file, as losses (the plug-in gives them no kind).
/// ([`vectorcraft_format::json_part`]), without an Export for Screens folder outside the read roots
/// ([`super::access::with_readable_settings_folder`]), and `p`'s `params`, for the file `p`'s `path`
/// names (else one named after the document) with that path's extension when the plug-in lists it,
/// else its first. Its warnings come back with the file, as losses (the plug-in gives them no kind).
fn plugin_file(doc: &Document, plugin: &vectorcraft_plugins::Plugin, f: &Format, p: &Value) -> Result<Encoded> {
use vectorcraft_plugins::{Error, export};
let doc = &*doc.without_edit_modes();
let doc = doc.without_edit_modes();
let doc = &*super::access::with_readable_settings_folder(&doc);
let file = vectorcraft_format::save_with(doc, &vectorcraft_format::SaveOptions::default()).map_err(|e| EngineError::Other(e.to_string()))?;
let path = p.get("path").and_then(Value::as_str);
let listed = path.map(super::extension).and_then(|e| f.extensions.iter().copied().find(|x| *x == e));
+3 -1
View File
@@ -280,8 +280,10 @@ fn thumbnail_of(preview: &Rendered, rect: Rect) -> Result<Raster> {
}
/// What the file carries to reopen: `doc` (with only artboard `board` when the file is one of
/// several artboards), with linked images whole when `include_linked`.
/// several artboards), with linked images whole when `include_linked`, and without an Export for
/// Screens folder outside the read roots ([`super::access::with_readable_settings_folder`]).
fn native(doc: &Document, board: Option<usize>, include_linked: bool) -> Vec<u8> {
let doc = &*super::access::with_readable_settings_folder(doc);
let several = board.filter(|_| doc.artboards.len() > 1);
if several.is_none() && !include_linked {
return vectorcraft_format::save(doc, false);
+2 -2
View File
@@ -838,13 +838,13 @@ fn other_open_filters() -> impl Iterator<Item = (&'static str, &'static [&'stati
/// Open-dialog filters for Swatch Libraries and Graphic Style Libraries Other Library… and Locate
/// Library…. The library formats come first so Linux file portals (which grey out files that don't
/// match the default filter) still list `.ase` and the other library extensions; then the same
/// filters as [`builtin_open_filters`], without a second copy of the library filter, so a document
/// filters as [`builtin_open_filters`], without a second filter of that label, so a document
/// can be picked for its swatches or graphic styles.
pub fn library_open_filters(
library_label: &'static str,
library_exts: &'static [&'static str],
) -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
std::iter::once((library_label, library_exts)).chain(builtin_open_filters().filter(move |f| *f != (library_label, library_exts)))
std::iter::once((library_label, library_exts)).chain(builtin_open_filters().filter(move |f| f.0 != library_label))
}
/// File → Place dialog filters: "All placeable files", then one per placeable format, then text,
+6 -3
View File
@@ -26,13 +26,16 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>, kin
Some(true) => pick.resolve(n).map_err(|e| bad(C, e))?.unwrap_or_else(|| (0..n).collect()),
_ => vec![pick.one(n).map_err(|e| bad(C, e))?],
};
let rects = boards
.iter()
.map(|&b| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1))))
.collect::<Result<Vec<_>>>()?;
// Raster effects (shadows, glows, blurs) as images, as PDF export does.
let flat = crate::flatten_raster_effects(doc);
let src = flat.as_ref().unwrap_or(doc);
let outs = vectorcraft_metafile::export_regions(src, &rects, kind).map_err(|e| bad(C, e))?;
let mut enc = Encoded::default();
for b in boards {
let region = doc.artboards.get(b).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)))?.rect;
let out = vectorcraft_metafile::export(src, region, kind).map_err(|e| bad(C, e))?;
for (b, out) in boards.into_iter().zip(outs) {
enc.files.push((Some(b), out.bytes));
for w in out.warnings {
if !enc.warnings.contains(&w) {
+4
View File
@@ -231,6 +231,8 @@ pub(super) fn encode_to(cmd: &str, f: &Format, doc: &Document, p: &Value, w: imp
}
other => other,
};
// Without an Export for Screens folder outside the read roots.
let native = super::access::with_readable_settings_folder(&native);
so.pretty = so.pretty_fits(&native);
vectorcraft_format::save_to(&native, &so, w).map_err(|e| bad(cmd, e.to_string()))
}
@@ -308,6 +310,8 @@ pub(super) fn ai_native(cmd: &str, doc: &Document, so: &SaveOptions) -> Result<V
} else {
Cow::Borrowed(doc)
};
// Without an Export for Screens folder outside the read roots.
let native = super::access::with_readable_settings_folder(&native);
vectorcraft_format::save_with(&native, so).map_err(|e| bad(cmd, e.to_string()))
}
File diff suppressed because one or more lines are too long
@@ -222,6 +222,13 @@ fn page_options(page: usize, o: &LoadOptions) -> ImportOptions {
ImportOptions { pages: Some(vec![page]), crop: o.crop, password: o.password.clone(), text_as: o.text_as, layers: false, ..Default::default() }
}
/// Whether `document.open`'s `linkPages` takes the file `name` holding `bytes`: a PDF or a
/// PDF-compatible `.ai` or `.ait` of at most [`document::MAX_FILE`] bytes. Its path, a password
/// and `textAs` are checked apart ([`linked_pages`]).
pub fn pages_can_link(name: &str, bytes: &[u8]) -> bool {
bytes.len() <= document::MAX_FILE && document::is_pdf(name, bytes)
}
/// `document.open` with `linkPages`: the pages `o` picks of the PDF (or PDF-compatible `.ai` or
/// `.ait`) `name`, read from `path`, as a document holding one placed document per page, linked to
/// that page of the file as File › Place with Link places one ([`document::source`]). Each page
+5 -1
View File
@@ -896,7 +896,10 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
params.entry("hiddenLayers").or_insert(Value::Bool(true));
}
let params = Value::Object(params);
super::check_linked_images(cmd, plan.format.id, st, &own, &params)?;
// Other formats are checked below, with the options the encoder reads.
if is_svg(plan.format) {
super::check_linked_images(cmd, plan.format.id, st, &own, &params)?;
}
// The file the document is saved as (else its own) titles it if New's name is all it has.
let file = plan.path.as_deref().filter(|_| plan.retargets()).or(st.path.as_deref());
if let Some(d) = super::titled_for_export(&own, file, plan.format.id) {
@@ -941,6 +944,7 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
_ => std::borrow::Cow::Borrowed(&params),
};
super::check_linked_scripts(cmd, plan.format.id, st, &checked)?;
super::access::check_native_images(cmd, plan.format.id, &st.doc, crate::cmd::links::LinkBase::of(st), &checked)?;
Ok(SaveJob { plan, doc, params, snapshot, source: st.doc.clone(), stamped, boards })
}
+43 -15
View File
@@ -1129,6 +1129,28 @@ fn names_scripts(item: &Item, r: &Row, single: Option<&[usize]>) -> bool {
super::access::names_linked_scripts(C, "pdf", &options, doc.artboards.len())
}
/// The document the file of `item` that row `r` writes carries when it carries one
/// ([`names_scripts`]): Full Document's PDF of every artboard, the item's artboard alone for a
/// native, `.ai` or EPS row ([`board_document`]), else the item's document.
fn carried_document<'a>(item: &'a Item, r: &Row, single: Option<&[usize]>) -> std::borrow::Cow<'a, Document> {
match (&item.every_artboard, r.format.id, single) {
(Some(all), "pdf", None) => std::borrow::Cow::Borrowed(&**all),
_ if r.whole_document() && item.artboard.is_some() => std::borrow::Cow::Owned(board_document(item)),
_ => std::borrow::Cow::Borrowed(&*item.doc),
}
}
/// The document a native, `.ai` or EPS row writes for `item`'s artboard: that artboard alone, with
/// its background color and the art on it, as Save's separateArtboards writes it (#3868).
fn board_document(item: &Item) -> Document {
let mut d = single_artboard(&item.doc, item.region, &item.name);
if let (Some(a), Some(from)) = (d.artboards.first_mut(), item.doc.artboards.get(item.artboard.unwrap_or(0))) {
a.color = from.color;
}
super::save::keep_art_on(&mut d, item.region);
d
}
/// Every chosen artboard (asset, layer, selected object) in every format row, one file each (a PDF
/// holds its artboard alone), or with `fullDocument` one file per row (a PDF of every artboard,
/// else the bounds of all art). Items that share a name get `-2`, `-3`… instead of overwriting, and
@@ -1177,6 +1199,23 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
super::check_images_in(C, r.format.id, &item.doc, base, &r.options_for(item.region, item.artboard)?)?;
}
}
// The native document the files of the other rows carry, each document looked through once.
if crate::file_access::current().is_some() {
let mut looked: HashSet<(usize, bool, Option<usize>)> = HashSet::new();
for r in rows.iter().filter(|r| !matches!(r.format.id, "svg" | "svgz")) {
// A single-file PDF carries the first item's document alone, as the writer writes it.
let carried = items.iter().enumerate().filter(|(index, _)| !(single.is_some() && r.format.id == "pdf" && *index > 0));
for (_, item) in carried.filter(|(_, i)| names_scripts(i, r, single.as_deref())) {
let all = item.every_artboard.is_some() && r.format.id == "pdf" && single.is_none();
let board = item.artboard.filter(|_| !all && r.whole_document());
if looked.insert((Arc::as_ptr(&item.doc) as usize, all, board))
&& crate::cmd::links::names_hidden_file(&carried_document(item, r, single.as_deref()), base)
{
return Err(bad(C, super::access::IMAGE_OUTSIDE));
}
}
}
}
// 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!({}) };
@@ -1318,8 +1357,9 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
}
Ok(bytes)
};
// A whole-document copy of an artboard, for the formats that write documents to edit.
let mut board_docs: std::collections::HashMap<usize, Arc<Document>> = std::collections::HashMap::new();
// A whole-document copy of an artboard of an item's document, for the formats that write
// documents to edit.
let mut board_docs: std::collections::HashMap<(usize, usize), Arc<Document>> = std::collections::HashMap::new();
let mut files = 0u64;
// One step per item and row, the files a name collision skips included.
let steps = (items.len() * rows.len()) as u64;
@@ -1358,19 +1398,7 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
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).
let d = board_docs
.entry(b)
.or_insert_with(|| {
let mut d = single_artboard(&item.doc, item.region, &item.name);
// It keeps its background color.
if let (Some(a), Some(from)) = (d.artboards.first_mut(), item.doc.artboards.get(b)) {
a.color = from.color;
}
super::save::keep_art_on(&mut d, item.region);
Arc::new(d)
})
.clone();
let d = board_docs.entry((Arc::as_ptr(&item.doc) as usize, b)).or_insert_with(|| Arc::new(board_document(item))).clone();
let mut options = r.options_for(item.region, None)?;
// An EPS page is the artboard, not its art's bounds: an artboard without art still writes.
if r.format.id == "eps" {
+1 -7
View File
@@ -183,13 +183,7 @@ pub(super) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) ->
/// The native document Preserve Editing embeds: `doc`, without an Export for Screens `folder`
/// outside the read roots of the request being served (the open document keeps it).
fn native_attachment(doc: &Document) -> Vec<u8> {
let settings = super::screens::leave_out_unreadable_settings_folder(doc.export_settings.clone());
if settings.len() == doc.export_settings.len() {
return vectorcraft_format::save(doc, false);
}
let mut kept = doc.clone();
kept.export_settings = settings;
vectorcraft_format::save(&kept, false)
vectorcraft_format::save(&super::access::with_readable_settings_folder(doc), false)
}
/// Encode `doc` as SVG (or gzipped, SVGZ): one file per chosen artboard, with the images they
+13
View File
@@ -492,6 +492,19 @@ fn library_open_filters_list_library_formats_first() {
}
}
/// Other Library…'s Swatch Libraries filter lists the `.ai` and `.eps` documents whose swatches load
/// as a library, and it is the only filter of that label.
#[test]
fn the_swatch_library_filter_lists_ai_and_eps_files() {
let filters: Vec<_> = library_open_filters("Swatch libraries", crate::cmd::swatchlib::LIBRARY_PICK_EXTS).collect();
for ext in ["ai", "ait", "eps", "epsf", "ase", "gpl", "acb", "vcswatches"] {
assert!(filters[0].1.contains(&ext), "{ext}: {:?}", filters[0]);
}
assert_eq!(filters.iter().filter(|f| f.0 == "Swatch libraries").count(), 1, "{filters:?}");
// File › Open still opens a `.ai` as a document, not as a swatch library.
assert!(!crate::cmd::swatchlib::LIBRARY_EXTS.contains(&"ai") && !opens_as_other("ai"));
}
/// The extensions usage texts list for export: one per writable format, each picking that format
/// (`.png` picks PNG; PNG-8 is asked for by `format`).
#[test]
@@ -413,6 +413,114 @@ fn a_swatch_library_in_a_ai_file_without_layers_loads_its_palette() {
assert!(matches!(sky, Some(vectorcraft_color::Paint::Gradient(_))), "{sky:?}");
}
/// A `.ai` swatch library (a palette and no layers) holding White, the gradient Sky and, in the
/// color group Textures, the swatch Tiles of the 4 pt pattern Dots, whose square is painted with
/// `square` (a color operator), a color the palette doesn't list.
fn textures_library(square: &str) -> Vec<u8> {
let dots = format!("%AI3_BeginPattern: (Dots)\n(Dots) 0 0 4 4\n%_{square}\n%_1 1 m\n%_3 1 L\n%_3 3 L\n%_1 3 L\n%_f\nE\n%AI3_EndPattern\n");
let gradient =
"%AI5_BeginGradient: (Sky)\n(Sky) 0 2 Bd\n[\n%_0 0 0 0 1 1 1 2 1 6 50 0 Bs\n%_0 0 0 1 0 0 0 2 0.5 6 50 100 Bs\nBD\n%AI5_EndGradient\n";
let palette = "%AI5_BeginPalette\n0 0 Pb\n0 0 0 0 1 1 1 Xa\n(White)\nPc\nBb\n2 (Sky) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n(Sky)\nPc\n\
1 (Textures) 1 Pg\n(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n(Tiles)\nPc\nPB\n%AI5_EndPalette\n";
let data = ai::editing_data(200.0, 100.0, &format!("{dots}{gradient}{palette}"));
ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f")
}
/// `swatch.library.load` of `file` named `name` → its library id.
fn load_library(s: &mut Session, name: &str, file: &[u8]) -> Value {
let p = json!({"dataBase64": vectorcraft_format::base64_encode(file), "name": name});
s.execute("swatch.library.load", &p).unwrap()["library"].clone()
}
/// Other Library… on a `.ai` swatch library lists its colors, gradients and pattern swatches in its
/// order and color groups, and adding the pattern swatch makes a pattern swatch with the pattern's
/// tile and art in the document, in the library's color group, not the pattern's colors.
#[test]
fn a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches() {
let mut s = Session::new();
let id = load_library(&mut s, "textures.ai", &textures_library("0 0 0 1 k"));
let lib = s.execute("swatch.library.get", &json!({"library": id})).unwrap();
let kinds: Vec<(&str, &str, Option<&str>)> =
lib["swatches"].as_array().unwrap().iter().map(|w| (w["name"].as_str().unwrap(), w["kind"].as_str().unwrap(), w["group"].as_str())).collect();
assert_eq!(kinds, [("White", "color", None), ("Sky", "gradient", None), ("Tiles", "pattern", Some("Textures"))], "{lib}");
assert_eq!(lib["swatches"][2]["pattern"], json!("Dots"), "{lib}");
// The library panel draws the pattern from the file it came from; a copy of the swatch isn't its own.
let (_, library) = crate::cmd::swatchlib::library(&s, id.as_str().unwrap()).unwrap();
let tiles = library.iter().find(|w| w.name == "Tiles").unwrap();
assert!(crate::cmd::swatchlib::pattern_source(&s, tiles).is_some_and(|d| d.pattern("Dots").is_some()));
assert!(crate::cmd::swatchlib::pattern_source(&s, &tiles.clone()).is_none());
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let r = s.execute("swatch.library.add", &json!({"library": id, "names": ["Textures"]})).unwrap();
assert_eq!(r["added"], json!(["Tiles"]), "{r}");
let doc = &s.doc().unwrap().doc;
let dots = doc.pattern("Dots").expect("the pattern comes with its swatch");
assert_eq!((dots.tile.width(), dots.tile.height()), (4.0, 4.0));
assert_eq!(dots.art.len(), 1, "{:?}", dots.art);
let textures = doc.swatch_groups.iter().find(|g| g.name == "Textures").expect("the color group comes too");
let tiles: Vec<_> = textures.swatches.iter().map(|w| (w.name.as_str(), &w.paint)).collect();
assert!(matches!(tiles[..], [("Tiles", vectorcraft_color::Paint::Pattern { pattern, .. })] if pattern == "Dots"), "{tiles:?}");
// Added again, the swatch the document has is used.
let again = s.execute("swatch.library.add", &json!({"library": id, "names": ["Tiles"]})).unwrap();
assert_eq!((again["added"].clone(), again["existing"].clone()), (json!([]), json!(["Tiles"])), "{again}");
}
/// A pattern swatch of a `.ai` library whose pattern paints with a color the library doesn't list
/// still comes in with that color in its art.
#[test]
fn a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks() {
let mut s = Session::new();
let id = load_library(&mut s, "textures.ai", &textures_library("0 0.5 1 0 k"));
let lib = s.execute("swatch.library.get", &json!({"library": id})).unwrap();
let names: Vec<&str> = lib["swatches"].as_array().unwrap().iter().map(|w| w["name"].as_str().unwrap()).collect();
assert_eq!(names, ["White", "Sky", "Tiles"], "the pattern's color isn't listed: {lib}");
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("swatch.library.add", &json!({"library": id, "names": ["Tiles"]})).unwrap();
let doc = &s.doc().unwrap().doc;
let art = &doc.pattern("Dots").unwrap().art;
let fill = art.first().and_then(|n| n.appearance.fill()).map(|f| f.paint.color());
assert_eq!(fill, Some(Some(vectorcraft_color::Color::cmyk(0.0, 0.5, 1.0, 0.0))), "{art:?}");
// Copy to User Defined would write a .vcswatches file, which can't hold the pattern swatch: it is
// refused, writes nothing and leaves the library loaded.
let dir = std::env::temp_dir().join(format!("vc-pattern-copy-{}", std::process::id()));
s.swatch_libraries.set_user_dir(Some(dir.to_string_lossy().to_string()));
let e = s.execute("swatch.library.copyToUser", &json!({"library": id})).unwrap_err().to_string();
assert!(e.contains("`textures` has pattern swatches"), "{e}");
assert!(!dir.exists() || std::fs::read_dir(&dir).unwrap().next().is_none(), "nothing written");
assert!(s.execute("swatch.library.get", &json!({"library": id})).is_ok());
std::fs::remove_dir_all(&dir).ok();
}
/// A `.ai` file without a palette of its own, and a document with no swatches, are refused as
/// swatch libraries with a message, not listed as the default swatches or as an empty library. A
/// damaged `.ai` is refused with the reader's error, and none of them is listed. A library file
/// with no swatches loads as an empty library.
#[test]
fn swatch_library_documents_without_swatches_or_damaged_are_refused() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.edit("Clear", |d, _| {
d.swatches.clear();
d.swatch_groups.clear();
Ok(())
})
.unwrap();
let b64 = s.execute("document.serialize", &json!({})).unwrap()["dataBase64"].as_str().unwrap().to_string();
let e = s.execute("swatch.library.load", &json!({"dataBase64": b64, "name": "Bare.vectorcraft"})).unwrap_err().to_string();
assert!(e.contains("`Bare.vectorcraft` has no swatches of its own"), "{e}");
let data = ai::editing_data(200.0, 100.0, &ai::layer("Art", &format!("0 0 0 1 k\n{}f\n", ai::rect(10.0, 50.0, 40.0, 90.0))));
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f")), "name": "art.ai"});
let e = s.execute("swatch.library.load", &p).unwrap_err().to_string();
assert!(e.contains("`art.ai` has no swatches of its own"), "{e}");
let damaged = json!({"data": "%PDF-1.4\n%damaged\n", "name": "damaged.ai"});
assert!(s.execute("swatch.library.load", &damaged).is_err());
let list = s.execute("swatch.library.list", &json!({})).unwrap();
assert!(list["libraries"].as_array().unwrap().iter().all(|l| l["category"] != "loaded"), "{list}");
// A library file without swatches still loads, as an empty library.
let r = s.execute("swatch.library.load", &json!({"data": "GIMP Palette\nName: Empty\n#\n", "name": "Empty.gpl"})).unwrap();
assert_eq!(r["count"], json!(0), "{r}");
}
/// Other Library… on a `.ai` graphic style library (art styles, their list and no layers) gives the
/// library the styles of its list, in the list's order, not the default styles; the file opens with
/// them too.
+18
View File
@@ -116,6 +116,24 @@ fn use_artboards_writes_one_drawing_per_artboard() {
assert!(e.contains("useArtboards"), "{e}");
}
#[test]
fn each_artboard_s_drawing_is_the_drawing_of_that_artboard_alone() {
let mut s = two_boards();
// A second rectangle on the second artboard, so the two drawings differ.
let second = s.doc().unwrap().doc.artboards[1].rect.x0;
s.execute("shape.rectangle", &json!({"x": second + 50.0, "y": 50, "width": 20, "height": 20})).unwrap();
let r = s.execute("document.export", &json!({"format": "dxf", "useArtboards": true, "unit": "pt"})).unwrap();
let files = r["files"].as_array().unwrap();
let doc = &s.doc().unwrap().doc;
let o = dxf::options(&json!({"unit": "pt"})).unwrap();
assert_eq!(files.len(), doc.artboards.len());
assert_ne!(b64(&files[0]), b64(&files[1]));
for (f, board) in files.iter().zip(&doc.artboards) {
let alone = vectorcraft_cad::export(doc, &vectorcraft_cad::DxfOptions { region: board.rect, crop: true, ..o.clone() }).unwrap();
assert_eq!(b64(f), alone.bytes, "{}", f["name"]);
}
}
#[test]
fn selected_only_exports_the_selection_in_its_layers() {
let mut s = two_boards();
@@ -410,3 +410,16 @@ fn a_placeholder_only_pdf_part_is_detected() {
assert!(open(&mut s, &two, json!({"pages": "1"})).is_err());
open(&mut s, &two, json!({})).unwrap();
}
/// `linkPages` takes a PDF up to the largest file placed, and nothing else.
#[test]
fn pages_can_link_a_pdf_up_to_the_largest_file_placed() {
let small = three_pages();
assert!(pages_can_link("pages.pdf", &small));
assert!(!pages_can_link("pages.svg", b"<svg xmlns=\"http://www.w3.org/2000/svg\"/>"));
let mut big = vec![0u8; crate::cmd::place::document::MAX_FILE + 1];
big[..small.len()].copy_from_slice(&small);
assert!(!pages_can_link("pages.pdf", &big), "over the limit");
big.pop();
assert!(pages_can_link("pages.pdf", &big), "at the limit");
}
@@ -1461,3 +1461,25 @@ fn an_export_preset_adds_no_notes() {
let r = export(&mut s, json!({"exportPreset": "Mixed"}));
assert!(unused(&r).is_empty(), "{r}");
}
/// Assets, layers and selected objects each write a native, `.ai` or EPS file of their own art:
/// every piece's file holds its own artboard, named after it, not the first piece's.
#[test]
fn each_piece_writes_its_own_native_document() {
let mut s = session(1);
s.execute("shape.ellipse", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
let ids: Vec<u64> = s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect();
let mut assets = vec![];
for (id, name) in ids.iter().zip(["Square", "Circle"]) {
assets.push(s.execute("assets.add", &json!({"ids": [id], "name": name})).unwrap()["assets"][0].as_u64().unwrap());
}
let r = export(&mut s, json!({"assets": assets, "formats": [{"format": "vectorcraft"}, {"format": "eps"}]}));
let written = files(&r);
assert_eq!(written.len(), 4, "{r}");
for (name, bytes) in written {
let native = if name.ends_with(".eps") { vectorcraft_eps::native(&bytes).expect("native document") } else { bytes };
let doc = vectorcraft_format::load(&native).unwrap();
let board = doc.artboards[0].name.clone();
assert!(name.contains(&board), "{name} holds the artboard {board}");
}
}
+66 -2
View File
@@ -532,6 +532,24 @@ pub(super) fn export_overflow_warning(d: &Document, layers: &[Arc<Node>], areas:
super::typecmd::export_overflow_warning(&overflow)
}
/// The objects behind production findings. Resource art points to its first visible owner on
/// the canvas, so a finding can be located without selecting an id outside the layer tree.
#[derive(Default)]
pub(super) struct PreflightType {
pub fonts: BTreeMap<UsedFont, BTreeSet<NodeId>>,
pub overflow: BTreeSet<NodeId>,
pub images: BTreeMap<NodeId, NodeId>,
}
pub(super) fn preflight_type(d: &Document, layers: &[Arc<Node>], areas: &[Rect]) -> PreflightType {
let mut walk = Printed::new(d);
walk.preflight = Some(PreflightType::default());
for l in layers {
walk.node(l, Some(areas));
}
walk.preflight.unwrap_or_default()
}
/// The walk of [`printed_type`].
struct Printed<'a> {
d: &'a Document,
@@ -546,13 +564,25 @@ struct Printed<'a> {
/// The symbols and patterns whose art was walked.
symbols: BTreeSet<String>,
patterns: BTreeSet<String>,
preflight: Option<PreflightType>,
owner: Option<NodeId>,
}
impl<'a> Printed<'a> {
/// A walk of `d` among its own objects, nothing found yet.
fn new(d: &'a Document) -> Self {
let boxes = d.symbol_boxes();
Self { d, boxes, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() }
Self {
d,
boxes,
own: true,
fonts: BTreeSet::new(),
overflow: BTreeSet::new(),
symbols: BTreeSet::new(),
patterns: BTreeSet::new(),
preflight: None,
owner: None,
}
}
/// Adds the fonts of `n` and its descendants that print, and the ids of those that don't fit
@@ -560,6 +590,15 @@ impl<'a> Printed<'a> {
/// art of a symbol, opacity mask, pattern or placed document, in brush pieces, or in a live
/// object) all of them but those outside the clipping path of a clip group.
fn node(&mut self, n: &Node, areas: Option<&[Rect]>) {
let previous = self.owner;
if self.own {
self.owner = Some(n.id);
}
self.node_contents(n, areas);
self.owner = previous;
}
fn node_contents(&mut self, n: &Node, areas: Option<&[Rect]>) {
if !n.visible || matches!(n.kind, NodeKind::Layer { template: true, .. }) {
return;
}
@@ -571,6 +610,14 @@ impl<'a> Printed<'a> {
&& !open
&& !self.meets(n, a)
{
// An entirely overset frame paints nothing, but is still a delivery problem. Keep
// the export walk unchanged; only preflight checks the frame itself in this case.
if let (Some(p), Some(owner), NodeKind::Text(t)) = (&mut self.preflight, self.owner, &n.kind)
&& n.geometric_bounds().is_some_and(|b| a.iter().any(|r| r.intersect(b).area() > 0.0 || r.contains_rect(b)))
&& vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).overflow
{
p.overflow.insert(owner);
}
return;
}
// The art that its opacity mask, pattern paints and brushed strokes draw.
@@ -616,16 +663,33 @@ impl<'a> Printed<'a> {
if overflows && self.own {
self.overflow.insert(n.id);
}
if overflows && let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
p.overflow.insert(owner);
}
for r in runs {
self.fonts.extend(run_fonts(r));
let fonts = run_fonts(r);
if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
for font in &fonts {
p.fonts.entry(font.clone()).or_default().insert(owner);
}
}
self.fonts.extend(fonts);
// Inline graphics draw their symbols' art.
if let Some(art) = r.inline.as_ref().filter(|_| draws_inline(r)) {
self.symbol(&art.symbol);
}
}
}
NodeKind::Image(_) => {
if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
p.images.entry(n.id).or_insert(owner);
}
}
NodeKind::SymbolInstance { symbol, .. } => self.symbol(symbol),
NodeKind::PlacedDocument(p) => {
if let (Some(report), Some(owner)) = (&mut self.preflight, self.owner) {
report.images.entry(n.id).or_insert(owner);
}
for art in p.art(n) {
self.art(&art);
}
+6 -1
View File
@@ -769,6 +769,7 @@ fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut
arrow_scale,
profile,
brush,
brush_options,
opacity,
blend,
visible,
@@ -781,7 +782,11 @@ fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut
bearing: _,
rotation: _,
} = m;
give_fields!(a, b, n: paint, width, cap, join, miter_limit, align, dash, start_arrow, end_arrow, arrow_scale, profile, brush, opacity, blend, visible, effects, arrow_align, overprint, gradient_mode);
give_fields!(a, b, n: paint, width, cap, join, miter_limit, align, dash, start_arrow, end_arrow, arrow_scale, profile, brush, brush_options, opacity, blend, visible, effects, arrow_align, overprint, gradient_mode);
// A stroke's own brush settings go with the brush they set: a new brush takes the model's.
if a.brush != b.brush {
n.brush_options = brush_options.clone();
}
}
_ => {}
}
+2 -1
View File
@@ -37,7 +37,8 @@ use axis::{nice_axis, tick_values};
#[cfg(test)]
use columns::{fill_totals, total_text};
pub use commands::specs;
pub(crate) use data::{apply_csv, parse_csv};
pub use data::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text};
pub(crate) use data::{apply_csv, graph_csv_from_file, parse_csv};
#[cfg(test)]
use data::{fmt_value, to_csv};
pub use edit::{GraphTypeSubject, graph_type_subject};
+101
View File
@@ -91,6 +91,102 @@ pub(super) fn to_csv(g: &GraphSpec) -> String {
g.to_csv()
}
// ---------- graph data files ----------
/// The largest graph data file that Graph Data's Import Data and Import Data Sets' `%` columns
/// read, 1 MB (1,048,576 bytes).
pub const MAX_GRAPH_DATA_FILE: usize = 1 << 20;
/// A graph data sheet's size: a row of labels over a graph's categories, a column of labels
/// before its series; a cell's longest text.
const SHEET_ROWS: usize = vectorcraft_doc::MAX_GRAPH_CATEGORIES + 1;
const SHEET_COLS: usize = vectorcraft_doc::MAX_GRAPH_SERIES + 1;
const SHEET_CELL: usize = 256;
/// A graph data file's bytes as text: UTF-16 with its byte-order mark (spreadsheets' "Unicode
/// Text"), else UTF-16 without one when the bytes hold NUL bytes and Import Data Sets' rule gives
/// them a byte order ([`crate::cmd::utf16_order_without_mark`]), else UTF-8 with or without one.
/// UTF-16 is read as it is after a byte-order mark: an odd last byte is left out, and an unpaired
/// surrogate reads as U+FFFD.
pub fn graph_data_text(bytes: &[u8]) -> String {
let utf16 = |rest: &[u8], le: bool| {
let units: Vec<u16> = rest.as_chunks::<2>().0.iter().map(|p| if le { u16::from_le_bytes(*p) } else { u16::from_be_bytes(*p) }).collect();
String::from_utf16_lossy(&units)
};
match bytes {
[0xFF, 0xFE, rest @ ..] => utf16(rest, true),
[0xFE, 0xFF, rest @ ..] => utf16(rest, false),
[0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8_lossy(rest).into_owned(),
_ => match bytes.contains(&0).then(|| crate::cmd::utf16_order_without_mark(bytes)).flatten() {
Some(le) => utf16(bytes, le),
None => String::from_utf8_lossy(bytes).into_owned(),
},
}
}
/// A graph data sheet cell's text: one line (tabs and line breaks become spaces), at most 256
/// characters.
pub fn graph_cell_text(s: &str) -> String {
s.chars().map(|c| if matches!(c, '\t' | '\r' | '\n') { ' ' } else { c }).take(SHEET_CELL).collect()
}
/// Text from a file or the clipboard as graph data sheet cells: tab-separated when any line holds
/// a tab, else comma-separated (decided once, so a label with a comma in a tab-separated file
/// stays whole), at most a graph's rows and columns.
pub fn graph_grid_from_text(text: &str) -> Vec<Vec<String>> {
let sep = if text.contains('\t') { '\t' } else { ',' };
text.lines().take(SHEET_ROWS).map(|l| l.trim_end_matches('\r').split(sep).take(SHEET_COLS).map(|c| graph_cell_text(c.trim())).collect()).collect()
}
/// A graph data sheet as `graph.setData` takes it: the first row holds the series labels, the
/// first column the category labels (none when all are blank), and the other cells the values (a
/// blank cell, or text that isn't a number, has none), without the empty rows and columns past
/// the data.
pub fn graph_data_from_grid(grid: &[Vec<String>]) -> Value {
let cell = |r: usize, c: usize| grid.get(r).and_then(|row| row.get(c)).cloned().unwrap_or_default();
let filled = |s: &String| !s.trim().is_empty();
// At most a graph's rows and columns, as a file gives (`graph_grid_from_text`): a grid sent by
// automation is any size, and the values are their product.
let grid = &grid[..grid.len().min(SHEET_ROWS)];
let rows = grid.iter().rposition(|r| r.iter().take(SHEET_COLS).any(filled)).map_or(1, |i| i + 1).max(1);
let cols = grid.iter().take(rows).filter_map(|r| r.iter().take(SHEET_COLS).rposition(filled)).max().map_or(1, |i| i + 1).max(1);
let label = |s: &str| {
let s = s.trim();
// A label typed in straight quotes (as the CSV form takes a number as a label) is the text inside.
s.strip_prefix('"').and_then(|t| t.strip_suffix('"')).unwrap_or(s).to_string()
};
// Series labels up to the last one given (none when all are blank).
let mut series: Vec<String> = (1..cols).map(|c| label(&cell(0, c))).collect();
while series.last().is_some_and(String::is_empty) {
series.pop();
}
let mut categories: Vec<String> = (1..rows).map(|r| label(&cell(r, 0))).collect();
if categories.iter().all(String::is_empty) {
categories.clear();
}
let values: Vec<Vec<Value>> = (1..rows)
.map(|r| {
(1..cols)
.map(|c| {
let t = cell(r, c);
t.trim().parse::<f64>().ok().filter(|v| v.is_finite() && !t.trim().starts_with('"')).map_or(Value::Null, |v| json!(v))
})
.collect()
})
.collect();
json!({ "series": series, "categories": categories, "rows": values })
}
/// The graph value (the CSV form [`apply_csv`] reads) of a graph data file's bytes, read as Graph
/// Data's Import Data reads the file into its sheet and Apply sends the sheet: so applying the
/// value gives a graph the data that Import Data and Apply give it.
pub(crate) fn graph_csv_from_file(bytes: &[u8]) -> Result<String> {
let data = graph_data_from_grid(&graph_grid_from_text(&graph_data_text(bytes)));
let mut spec = GraphSpec::default();
apply_data(&mut spec, &data, "dataset.import")?;
Ok(spec.to_csv())
}
/// Apply CSV graph data to the graph root `id` and rebuild its art (Variables data merge), as `graph.setData` with
/// `csv` does. Data the graph already holds leaves the graph as it is.
pub(crate) fn apply_csv(d: &mut Document, id: NodeId, csv: &str) -> Result<()> {
@@ -149,6 +245,11 @@ pub(super) fn apply_data(g: &mut GraphSpec, p: &Value, cmd: &str) -> Result<bool
if let Some(csv) = csv {
let (s, c, r) = parse_csv(csv);
g.series = s;
// Series labels up to the last one given, as Graph Data's sheet keeps them
// ([`graph_data_from_grid`]): `to_csv` writes a blank label for each series without one.
while g.series.last().is_some_and(String::is_empty) {
g.series.pop();
}
g.categories = c;
g.set_cells(r);
changed = true;
+48 -18
View File
@@ -3,7 +3,7 @@
use serde_json::{Value, json};
use vectorcraft_doc::text::INLINE_MAX_SCALE;
use vectorcraft_doc::{Document, InlineArt, NodeId, NodeKind, TextRun};
use vectorcraft_doc::{Document, InlineArt, InlineMeasured, NodeId, NodeKind, TextRun};
use vectorcraft_text::edit;
use super::brushsym::current_symbol;
@@ -25,12 +25,33 @@ pub fn specs() -> Vec<CommandSpec> {
/// Inline graphics follow their symbols: after an edit of a document that has (or had) symbols,
/// resolve the inline art of every text again, in the layers and in the art of symbols, graph
/// designs, pattern tiles and opacity masks, and lay out again the texts whose art changed (a
/// symbol's type before the type that shows that symbol inline).
pub(crate) fn refresh(before: &Document, d: &mut Document) {
/// symbol's type before the type that shows that symbol inline). `last` is the document the last
/// refresh left resolved, with what it measured: when nothing the inline art depends on changed
/// since, only the layer trees that differ from its own are checked
/// ([`Document::resolve_inline_art_since`]). Returns what this refresh measured, or `None` when
/// neither document has symbols and nothing was checked.
pub(crate) fn refresh(last: Option<&Resolved>, before: &Document, d: &mut Document) -> Option<InlineMeasured> {
if before.symbols.is_empty() && d.symbols.is_empty() {
return;
return None;
}
d.resolve_inline_art_with(&mut refresh_bounds);
#[cfg(test)]
let last = last.filter(|_| !FULL_PASS.get());
let pass = d.resolve_inline_art_since(last.map(|(doc, m)| (&**doc, m)), &mut refresh_bounds);
#[cfg(test)]
PASSES.with(|p| p.borrow_mut().push((pass.partial, pass.changed.clone())));
Some(pass.measured)
}
/// A document a [`refresh`] left resolved, and what that refresh measured.
pub(crate) type Resolved = (std::sync::Arc<Document>, InlineMeasured);
#[cfg(test)]
thread_local! {
/// Each [`refresh`] on this thread that checked the document: whether it checked only the
/// changed layer trees, and the ids of the texts in the layers that changed.
pub(crate) static PASSES: std::cell::RefCell<Vec<(bool, Vec<NodeId>)>> = const { std::cell::RefCell::new(vec![]) };
/// Set: every [`refresh`] on this thread takes the full pass.
pub(crate) static FULL_PASS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
fn insert_inline(s: &mut Session, p: &Value) -> Result<Value> {
@@ -47,18 +68,22 @@ fn insert_inline(s: &mut Session, p: &Value) -> Result<Value> {
};
let len = edit::runs_len(&t.runs);
let from_tool = editing == Some(id);
let (a, b) = match p.get("at") {
None | Some(Value::Null) if from_tool => {
let g = |k: &str| tool.get(k).and_then(Value::as_u64).map_or(len, |v| (v as usize).min(len));
let (x, y) = (g("start"), g("end"));
(x.min(y), x.max(y))
}
None | Some(Value::Null) => (len, len),
Some(v) => {
let at = v.as_u64().ok_or_else(|| bad(C, "`at` must be a byte offset"))?.min(len as u64) as usize;
(at, at)
}
// Where the graphic goes in text `len` bytes long.
let range = |len: usize| -> Result<(usize, usize)> {
Ok(match p.get("at") {
None | Some(Value::Null) if from_tool => {
let g = |k: &str| tool.get(k).and_then(Value::as_u64).map_or(len, |v| (v as usize).min(len));
let (x, y) = (g("start"), g("end"));
(x.min(y), x.max(y))
}
None | Some(Value::Null) => (len, len),
Some(v) => {
let at = v.as_u64().ok_or_else(|| bad(C, "`at` must be a byte offset"))?.min(len as u64) as usize;
(at, at)
}
})
};
let (mut a, mut b) = range(len)?;
let symbol = match str_param(p, "symbol") {
Some(n) if doc.symbols.iter().any(|s| s.name == n) => n.to_string(),
Some(n) => return Err(bad(C, format!("no symbol named `{n}`"))),
@@ -76,11 +101,16 @@ fn insert_inline(s: &mut Session, p: &Value) -> Result<Value> {
None | Some(Value::Null) => 0.0,
Some(v) => v.as_f64().filter(|k| k.is_finite() && k.abs() <= 1e5).ok_or_else(|| bad(C, "`shift` must be a number of points"))?,
};
// A typing session ends first: the insertion is a step of its own.
// A typing session ends first: the insertion is a step of its own. Typing that Real-time
// Drawing off left unapplied is applied first, and the caret is read in the typed text.
let typing = tool.get("typing").and_then(Value::as_bool) == Some(true);
if typing && from_tool {
s.set_tool_option("commitTyping", &Value::Bool(true));
s.commit_interaction()?;
super::settle_interaction(s)?;
let NodeKind::Text(t) = &s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.kind else {
return Err(bad(C, format!("node {} is not text", id.0)));
};
(a, b) = range(edit::runs_len(&t.runs))?;
}
let caret = s.edit("Insert Inline Symbol", |d, _| {
let mut art = InlineArt { scale, baseline_shift: shift, ..InlineArt::new(symbol.clone()) };
+22 -13
View File
@@ -29,7 +29,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New Layer…",
["Window", "Layers"],
Some("Cmd+L"),
"{name?, top?: bool, below?: bool, color?, template?, locked?, visible?, printable?, preview?, dimImages?} a layer directly above the current layer, at its level (a sublayer beside a current sublayer); `top`: above all layers (Ctrl/Cmd-click the button); `below`: directly below the current layer, at its level (Ctrl/Cmd+Alt-click the button), not with `top`. Options as layer.setProps; refused while an opacity mask is edited (the Layers panel lists only the mask) → {id}",
"{name?, top?: bool, below?: bool, color?, template?, locked?, visible?, printable?, preview?, dimImages?} a layer directly above the current layer, at its level (a sublayer beside a current sublayer), or directly below it in Draw Behind; `top`: above all layers (Ctrl/Cmd-click the button); `below`: directly below the current layer, at its level (Ctrl/Cmd+Alt-click the button), not with `top`. Options as layer.setProps; refused while an opacity mask is edited (the Layers panel lists only the mask) → {id}",
super::maskedit::outside_mask_editing,
new_layer
),
@@ -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, 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}",
"{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, which may also go above or below a row they copy (the target among `ids`). 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
),
@@ -526,12 +526,15 @@ fn add_layer(s: &mut Session, p: &Value, cmd: &str, label: &str, place: impl FnO
fn new_layer(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "layer.new";
let below = switch_or(p, "below", false, C)?;
if below && bool_or(p, "top", false) {
let top = bool_or(p, "top", false);
if below && top {
return Err(bad(C, "`top` and `below` can't both be true"));
}
// In Draw Behind a layer given neither `top` nor `below` goes below the current layer.
let below = below || (!top && s.draw_mode == crate::DrawMode::Behind);
let st = s.doc()?;
// Above the current layer, at its level; below it with `below`; on top of everything with `top`.
let cur = st.current_layer().filter(|_| !bool_or(p, "top", false));
let cur = st.current_layer().filter(|_| !top);
add_layer(s, p, C, "New Layer", |d| match cur.and_then(|c| d.position(c)) {
Some((parent, i, _)) => Ok((parent, if below { i } else { i + 1 })),
None => Ok((None, if below { 0 } else { usize::MAX })),
@@ -733,19 +736,18 @@ fn select_art(s: &mut Session, p: &Value) -> Result<Value> {
} else {
vec![id]
};
let all_selected = !ids.is_empty() && ids.iter().all(|i| st.selection.contains(*i));
let all_selected = add && !ids.is_empty() && {
let selected: HashSet<NodeId> = st.selection.objects.iter().copied().collect();
ids.iter().all(|i| selected.contains(i))
};
let rows = st.layer_rows.clone();
s.select(|_, sel| {
if !add {
sel.set(ids.iter().copied());
} else if all_selected {
for i in &ids {
sel.remove(*i);
}
sel.remove_all(ids.iter().copied());
} else {
for i in &ids {
sel.add(*i);
}
sel.add_all(ids.iter().copied());
}
})?;
let st = s.doc_mut()?;
@@ -784,9 +786,11 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> {
if ids.is_empty() {
return Err(bad(C, "no such rows"));
}
// Never into itself or a row inside it.
// Never into itself or a row inside it. A copy may go above or below one of the rows it
// copies, which a move there would leave where it is (#8237).
let beside_itself = copy && place != Place::Inside && ids.contains(&target);
let around = d.ancestry(target).unwrap_or_default();
if ids.iter().any(|i| around.contains(i)) {
if ids.iter().any(|i| around.contains(i) && !(beside_itself && *i == target)) {
return Err(bad(C, "a row can't go into itself"));
}
let nodes: Vec<&Node> = ids.iter().filter_map(|i| d.node(*i)).collect();
@@ -798,6 +802,11 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> {
parent => (parent, Some(target)),
},
};
// A copy beside a top-level layer it copies, with objects among the rows, would go inside
// that layer: into itself.
if parent.is_some_and(|p| ids.contains(&p)) {
return Err(bad(C, "a row can't go into itself"));
}
if let Some(n) = nodes.iter().find(|n| !accepts(d, parent, n)) {
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())));
+13 -4
View File
@@ -132,7 +132,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Locate Object",
["Window", "Layers"],
None,
"{id?} (default: the last selected object) highlight the object's row; the Layers panel opens the layers around it and scrolls to it → {id, ancestry: [layer…, id]}",
"{id?, layersOnly?} (default: the last selected object) highlight the object's row; the Layers panel opens the layers around it and scrolls to it, also when the row was already highlighted →{id, ancestry: [layer…, id]}. layersOnly (default false; the panel sends true while Show Layers Only is on, as Locate Layer) highlights the innermost layer or sublayer holding the object instead, or a layer id itself → {id: layer, objectId, ancestry: [layer…]}",
has_doc,
locate
),
@@ -435,10 +435,19 @@ fn reverse(s: &mut Session, p: &Value) -> Result<Value> {
fn locate(s: &mut Session, p: &Value) -> Result<Value> {
let id = object_param(p, "id", "layer.locate")?;
let layers_only = switch_or(p, "layersOnly", false, "layer.locate")?;
let st = s.doc_mut()?;
let id = id.or_else(|| st.selection.objects.last().copied()).ok_or_else(|| bad("layer.locate", "nothing selected"))?;
let ancestry = st.doc.ancestry(id).ok_or(EngineError::NoNode(id))?;
st.layer_rows = vec![id];
let mut ancestry = st.doc.ancestry(id).ok_or(EngineError::NoNode(id))?;
if layers_only {
// Locate Layer: the innermost layer or sublayer holding the object (a layer locates itself).
let at = ancestry.iter().rposition(|a| st.doc.node(*a).is_some_and(Node::is_layer)).ok_or(EngineError::NoNode(id))?;
ancestry.truncate(at + 1);
}
let row = ancestry.last().copied().ok_or(EngineError::NoNode(id))?;
st.layer_rows = vec![row];
st.locate_reveal = Some(row);
st.revision += 1;
Ok(json!({ "id": id.0, "ancestry": ancestry.iter().map(|i| i.0).collect::<Vec<_>>() }))
let ancestry: Vec<u64> = ancestry.iter().map(|i| i.0).collect();
Ok(if layers_only { json!({ "id": row.0, "objectId": id.0, "ancestry": ancestry }) } else { json!({ "id": id.0, "ancestry": ancestry }) })
}
+193 -6
View File
@@ -36,7 +36,7 @@ use vectorcraft_doc::{
use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes};
use super::fileio::{self, RasterImage, absolute_path, file_created, file_stamp, read_file, write_file};
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param, switch_or};
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param, switch_or, text_param};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Unembed",
[],
None,
"{id?: an embedded image (default: the one selected), path?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to)",
"{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds. One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors",
has_doc,
unembed
),
@@ -2686,11 +2686,35 @@ fn convert_image(bytes: &[u8], ext: &str) -> std::result::Result<Vec<u8>, String
craft_image_codecs::encode(&raw, format, &craft_image_codecs::EncodeOptions::default()).map_err(|e| e.to_string())
}
/// The extension of the format embedded image `blob` is stored in (PNG for one Unembed doesn't
/// name).
fn stored_extension(blob: &vectorcraft_doc::ImageBlob) -> &'static str {
fileio::FORMATS.iter().find(|f| f.raster && f.mime == blob.mime).map_or("png", |f| f.extensions.first().copied().unwrap_or("png"))
}
/// The bytes of embedded image `blob` in the format of extension `ext`: its own bytes when it is
/// stored in that format, else converted.
fn unembed_bytes(blob: &vectorcraft_doc::ImageBlob, ext: &str) -> std::result::Result<Vec<u8>, String> {
let same = fileio::format(ext).is_some_and(|f| f.mime == blob.mime);
if same { Ok(blob.bytes.to_vec()) } else { convert_image(&blob.bytes, ext) }
}
fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "links.unembed";
let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null());
// `id` with `ids`, and `path` with `folder`, are refused, in a replayed step too.
super::params::check_exclusive_keys(C, p)?;
let ids = ids_param(p, "ids", C)?;
if given("folder") || ids.as_ref().is_some_and(|ids| ids.len() != 1) {
return unembed_to_folder(s, p, ids);
}
let st = s.doc()?;
let doc = with_brush_art(&st.doc);
let id = image_param(st, &doc, p, C)?;
// `ids` of one image is `id`.
let id = match ids.as_deref() {
Some(&[id]) => id,
_ => image_param(st, &doc, p, C)?,
};
let n = stored(&doc, id).ok_or(crate::EngineError::NoNode(id))?;
let im = image_of(&doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?;
if im.link.is_some() {
@@ -2698,15 +2722,14 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
}
let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?;
// As stored (PNG, JPEG, GIF, WebP), unless the path names another format.
let stored = fileio::FORMATS.iter().find(|f| f.raster && f.mime == blob.mime).map_or("png", |f| f.extensions.first().copied().unwrap_or("png"));
let stored = stored_extension(blob);
let path = str_param(p, "path");
let ext = match path.map(fileio::extension) {
Some(e) if UNEMBED_EXTS.contains(&e.as_str()) => e,
Some(e) if !e.is_empty() => return Err(bad(C, format!("can't write .{e} images: use .png, .jpg, .gif, .webp, .tif or .bmp"))),
_ => stored.to_string(),
};
let same = fileio::format(&ext).is_some_and(|f| f.mime == blob.mime);
let bytes = if same { blob.bytes.to_vec() } else { convert_image(&blob.bytes, &ext).map_err(|e| bad(C, e))? };
let bytes = unembed_bytes(blob, &ext).map_err(|e| bad(C, e))?;
let Some(path) = path else {
let name = n.display_name();
let stem = Path::new(&name).file_stem().map_or_else(|| name.clone(), |s| s.to_string_lossy().into_owned());
@@ -2722,6 +2745,146 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "id": id.0, "path": path }))
}
/// `links.unembed {ids?, folder}`: each embedded image of `ids` (`id` as `ids` of one; default: the
/// selected embedded images) written to a new file in `folder` as stored (as PNG when that format is not one of
/// VectorCraft's raster file formats) and linked to it, in one undo step. Linked images are skipped. When any image fails, the files written before it
/// are removed and the document does not change.
fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option<Vec<NodeId>>) -> Result<Value> {
const C: &str = "links.unembed";
let folder = text_param(p, "folder", C)?.filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "missing `folder`"))?;
let ids = match ids {
Some(ids) => Some(ids),
None => object_param(p, "id", C)?.map(|id| vec![id]),
};
let st = s.doc()?;
let doc = with_brush_art(&st.doc);
let ids = ids.unwrap_or_else(|| selected_images(st, |im| im.link.is_none()));
let mut seen = BTreeSet::new();
if !ids.iter().all(|id| seen.insert(id.0)) {
return Err(bad(C, "`ids` names an object twice"));
}
let (mut embedded, mut skipped) = (vec![], vec![]);
for &id in &ids {
let n = stored(&doc, id).ok_or(crate::EngineError::NoNode(id))?;
let im = image_of(&doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?;
if im.link.is_some() {
skipped.push(id);
continue;
}
let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?;
embedded.push((id, n.display_name(), blob));
}
match (embedded.is_empty(), skipped.first()) {
(true, Some(id)) => return Err(bad(C, format!("image {} is linked already", id.0))),
(true, None) => return Err(bad(C, "select an image")),
_ => {}
}
let dir = absolute_path(folder);
writable_folder(&dir)?;
// One image at a time: its bytes are read before its file is written, so pixels that can't be
// read leave no file behind.
let mut written: Vec<String> = vec![];
let mut reads = Vec::with_capacity(embedded.len());
let wrote = embedded.iter().try_for_each(|(id, name, blob)| {
vectorcraft_doc::cancel::check()?;
let ext = stored_extension(blob);
let bytes = unembed_bytes(blob, ext).map_err(|e| bad(C, e))?;
let name = format!("{}.{ext}", unembed_stem(name));
let img = linked_image(&bytes, Some(Path::new(&dir).join(&name).to_string_lossy().as_ref()))?;
let path = write_numbered(&dir, &name, &bytes)?;
written.push(path.clone());
reads.push((*id, (link_info(&path, &bytes), img)));
Ok(())
});
let remove_written = |written: &[String]| {
for path in written {
let _ = std::fs::remove_file(path);
}
};
if let Err(e) = wrote {
remove_written(&written);
return Err(e);
}
drop(doc);
let done: Vec<Value> = reads.iter().map(|(id, (l, _))| json!({ "id": id.0, "path": l.path })).collect();
let edited = s.edit("Unembed", |d, _| {
editing_brush_art(d, |d| reads.into_iter().try_for_each(|(id, read)| install(d, &[id], read, Some(Preserve::Bounds), None)))
});
if let Err(e) = edited {
remove_written(&written);
return Err(e);
}
Ok(json!({ "unembedded": done, "skipped": ids_json(&skipped) }))
}
/// The name Unembed gives image `name`'s file in a folder, before its extension: the name without
/// a folder part or extension, each character a file name can't hold on some system
/// (`/ \ : * ? " < > |` and control characters) as `_`, without leading spaces or trailing dots and
/// spaces, at most 150 bytes long, and `Image` when nothing is left. A name Windows keeps for a
/// device (`CON`, `NUL`, `COM1` …) gets `_` after it.
fn unembed_stem(name: &str) -> String {
let base = name.rsplit(['/', '\\']).next().unwrap_or_default();
let stem = match base.rfind('.') {
Some(i) if i > 0 => &base[..i],
_ => base,
};
let mut clean = String::new();
for c in stem.chars().map(|c| if c.is_control() || "/\\:*?\"<>|".contains(c) { '_' } else { c }) {
if clean.len() + c.len_utf8() > 150 {
break;
}
clean.push(c);
}
let clean = clean.trim_start_matches(' ').trim_end_matches(['.', ' ']);
if clean.is_empty() {
return "Image".to_string();
}
let device = clean.split('.').next().unwrap_or_default().trim_end().to_ascii_uppercase();
let numbered = |prefix: &str| device.strip_prefix(prefix).is_some_and(|d| d.len() == 1 && matches!(d.as_bytes().first(), Some(b'1'..=b'9')));
if matches!(device.as_str(), "CON" | "PRN" | "AUX" | "NUL") || numbered("COM") || numbered("LPT") {
format!("{clean}_")
} else {
clean.to_string()
}
}
/// Folder `path` may take Unembed's files: inside the automation write roots, and a folder.
#[cfg(not(target_arch = "wasm32"))]
fn writable_folder(path: &str) -> Result<()> {
crate::file_access::check_write(path).map_err(EngineError::Other)?;
if !std::fs::metadata(path).is_ok_and(|m| m.is_dir()) {
return Err(EngineError::Other(format!("{path} is not a folder")));
}
Ok(())
}
/// Write `bytes` to a new file named `name` in folder `dir`, never replacing a file there: `Name.ext`,
/// else `Name 2.ext` up to `Name 99.ext`, as [`fileio::copy_new`] names them → its path.
#[cfg(not(target_arch = "wasm32"))]
fn write_numbered(dir: &str, name: &str, bytes: &[u8]) -> Result<String> {
use std::io::Write as _;
let create = |to: &Path| {
crate::file_access::check_write(&to.to_string_lossy()).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?;
vectorcraft_format::write_new_with(to, |f| f.write_all(bytes))
};
match fileio::copy_new(Path::new(name), Path::new(dir), create, |_, _| false) {
Ok(Some(fileio::Placed::Copied(to) | fileio::Placed::Kept(to))) => Ok(to.to_string_lossy().into_owned()),
Ok(None) => Err(EngineError::Other(format!("every numbered name for {name} is taken in that folder"))),
Err(e) => Err(EngineError::Other(format!("{dir}: {e}"))),
}
}
/// The web has no folders to write to.
#[cfg(target_arch = "wasm32")]
fn writable_folder(_: &str) -> Result<()> {
Err(EngineError::Other("no file system here".into()))
}
#[cfg(target_arch = "wasm32")]
fn write_numbered(_: &str, _: &str, _: &[u8]) -> Result<String> {
Err(EngineError::Other("no file system here".into()))
}
/// Placement Options as `{preserve, align, clip}`.
fn placement_json(o: PlacementOptions) -> Value {
json!({ "preserve": o.preserve.id(), "align": o.align.id(), "clip": o.clip })
@@ -2901,4 +3064,28 @@ mod tests {
let c = read();
assert!(!Arc::ptr_eq(&a.blob.bytes, &c.blob.bytes));
}
#[test]
fn unembed_names_a_file_after_the_image_with_only_characters_a_file_name_holds() {
for (name, stem) in [
("photo.png", "photo"),
("Image", "Image"),
("../../etc/passwd", "passwd"),
("C:\\art\\logo.tif", "logo"),
("a:b*c?d\"e<f>g|h", "a_b_c_d_e_f_g_h"),
("tab\there", "tab_here"),
(" name. .png", "name"),
("..", "Image"),
("", "Image"),
(".hidden", ".hidden"),
("CON.png", "CON_"),
("lpt1", "lpt1_"),
("COM0", "COM0"),
("console", "console"),
] {
assert_eq!(unembed_stem(name), stem, "{name:?}");
}
let long = unembed_stem(&"é".repeat(200));
assert!(long.len() <= 150 && long.chars().all(|c| c == 'é'), "{}", long.len());
}
}
+2
View File
@@ -29,6 +29,8 @@ mod commands;
mod common;
mod envelope;
mod mesh;
#[cfg(test)]
mod selected_tests;
pub(crate) use blend::expand_blends;
pub use commands::specs;
+2 -3
View File
@@ -657,9 +657,8 @@ pub(super) fn blend_replace_spine(s: &mut Session, _: &Value) -> Result<Value> {
}
/// Is any selected blend one made without a spine?
fn any_without_spine(s: &Session) -> bool {
let Ok(st) = s.doc() else { return false };
selected_of(s, is_blend).iter().any(|b| matches!(st.doc.node(*b).map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine))
pub(super) fn any_without_spine(s: &Session) -> bool {
super::common::any_selected_of(s, is_blend, |n| matches!(&n.kind, NodeKind::Blend { spec, .. } if spec.no_spine))
}
pub(super) fn blend_reverse_spine(s: &mut Session, _: &Value) -> Result<Value> {
+21 -11
View File
@@ -1,3 +1,5 @@
use std::collections::HashSet;
use super::mesh::whole;
use super::{
Arc, BlendEase, BlendEaseType, BlendOrientation, BlendSpacing, Document, EngineError, Node, NodeId, NodeKind, Result, Selection, Session, Value,
@@ -20,13 +22,14 @@ pub(super) fn roots_param(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
let mut sel = Selection::default();
sel.set(ids.iter().copied().filter(|id| st.doc.node(*id).is_some_and(|n| !n.is_layer())));
let ordered = sel.in_paint_order(&st.doc);
let given: HashSet<NodeId> = ordered.iter().copied().collect();
// Drop ids nested inside other given ids.
return Ok(ordered
.iter()
.copied()
.filter(|id| {
let anc = st.doc.ancestry(*id).unwrap_or_default();
!anc[..anc.len().saturating_sub(1)].iter().any(|a| ordered.contains(a))
!anc[..anc.len().saturating_sub(1)].iter().any(|a| given.contains(a))
})
.collect());
}
@@ -37,20 +40,27 @@ pub(super) fn roots_param(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
/// dynamic symbol instance's art is selected.
pub(super) fn selected_of(s: &Session, pred: fn(&Node) -> bool) -> Vec<NodeId> {
let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return vec![] };
let mut find = st.doc.nearest_finder();
let mut seen = HashSet::new();
let mut out = vec![];
for id in &st.selection.objects {
for a in st.doc.ancestry(*id).unwrap_or_default().into_iter().rev() {
if st.doc.node(a).is_some_and(pred) {
if !out.contains(&a) {
out.push(a);
}
break;
}
if let Some(n) = find.nearest(*id, pred)
&& seen.insert(n.id)
{
out.push(n.id);
}
}
out
}
/// Whether some selected object's node of a kind ([`selected_of`]) passes `test`; stops at the
/// first one that does.
pub(super) fn any_selected_of(s: &Session, pred: fn(&Node) -> bool, test: impl Fn(&Node) -> bool) -> bool {
let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return false };
let mut find = st.doc.nearest_finder();
st.selection.objects.iter().any(|id| find.nearest(*id, pred).is_some_and(&test))
}
pub(super) fn is_blend(n: &Node) -> bool {
matches!(n.kind, NodeKind::Blend { .. })
}
@@ -66,19 +76,19 @@ pub(super) fn is_mesh(n: &Node) -> bool {
pub(super) fn has_blend(s: &Session) -> std::result::Result<(), String> {
has_selection(s)?;
crate::cmd::edit::no_symbol_part(s)?;
if selected_of(s, is_blend).is_empty() { Err("select a blend".into()) } else { Ok(()) }
if any_selected_of(s, is_blend, |_| true) { Ok(()) } else { Err("select a blend".into()) }
}
pub(super) fn has_envelope(s: &Session) -> std::result::Result<(), String> {
has_selection(s)?;
crate::cmd::edit::no_symbol_part(s)?;
if selected_of(s, is_envelope).is_empty() { Err("select an envelope".into()) } else { Ok(()) }
if any_selected_of(s, is_envelope, |_| true) { Ok(()) } else { Err("select an envelope".into()) }
}
pub(super) fn has_mesh(s: &Session) -> std::result::Result<(), String> {
has_selection(s)?;
crate::cmd::edit::no_symbol_part(s)?;
if selected_of(s, is_mesh).is_empty() { Err("select a gradient mesh".into()) } else { Ok(()) }
if any_selected_of(s, is_mesh, |_| true) { Ok(()) } else { Err("select a gradient mesh".into()) }
}
/// Wrap `roots` (paint order) into a new node built by `make`, placed where the topmost root was.
@@ -0,0 +1,324 @@
//! The selected blend, envelope and mesh ([`selected_of`] and the checks built on it) are the ones
//! the lookup of every ancestor by id found: the same ids in the same order, the same availability
//! and errors, on selections with keys, nested blends, stale and repeated ids and a damaged tree.
use std::sync::atomic::{AtomicUsize, Ordering};
use serde_json::json;
use vectorcraft_doc::{Node, NodeId, NodeKind, SymbolPart};
use super::Session;
use super::blend::any_without_spine;
use super::common::{any_selected_of, has_blend, has_envelope, has_mesh, is_blend, is_envelope, is_mesh, selected_of};
/// [`selected_of`] as each ancestor was looked up by id: `ancestry`, then `node` for each id from
/// the object up, repeats dropped by a scan of the list.
fn selected_of_by_ids(s: &Session, pred: fn(&Node) -> bool) -> Vec<NodeId> {
let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return vec![] };
let mut out = vec![];
for id in &st.selection.objects {
for a in st.doc.ancestry(*id).unwrap_or_default().into_iter().rev() {
if st.doc.node(a).is_some_and(pred) {
if !out.contains(&a) {
out.push(a);
}
break;
}
}
}
out
}
/// The availability [`has_blend`] and the others gave, from [`selected_of_by_ids`].
fn has_by_ids(s: &Session, pred: fn(&Node) -> bool, msg: &str) -> std::result::Result<(), String> {
super::has_selection(s)?;
crate::cmd::edit::no_symbol_part(s)?;
if selected_of_by_ids(s, pred).is_empty() { Err(msg.into()) } else { Ok(()) }
}
/// The no-spine check [`any_without_spine`] made, from [`selected_of_by_ids`].
fn without_spine_by_ids(s: &Session) -> bool {
let Ok(st) = s.doc() else { return false };
selected_of_by_ids(s, is_blend).iter().any(|b| matches!(st.doc.node(*b).map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine))
}
/// Every check on the current selection gives what the lookups by id gave.
fn agree(s: &Session, what: &str) {
type Has = fn(&Session) -> std::result::Result<(), String>;
for (name, pred, has, msg) in [
("blend", is_blend as fn(&Node) -> bool, has_blend as Has, "select a blend"),
("envelope", is_envelope, has_envelope, "select an envelope"),
("mesh", is_mesh, has_mesh, "select a gradient mesh"),
] {
let want = selected_of_by_ids(s, pred);
assert_eq!(selected_of(s, pred), want, "{what}: selected {name}s");
assert_eq!(any_selected_of(s, pred, |_| true), !want.is_empty(), "{what}: any {name}");
assert_eq!(has(s), has_by_ids(s, pred, msg), "{what}: has {name}");
}
assert_eq!(any_without_spine(s), without_spine_by_ids(s), "{what}: a blend without a spine");
}
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
s
}
fn id_of(v: &serde_json::Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
fn rect(s: &mut Session, x: f64) -> NodeId {
id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap())
}
fn select(s: &mut Session, ids: &[NodeId]) {
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
}
fn run(s: &mut Session, cmd: &str, ids: &[NodeId], p: serde_json::Value) -> NodeId {
select(s, ids);
id_of(&s.execute(cmd, &p).unwrap())
}
/// Every node id under the layers, parents before children (as Direct Selection can pick them).
fn all_ids(s: &Session) -> Vec<NodeId> {
fn walk(nodes: &[std::sync::Arc<Node>], out: &mut Vec<NodeId>) {
for n in nodes {
out.push(n.id);
if let Some(ch) = n.children() {
walk(ch, out);
}
}
}
let mut out = vec![];
for l in &s.doc().unwrap().doc.layers {
walk(l.children().map_or(&[][..], |c| c.as_slice()), &mut out);
}
out
}
/// The active document, to change in place.
fn doc_mut(s: &mut Session) -> &mut vectorcraft_doc::Document {
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc)
}
/// Set the selection's objects as given, stale and repeated ids included.
fn set_objects(s: &mut Session, ids: Vec<NodeId>) {
s.doc_mut().unwrap().selection.objects = ids;
}
/// Two blends, a blend in a key group of a third, an envelope and a mesh; one blend has no spine.
/// Returns the blends `a`, `b` and `c`, the group `g` of `c` that holds `a`, the envelope, and a key
/// of `a`.
fn document() -> (Session, [NodeId; 6]) {
let mut s = session();
let r: Vec<NodeId> = (0..10).map(|i| rect(&mut s, 40.0 * i as f64)).collect();
let a = run(&mut s, "object.blend.make", &[r[0], r[1]], json!({}));
let b = run(&mut s, "object.blend.make", &[r[2], r[3]], json!({}));
let g = run(&mut s, "object.group", &[a, r[4]], json!({}));
let c = run(&mut s, "object.blend.make", &[g, r[5]], json!({}));
let e = run(&mut s, "object.envelope.makeWithWarp", &[r[6]], json!({"style": "arch", "bend": 50}));
select(&mut s, &[r[7]]);
s.execute("object.mesh.create", &json!({"ids": [r[7].0], "rows": 1, "cols": 1})).unwrap();
if let Some(NodeKind::Blend { spec, .. }) = doc_mut(&mut s).node_mut(b).map(|n| &mut n.kind) {
spec.no_spine = true;
}
(s, [a, b, c, g, e, r[0]])
}
#[test]
fn selected_blends_envelopes_and_meshes_match_the_lookups_by_id() {
let (mut s, [a, b, c, g, e, inner_key]) = document();
s.execute("select.all", &json!({})).unwrap();
agree(&s, "select all");
let all = all_ids(&s);
let keys: Vec<NodeId> = all.iter().copied().filter(|id| ![a, b, c, g, e].contains(id)).collect();
set_objects(&mut s, keys.clone());
agree(&s, "keys, as Direct Selection picks them");
set_objects(&mut s, all.iter().rev().copied().collect());
agree(&s, "every node, children first");
set_objects(&mut s, vec![a, keys[0], b, keys[1], keys[0], NodeId(999_999), a]);
agree(&s, "repeated and stale ids, in first-seen order");
assert_eq!(selected_of(&s, is_blend), vec![a, b], "the blend with no spine is listed once, in order");
set_objects(&mut s, vec![NodeId(999_999)]);
agree(&s, "only a stale id");
set_objects(&mut s, vec![]);
agree(&s, "nothing");
// A blend in another blend's key group: the inner one.
set_objects(&mut s, vec![inner_key]);
agree(&s, "a key of a blend nested in another's key group");
assert_eq!(selected_of(&s, is_blend), vec![a]);
// An object of a dynamic symbol instance's art: nothing.
set_objects(&mut s, all.clone());
s.doc_mut().unwrap().selection.symbol_part = Some(SymbolPart { instance: a, path: vec![0] });
agree(&s, "a symbol part");
assert!(selected_of(&s, is_blend).is_empty());
}
/// A damaged tree: an earlier node of another kind with the id of a blend on the selected key's
/// path. `node` gives the earlier node, so that blend does not count, before and after the cache is
/// built again.
#[test]
fn a_repeated_id_counts_as_its_first_node() {
let (mut s, [a, _, c, _, _, inner_key]) = document();
let all = all_ids(&s);
s.doc().unwrap().doc.node(a);
let doc = doc_mut(&mut s);
if let Some(ch) = std::sync::Arc::make_mut(&mut doc.layers[0]).children_mut() {
ch.insert(0, std::sync::Arc::new(Node::group(a, vec![])));
}
set_objects(&mut s, all.clone());
agree(&s, "a repeated id, the cache older than the tree");
s.doc().unwrap().doc.drop_lookup_cache();
agree(&s, "a repeated id, no cache");
s.doc().unwrap().doc.node(a);
agree(&s, "a repeated id, cached afresh");
set_objects(&mut s, vec![inner_key]);
assert_eq!(selected_of(&s, is_blend), vec![c], "the nested blend's id is the group's, so the outer blend counts");
}
/// Large selections: with the lookup cache built, finding the selected blends looks no id up, and
/// the checks stop at the first selected object that has one.
#[test]
fn selected_blends_take_no_lookups_by_id() {
let mut s = session();
let mut keys = vec![];
for i in 0..300 {
let (x, y) = (rect(&mut s, i as f64), rect(&mut s, i as f64 + 30.0));
run(&mut s, "object.blend.make", &[x, y], json!({}));
keys.extend([x, y]);
}
for i in 0..1_000 {
rect(&mut s, i as f64);
}
s.execute("select.all", &json!({})).unwrap();
s.doc().unwrap().doc.drop_lookup_cache();
s.doc().unwrap().doc.node(keys[0]);
let before = vectorcraft_doc::path_lookups();
assert_eq!(selected_of(&s, is_blend).len(), 300);
assert!(!any_selected_of(&s, is_mesh, |_| true));
set_objects(&mut s, keys.clone());
assert_eq!(selected_of(&s, is_blend).len(), 300, "each blend once from its two keys");
assert_eq!(vectorcraft_doc::path_lookups() - before, 0, "lookups by id");
// The first key is in a blend: the check tests that key and its blend only.
static TESTED: AtomicUsize = AtomicUsize::new(0);
fn counted(n: &Node) -> bool {
TESTED.fetch_add(1, Ordering::Relaxed);
is_blend(n)
}
assert!(any_selected_of(&s, counted, |_| true));
assert_eq!(TESTED.load(Ordering::Relaxed), 2, "nodes tested");
}
/// `n` and everything under it with new ids.
fn renumber(d: &mut vectorcraft_doc::Document, n: &Node) -> Node {
let mut n = n.clone();
n.id = d.alloc_id();
if let Some(ch) = n.children_mut() {
for c in ch.iter_mut() {
*c = std::sync::Arc::new(renumber(d, c));
}
}
n
}
/// This thread's CPU time in nanoseconds, where the system reports it (Linux).
fn cpu_ns() -> Option<u64> {
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
}
/// Milliseconds one call of `f` takes over `calls` calls, in CPU time where the system reports it,
/// otherwise in wall-clock time.
fn ms_per_call(calls: u32, f: &dyn Fn()) -> f64 {
let (cpu, wall) = (cpu_ns(), std::time::Instant::now());
for _ in 0..calls {
f();
}
let ms = match (cpu, cpu_ns()) {
(Some(a), Some(b)) => b.saturating_sub(a) as f64 / 1e6,
_ => wall.elapsed().as_secs_f64() * 1e3,
};
ms / f64::from(calls)
}
/// The medians of 7 runs of `a` and of `b`, the runs taking turns.
fn medians(calls: u32, a: &dyn Fn(), b: &dyn Fn()) -> (f64, f64) {
let (mut ta, mut tb) = (vec![], vec![]);
for _ in 0..7 {
ta.push(ms_per_call(calls, a));
tb.push(ms_per_call(calls, b));
}
ta.sort_by(f64::total_cmp);
tb.sort_by(f64::total_cmp);
(ta[3], tb[3])
}
/// Timings of the lookups by id and of the one-path lookup on 100,000 rectangles in 10 layers,
/// 2,000 two-key blends (every fourth one in a group) and 200 envelopes, all selected. Run with
/// `cargo test --release -p vectorcraft-engine --lib selected_tests::timing -- --ignored --nocapture`.
#[test]
#[ignore = "timing; run by hand"]
fn timing_of_the_selected_blend_checks() {
let mut s = session();
let (a, b, c) = (rect(&mut s, 0.0), rect(&mut s, 40.0), rect(&mut s, 80.0));
let square = rect(&mut s, 120.0);
let blend = run(&mut s, "object.blend.make", &[a, b], json!({}));
let envelope = run(&mut s, "object.envelope.makeWithWarp", &[c], json!({"style": "arch", "bend": 50}));
let doc = doc_mut(&mut s);
let templates: Vec<Node> = [square, blend, envelope].iter().map(|id| doc.node(*id).cloned().unwrap()).collect();
let mut layers = vec![];
for l in 0..10 {
let mut layer = Node::layer(doc.alloc_id(), &format!("Layer {l}"), vectorcraft_doc::LayerColor::Preset(0));
let mut kids = vec![];
for _ in 0..10_000 {
kids.push(std::sync::Arc::new(renumber(doc, &templates[0])));
}
for i in 0..200 {
let b = renumber(doc, &templates[1]);
let b = if i % 4 == 0 { Node::group(doc.alloc_id(), vec![std::sync::Arc::new(b)]) } else { b };
kids.push(std::sync::Arc::new(b));
}
for _ in 0..20 {
kids.push(std::sync::Arc::new(renumber(doc, &templates[2])));
}
if let Some(ch) = layer.children_mut() {
*ch = kids;
}
layers.push(std::sync::Arc::new(layer));
}
doc.layers = layers;
s.execute("select.all", &json!({})).unwrap();
let first = s.doc().unwrap().selection.objects[0];
s.doc().unwrap().doc.drop_lookup_cache();
s.doc().unwrap().doc.node(first);
println!("{} objects selected", s.doc().unwrap().selection.objects.len());
type Check = fn(&Session) -> bool;
let checks: [(&str, Check, Check); 5] = [
("has_blend", |s| has_by_ids(s, is_blend, "").is_ok(), |s| has_blend(s).is_ok()),
("has_envelope", |s| has_by_ids(s, is_envelope, "").is_ok(), |s| has_envelope(s).is_ok()),
("has_mesh", |s| has_by_ids(s, is_mesh, "").is_ok(), |s| has_mesh(s).is_ok()),
(
"selected blends (object.blend.info and the Blend commands)",
|s| !selected_of_by_ids(s, is_blend).is_empty(),
|s| !selected_of(s, is_blend).is_empty(),
),
("a blend without a spine (Reverse Spine, the Blend panel)", without_spine_by_ids, any_without_spine),
];
assert_eq!(selected_of(&s, is_blend), selected_of_by_ids(&s, is_blend));
println!("| Check | Lookups by id (ms) | One path (ms) |");
println!("|---|---:|---:|");
for (name, by_ids, one_path) in checks {
assert_eq!(by_ids(&s), one_path(&s), "{name}");
let (old, new) = medians(
15,
&|| {
std::hint::black_box(by_ids(&s));
},
&|| {
std::hint::black_box(one_path(&s));
},
);
println!("| {name} | {old:.3} | {new:.3} |");
}
}
+79 -6
View File
@@ -1,6 +1,6 @@
//! Object menu long tail: Lock/Hide All Artwork Above & Other Layers, Transform Each, Reset
//! Bounding Box, Rasterize, Crop Image, Mask (an image), Create Trim Marks, Convert to Shape and
//! Artboards → Convert / Rearrange. (Live blends are in `live.rs`.)
//! Bounding Box, Rotate Bounding Box, Rasterize, Crop Image, Mask (an image), Create Trim Marks,
//! Convert to Shape and Artboards → Convert / Rearrange. (Live blends are in `live.rs`.)
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::sync::Arc;
@@ -15,8 +15,8 @@ use vectorcraft_render::encode::{RasterExportOptions, RasterFormat};
use super::edit::{duplicate_in, selected_roots, selected_roots_to_transform};
use super::{
CommandSpec, EngineError, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, fileio, find_command, has_doc, has_selected_member,
has_selection, switch_or,
CommandSpec, EngineError, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, fileio, find_command, has_doc,
has_selected_member, has_selection, switch_or,
};
/// Session-level (not saved) state owned by the menu commands.
@@ -110,6 +110,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_selection,
reset_bounding_box
),
cmd!(
"object.rotateBoundingBox",
"Rotate Bounding Box…",
["Object", "Transform"],
None,
"{angle: degrees (counter-clockwise), absolute?: bool (true: turn the box to angle; default false: turn it by angle from the angle the selected objects share, 0 when theirs differ)} turn the bounding box of the selected objects to one angle without moving their art; the objects inside them (the children of groups, compound paths, clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks) turn with them and keep their angle relative to them; a path of a compound path selected on its own turns only its own box; one undo step, none when every box is already at the angle; object.resetBoundingBox squares the boxes again; a missing or non-numeric angle is an error → {angle: the new angle of the boxes, in (-180, 180], changed: objects whose box turned, the objects inside the selected ones included}",
has_selection,
rotate_bounding_box
),
cmd!(
"object.rasterize",
"Rasterize…",
@@ -225,9 +234,10 @@ pub(crate) fn squash(s: &mut Session, from: usize, label: &str) {
// ---------- Reset Bounding Box ----------
/// Squares each selected object and every object inside it: the children of groups, compound paths,
/// clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks.
/// clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks. A
/// path of a compound path selected on its own is squared alone, as the transforms move it alone.
fn reset_bounding_box(s: &mut Session, _: &Value) -> Result<Value> {
let ids = selected_roots(s)?;
let ids = selected_roots_to_transform(s)?;
let d = &s.doc()?.doc;
let mut changed = 0;
let squared: Vec<(NodeId, Node)> = ids
@@ -251,6 +261,69 @@ fn reset_bounding_box(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({ "changed": changed }))
}
// ---------- Rotate Bounding Box ----------
/// Turns the bounding box of the selected objects to one angle without moving their art: by `angle`
/// from the angle they share (0 when it differs), or to `angle` with `absolute`. Each object's box
/// turns by what takes it there, and so do the boxes of the objects inside it (the children of
/// groups and the art of linked opacity masks), which keep their angle relative to it.
fn rotate_bounding_box(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.rotateBoundingBox";
// A JSON number is always finite.
let angle = f64_req(p, "angle", C)?;
let absolute = switch_or(p, "absolute", false, C)?;
// The same objects the transforms move: a path of a compound path selected on its own turns
// its own box. Layers are left out, as they have no box.
let owners = selected_roots_to_transform(s)?;
let d = &s.doc()?.doc;
let start = if absolute { 0.0 } else { d.bbox_angle(&owners) };
// An angle within the tolerance of 0 is stored as 0, as `Node::turn_boxes` stores it.
let target = match vectorcraft_geom::normalize_deg(start + angle) {
a if a.abs() <= BOX_EPS_DEG => 0.0,
a => a,
};
let mut changed = 0;
let turned: Vec<(NodeId, Node)> = owners
.iter()
.filter_map(|id| {
let n = d.node(*id)?;
let by = vectorcraft_geom::normalize_deg(target - n.bbox_angle);
(by.abs() > BOX_EPS_DEG).then(|| {
let mut c = n.clone();
c.turn_boxes(by);
// The selected object's box is set to the target itself, so repeated turns add no
// rounding error to it.
c.bbox_angle = target;
changed += boxes(&c);
(*id, c)
})
})
.collect();
if !turned.is_empty() {
s.edit("Rotate Bounding Box", |d, _| {
for (id, n) in turned {
if let Some(slot) = d.node_mut(id) {
*slot = n;
}
}
Ok(())
})?;
}
Ok(json!({ "angle": target, "changed": changed }))
}
/// Angles closer than this (degrees) are the same, as `vectorcraft_doc::orient` compares them.
const BOX_EPS_DEG: f64 = 1e-6;
/// The number of objects in `n`'s subtree whose box [`Node::turn_boxes`] turns: `n`, its children
/// and the art of a linked opacity mask, layers left out.
fn boxes(n: &Node) -> usize {
let own = usize::from(!n.is_layer());
let children: usize = n.children().into_iter().flatten().map(|c| boxes(c)).sum();
let mask = n.extras().mask.as_ref().filter(|m| m.linked).map_or(0, |m| boxes(&m.art));
own + children + mask
}
/// A copy of `n` with the angle of every object in its subtree set to 0, or `None` when no box in
/// it stands at an angle, and the number of objects squared. The subtree takes in children and the
/// art of linked opacity masks (an unlinked mask's art turns on its own); layers have no box. Only
+34 -2
View File
@@ -7,12 +7,16 @@
//! panel's New Art Has Basic Appearance off, the whole appearance of the last selection. With the
//! option on (the default) an inherited appearance gives new art its top stroke's options only,
//! and a change of selection loads only the proxies. `paint.default` resets it.
//!
//! A document whose Default Graphic Style no longer has the shipped look (a New Document profile
//! redefined it) gives the reset that style's fills, strokes and effects instead, and `file.new`
//! resets new art when it opens such a document.
use std::borrow::Cow;
use serde_json::{Value, json};
use vectorcraft_color::{BlendMode, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, GraphicStyle, Node, NodeKind, StrokeLayer};
use vectorcraft_doc::{Appearance, AppearanceItem, ColorMode, DEFAULT_GRAPHIC_STYLE, Document, FillLayer, GraphicStyle, Node, NodeKind, StrokeLayer};
use vectorcraft_tools::PaintDefaults;
use super::gradient::unplaced;
@@ -263,7 +267,35 @@ fn describe(s: &mut Session, _: &Value) -> Result<Value> {
}))
}
/// The defaults for new art reset (`paint.default`): white fill, 1 pt black stroke, no template.
/// The defaults for new art reset (`paint.default`): white fill, 1 pt black stroke, no template;
/// in a document whose Default Graphic Style was redefined, that style's fills, strokes and effects
/// at full opacity, not linked to the style.
pub(crate) fn reset(s: &mut Session) {
s.paint = PaintDefaults::default();
let style = s.doc().ok().and_then(|st| redefined_default_style(&st.doc)).cloned();
if let Some(g) = style {
let ap = if g.unit_box { g.appearance } else { unplace_all(g.appearance) };
s.take_new_art(ap, 1.0, BlendMode::Normal, None, false);
}
}
/// `d`'s Default Graphic Style when its fills, strokes, effects or transparency differ from the
/// shipped style's (white fill, 1 pt black stroke), the shipped colors converted to `d`'s color mode
/// as a New Document profile's are.
pub(crate) fn redefined_default_style(d: &Document) -> Option<&GraphicStyle> {
let g = d.graphic_styles.iter().find(|g| g.name == DEFAULT_GRAPHIC_STYLE)?;
let same =
|o: &GraphicStyle| (&o.appearance, o.opacity, o.blend, o.isolate, o.knockout) == (&g.appearance, g.opacity, g.blend, g.isolate, g.knockout);
if same(&GraphicStyle::new(DEFAULT_GRAPHIC_STYLE, Appearance::default_art())) {
return None;
}
if d.color_mode != ColorMode::Rgb {
let mut shipped = Document::new_with_mode(1.0, 1.0, ColorMode::Rgb);
shipped.graphic_styles.retain(|o| o.name == DEFAULT_GRAPHIC_STYLE);
super::colormgmt::set_color_mode(&mut shipped, d.color_mode, true, None, super::colormgmt::Grays::Profile);
if shipped.graphic_styles.first().is_some_and(same) {
return None;
}
}
Some(g)
}
+4
View File
@@ -814,6 +814,10 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result<Value> {
// The profile's links keep their relative paths, which name places from the profile's file, as
// a new document from a history state keeps its source's.
s.doc_mut()?.links_from = links_from;
// A profile whose Default Graphic Style was redefined gives new art in the document that style.
if super::newart::redefined_default_style(&s.doc()?.doc).is_some() {
super::newart::reset(s);
}
// Overprint Preview is the engine's (the UI turns Pixel Preview on from `previewMode`). Both
// are views of the whole app, so Default leaves them as they are.
if settings.preview_mode == PreviewMode::Overprint {
+1
View File
@@ -42,3 +42,4 @@ pub(crate) use pixelgrid::{
};
pub(super) use shape::recut;
pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects};
pub use transform::{reflect_axis, scale_factors, shear_tangent};
+14 -3
View File
@@ -384,6 +384,11 @@ fn add_drawn_live_paint(s: &mut Session, isolated: NodeId, next: Option<NodeId>)
}
pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
let key = "all";
let all = match p.get(key) {
None => false,
Some(v) => v.as_bool().ok_or_else(|| bad("object.exitIsolation", format!("`{key}` must be true or false")))?,
};
// Opacity mask editing, pattern editing and symbol editing isolate their editing layer. Leaving
// isolation mode then leaves that mode, as Stop Editing Opacity Mask and the isolation bar's
// Done do. A group isolated inside the symbol's art goes back to the symbol's layer.
@@ -419,12 +424,18 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
return ok();
}
let menu = s.menu.clone();
let prev = s.active().and_then(|d| d.isolation);
let prev = st.isolation;
// An isolated sublayer goes up to its parent layer, which stays isolated, unless `all` is true or
// that layer is hidden or locked; anything else leaves isolation mode.
let up = prev
.filter(|i| !all && st.doc.node(*i).is_some_and(Node::is_layer))
.and_then(|i| st.doc.parent_of(i))
.filter(|parent| st.doc.is_editable(*parent));
if let Some(i) = prev {
crate::cmd::settle_interaction(s)?;
let left = add_drawn_live_paint(s, i, None)?.unwrap_or(i);
let left = add_drawn_live_paint(s, i, up)?.unwrap_or(i);
let st = s.doc_mut()?;
st.isolation = None;
st.isolation = up;
crate::cmd::distortcmds::finish_edit_text(st, i);
let target = st.doc.parent_of(left).filter(|p| st.doc.node(*p).is_some_and(|n| n.extras().shaper.is_some())).unwrap_or(left);
st.selection.set([target]);
+1 -1
View File
@@ -59,7 +59,7 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64, anchor
let refi = reference_index(p)?;
let st = s.doc()?;
check_switches(p, &TRANSFORM_SWITCHES, "object.setBounds")?;
check_switches(p, &["proportional"], "object.setBounds")?;
check_switches(p, &["proportional", "interpolate"], "object.setBounds")?;
let how = s.bounds_measure();
if anchors
&& transforms_objects(p)
+8 -8
View File
@@ -16,7 +16,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Transform",
[],
None,
"{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), releaseOutside?: bool} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects); strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do",
"{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), releaseOutside?: bool, interpolate?: bool (with anchors and a matrix that only moves them: the handles of each segment with one moved end are re-mapped, as path.moveAnchors's; default: prefs interpolateControlPoints)} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects); strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do",
has_doc,
transform
),
@@ -25,7 +25,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move…",
["Object", "Transform"],
Some("Cmd+Shift+M"),
"{ids?: [id…] (selected first; default: the selection), dx, dy, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
"{ids?: [id…] (selected first; default: the selection), dx, dy, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
has_selection_or_guides,
move_cmd
),
@@ -61,7 +61,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Shear…",
["Object", "Transform"],
None,
"{ids?: [id…] (selected first; default: the selection), angle: deg (positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\", origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
"{ids?: [id…] (selected first; default: the selection), angle: deg (-359 to 359, sheared by its tangent, so 120 slants as -60; 0 and ±180 have no slant and, without copy, change nothing; ±90 and ±270 are an error; positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\"|deg (the line the art slides along, counter-clockwise from horizontal on the page, -359 to 359; 0: horizontal, 90: vertical; omitted: horizontal), origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
has_selection,
shear
),
@@ -70,7 +70,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Transform Again",
["Object", "Transform"],
Some("Cmd+D"),
"{copy?, strokes?, corners?, patterns?, typeAreas?: bool (as object.transform's; default: the value the transform it repeats used, else object.transform's default)} the last transform's matrix on the selection (after a perspective move or scale: that plane-space transform, without these params)",
"{copy?, strokes?, corners?, patterns?, typeAreas?, interpolate?: bool (as object.transform's; default: the value the transform it repeats used, else object.transform's default)} the last transform's matrix on the selection (after a perspective move or scale: that plane-space transform, without these params)",
has_selection,
transform_again
),
@@ -79,7 +79,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Nudge",
[],
None,
"{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} arrow-key nudge by the keyboard increment (the selected anchors, else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)",
"{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)} arrow-key nudge by the keyboard increment (the selected anchors, else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)",
has_selection_or_guides,
nudge
),
@@ -250,7 +250,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Exit Isolation Mode",
[],
None,
"{} leave isolation mode; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same",
"{all?: bool (default false)} leave isolation mode; from an isolated sublayer, go up one level to its parent layer instead (the next call goes up again), unless all is true or the parent layer is hidden or locked; no undo step for the move up; while a symbol is edited, a group isolated in its art goes back to the symbol's layer first, with or without all; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same",
has_doc,
exit_isolation
),
@@ -295,7 +295,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Set Bounds",
[],
None,
"{x?, y?, width?, height?, reference?: whole number >= 0 (9-point grid 0..8; 0.0 equals 0; a whole number past 8 is read as 8; omitted/null: center, 4), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))",
"{x?, y?, width?, height?, reference?: whole number >= 0 (9-point grid 0..8; 0.0 equals 0; a whole number past 8 is read as 8; omitted/null: center, 4), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (with anchor points selected and only x or y changed: as path.moveAnchors's; default: prefs interpolateControlPoints)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))",
has_selection,
set_bounds
),
@@ -305,7 +305,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Shape Properties",
[],
None,
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse)} (Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius)",
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint)} (Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
has_selection,
set_live_shape
),
+71 -3
View File
@@ -6,6 +6,7 @@ use super::{
BTreeSet, CornerKind, EngineError, LiveCorners, LiveShape, NodeId, NodeKind, Result, Session, Value, bad, check_numbers, check_switches,
convert_radii_relative, ok, selected_roots, set_corners, targets,
};
use crate::MAX_COORD;
/// The largest scale of 0 or more at which `spans`, with the margins that scale grown by `k`,
/// reach across `size` together. Returns 1 when their geometric boxes reach 1e-9 or less across
@@ -98,8 +99,32 @@ fn corners_param(p: &Value) -> Result<Option<BTreeSet<usize>>> {
list.iter().map(|k| k.as_u64().and_then(|k| usize::try_from(k).ok()).ok_or_else(err)).collect::<Result<_>>().map(Some)
}
/// Live line `l` with Line Length `len` (its first end stays) and then Line Angle `angle` (about
/// its midpoint; a line whose ends meet has none to turn), or None when neither changes it.
fn line_edit(l: &LiveShape, len: Option<f64>, angle: Option<f64>) -> Option<LiveShape> {
let now = l.line_length()?;
let mut new = l.clone();
let mut changed = false;
if let Some(len) = len
&& (len - now).abs() > 1e-9 * len.max(now)
{
new.set_line_length(len);
changed = true;
}
if let Some(a) = angle
&& new.line_length().is_some_and(|n| n > 0.0)
&& let Some(turn) = new.line_angle().map(|now| (a - now).rem_euclid(360.0))
&& turn > 1e-9
&& turn < 360.0 - 1e-9
{
new.set_line_angle(a);
changed = true;
}
(changed && new != *l).then_some(new)
}
pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
check_switches(p, &["invertPie", "makeSidesEqual", "relativeRadii"], "object.setLiveShape")?;
check_switches(p, &["constrainPie", "invertPie", "makeSidesEqual", "relativeRadii"], "object.setLiveShape")?;
check_numbers(p, &["radius", "sides"], "object.setLiveShape")?;
// `items`: objects each with its own `corners`; else `ids` (or the selection) sharing them.
let items = match p.get("items").filter(|v| !v.is_null()) {
@@ -148,7 +173,7 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
}
};
let angle = |k: &str| Ok::<_, EngineError>(number(k, |_| true, "an angle in degrees")?.map(|a| a.rem_euclid(360.0)));
let length = |k: &str| number(k, |x| x > 0.0 && x <= crate::MAX_COORD, "a length in points above 0");
let length = |k: &str| number(k, |x| x > 0.0 && x <= MAX_COORD, "a length in points above 0");
// Saved steps ([`Session::replay`]) can hold values a direct call refuses, recorded before these
// checks: a negative radius is 0, a whole side count of 0 or more is brought into 3 to 1000, and
// a fractional or negative one is ignored. A whole number written as 5.0 counts as 5, as in a
@@ -168,21 +193,58 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
// An ellipse's pie (Ellipse Properties: Pie Start and End Angle, degrees; Invert Pie swaps them).
let (pie_start, pie_end) = (angle("pieStart")?, angle("pieEnd")?);
let invert = p.get("invertPie").and_then(Value::as_bool) == Some(true);
// Constrain Pie Angle: the one angle given moves the other by as much, so each ellipse keeps
// its span (its end angle less its start angle, counterclockwise).
let constrain = p.get("constrainPie").and_then(Value::as_bool) == Some(true);
if constrain && (invert || pie_start.is_some() == pie_end.is_some()) {
return Err(bad("object.setLiveShape", "`constrainPie` needs one of `pieStart` and `pieEnd`, without `invertPie`"));
}
// A polygon's Polygon Properties: its angle, radius or side length, Make Sides Equal.
let (polygon_angle, polygon_radius, side) = (angle("polygonAngle")?, length("polygonRadius")?, length("sideLength")?);
let equal = p.get("makeSidesEqual").and_then(Value::as_bool) == Some(true);
// A line's Line Properties: its length (its first end stays) and its angle (about its midpoint).
// A line's length can reach across the whole canvas, past `MAX_COORD`: its ends are checked below.
let line_length = number("lineLength", |x| x > 0.0, "a length in points above 0")?;
let line_angle = angle("lineAngle")?;
// An ellipse's pie becomes `pie_of(pie)`. An end of 0 is a full turn (Illustrator shows a whole
// ellipse as 0° to 360°).
let end_of = |a: f64| if a == 0.0 { 360.0 } else { a };
let pie_of = |pie: (f64, f64)| {
let pie = (pie_start.unwrap_or(pie.0), pie_end.map_or(pie.1, end_of));
let span = (pie.1 - pie.0).rem_euclid(360.0);
let pie = match (constrain, pie_start, pie_end) {
// The angle it already has: nothing moves.
(true, Some(a), _) if a == pie.0 => pie,
(true, _, Some(a)) if end_of(a) == pie.1 => pie,
// A whole ellipse (a span of 0) stays whole.
(true, Some(a), _) => (a, end_of((a + span).rem_euclid(360.0))),
(true, _, Some(a)) => ((a - span).rem_euclid(360.0), end_of(a)),
_ => (pie_start.unwrap_or(pie.0), pie_end.map_or(pie.1, end_of)),
};
if invert { (pie.1.rem_euclid(360.0), end_of(pie.0)) } else { pie }
};
// When every value given is the current one, the document and its undo history stay as they
// are.
let st = s.doc()?;
// The lines that Line Length or Line Angle changes, as they become. A line that would reach
// past the document's coordinate limit is an error before anything changes.
let mut lines = std::collections::BTreeMap::new();
if line_length.is_some() || line_angle.is_some() {
for id in &ids {
let Some(NodeKind::Path { live: Some(l), .. }) = st.doc.node(*id).map(|n| &n.kind) else { continue };
if let Some(new) = line_edit(l, line_length, line_angle) {
let LiveShape::Line { a, b } = &new else { continue };
if ![a.x, a.y, b.x, b.y].iter().all(|c| c.abs() <= MAX_COORD) {
return Err(bad("object.setLiveShape", format!("coordinate out of range (limit ±{MAX_COORD} pt)")));
}
lines.insert(*id, new);
}
}
}
let has_values = |id: &NodeId| {
let Some(NodeKind::Path { path, live, .. }) = st.doc.node(*id).map(|n| &n.kind) else { return true };
if lines.contains_key(id) {
return false;
}
match live.as_deref() {
Some(l @ LiveShape::Polygon { sides: now, .. })
if !(sides.is_none_or(|n| n.clamp(3, 1000) == u64::from(*now))
@@ -244,6 +306,12 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
}
*path = l.to_path();
}
if let Some(new) = lines.get(id)
&& let Some(l) = live.as_deref_mut()
{
*l = new.clone();
*path = l.to_path();
}
if let Some(on) = relative_radii
&& let Some(l) = live.as_deref_mut()
{
+83 -22
View File
@@ -125,9 +125,14 @@ fn apply_transform_moving_guides(
let d = &s.doc()?.doc;
let paths = d.index_paths(ids.iter().copied());
let none = paths.is_empty() && !has_guides;
// A move of direct-selected anchors may re-map the handles beside them (`interpolate`).
let mut interpolate = None;
let ids = if anchors && objects && !copy && !s.doc()?.selection.anchors.is_empty() {
if c[..4] == [1.0, 0.0, 0.0, 1.0] {
interpolate = Some(crate::cmd::path::interpolates_handles(s, p, label)?);
}
if xf != Affine::IDENTITY {
crate::cmd::path::transform_anchors(s, label, xf, sc)?;
crate::cmd::path::transform_anchors(s, label, xf, sc, interpolate.unwrap_or(false))?;
}
ids
} else if none || (!copy && xf == Affine::IDENTITY) {
@@ -195,6 +200,9 @@ fn apply_transform_moving_guides(
options["strokes"] = json!(sc.strokes);
options["corners"] = json!(!sc.keep_corners);
}
if let Some(on) = interpolate {
options["interpolate"] = json!(on);
}
st.last_transform = Some(LastTransform::Matrix(xf, options));
st.last_perspective = None;
}
@@ -248,7 +256,7 @@ fn resize_type_area(n: &mut Node, xf: Affine) -> bool {
pub(super) fn transform(s: &mut Session, p: &Value) -> Result<Value> {
check_switches(p, &TRANSFORM_SWITCHES, "object.transform")?;
check_switches(p, &["anchors", "releaseOutside"], "object.transform")?;
check_switches(p, &["anchors", "releaseOutside", "interpolate"], "object.transform")?;
let m = matrix_param(p, "matrix").ok_or_else(|| bad("object.transform", "missing matrix [a,b,c,d,e,f]"))?;
// An object selected in a symbol instance's art stays where the symbol puts it: the selection
// is left as it is, and the reply's warning goes to the status bar.
@@ -292,6 +300,7 @@ pub(super) fn transform(s: &mut Session, p: &Value) -> Result<Value> {
pub(super) fn move_cmd(s: &mut Session, p: &Value) -> Result<Value> {
check_numbers(p, &["dx", "dy"], "object.move")?;
check_switches(p, &TRANSFORM_SWITCHES, "object.move")?;
check_switches(p, &["interpolate"], "object.move")?;
let ids = selected_roots_to_transform(s)?;
apply_transform(s, "Move", ids, Affine::translate((f64_or(p, "dx", 0.0), f64_or(p, "dy", 0.0))), p, true)
}
@@ -311,7 +320,7 @@ pub(crate) fn along_constrain_angle(dx: f64, dy: f64, deg: f64) -> (f64, f64) {
pub(super) fn nudge(s: &mut Session, p: &Value) -> Result<Value> {
check_numbers(p, &["dx", "dy"], "object.nudge")?;
check_switches(p, &TRANSFORM_SWITCHES, "object.nudge")?;
check_switches(p, &["big"], "object.nudge")?;
check_switches(p, &["big", "interpolate"], "object.nudge")?;
let k = s.prefs.keyboard_increment * if bool_or(p, "big", false) { 10.0 } else { 1.0 };
let (dx, dy) = (f64_or(p, "dx", 0.0) * k, f64_or(p, "dy", 0.0) * k);
// Guides keep to the page's axes; art and anchors move along the constrain angle's.
@@ -322,7 +331,7 @@ pub(super) fn nudge(s: &mut Session, p: &Value) -> Result<Value> {
if dx == 0.0 && dy == 0.0 {
return ok();
}
return crate::cmd::path::move_anchors(s, &json!({ "dx": dx, "dy": dy, "patterns": p.get("patterns") }));
return crate::cmd::path::move_anchors(s, &json!({ "dx": dx, "dy": dy, "patterns": p.get("patterns"), "interpolate": p.get("interpolate") }));
}
if s.doc()?.selection.is_empty() {
let copy = bool_or(p, "copy", false);
@@ -360,15 +369,22 @@ pub(super) fn scale(s: &mut Session, p: &Value) -> Result<Value> {
check_switches(p, &TRANSFORM_SWITCHES, "object.scale")?;
let ids = selected_roots_to_transform(s)?;
let o = origin_of(s, p, &ids)?;
let sx = f64_req(p, "sx", "object.scale")? / 100.0;
let sy = f64_or(p, "sy", sx * 100.0) / 100.0;
if sx == 0.0 || sy == 0.0 {
return Err(bad("object.scale", "scale must be non-zero"));
}
let sx = f64_req(p, "sx", "object.scale")?;
let (sx, sy) = scale_factors(sx, f64_or(p, "sy", sx)).map_err(|e| bad("object.scale", e))?;
let frame = basis_frame(s, p, "object.scale", &ids)?;
apply_transform(s, "Scale", ids, about(o, frame.conjugate(Affine::scale_non_uniform(sx, sy))), p, true)
}
/// The factors `object.scale` applies for `sx` and `sy` in percent, or the error it returns when
/// either factor is 0.
pub fn scale_factors(sx: f64, sy: f64) -> std::result::Result<(f64, f64), String> {
let (sx, sy) = (sx / 100.0, sy / 100.0);
if sx == 0.0 || sy == 0.0 {
return Err("scale must be non-zero".into());
}
Ok((sx, sy))
}
/// The frame that `object.scale` and a named `object.reflect` act in, from the `basis` param:
/// `"box"` (the default) is the bounding box of `ids`, turned with rotated objects until Reset
/// Bounding Box ([`Document::bbox_angle`]); `"page"` is the page's axes. Anchors selected with
@@ -393,16 +409,7 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result<Value> {
let ids = selected_roots_to_transform(s)?;
let o = origin_of(s, p, &ids)?;
// A named axis is the bounding box's own (see [`basis_frame`]); an angle is a line on the page.
let named = match p.get("axis") {
Some(Value::String(a)) if a == "horizontal" => Some(Affine::scale_non_uniform(1.0, -1.0)),
Some(Value::Number(_)) => None,
None | Some(Value::Null) => Some(Affine::scale_non_uniform(-1.0, 1.0)),
Some(Value::String(a)) if a == "vertical" => Some(Affine::scale_non_uniform(-1.0, 1.0)),
Some(v) => {
let given = v.as_str().map_or_else(|| v.to_string(), str::to_string);
return Err(bad("object.reflect", format!("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{given}`")));
}
};
let named = reflect_axis(p.get("axis")).map_err(|e| bad("object.reflect", e))?;
let m = match named {
Some(m) => basis_frame(s, p, "object.reflect", &ids)?.conjugate(m),
None => {
@@ -414,22 +421,76 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result<Value> {
apply_transform(s, "Reflect", ids, about(o, m), p, true)
}
/// The reflection `object.reflect` applies for its `axis` param: the matrix for a named axis
/// (`"vertical"`, the default, or `"horizontal"`), in the bounding box's frame; `None` for an angle,
/// which is a line on the page; or the error for any other value.
pub fn reflect_axis(axis: Option<&Value>) -> std::result::Result<Option<Affine>, String> {
match axis {
Some(Value::String(a)) if a == "horizontal" => Ok(Some(Affine::scale_non_uniform(1.0, -1.0))),
Some(Value::Number(_)) => Ok(None),
None | Some(Value::Null) => Ok(Some(Affine::scale_non_uniform(-1.0, 1.0))),
Some(Value::String(a)) if a == "vertical" => Ok(Some(Affine::scale_non_uniform(-1.0, 1.0))),
Some(v) => {
let given = v.as_str().map_or_else(|| v.to_string(), str::to_string);
Err(format!("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{given}`"))
}
}
}
/// Angles closer than this many degrees to ±90 or ±270, or to 0 or ±180, count as those angles. It
/// is far above the rounding error of an angle up to 359° and below any angle a field shows.
const SHEAR_ANGLE_TOLERANCE: f64 = 1e-9;
/// The slant `object.shear` applies for `angle` in degrees: its tangent, and 0 for 0 and ±180. An
/// angle outside -359 to 359, or ±90 or ±270, is an error.
pub fn shear_tangent(angle: f64) -> std::result::Result<f64, String> {
if !(-359.0..=359.0).contains(&angle) {
return Err(format!("`angle` must be from -359 to 359 degrees, not {angle}"));
}
// ±90 and ±270 slant an edge onto the shear axis: their tangent is unbounded.
let flat = angle.rem_euclid(180.0);
if (flat - 90.0).abs() < SHEAR_ANGLE_TOLERANCE {
return Err(format!("`angle` cannot be {angle}: ±90 and ±270 degrees have no shear"));
}
// 0 and ±180 have no slant, but the tangent of ±180° in radians is about 1e-16, not 0.
Ok(if flat < SHEAR_ANGLE_TOLERANCE || 180.0 - flat < SHEAR_ANGLE_TOLERANCE { 0.0 } else { angle.to_radians().tan() })
}
pub(super) fn shear(s: &mut Session, p: &Value) -> Result<Value> {
check_numbers(p, &["angle"], "object.shear")?;
check_switches(p, &TRANSFORM_SWITCHES, "object.shear")?;
let t = shear_tangent(f64_or(p, "angle", 0.0)).map_err(|e| bad("object.shear", e))?;
let ids = selected_roots_to_transform(s)?;
let o = origin_of(s, p, &ids)?;
let t = f64_or(p, "angle", 0.0).clamp(-89.0, 89.0).to_radians().tan();
let vertical = choice(p, "object.shear", "axis", &["horizontal", "vertical"])? == Some("vertical");
let m = if vertical { Affine::new([1.0, t, 0.0, 1.0, 0.0, 0.0]) } else { Affine::new([1.0, 0.0, -t, 1.0, 0.0, 0.0]) };
let horizontal = Affine::new([1.0, 0.0, -t, 1.0, 0.0, 0.0]);
// A named axis, or a line on the page at an angle in degrees, counter-clockwise from horizontal.
let m = match p.get("axis") {
None | Some(Value::Null) => horizontal,
Some(Value::String(a)) if a == "horizontal" => horizontal,
Some(Value::String(a)) if a == "vertical" => Affine::new([1.0, t, 0.0, 1.0, 0.0, 0.0]),
Some(Value::Number(n)) if n.as_f64().is_some_and(|a| (-SHEAR_AXIS_MAX..=SHEAR_AXIS_MAX).contains(&a)) => {
// y is down, so the page's counter-clockwise angle turns the other way on screen.
let r = -n.as_f64().unwrap_or(0.0).to_radians();
Affine::rotate(r) * horizontal * Affine::rotate(-r)
}
Some(v) => {
let given = v.as_str().map_or_else(|| v.to_string(), str::to_string);
let range = format!("from -{SHEAR_AXIS_MAX} to {SHEAR_AXIS_MAX}");
return Err(bad("object.shear", format!("axis must be \"horizontal\", \"vertical\" or an angle in degrees {range}, not `{given}`")));
}
};
apply_transform(s, "Shear", ids, about(o, m), p, true)
}
/// The largest angle, either way from horizontal, of the axis `object.shear` takes in degrees.
const SHEAR_AXIS_MAX: f64 = 359.0;
/// The last transform on the selection, with the options `last_transform` keeps for it; an option
/// that `p` sets to true or false (a recorded Transform Again's) takes precedence. A Transform
/// Each is repeated by running it again (its transform is per object, about each one's bounds).
pub(super) fn transform_again(s: &mut Session, p: &Value) -> Result<Value> {
check_switches(p, &TRANSFORM_SWITCHES, "object.transformAgain")?;
check_switches(p, &["interpolate"], "object.transformAgain")?;
if let Some(again) = s.doc()?.last_perspective.clone() {
return crate::cmd::distortcmds::transform_again(s, &again);
}
+85 -18
View File
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Package",
[],
None,
"{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder. The warnings and the report name a file outside the automation read roots by its file name. Under automation read roots, the package is refused, before any file is written, while the document, or a linked native document or a linked PDF, .ai or EPS file's native document, links a JavaScript file outside them (svgInteractivity; a URL is not checked)",
"{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder. The warnings and the report name a file outside the automation read roots by its file name. Under automation read roots, the package is refused, before any file is written, while the document, or a linked native document or a linked PDF, .ai or EPS file's native document, links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while a linked native document, or a linked PDF, .ai or EPS file that carries one, can't be read to check it (a damaged file, or a PDF that needs a password to open); a PDF or EPS file without editing data is copied",
has_doc,
package
)]
@@ -113,27 +113,86 @@ thread_local! {
pub(crate) static PARTS_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// The native document that the linked file `name` (`bytes`) is, or carries as the editing data of
/// a PDF, `.ai` or EPS file; `None` for other files and for data that can't be read.
fn carried_document(name: &str, bytes: &[u8]) -> Option<Document> {
if super::place::document::is_native(name, bytes) {
return vectorcraft_format::load_file(bytes).ok().map(|f| f.doc);
}
let data =
if super::place::document::is_pdf(name, bytes) { vectorcraft_pdf::editing(bytes).map(|e| e.data) } else { vectorcraft_eps::native(bytes) };
vectorcraft_format::load(&data?).ok()
/// The native document a linked file is or carries ([`carried_document`]).
enum Carried {
/// The file is no native document and carries none: an image, or a PDF, `.ai` or EPS file
/// without editing data.
Absent,
/// The native document, read.
Readable(Box<Document>),
/// The file is a native document, or carries one, that can't be read: a damaged native file,
/// a PDF or `.ai` file that can't be opened without a password or can't be read at all, a PDF
/// or `.ai` file listing an editing file whose data can't be resolved, a PDF or `.ai` file
/// whose attachments are too many to search to their end, or editing data that doesn't read as
/// a native document.
Unreadable,
}
/// The native document that the linked file `name` (`bytes`) is, or carries as the editing data of
/// a PDF, `.ai` or EPS file.
fn carried_document(name: &str, bytes: &[u8]) -> Carried {
let read = |data: &[u8]| vectorcraft_format::load(data).map_or(Carried::Unreadable, |d| Carried::Readable(Box::new(d)));
if super::place::document::is_native(name, bytes) {
return vectorcraft_format::load_file(bytes).map_or(Carried::Unreadable, |f| Carried::Readable(Box::new(f.doc)));
}
if super::place::document::is_pdf(name, bytes) {
// A PDF that can't be opened may carry editing data all the same.
return match vectorcraft_pdf::open_pdf(bytes, None) {
// Attachments left unsearched may list another editing file, which can't be checked.
Ok(opened) if opened.editing_search_cut() => Carried::Unreadable,
// An editing file listed whose data can't be resolved can't be checked either.
Ok(opened) => match opened.editing() {
Some(e) => read(&e.data),
None if opened.has_editing_file() => Carried::Unreadable,
None => Carried::Absent,
},
Err(_) => Carried::Unreadable,
};
}
if !vectorcraft_eps::has_native(bytes) {
return Carried::Absent;
}
vectorcraft_eps::native(bytes).map_or(Carried::Unreadable, |data| read(&data))
}
/// The error for a linked file the package would copy whose native document can't be read to
/// check the files and folders it names against the read roots.
const UNREADABLE: &str = "a linked file's editing data can't be read to check it against the read roots";
/// Under read roots, the linked file `name` (`bytes`, found at `path`) is copied only when the
/// native document it is or carries ([`carried_document`]) links no JavaScript file outside them (a
/// relative path taken from the file's folder): the copy would name it.
/// native document it is or carries ([`carried_document`]) can be read and links no JavaScript file
/// outside them (a relative path taken from the file's folder): the copy would name it. A file
/// whose native document can't be read is refused, as its links can't be checked. The error names
/// no file or folder.
fn check_carried_scripts(name: &str, bytes: &[u8], path: &str) -> Result<()> {
if crate::file_access::current().is_none() {
return Ok(());
}
match carried_document(name, bytes) {
Some(carried) => super::fileio::check_scripts_of(C, &carried, Some(path), || true),
None => Ok(()),
Carried::Readable(carried) => super::fileio::check_scripts_of(C, &carried, Some(path), || true),
Carried::Unreadable => Err(bad(C, UNREADABLE)),
Carried::Absent => Ok(()),
}
}
/// The error for a linked file the package would copy with an Export for Screens folder outside
/// the read roots in the native document it is or carries.
const FOLDER_OUTSIDE: &str = "a linked file's export folder is outside the read roots";
/// Under read roots, the linked file `name` (`bytes`, as the package writes it) is copied only when
/// the native document it is or carries ([`carried_document`]) keeps no Export for Screens folder
/// outside them: a file copied as it is, a PDF, `.ai` or EPS file or a native document not
/// rewritten, would name it. The error names no file or folder.
fn check_carried_folder(name: &str, bytes: &[u8]) -> Result<()> {
if crate::file_access::current().is_none() {
return Ok(());
}
match carried_document(name, bytes) {
Carried::Readable(carried) if matches!(super::fileio::with_readable_settings_folder(&carried), std::borrow::Cow::Owned(_)) => {
Err(bad(C, FOLDER_OUTSIDE))
}
Carried::Unreadable => Err(bad(C, UNREADABLE)),
_ => Ok(()),
}
}
@@ -363,6 +422,7 @@ impl<'a> Collector<'a> {
options.profiles = saved.profiles;
options.compress = compressed;
options.include_linked = include_linked;
let nested = super::fileio::with_readable_settings_folder(&nested);
match vectorcraft_format::save_with(&nested, &options) {
Ok(rewritten) => bytes = rewritten,
Err(e) => self.warn(
@@ -381,6 +441,7 @@ impl<'a> Collector<'a> {
}
}
}
check_carried_folder(&file.name, &bytes)?;
let copy = Copied { name: destination_file.clone(), size: Some(bytes.len() as u64), hash: Some(hash_bytes(&bytes)) };
self.copies.insert(found_path.to_string(), copy.clone());
local.insert(file.path.clone(), copy);
@@ -478,6 +539,9 @@ pub struct Package {
root: Option<PathBuf>,
info: Option<String>,
doc: std::sync::Arc<Document>,
/// The read roots in force where the package was prepared: [`Package::write`] collects under
/// them.
scope: crate::file_access::ScopeHandle,
}
impl Session {
@@ -520,23 +584,26 @@ fn prepare(s: &mut Session, p: &Value) -> Result<Package> {
}
let root = folder.map(|f| Path::new(f).join(&name));
let info = if o.report { Some(super::docinfo::report(s, false)?) } else { None };
// The package's document leaves out an Export for Screens folder outside the read roots.
let doc = s.doc()?.doc.clone();
let doc = if let std::borrow::Cow::Owned(kept) = super::fileio::with_readable_settings_folder(&doc) { std::sync::Arc::new(kept) } else { doc };
let links_from = s.doc()?.links_from.clone().unwrap_or_else(|| doc_path.clone());
Ok(Package { o, doc_path, links_from, stem, name, root, info, doc })
let scope = crate::file_access::ScopeHandle::capture();
Ok(Package { o, doc_path, links_from, stem, name, root, info, doc, scope })
}
impl Package {
/// Collect the linked files and fonts and write the package's files with `write` into
/// `folder/name`, making its folders first, or into the zip without a folder → the reply of
/// `file.package`.
/// `file.package`, with the read roots in force where it was prepared, on any thread.
pub fn write(self, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
collect_and_write(self, write)
self.scope.clone().run(|| collect_and_write(self, write))
}
}
/// [`Package::write`].
fn collect_and_write(package: Package, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
let Package { o, doc_path, links_from, stem, name, root, info, doc: original } = package;
let Package { o, doc_path, links_from, stem, name, root, info, doc: original, scope: _ } = package;
let mut doc = (*original).clone();
let doc_name = format!("{stem}.{}", vectorcraft_format::EXTENSION);
let base = LinkBase { doc: Some(&doc_path), relative: Some(&links_from) };
+25 -12
View File
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Default Fill and Stroke",
[],
Some("D"),
"{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults; type gets black fill and no stroke. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md)",
"{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md)",
has_doc,
default_paint
),
@@ -274,8 +274,9 @@ impl DocState {
/// Whether the selected objects' fills and strokes differ as the proxies show them (a "?"
/// proxy; a group whose contents differ counts). `item` (the Appearance panel's active item)
/// stands for the proxy of its kind, as in [`Session::proxy_paints`]: that fill or stroke of
/// each selected object's own stack is compared. One walk of the document, so callers that ask
/// every frame cache it by revision.
/// each selected object's own stack is compared. The selected objects are found through the id
/// cache ([`vectorcraft_doc::Document::nodes_in_order`]); a large selection takes one walk
/// of the document, so callers that ask every frame cache it by revision.
pub fn proxy_mixed(&self, item: Option<usize>) -> (bool, bool) {
self.proxy_mixed_with(item, &[])
}
@@ -290,15 +291,17 @@ impl DocState {
if self.selection.symbol_part.is_some() {
return (false, false);
}
let ids: std::collections::HashSet<NodeId> = self.selection.objects.iter().copied().collect();
let (mut selected, mut nodes) = (vec![], vec![]);
self.doc.walk(|n| {
if ids.contains(&n.id) {
selected.push(n);
painted(n, true, &mut nodes);
}
});
// Looking the first object up builds the id cache when there is none.
let first = self.selection.objects.first().and_then(|id| self.doc.node(*id));
let (mut selected, mut nodes) = (vec![], vec![]);
// Every node with a selected id, in tree order: a repeated id (a damaged file) counts at each
// place it appears.
for n in self.doc.nodes_in_order(self.selection.objects.iter().copied()) {
#[cfg(test)]
tests::note_gathered();
selected.push(n);
painted(n, true, &mut nodes);
}
let differ = |stroke: bool| {
let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke));
let set = if item.is_some() { &selected } else { &nodes };
@@ -1035,6 +1038,8 @@ fn default_paint(s: &mut Session, p: &Value) -> Result<Value> {
if !ids.is_empty() {
// When every object comes out as it was, the document and its undo history stay as they are.
let before = s.doc()?.doc.clone();
// A redefined Default Graphic Style gives other art its fills, strokes and effects, placed on each object.
let style = super::newart::redefined_default_style(&before).cloned();
super::overprint::edit_counted(s, "Default Fill and Stroke", |d| {
for id in &ids {
let Some(n) = d.node_mut(*id) else { continue };
@@ -1045,7 +1050,12 @@ fn default_paint(s: &mut Session, p: &Value) -> Result<Value> {
r.style.stroke = Paint::None;
}
}
_ => n.appearance = Appearance::default_art().into(),
_ => {
n.appearance = match &style {
Some(g) => g.appearance_on(n).into_owned().into(),
None => Appearance::default_art().into(),
}
}
}
}
let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, false);
@@ -1316,3 +1326,6 @@ fn transparency(s: &mut Session, p: &Value) -> Result<Value> {
}
s.execute("object.setProps", &Value::Object(q))
}
#[cfg(test)]
mod tests;
+335
View File
@@ -0,0 +1,335 @@
//! The Fill/Stroke proxies' "?" ([`DocState::proxy_mixed`]) finds the selected objects through the
//! id cache: it answers as a walk of the whole document does, and with a few objects selected it
//! reads only those.
use std::cell::Cell;
use std::collections::HashSet;
use std::sync::Arc;
use serde_json::json;
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, LayerColor, Node, NodeId, NodeKind};
use vectorcraft_geom::{Rect, shapes};
use super::{painted, picked_colors, proxy_paint, same_in_proxy};
use crate::{DocState, Session};
thread_local! {
/// [`gathered`] of this thread.
static GATHERED: Cell<u64> = const { Cell::new(0) };
}
/// Adds one to [`gathered`]: `proxy_mixed_with` read a node while looking for the selected ones.
pub(super) fn note_gathered() {
GATHERED.set(GATHERED.get() + 1);
}
/// How many nodes `proxy_mixed_with` has read on this thread while looking for the selected ones.
fn gathered() -> u64 {
GATHERED.get()
}
/// `proxy_mixed_with` as it was when it found the selected objects by walking the whole document.
fn walked(st: &DocState, item: Option<usize>, points: &[(NodeId, Vec<usize>)]) -> (bool, bool) {
if st.selection.is_empty() {
return (false, false);
}
if st.selection.symbol_part.is_some() {
return (false, false);
}
let ids: HashSet<NodeId> = st.selection.objects.iter().copied().collect();
let (mut selected, mut nodes) = (vec![], vec![]);
st.doc.walk(|n| {
if ids.contains(&n.id) {
selected.push(n);
painted(n, true, &mut nodes);
}
});
let first = st.selection.objects.first().and_then(|id| st.doc.node(*id));
let differ = |stroke: bool| {
let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke));
let set = if item.is_some() { &selected } else { &nodes };
let mut paints = set.iter().flat_map(|n| match picked_colors(n, if stroke || item.is_some() { &[] } else { points }) {
c if c.is_empty() => vec![proxy_paint(n, stroke, item)],
c => c.into_iter().map(Paint::solid).collect(),
});
let Some(p0) = paints.next() else { return false };
paints.any(|p| !same_in_proxy(&p0, &p))
};
(differ(false), differ(true))
}
/// `proxy_mixed_with` answers as [`walked`] does for `st`'s selection, for every Appearance item
/// and with and without `points`, with the id cache built and without it.
fn agree(st: &DocState, points: &[(NodeId, Vec<usize>)], what: &str) {
for cold in [true, false] {
if cold {
st.doc.drop_lookup_cache();
}
for item in [None, Some(0), Some(1), Some(2), Some(3)] {
for points in [points, &[]] {
assert_eq!(
st.proxy_mixed_with(item, points),
walked(st, item, points),
"{what}: item {item:?}, {} picked points, cold cache {cold}",
points.len()
);
}
}
}
}
fn id_of(v: &serde_json::Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
fn rect(s: &mut Session, x: f64, fill: &str, stroke: &str) -> NodeId {
let id = id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap());
s.execute("paint.setFill", &json!({"ids": [id.0], "color": fill})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [id.0], "color": stroke})).unwrap();
id
}
/// Every case of [`DocState::proxy_mixed`]'s rule, each answered as a walk answers it: one object,
/// different fills or strokes, a group with different contents, a group with one of its objects,
/// objects on two layers, a hidden object, an object with two fills under an Appearance item, a
/// gradient mesh with points picked beside another object, ids not in the document and an id that
/// appears twice (a damaged file) with different paints.
#[test]
fn the_question_marks_match_a_walk_of_the_document() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
let a = rect(&mut s, 10.0, "#ff0000", "#000000");
let b = rect(&mut s, 40.0, "#0000ff", "#000000");
let c = rect(&mut s, 70.0, "#ff0000", "#00ff00");
// Two fills: [Fill, Stroke, Fill].
s.execute("select.set", &json!({"ids": [c.0]})).unwrap();
s.execute("appearance.addFill", &json!({})).unwrap();
s.execute("appearance.setItem", &json!({"index": 2, "color": "#0000ff"})).unwrap();
let e = rect(&mut s, 100.0, "#ff0000", "#000000");
let f = rect(&mut s, 130.0, "#00ff00", "#000000");
let g = id_of(&s.execute("object.group", &json!({"ids": [e.0, f.0]})).unwrap());
let mesh = rect(&mut s, 160.0, "#ff0000", "#000000");
s.execute("object.mesh.create", &json!({"ids": [mesh.0], "rows": 2, "cols": 2})).unwrap();
let hidden = rect(&mut s, 190.0, "#0000ff", "#000000");
s.execute("object.hide", &json!({"ids": [hidden.0]})).unwrap();
s.execute("layer.new", &json!({})).unwrap();
let h = rect(&mut s, 220.0, "#ff0000", "#000000");
let missing = NodeId(999_999);
let Some(NodeKind::Mesh(m)) = s.doc().unwrap().doc.node(mesh).map(|n| &n.kind) else { panic!("a gradient mesh") };
let (p00, p01, p11) = (m.idx(0, 0), m.idx(0, 1), m.idx(1, 1));
s.execute("object.mesh.setPointColor", &json!({"id": mesh.0, "index": p00, "color": "#00ff00"})).unwrap();
let points = vec![(mesh, vec![p00, p01])];
let points_alike = vec![(mesh, vec![p01, p11])];
let selections = [
vec![a],
vec![a, b],
vec![b, a],
vec![a, h],
vec![g],
vec![g, e],
vec![e, g],
vec![f, e],
vec![c],
vec![c, a],
vec![a, c],
vec![mesh],
vec![mesh, a],
vec![a, mesh, h],
vec![hidden],
vec![hidden, b],
vec![missing],
vec![missing, a],
vec![a, missing, b],
vec![a, a],
];
let check = |s: &mut Session, what: &str| {
for sel in &selections {
let st = s.active_mut().unwrap();
st.selection.objects = sel.clone();
let st = s.active().unwrap();
agree(st, &points, &format!("{what}: {sel:?}"));
agree(st, &points_alike, &format!("{what}: {sel:?}, alike points"));
}
s.execute("select.all", &json!({})).unwrap();
agree(s.active().unwrap(), &points, &format!("{what}: Select All"));
};
check(&mut s, "unique ids");
// A second node with a's id and another fill, at the end of the tree.
let st = s.active_mut().unwrap();
let mut copy = st.doc.node(a).unwrap().clone();
copy.appearance.set_fill(Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
let doc = Arc::make_mut(&mut st.doc);
let last = doc.layers.len() - 1;
Arc::make_mut(&mut doc.layers[last]).children_mut().unwrap().push(Arc::new(copy));
doc.drop_lookup_cache();
check(&mut s, "a repeated id");
let st = s.active_mut().unwrap();
st.selection.objects = vec![a];
assert_eq!(st.proxy_mixed_with(None, &[]), (true, false), "the two places of a's id differ in fill");
}
/// A document of `layers` layers, each with `groups` groups of `per_group` rectangles; every other
/// rectangle red, the rest blue. Returns it with the rectangles' ids, in tree order.
fn big(layers: usize, groups: usize, per_group: usize) -> (Document, Vec<NodeId>) {
let mut d = Document::new(612.0, 792.0);
d.layers.clear();
let mut rects = vec![];
for l in 0..layers {
let mut layer = Node::layer(d.alloc_id(), &format!("L{l}"), LayerColor::Preset(0));
for _ in 0..groups {
let children = (0..per_group)
.map(|_| {
let id = d.alloc_id();
let mut ap = Appearance::default_art();
let red = rects.len() % 2 == 0;
ap.set_fill(Paint::solid(if red { Color::rgb(1.0, 0.0, 0.0) } else { Color::rgb(0.0, 0.0, 1.0) }));
rects.push(id);
Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), ap))
})
.collect();
let group = Node::group(d.alloc_id(), children);
layer.children_mut().unwrap().push(Arc::new(group));
}
d.layers.push(Arc::new(layer));
}
(d, rects)
}
fn state(doc: Document) -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 612, "height": 792})).unwrap();
s.active_mut().unwrap().doc = Arc::new(doc);
s
}
/// With one object selected, the "?" reads only that object, not every node of the document, and
/// does not walk the tree once the id cache is built; with every object selected it walks the tree
/// once.
#[test]
fn the_question_marks_read_only_the_selected_objects() {
let (doc, rects) = big(2, 40, 25);
let mut s = state(doc);
let st = s.active_mut().unwrap();
st.selection.objects = vec![rects[777]];
assert_eq!(st.proxy_mixed(None), (false, false));
let (read, walks) = (gathered(), vectorcraft_doc::tree_walks());
assert_eq!(st.proxy_mixed(None), (false, false));
assert_eq!(gathered() - read, 1, "only the selected object is read");
assert_eq!(vectorcraft_doc::tree_walks() - walks, 0, "the cached path answers");
st.selection.objects = vec![rects[3], rects[1500]];
let (read, walks) = (gathered(), vectorcraft_doc::tree_walks());
assert_eq!(st.proxy_mixed(None), (true, false));
assert_eq!((gathered() - read, vectorcraft_doc::tree_walks() - walks), (2, 0));
st.selection.objects = rects.clone();
let (read, walks) = (gathered(), vectorcraft_doc::tree_walks());
assert_eq!(st.proxy_mixed(None), (true, false));
assert_eq!(gathered() - read, rects.len() as u64);
assert!(vectorcraft_doc::tree_walks() - walks <= 1, "one walk for a large selection");
}
/// Random selections of a document with nested groups answer as a walk does.
#[test]
fn random_selections_match_a_walk_of_the_document() {
let (doc, rects) = big(3, 12, 6);
let mut s = state(doc);
let groups: Vec<NodeId> = s.active().unwrap().doc.layers.iter().flat_map(|l| l.children().unwrap().iter().map(|g| g.id)).collect();
let layers: Vec<NodeId> = s.active().unwrap().doc.layers.iter().map(|l| l.id).collect();
let all: Vec<NodeId> = rects.iter().chain(&groups).chain(&layers).copied().chain([NodeId(999_999)]).collect();
let mut r = 0x2545_f491_4f6c_dd1d_u64;
let mut next = |n: usize| {
r ^= r << 13;
r ^= r >> 7;
r ^= r << 17;
(r % n as u64) as usize
};
for round in 0..200 {
let count = 1 + next(if round % 10 == 0 { all.len() } else { 6 });
let sel: Vec<NodeId> = (0..count).map(|_| all[next(all.len())]).collect();
let st = s.active_mut().unwrap();
st.selection.objects = sel.clone();
agree(s.active().unwrap(), &[], &format!("round {round}: {sel:?}"));
}
}
/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere.
fn thread_cpu() -> Option<std::time::Duration> {
let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?;
stat.split_whitespace().next()?.parse().ok().map(std::time::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()) -> std::time::Duration {
match thread_cpu() {
Some(before) => {
f();
thread_cpu().map_or(std::time::Duration::ZERO, |after| after.saturating_sub(before))
}
None => {
let start = std::time::Instant::now();
f();
start.elapsed()
}
}
}
/// The time of `proxy_mixed` against a walk of the document, on 50,000 rectangles in 500 groups on
/// 5 layers: `cargo test --release -p vectorcraft-engine --lib proxy_mixed_timing -- --ignored --nocapture`.
#[test]
#[ignore = "timing; run by hand"]
fn proxy_mixed_timing() {
let (doc, rects) = big(5, 100, 100);
let mut s = state(doc);
let groups: Vec<NodeId> = s.active().unwrap().doc.layers.iter().flat_map(|l| l.children().unwrap().iter().map(|g| g.id)).collect();
let cases: [(&str, Vec<NodeId>); 5] = [
("1 object", vec![rects[25_000]]),
("2 objects, different fills", vec![rects[10], rects[40_001]]),
("a group of 100", vec![groups[250]]),
("all 500 groups", groups.clone()),
("all 50,000 objects", rects.clone()),
];
const CALLS: usize = 200;
let median = |mut v: Vec<f64>| {
v.sort_by(f64::total_cmp);
v[v.len() / 2]
};
println!("proxy_mixed_timing: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" });
println!("| Selection | Id cache | Walk (µs/call) | Id cache (µs/call) | Runs (walk / id cache, µs) |");
println!("|---|---|---|---|---|");
for (name, sel) in &cases {
for cold in [false, true] {
let st = s.active_mut().unwrap();
st.selection.objects = sel.clone();
let st = s.active().unwrap();
assert_eq!(st.proxy_mixed_with(None, &[]), walked(st, None, &[]), "{name}");
let (mut old, mut new) = (vec![], vec![]);
let calls = if cold { CALLS / 10 } else { CALLS };
for _ in 0..7 {
for (times, use_walk) in [(&mut old, true), (&mut new, false)] {
let d = time(|| {
for _ in 0..calls {
if cold {
st.doc.drop_lookup_cache();
}
std::hint::black_box(if use_walk { walked(st, None, &[]) } else { st.proxy_mixed_with(None, &[]) });
}
});
times.push(d.as_secs_f64() * 1e6 / calls as f64);
}
}
let runs = |v: &[f64]| v.iter().map(|x| format!("{x:.1}")).collect::<Vec<_>>().join(" ");
println!(
"| {name} | {} | {:.1} | {:.1} | {} / {} |",
if cold { "dropped before each call" } else { "built" },
median(old.clone()),
median(new.clone()),
runs(&old),
runs(&new)
);
}
}
}
File diff suppressed because one or more lines are too long
+144 -13
View File
@@ -36,6 +36,9 @@
//! `channel` that the effect doesn't have are refused by `effect.apply` and `effect.setParams`
//! themselves ([`check_effect_color`], [`check_effect_channel`]).
use std::collections::HashMap;
use std::sync::OnceLock;
use serde_json::Value;
use vectorcraft_apischema::shown_key;
@@ -43,7 +46,7 @@ use super::{bad, command_specs, find_command};
use crate::Result;
/// What a params description says about the keys of the params object.
#[derive(Debug, Default, PartialEq)]
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ParamKeys<'a> {
/// The keys it names.
pub keys: Vec<&'a str>,
@@ -107,6 +110,8 @@ pub(crate) fn is_key(s: &str) -> bool {
/// The keys a params description names, or what in it doesn't read as one.
pub fn doc_keys(doc: &str) -> std::result::Result<ParamKeys<'_>, String> {
#[cfg(test)]
PARSES.with(|n| n.set(n.get() + 1));
let mut out = ParamKeys::default();
let (mut body, mut rest) = object_body(doc)?;
let mut entries = split_top(body, ',');
@@ -155,7 +160,12 @@ fn named_commands(more: &str) -> impl Iterator<Item = &'static super::CommandSpe
/// `None`: any key (a `…` entry naming no command, or a description that doesn't parse, which
/// the tests rule out).
fn accepted(doc: &'static str, depth: usize) -> Option<Vec<&'static str>> {
let parsed = doc_keys(doc).ok()?;
resolve(doc, depth, &mut |doc| doc_keys(doc).ok())
}
/// [`accepted`], with `parse` reading each description it reaches.
fn resolve(doc: &'static str, depth: usize, parse: &mut dyn FnMut(&'static str) -> Option<ParamKeys<'static>>) -> Option<Vec<&'static str>> {
let parsed = parse(doc)?;
let mut keys = parsed.keys;
for more in parsed.more {
let mut named = named_commands(more).peekable();
@@ -168,22 +178,120 @@ fn accepted(doc: &'static str, depth: usize) -> Option<Vec<&'static str>> {
if UNCHECKED.contains(&spec.id) {
return None;
}
keys.extend(accepted(spec.params, depth + 1)?);
keys.extend(resolve(spec.params, depth + 1, parse)?);
}
}
Some(keys)
}
/// What the params description of a built-in command says about its keys, read once per process
/// ([`known`]).
#[derive(Debug)]
struct Known {
/// The keys it names itself; none when it doesn't parse.
own: Vec<&'static str>,
/// [`accepted`] of it.
accepted: Option<Vec<&'static str>>,
/// [`id_stands_for_ids`] of it.
id_stands_for_ids: bool,
}
impl Known {
/// [`takes_key`] of the description.
fn takes(&self, key: &str) -> bool {
self.own.contains(&key) || self.accepted.as_ref().is_some_and(|keys| keys.contains(&key))
}
}
/// The place and length of `doc`'s text: a description with the same words elsewhere (a plug-in's)
/// has another place.
fn text_key(doc: &str) -> (usize, usize) {
(doc.as_ptr().addr(), doc.len())
}
/// [`Known`] of each description in `docs`, each one and each one its `…` entries name parsed once.
/// A description is left out when one it reaches has a `…` entry naming a plug-in command, whose
/// keys change as plug-ins are installed and removed.
fn read_descriptions(docs: impl IntoIterator<Item = &'static str>) -> HashMap<(usize, usize), Known> {
let names_plugin =
|more: &str| more.split_whitespace().any(|w| w.trim_matches(|c: char| !c.is_ascii_alphanumeric()).starts_with(vectorcraft_plugins::PREFIX));
let mut parsed: HashMap<(usize, usize), (Option<ParamKeys<'static>>, bool)> = HashMap::new();
let mut table = HashMap::new();
for doc in docs {
if table.contains_key(&text_key(doc)) {
continue;
}
let mut live = false;
let mut parse = |doc: &'static str| {
let (keys, plugin) = parsed.entry(text_key(doc)).or_insert_with(|| {
let keys = doc_keys(doc).ok();
let plugin = keys.as_ref().is_some_and(|k| k.more.iter().any(|m| names_plugin(m)));
(keys, plugin)
});
live |= *plugin;
keys.clone()
};
let own = parse(doc).map(|p| p.keys).unwrap_or_default();
let accepted = resolve(doc, 0, &mut parse);
if live {
continue;
}
let mut known = Known { own, accepted, id_stands_for_ids: false };
known.id_stands_for_ids = known.takes("ids") && known.takes("id") && no_required_id_beside_ids(doc);
table.insert(text_key(doc), known);
}
table
}
/// [`Known`] of `doc` when it is the params description of a built-in command.
fn known(doc: &str) -> Option<&'static Known> {
#[cfg(test)]
if UNCACHED.get() {
return None;
}
static TABLE: OnceLock<HashMap<(usize, usize), Known>> = OnceLock::new();
TABLE.get_or_init(|| read_descriptions(command_specs().iter().map(|c| c.params))).get(&text_key(doc))
}
#[cfg(test)]
thread_local! {
/// The times [`doc_keys`] parsed a description on this thread.
pub(crate) static PARSES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// Whether [`known`] is skipped on this thread ([`uncached`]).
static UNCACHED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// Whether [`read_descriptions`] keeps what `doc` says.
#[cfg(test)]
pub(crate) fn read_once(doc: &'static str) -> bool {
read_descriptions([doc]).contains_key(&text_key(doc))
}
/// `f`'s result with every description parsed again where it is used, as without [`known`].
#[cfg(test)]
pub(crate) fn uncached<T>(f: impl FnOnce() -> T) -> T {
let before = UNCACHED.replace(true);
let out = f();
UNCACHED.set(before);
out
}
/// Every key the description `doc` takes, those of the commands its `…` entries name included, or
/// `None` when that isn't known: it doesn't parse, a `…` entry names no command, or one names a
/// command in [`UNCHECKED`].
pub(crate) fn accepted_keys(doc: &'static str) -> Option<Vec<&'static str>> {
accepted(doc, 0)
match known(doc) {
Some(known) => known.accepted.clone(),
None => accepted(doc, 0),
}
}
/// Does the description `doc` name `key` as a parameter (its own keys, and those of the commands
/// its `…` entries name)?
pub fn takes_key(doc: &'static str, key: &str) -> bool {
if let Some(known) = known(doc) {
return known.takes(key);
}
doc_keys(doc).is_ok_and(|parsed| parsed.keys.contains(&key)) || accepted(doc, 0).is_some_and(|keys| keys.contains(&key))
}
@@ -191,12 +299,17 @@ pub fn takes_key(doc: &'static str, key: &str) -> bool {
/// (instead of id)}`, `{id} or {ids: […]}`): it names both keys, and no params object of it names
/// `ids` beside a required `id`, which is something else (`plugin.run {id, ids?}`: the plug-in's)?
pub(crate) fn id_stands_for_ids(doc: &'static str) -> bool {
if let Some(known) = known(doc) {
return known.id_stands_for_ids;
}
takes_key(doc, "ids") && takes_key(doc, "id") && no_required_id_beside_ids(doc)
}
/// No params object of `doc` names `ids` beside a required `id`.
fn no_required_id_beside_ids(doc: &str) -> bool {
fn head(alternative: &str) -> &str {
alternative.split([':', '=', '(']).next().unwrap_or_default().trim()
}
if !takes_key(doc, "ids") || !takes_key(doc, "id") {
return false;
}
let mut rest = doc;
while let Ok((body, after)) = object_body(rest) {
let entries = split_top(body, ',');
@@ -249,20 +362,33 @@ pub fn check_keys(id: &str, doc: &'static str, params: &Value) -> Result<()> {
if given.is_empty() {
return Ok(());
}
let Some(keys) = accepted(doc, 0) else { return Ok(()) };
let live;
let keys = match known(doc) {
Some(known) => known.accepted.as_deref(),
None => {
live = accepted(doc, 0);
live.as_deref()
}
};
let Some(keys) = keys else { return Ok(()) };
match given.keys().find(|k| !keys.contains(&k.as_str())) {
Some(key) => Err(unknown(id, key, &keys)),
Some(key) => Err(unknown(id, key, keys)),
None => Ok(()),
}
}
/// Parameters a command takes instead of one another: (command, key, other key). Giving both,
/// neither null, is a parameter error ([`check_exclusive_keys`]).
const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[("addon.pathtools.cornerSet", "items", "ids"), ("addon.pathtools.cornerRemove", "items", "ids")];
const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[
("addon.pathtools.cornerSet", "items", "ids"),
("addon.pathtools.cornerRemove", "items", "ids"),
("links.unembed", "id", "ids"),
("links.unembed", "path", "folder"),
];
/// `params` of command `id` give at most one of each pair in [`EXCLUSIVE_KEYS`], or the parameter
/// error naming the pair.
fn check_exclusive_keys(id: &str, params: &Value) -> Result<()> {
pub(crate) fn check_exclusive_keys(id: &str, params: &Value) -> Result<()> {
let given = |key: &str| params.get(key).filter(|v| !v.is_null());
for (_, key, other) in EXCLUSIVE_KEYS.iter().filter(|(c, ..)| *c == id) {
if given(key).is_some() && given(other).is_some() {
@@ -928,9 +1054,14 @@ fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> {
crate::schemas::check(spec, params, false)?;
}
if matches!(id, "command.batch" | "action.batch") && !in_batch {
for step in params.get("commands").and_then(Value::as_array).into_iter().flatten() {
for (i, step) in params.get("commands").and_then(Value::as_array).into_iter().flatten().enumerate() {
if let Some(step_id) = step.get("command").and_then(Value::as_str) {
check_params_in(step_id, step.get("params").unwrap_or(&Value::Null), true)?;
let checked = check_params_in(step_id, step.get("params").unwrap_or(&Value::Null), true);
// An `action.batch` names the step it refuses by its place, from 1, as its own checks and its steps' errors do.
match checked {
Err(e) if id == "action.batch" => return Err(bad(id, super::fileio::action_step(i, step_id, &e.to_string()))),
checked => checked?,
}
}
}
}
+154 -10
View File
@@ -1,10 +1,10 @@
//! Path editing commands (used by the Pen and Direct Selection tools and Object → Path).
use std::collections::BTreeSet;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Scaling, Selection};
use vectorcraft_doc::{AnchorRef, Document, Node, NodeId, NodeKind, Scaling, Selection};
use vectorcraft_geom::{Anchor, AnchorKind, Anchors, PathData, Point, SubPath, Vec2};
use super::create::anchor_from_json;
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Anchors",
[],
None,
"{dx, dy, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles)} move direct-selected anchors (whole paths if fully selected); refused while an object of a symbol instance's art is selected",
"{dx, dy, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), interpolate?: bool (Interpolate Control Points: the handles of each segment with one moved end are re-mapped by the turn, scale and move that take its old ends to its new ends; default: prefs interpolateControlPoints)} move direct-selected anchors (whole paths if fully selected); refused while an object of a symbol instance's art is selected",
has_selection,
move_anchors
),
@@ -245,28 +245,43 @@ fn close(s: &mut Session, p: &Value) -> Result<Value> {
pub(crate) fn move_anchors(s: &mut Session, p: &Value) -> Result<Value> {
let d = Vec2::new(number_or(p, "dx", 0.0, "path.moveAnchors")?, number_or(p, "dy", 0.0, "path.moveAnchors")?);
check_switches(p, &["patterns"], "path.moveAnchors")?;
check_switches(p, &["patterns", "interpolate"], "path.moveAnchors")?;
// An object selected in a symbol instance's art stays where the symbol puts it.
super::edit::refuse_symbol_part(s)?;
// Objects selected whole move as objects, and their pattern tiles move with them when
// `patterns` (default: General › Transform Pattern Tiles) is on.
let whole = s.doc()?.selection.whole();
let sc = Scaling { patterns: super::object::transform_patterns(s, p, &whole)?, ..Scaling::default() };
transform_anchors(s, "Move", vectorcraft_geom::Affine::translate(d), sc)?;
let interpolate = interpolates_handles(s, p, "path.moveAnchors")?;
transform_anchors(s, "Move", vectorcraft_geom::Affine::translate(d), sc, interpolate)?;
// Transform Again repeats a move that moved something; a drag records it when it commits.
let st = s.doc_mut()?;
if st.interaction.is_none() && (d.x != 0.0 || d.y != 0.0) {
let options = json!({ "copy": false, "patterns": sc.patterns });
let options = json!({ "copy": false, "patterns": sc.patterns, "interpolate": interpolate });
st.last_transform = Some(crate::LastTransform::Matrix(vectorcraft_geom::Affine::translate(d), options));
st.last_perspective = None;
}
ok()
}
/// Interpolate Control Points: does a move of direct-selected anchors re-map the handles of the
/// segments beside them (`interpolate` param, else General › Interpolate Control Points When
/// Moving Anchors)? Noted in the journal, so a replay re-maps them alike whatever the preference
/// is then. A saved step without `interpolate` ([`Session::replay`]) was recorded before the
/// preference existed, so it moves the handles as it did then, without re-mapping them.
pub(crate) fn interpolates_handles(s: &mut Session, p: &Value, cmd: &str) -> Result<bool> {
let default = s.prefs.interpolate_control_points && !s.replaying();
let on = switch_or(p, "interpolate", default, cmd)?;
s.note_journal("interpolate", json!(on));
Ok(on)
}
/// Apply `xf` to the direct-selected anchors, their handles with them, and (with `sc`) to the
/// objects selected whole (those with no entry in the selection's `anchors`). An object inside
/// another selected object, such as a path in a selected group, moves once, with that object.
pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling) -> Result<()> {
/// When `xf` is a move and `interpolate` is on, the handles of each segment with one moved end
/// are re-mapped ([`move_interpolating_handles`]).
pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> {
let sel = s.doc()?.selection.clone();
let ids = super::edit::outermost(&s.doc()?.doc, sel.objects.clone());
let c = xf.as_coeffs();
@@ -277,9 +292,15 @@ pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_ge
match sel.anchors.get(id) {
Some(set) => {
let path = path_mut(doc, *id)?;
for &(si, ai) in set {
if let Some(a) = path.anchor_mut(si, ai) {
*a = a.transform(xf);
// Only an exact move takes the interpolating path: a near-identity scale or
// turn still transforms the anchors as asked.
if interpolate && c[..4] == [1.0, 0.0, 0.0, 1.0] {
move_interpolating_handles(path, set, delta);
} else {
for &(si, ai) in set {
if let Some(a) = path.anchor_mut(si, ai) {
*a = a.transform(xf);
}
}
}
// A pixel-aligned path, or the pixel-aligned compound path that holds it, snaps
@@ -307,6 +328,129 @@ pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_ge
})
}
/// Move the anchors `set` of `path` by `d`, their handles with them, then re-map the two handles
/// of each segment with exactly one moved end by the map that takes the segment's old ends to its
/// new ends: a turn, a uniform scale and a move. Between two corner anchors the segment keeps its
/// shape relative to its ends. A segment with both ends moved, or with its ends at the same place
/// before or after the move, moves as it does without the preference. A smooth anchor keeps its
/// two handles in line ([`line_up_handles`]).
fn move_interpolating_handles(path: &mut PathData, set: &BTreeSet<AnchorRef>, d: Vec2) {
// (subpath, anchor, outgoing handle?, new position)
let mut placed: Vec<(usize, usize, bool, Point)> = Vec::new();
if d != Vec2::ZERO {
// Only the segments beside a moved anchor can have one moved end: (subpath, first anchor).
let mut segments: BTreeSet<AnchorRef> = BTreeSet::new();
for &(si, ai) in set {
let Some(sp) = path.subpaths.get(si) else { continue };
let n = sp.anchors.len();
if ai >= n || n < 2 {
continue;
}
if ai > 0 || sp.closed {
segments.insert((si, (ai + n - 1) % n));
}
if ai + 1 < n || sp.closed {
segments.insert((si, ai));
}
}
for (si, from) in segments {
let Some(sp) = path.subpaths.get(si) else { continue };
let to = (from + 1) % sp.anchors.len().max(1);
let (moved_from, moved_to) = (set.contains(&(si, from)), set.contains(&(si, to)));
if moved_from == moved_to {
continue;
}
let (Some(a), Some(b)) = (sp.anchors.get(from), sp.anchors.get(to)) else { continue };
let old = b.p - a.p;
let len2 = old.hypot2();
if len2 <= 1e-12 || !len2.is_finite() {
continue;
}
let start = if moved_from { a.p + d } else { a.p };
let end = if moved_to { b.p + d } else { b.p };
let new = end - start;
// A move that puts the two ends at the same place would collapse both handles onto
// them, past recovering by moving back.
if new.hypot2() <= 1e-12 {
continue;
}
// `new / old` as complex numbers: the turn and scale between the two chords.
let (re, im) = ((new.x * old.x + new.y * old.y) / len2, (new.y * old.x - new.x * old.y) / len2);
let map = |h: Point| {
let v = h - a.p;
start + Vec2::new(v.x * re - v.y * im, v.x * im + v.y * re)
};
// A retracted handle goes to its anchor's new place exactly: mapped, it could land a
// rounding error away, which `line_up_handles` would read as a direction.
let h_out = if a.h_out == a.p { start } else { map(a.h_out) };
let h_in = if b.h_in == b.p { end } else { map(b.h_in) };
if h_out.is_finite() && h_in.is_finite() {
placed.push((si, from, true, h_out));
placed.push((si, to, false, h_in));
}
}
}
for &(si, ai) in set {
if let Some(a) = path.anchor_mut(si, ai) {
a.translate(d);
}
}
// For each anchor with a re-mapped handle: its handles as the plain move left them, and which
// of them (outgoing, incoming) were re-mapped.
let mut touched: BTreeMap<AnchorRef, (Point, Point, bool, bool)> = BTreeMap::new();
for &(si, ai, out, pos) in &placed {
if let Some(a) = path.anchor_mut(si, ai) {
let e = touched.entry((si, ai)).or_insert((a.h_out, a.h_in, false, false));
if out {
a.h_out = pos;
e.2 = true;
} else {
a.h_in = pos;
e.3 = true;
}
}
}
for ((si, ai), (rigid_out, rigid_in, out, inn)) in touched {
let Some(a) = path.anchor_mut(si, ai) else { continue };
if a.kind == AnchorKind::Smooth && !line_up_handles(a, out, inn) {
a.h_out = rigid_out;
a.h_in = rigid_in;
}
}
}
/// Put the handles of the smooth anchor `a` back in line after [`move_interpolating_handles`]
/// re-mapped its outgoing handle (`out`), its incoming handle (`inn`) or both. A re-mapped handle
/// turns to point away from the other handle, at its own new length; when both were re-mapped,
/// both point along the mean of their directions. A retracted handle is left as it is. False when
/// both were re-mapped to point the same way, which has no mean direction: the caller then moves
/// both handles with the anchor.
fn line_up_handles(a: &mut Anchor, out: bool, inn: bool) -> bool {
let (v_out, v_in) = (a.h_out - a.p, a.h_in - a.p);
let (l_out, l_in) = (v_out.hypot(), v_in.hypot());
if l_out <= 0.0 || l_in <= 0.0 || !l_out.is_finite() || !l_in.is_finite() {
return true;
}
let dir = match (out, inn) {
(true, true) => v_out / l_out - v_in / l_in,
(true, false) => -v_in / l_in,
(false, true) => v_out / l_out,
(false, false) => return true,
};
let l = dir.hypot();
if l <= 1e-12 || !l.is_finite() {
return false;
}
let dir = dir / l;
if out {
a.h_out = a.p + dir * l_out;
}
if inn {
a.h_in = a.p - dir * l_in;
}
true
}
fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
let id = object_param(p, "id", "path.setHandle")?.ok_or_else(|| bad("path.setHandle", "missing id"))?;
let si = usize_opt(p, "subpath", "path.setHandle")?.unwrap_or(0);
+61 -8
View File
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Unite",
["Window", "Pathfinder"],
None,
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}",
has_selection,
|s, p| run_pf(s, p, PathfinderOp::Unite)
),
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Minus Front",
["Window", "Pathfinder"],
None,
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}",
has_selection,
|s, p| run_pf(s, p, PathfinderOp::MinusFront)
),
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Intersect",
["Window", "Pathfinder"],
None,
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}",
has_selection,
|s, p| run_pf(s, p, PathfinderOp::Intersect)
),
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Exclude",
["Window", "Pathfinder"],
None,
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}",
has_selection,
|s, p| run_pf(s, p, PathfinderOp::Exclude)
),
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Minus Back",
["Window", "Pathfinder"],
None,
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}",
has_selection,
|s, p| run_pf(s, p, PathfinderOp::MinusBack)
),
@@ -285,6 +285,37 @@ impl Style {
}
}
/// The Shape Mode commands' warning, which the status bar shows, when a selected object is or holds
/// a line or another open path that encloses no area once closed, and so does not change the result's
/// shape (the result still takes its paint from the frontmost object, as without the warning).
pub const SHAPE_MODE_OPEN_PATH_NO_AREA: &str = "a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first";
/// `path` has an open subpath that encloses no area once closed (a straight line, or an evenodd
/// contour traced twice), by the area its fill rule gives, so a self-crossing path whose signed
/// area is zero (a bow tie) still counts as enclosing area, as Divide measures it.
fn has_open_subpath_without_area(path: &PathData, rule: FillRule) -> bool {
path.subpaths.iter().filter(|sp| !sp.closed).any(|sp| {
// A point or a straight two-anchor line needs no area measurement.
if sp.anchors.len() < 2 || (sp.anchors.len() == 2 && sp.anchors.iter().all(|a| a.h_in == a.p && a.h_out == a.p)) {
return true;
}
let mut closed = sp.clone();
closed.closed = true;
// The signed-area test alone only holds for nonzero: evenodd can fill nothing where the
// signed area is not zero (a contour traced twice).
!(rule == FillRule::NonZero && po::encloses_area(sp)) && po::area(&PathData::single(closed), rule) <= 0.0
})
}
/// The area `path` fills with its open subpaths closed, as the Shape Modes fill it.
fn closed_area(path: &PathData, rule: FillRule) -> f64 {
let mut closed = path.clone();
for sp in &mut closed.subpaths {
sp.closed = true;
}
po::area(&closed, rule)
}
/// All subpaths of a path or compound path node, in document coordinates, with its fill rule.
pub(crate) fn node_path(n: &Node) -> Option<(PathData, FillRule)> {
match &n.kind {
@@ -685,8 +716,9 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
let keeps_hidden = matches!(op, PathfinderOp::Intersect | PathfinderOp::MinusFront | PathfinderOp::MinusBack | PathfinderOp::Crop);
let label = pf_label(op);
let options = pf_options(s, p, &format!("object.pathfinder.{}", pf_id(op)))?;
let ids = s.edit(label, |d, sel| {
let (ids, no_area) = s.edit(label, |d, sel| {
// Build the stack (back → front); names are separate from paint/style identity.
let mut no_area = false;
let mut styles: Vec<Style> = vec![];
let mut shapes: Vec<po::Shape> = vec![];
let mut names: Vec<Option<String>> = vec![];
@@ -759,6 +791,7 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
continue;
};
let top = *top;
no_area = no_area || parts.iter().any(|(_, p, r)| has_open_subpath_without_area(p, *r));
let refs: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, p, r)| (p, *r)).collect();
push(
po::try_unite_all_with(&refs, options.precision).map_err(|e| EngineError::Other(e.to_string()))?,
@@ -771,6 +804,7 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
} else {
for (l, clip) in &lv {
if let Some((p, r)) = node_path(l) {
no_area = no_area || (shape_mode && has_open_subpath_without_area(&p, r));
push(p, r, style_of(l), n.name.clone().or_else(|| l.name.clone()), clip.as_deref(), clip.is_some())?;
}
}
@@ -798,6 +832,21 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
}
}
if results.iter().all(|r| r.path.is_empty()) {
// The lines left the result empty when the other shapes give a result without them, or
// when nothing else is selected. A closed shape without area stays among the others.
let lines_emptied = no_area && {
let kept: Vec<po::Shape> = shapes
.iter()
.filter(|s| closed_area(&s.path, s.rule) > 0.0 || !has_open_subpath_without_area(&s.path, s.rule))
.cloned()
.collect();
kept.is_empty() || po::pathfinder_with(op, &kept, options.precision).iter().any(|r| !r.path.is_empty())
};
if lines_emptied {
return Err(EngineError::Other(format!(
"{label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first"
)));
}
return Err(EngineError::Other(format!("{label} produced an empty result")));
}
let new_node = if shape_mode {
@@ -833,9 +882,13 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
};
let nid = d.wrap(&roots, |_| new_node)?;
sel.set([nid]);
Ok(vec![nid])
Ok((vec![nid], no_area))
})?;
Ok(ids_json(&ids))
let mut out = ids_json(&ids);
if no_area {
out["warning"] = json!(SHAPE_MODE_OPEN_PATH_NO_AREA);
}
Ok(out)
}
// ---------- Trap ----------
+60 -5
View File
@@ -12,7 +12,7 @@ use vectorcraft_geom::{PathData, Point, Rect, SubPath, shapes};
use super::Result;
use super::clipboard::Clipboard;
use super::clipboard::resources::SwatchChoices;
use super::clipboard::resources::{Imported, SwatchChoices};
use super::swatchlib::LibraryInfo;
/// A built-in pattern library: a stable id, its menu name and the function that adds its patterns.
@@ -87,12 +87,67 @@ pub fn swatch_source(w: &Swatch) -> Option<Arc<Document>> {
/// Add pattern `name` of library `lib` to `d` with the resources its art uses, as pasting art
/// painted with it does: the same pattern there already is used, and a name another pattern or
/// swatch has gets a number → the pattern's name in `d`.
pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<String> {
/// swatch has gets a number → the pattern's name in `d`, and the swatches the import added for
/// the pattern's art: (the swatch's name in `lib`, its name in `d`), pattern swatches left out.
/// A global or spot color whose name `d` gives another color comes in under a free name, as Add
/// to Swatches adds such a color, so that the pattern keeps the library's colors.
pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<(String, Vec<(String, String)>)> {
let had: std::collections::HashSet<String> = d.swatches_iter().map(|w| w.name.clone()).collect();
let imported = gather(lib, name).import_into(d, &SwatchChoices::add_all(), false)?;
let from = |to: &str| {
let renamed = imported.renamed.iter().find(|r| r["kind"] == "swatch" && r["to"] == to).and_then(|r| r["from"].as_str());
renamed.unwrap_or(to).to_string()
};
let added = d
.swatches_iter()
.filter(|w| !had.contains(&w.name) && !matches!(w.paint, Paint::Pattern { .. }))
.map(|w| (from(&w.name), w.name.clone()))
.collect();
Ok((imported_name(&imported, name), added))
}
/// Pattern `name` of `lib` with the resources its art uses, as an object painted with it is copied.
fn gather(lib: &Document, name: &str) -> Clipboard {
let user = Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::basic(pattern_paint(name), Paint::None, 0.0));
let imported = Clipboard::gather(lib, vec![user]).import_into(d, &SwatchChoices::default(), false)?;
Clipboard::gather(lib, vec![user])
}
/// The name pattern `name` has in the document `imported` went into.
fn imported_name(imported: &Imported, name: &str) -> String {
let renamed = imported.renamed.iter().find(|r| r["kind"] == "pattern" && r["from"] == name).and_then(|r| r["to"].as_str());
Ok(renamed.unwrap_or(name).to_string())
renamed.unwrap_or(name).to_string()
}
/// The pattern of `d` that [`import`] of pattern `name` of library `lib` would use without adding
/// anything to `d` → its name in `d`. A pattern whose art uses no other resource is compared as
/// [`existing_pattern`] does. One whose art uses other resources, such as a pattern it is painted
/// with, is imported into a copy of `d`, so that those resources are compared too.
pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Option<String> {
let gathered = gather(lib, name);
let only_pattern = gathered.patterns.len() == 1
&& gathered.symbols.is_empty()
&& gathered.swatches.is_empty()
&& gathered.graphic_styles.is_empty()
&& gathered.char_styles.is_empty()
&& gathered.para_styles.is_empty()
&& gathered.brushes.is_empty()
&& gathered.images.is_empty();
if only_pattern {
return existing_pattern(d, lib, name);
}
// Importing reuses only a pattern under that name or a numbered copy of it with the same tile
// options and as many art objects; without one, the document is not copied.
let def = lib.pattern(name)?;
let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() };
let copy = |n: &str| {
n == name || n.strip_prefix(name).and_then(|r| r.strip_prefix(' ')).is_some_and(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
};
if !d.patterns.iter().any(|p| copy(&p.name) && p.art.len() == def.art.len() && bare(p) == bare(def)) {
return None;
}
let mut probe = d.clone();
let imported = gathered.import_into(&mut probe, &SwatchChoices::add_all(), false).ok()?;
(imported.added == 0).then(|| imported_name(&imported, name))
}
/// The pattern of `d` that is pattern `name` of library `lib`: the same tile options and art under
File diff suppressed because one or more lines are too long
-2
View File
@@ -171,8 +171,6 @@ fn parse(xml: &str, name: &str, cmd: &str) -> Result<El> {
craft_xml::Error::TooDeep(_) => bad(cmd, format!("`{name}` in the Word document nests elements more than {MAX_NESTING} deep")),
_ => bad(cmd, format!("`{name}` in the Word document is not well-formed XML: {e}")),
})?;
crate::cmd::xmlattrs::validate(xml.as_bytes(), opts.limits)
.map_err(|e| bad(cmd, format!("`{name}` in the Word document is not well-formed XML: {e}")))?;
Ok(doc)
}
+140 -23
View File
@@ -3,8 +3,8 @@
use serde_json::Value;
use super::super::utf16_order_without_mark;
use super::{Point, Rect, Result, bad, bool_or, fileio, shapes, str_param};
use super::super::{text_param, utf16_order_without_mark};
use super::{Point, Rect, Result, bad, fileio, shapes, switch_or};
/// Text files as `file.place` reports them (not a format `document.open` reads).
pub(super) const FORMAT: fileio::Format = fileio::Format {
@@ -22,13 +22,68 @@ pub(super) const FORMAT: fileio::Format = fileio::Format {
/// document may give.
pub(super) const MAX_TEXT: usize = 4 << 20;
/// A character set of Text Import Options (`text.characterSet`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum CharacterSet {
/// UTF-8, or UTF-16 with or without a byte-order mark ([`decode`]).
#[default]
Unicode,
/// The platform's 8-bit character set: Windows-1252, or Mac Roman on a Mac.
Ansi,
ShiftJis,
Gb2312,
ChineseBig5,
Cyrillic,
Gb18030,
Greek,
Turkish,
Baltic,
CentralEuropean,
}
/// Each character set by its `text.characterSet` value.
const CHARACTER_SETS: [(&str, CharacterSet); 11] = [
("unicode", CharacterSet::Unicode),
("ansi", CharacterSet::Ansi),
("shiftJis", CharacterSet::ShiftJis),
("gb2312", CharacterSet::Gb2312),
("chineseBig5", CharacterSet::ChineseBig5),
("cyrillic", CharacterSet::Cyrillic),
("gb18030", CharacterSet::Gb18030),
("greek", CharacterSet::Greek),
("turkish", CharacterSet::Turkish),
("baltic", CharacterSet::Baltic),
("centralEuropean", CharacterSet::CentralEuropean),
];
impl CharacterSet {
/// The Encoding Standard decoder of a set other than Unicode and ANSI, for a file from a Mac
/// when `mac`: GB2312 reads as GBK, Cyrillic as windows-1251 (x-mac-cyrillic on a Mac), and
/// Greek, Turkish, Baltic and Central European as windows-1253, 1254, 1257 and 1250 on both
/// platforms.
fn encoding(self, mac: bool) -> Option<&'static encoding_rs::Encoding> {
Some(match self {
Self::Unicode | Self::Ansi => return None,
Self::ShiftJis => encoding_rs::SHIFT_JIS,
Self::Gb2312 => encoding_rs::GBK,
Self::ChineseBig5 => encoding_rs::BIG5,
Self::Cyrillic if mac => encoding_rs::X_MAC_CYRILLIC,
Self::Cyrillic => encoding_rs::WINDOWS_1251,
Self::Gb18030 => encoding_rs::GB18030,
Self::Greek => encoding_rs::WINDOWS_1253,
Self::Turkish => encoding_rs::WINDOWS_1254,
Self::Baltic => encoding_rs::WINDOWS_1257,
Self::CentralEuropean => encoding_rs::WINDOWS_1250,
})
}
}
/// Text Import Options (`file.place`'s `text` param).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(super) struct TextOptions {
/// Decode as the platform's 8-bit character set (Windows-1252 or Mac Roman) instead of
/// Unicode.
ansi: bool,
/// The file comes from a Mac (its 8-bit character set is Mac Roman).
/// The character set the file's bytes are decoded as.
character_set: CharacterSet,
/// The file comes from a Mac (its ANSI set is Mac Roman, its Cyrillic set x-mac-cyrillic).
mac: bool,
/// Join the lines of each block of text (blank lines end paragraphs).
remove_line_returns: bool,
@@ -45,11 +100,13 @@ impl TextOptions {
if !t.is_object() {
return Err(bad(cmd, "text must be {characterSet?, platform?, removeLineReturns?, removeParagraphReturns?, replaceSpaces?}"));
}
let choice = |key: &str, values: [&str; 2]| match str_param(t, key) {
None => Ok(false),
Some(v) if v == values[0] => Ok(false),
Some(v) if v == values[1] => Ok(true),
Some(v) => Err(bad(cmd, format!("text.{key} `{v}`: use \"{}\" or \"{}\"", values[0], values[1]))),
// The index of `text[key]` in `values`; 0 when it is omitted or null.
let choice = |key: &str, values: &[&str]| -> Result<usize> {
let Some(v) = text_param(t, key, cmd)? else { return Ok(0) };
values.iter().position(|x| *x == v).ok_or_else(|| {
let (last, rest) = values.split_last().map_or(("", &[][..]), |(last, rest)| (*last, rest));
bad(cmd, format!("text.{key} `{v}`: use \"{}\" or \"{}\"", rest.join("\", \""), last))
})
};
let spaces_to_tab = match t.get("replaceSpaces") {
None | Some(Value::Null) => None,
@@ -58,11 +115,12 @@ impl TextOptions {
as usize,
),
};
let set = choice("characterSet", &CHARACTER_SETS.map(|(name, _)| name))?;
Ok(Self {
ansi: choice("characterSet", ["unicode", "ansi"])?,
mac: choice("platform", ["windows", "mac"])?,
remove_line_returns: bool_or(t, "removeLineReturns", false),
remove_paragraph_returns: bool_or(t, "removeParagraphReturns", false),
character_set: CHARACTER_SETS.get(set).map_or(CharacterSet::Unicode, |(_, s)| *s),
mac: choice("platform", &["windows", "mac"])? == 1,
remove_line_returns: switch_or(t, "removeLineReturns", false, cmd)?,
remove_paragraph_returns: switch_or(t, "removeParagraphReturns", false, cmd)?,
spaces_to_tab,
})
}
@@ -80,10 +138,15 @@ pub(super) fn import(bytes: &[u8], o: TextOptions, cmd: &str) -> Result<String>
/// `bytes` as text: Unicode (UTF-8, or UTF-16 with a byte-order mark, or without one when the
/// file has an even length, reads as valid UTF-16 with no NUL character in the byte order
/// [`utf16_order_without_mark`] gives; bytes that aren't UTF-8 are read as the platform's 8-bit
/// set), or the platform's 8-bit character set.
/// set), the platform's 8-bit character set, or another set's decoder
/// ([`CharacterSet::encoding`]), which reads a byte-order mark as ordinary bytes and a malformed
/// sequence as U+FFFD.
fn decode(bytes: &[u8], o: TextOptions) -> String {
if let Some(encoding) = o.character_set.encoding(o.mac) {
return encoding.decode_without_bom_handling(bytes).0.into_owned();
}
let eight_bit = |b: &[u8]| -> String { b.iter().map(|&c| if o.mac { mac_roman(c) } else { windows_1252(c) }).collect() };
if o.ansi {
if o.character_set == CharacterSet::Ansi {
return eight_bit(bytes);
}
let utf16 = |rest: &[u8], le: bool| {
@@ -278,22 +341,76 @@ mod tests {
assert_eq!(decode(&[0xFF, 0xFE, b'h', 0, 0xE9, 0], unicode), "hé", "UTF-16 LE");
assert_eq!(decode(&[0xFE, 0xFF, 0, b'h', 0x20, 0xAC], unicode), "h€", "UTF-16 BE");
assert_eq!(decode(&[b'c', b'a', b'f', 0xE9, 0x80], unicode), "café€", "not UTF-8: Windows-1252");
let ansi = TextOptions { ansi: true, ..TextOptions::default() };
let ansi = TextOptions { character_set: CharacterSet::Ansi, ..TextOptions::default() };
assert_eq!(decode(&[0x93, b'q', 0x94, 0xE9], ansi), "“q”é");
let mac = TextOptions { ansi: true, mac: true, ..TextOptions::default() };
let mac = TextOptions { character_set: CharacterSet::Ansi, mac: true, ..TextOptions::default() };
assert_eq!(decode(&[0xD2, b'q', 0xD3, 0x8E, 0xA5, 0xDB], mac), "“q”é•€");
}
/// The other character sets decode by their Encoding Standard decoders: the platform matters
/// for Cyrillic alone, a byte-order mark is read as ordinary bytes, and a malformed sequence
/// reads as U+FFFD.
#[test]
fn decodes_the_other_character_sets() {
let cases: [(CharacterSet, &[u8], &str); 9] = [
(CharacterSet::ShiftJis, &[0x93, 0xFA, 0x96, 0x7B], "日本"),
(CharacterSet::Gb2312, &[0xD6, 0xD0, 0xCE, 0xC4], "中文"),
(CharacterSet::ChineseBig5, &[0xA4, 0xA4, 0xA4, 0xE5], "中文"),
(CharacterSet::Cyrillic, &[0xCF, 0xF0, 0xE8, 0xE2, 0xE5, 0xF2], "Привет"),
(CharacterSet::Gb18030, &[0x95, 0x32, 0x82, 0x36], "\u{20000}"),
(CharacterSet::Greek, &[0xC5, 0xEB, 0xEB, 0xDC, 0xE4, 0xE1], "Ελλάδα"),
(CharacterSet::Turkish, &[0xDD, 0x73, 0x74], "İst"),
(CharacterSet::Baltic, &[0x52, 0xEE, 0x67, 0x61], "Rīga"),
(CharacterSet::CentralEuropean, &[0xA3, 0xF3, 0x64, 0x9F], "Łódź"),
];
for (set, bytes, text) in cases {
let windows = TextOptions { character_set: set, ..TextOptions::default() };
assert_eq!(decode(bytes, windows), text, "{set:?}");
if set != CharacterSet::Cyrillic {
assert_eq!(decode(bytes, TextOptions { mac: true, ..windows }), text, "{set:?} from a Mac");
}
}
let mac_cyrillic = TextOptions { character_set: CharacterSet::Cyrillic, mac: true, ..TextOptions::default() };
assert_eq!(decode(&[0x8F, 0xF0, 0xE8, 0xE2, 0xE5, 0xF2], mac_cyrillic), "Привет");
let shift_jis = TextOptions { character_set: CharacterSet::ShiftJis, ..TextOptions::default() };
assert_eq!(decode(&[0x82, 0x22], shift_jis), "\u{FFFD}\"", "a lead byte before ASCII");
assert_eq!(decode(&[b'a', 0x82], shift_jis), "a\u{FFFD}", "a lead byte at the end");
let central = TextOptions { character_set: CharacterSet::CentralEuropean, ..TextOptions::default() };
assert_eq!(decode(&[0xEF, 0xBB, 0xBF, b'A'], central), "A", "a UTF-8 byte-order mark is read as windows-1250");
assert_eq!(decode(&[0xFF, 0xFE, b'A', 0], shift_jis), "\u{FFFD}\u{FFFD}A\0", "a UTF-16 byte-order mark is read as Shift JIS");
}
#[test]
fn options_parse_and_reject_bad_values() {
let p = serde_json::json!({"text": {"characterSet": "ansi", "platform": "mac", "removeLineReturns": true, "replaceSpaces": 4}});
let o = TextOptions::parse(&p, "file.place").unwrap();
assert_eq!(o, TextOptions { ansi: true, mac: true, remove_line_returns: true, remove_paragraph_returns: false, spaces_to_tab: Some(4) });
assert_eq!(
o,
TextOptions {
character_set: CharacterSet::Ansi,
mac: true,
remove_line_returns: true,
remove_paragraph_returns: false,
spaces_to_tab: Some(4)
}
);
for (name, set) in CHARACTER_SETS {
let o = TextOptions::parse(&serde_json::json!({"text": {"characterSet": name}}), "file.place").unwrap();
assert_eq!(o.character_set, set, "{name}");
}
assert_eq!(TextOptions::parse(&serde_json::json!({}), "file.place").unwrap(), TextOptions::default());
for bad in
[serde_json::json!({"text": 3}), serde_json::json!({"text": {"platform": "amiga"}}), serde_json::json!({"text": {"replaceSpaces": 1}})]
{
for bad in [
serde_json::json!({"text": 3}),
serde_json::json!({"text": {"platform": "amiga"}}),
serde_json::json!({"text": {"replaceSpaces": 1}}),
serde_json::json!({"text": {"characterSet": 3}}),
serde_json::json!({"text": {"platform": true}}),
serde_json::json!({"text": {"removeLineReturns": "yes"}}),
serde_json::json!({"text": {"removeParagraphReturns": 1}}),
] {
assert!(TextOptions::parse(&bad, "file.place").is_err(), "{bad}");
}
let null = serde_json::json!({"text": {"characterSet": null, "platform": null, "removeLineReturns": null}});
assert_eq!(TextOptions::parse(&null, "file.place").unwrap(), TextOptions::default(), "null leaves the default");
}
}
+15 -3
View File
@@ -161,6 +161,8 @@ pub struct FilterRun {
parent: Option<NodeId>,
/// The document it was made from, and that document's revision then.
document: (u64, u64),
/// The plug-in's limits with the Plug-in Instruction Budget in force when it was made.
limits: vectorcraft_plugins::Limits,
}
/// A filter's output handed in by a [`FilterRun`] made away from `plugin.run`, with what the run
@@ -245,7 +247,11 @@ impl FilterRun {
let capacity = (plugin.limits().max_memory_bytes / 2).min(i32::MAX as usize).saturating_sub(params.len());
let (input, read_only) = objects::encode_input_with(&st.doc, &inputs, &kinds, capacity).map_err(err)?;
let document = (st.uid, st.revision);
Ok(FilterRun { plugin, command, input, params, inputs, read_only, parent, document })
let limits = match s.prefs.plugin_instruction_budget {
crate::PluginBudget::Normal => plugin.limits().clone(),
crate::PluginBudget::Large => plugin.large_limits(),
};
Ok(FilterRun { plugin, command, input, params, inputs, read_only, parent, document, limits })
}
/// The plug-in, for its name and budget.
@@ -274,7 +280,13 @@ impl FilterRun {
/// can run on any thread; inside a [`vectorcraft_doc::cancel::scope`] Cancel stops it between
/// two slices of its budget.
pub fn run(&self) -> Result<Vec<u8>> {
self.plugin.run(&self.input, &self.params).map_err(err)
self.plugin.run_limited(&self.input, &self.params, &self.limits).map_err(err)
}
/// The limits it runs under: the plug-in's, with the Plug-in Instruction Budget in force when
/// it was made.
pub fn limits(&self) -> &vectorcraft_plugins::Limits {
&self.limits
}
/// Does the plug-in call commands (its manifest's `commandAllowlist`)? Then it runs only in the
@@ -289,7 +301,7 @@ impl FilterRun {
let may = self.plugin.manifest().permissions();
let calls = super::plugin_call::Calls::of(s, may.contains(&Permission::DocRead), may.contains(&Permission::DocWrite));
let mut bridge = |id: &str, args: &Value| super::plugin_call::call(s, &calls, id, args);
self.plugin.run_calling(&self.input, &self.params, self.plugin.limits(), &mut bridge).0.map_err(err)
self.plugin.run_calling(&self.input, &self.params, &self.limits, &mut bridge).0.map_err(err)
}
/// Runs a plug-in that calls commands and applies its output: the calls and the output are one
+1
View File
@@ -64,6 +64,7 @@ const DENIED_PREFIXES: &[&str] = &[
"edit.newDocument",
"edit.colorSettings",
"edit.dropSelection",
"symbol.placeFromDocument",
"artboard.copy",
"artboard.cut",
"text.rescanFonts",
@@ -41,10 +41,12 @@ pub(super) const ALLOWED: &[&str] = &[
"addon.image.removeBackground",
"addon.image.removeColorMask",
"addon.packaging.check",
"addon.packaging.fold",
"addon.packaging.roles",
"addon.packaging.setRole",
"addon.packaging.setRoleSwatch",
"addon.pathtools.addPoints",
"addon.pathtools.bridge",
"addon.pathtools.close",
"addon.pathtools.commonTangents",
"addon.pathtools.corner",
@@ -84,6 +86,8 @@ pub(super) const ALLOWED: &[&str] = &[
"addon.shapes.star",
"addon.type.releasePath",
"addon.type.textTweaker",
"addon.units.convert",
"addon.units.selectionSize",
"appearance.addEffect",
"appearance.addFill",
"appearance.addStroke",
@@ -124,6 +128,7 @@ pub(super) const ALLOWED: &[&str] = &[
"brush.list",
"brush.move",
"brush.new",
"brush.objectOptions",
"brush.options",
"brush.placeArt",
"brush.remove",
@@ -366,6 +371,7 @@ pub(super) const ALLOWED: &[&str] = &[
"object.repeat.release",
"object.resetBoundingBox",
"object.rotate",
"object.rotateBoundingBox",
"object.scale",
"object.setBounds",
"object.setLiveShape",
+133
View File
@@ -0,0 +1,133 @@
//! Production preflight: the existing output-aware type walk, linked-file probes and image
//! resolution calculation, returned as findings that the interface can locate and recheck.
use serde_json::{Value, json};
use vectorcraft_doc::NodeId;
use vectorcraft_text::{FontDb, FontMatch};
use super::{CommandSpec, Result, Session, bad, cmd, has_doc, number_or, text_param};
const COMMAND: &str = "document.preflight";
const KINDS: [&str; 4] = ["fonts", "text", "links", "resolution"];
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
query "document.preflight",
"Production Preflight",
[],
None,
"{output?: pdf|print|screen (pdf), minPpi?: 1..9600 (300, or 96 for screen), artboards?: [index, …] (0-based whole numbers; default all)} check the selected output without writing files or editing the document; print reuses the saved print settings with these artboards, pdf and screen check visible artwork on these artboards. Reuses output-aware font and overflow checks, Links file status and image.info effective resolution. Resource findings locate their first visible canvas owner; resolution inside resource art is reported as not checked because its placed scale can differ. → {output, minPpi, artboards, checks: [{kind: fonts|text|links|resolution, status: passed|failed|notChecked, count, notChecked}], findings: [{kind, code, ids (canvas objects), name, detail?, sourceId?, effectivePpi?, threshold?}], outputWarnings, limitations}; a pass covers only these checks, not certification of a produced file",
has_doc,
check
)]
}
fn check(s: &mut Session, p: &Value) -> Result<Value> {
let output = text_param(p, "output", COMMAND)?.unwrap_or("pdf");
if !matches!(output, "pdf" | "print" | "screen") {
return Err(bad(COMMAND, "output must be pdf, print or screen"));
}
let min_ppi = number_or(p, "minPpi", if output == "screen" { 96.0 } else { 300.0 }, COMMAND)?;
if !min_ppi.is_finite() || !(1.0..=9600.0).contains(&min_ppi) {
return Err(bad(COMMAND, "minPpi must be from 1 to 9600"));
}
let indices = match p.get("artboards").filter(|v| !v.is_null()) {
Some(v) => super::panelcmds::listed_artboards(&s.doc()?.doc, v, "artboards", COMMAND)?,
None => (0..s.doc()?.doc.artboards.len()).collect(),
};
let context = if output == "print" {
super::print::preflight_context(s, &indices)?
} else {
let doc = &s.doc()?.doc;
let pages = indices.iter().filter_map(|i| doc.artboards.get(*i).map(|a| (a.rect, vectorcraft_geom::Affine::IDENTITY))).collect();
super::print::PreflightContext { layers: vectorcraft_pdf::PrintLayers::Visible, pages, warnings: vec![] }
};
let areas = context.pages.iter().map(|(r, _)| *r).collect::<Vec<_>>();
let st = s.doc()?;
let doc = st.doc.with_placed_art();
let mut layers = doc.layers.clone();
vectorcraft_pdf::keep_layers(&mut layers, context.layers);
let typed = super::fonts::preflight_type(&doc, &layers, &areas);
let statuses = super::links::statuses(st);
let mut findings = vec![];
let db = FontDb::global();
for (font, ids) in typed.fonts {
let code = match db.resolve(&font.0, &font.1).map(|(_, m)| m) {
None | Some(FontMatch::Missing) => "missingFont",
Some(FontMatch::Style) => "substitutedFont",
_ => continue,
};
findings.push(
json!({ "kind": "fonts", "code": code, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "name": super::fonts::font_label(&font) }),
);
}
for id in typed.overflow {
findings.push(finding("text", "overflow", id, &doc));
}
let mut resolution_unchecked = 0usize;
for (source, owner) in typed.images {
if let Some((status, _, _)) = statuses.get(&source) {
let code = match status.as_str() {
"missing" => Some("missingLink"),
"modified" => Some("modifiedLink"),
_ => None,
};
if let Some(code) = code {
let mut f = finding("links", code, owner, &doc);
f["sourceId"] = json!(source.0);
findings.push(f);
}
}
// A vector placed document has no single bitmap resolution. Its embedded artwork, and
// resources with their own coordinate systems, must never be certified at a local scale.
if doc.node(source).is_none() || source != owner {
resolution_unchecked += 1;
continue;
}
let Some(vectorcraft_doc::NodeKind::Image(im)) = doc.node(source).map(|n| &n.kind) else {
resolution_unchecked += 1;
continue;
};
let bounds = doc.node(source).and_then(|n| vectorcraft_render::painted_bounds(&doc, n));
let ppi = context
.pages
.iter()
.filter(|(area, _)| bounds.is_some_and(|b| area.intersect(b).area() > 0.0))
.map(|(_, to_page)| super::place::effective_ppi(*to_page * im.xf))
.reduce(|[a, b], [c, d]| [a.min(c), b.min(d)]);
let Some(ppi) = ppi else {
resolution_unchecked += 1;
continue;
};
// Inverting the placed-size transform can round an exact threshold slightly down.
if ppi.iter().any(|n| !n.is_finite() || *n <= 0.0) {
resolution_unchecked += 1;
} else if ppi.iter().any(|n| *n < min_ppi * (1.0 - 1e-9)) {
let mut f = finding("resolution", "lowResolution", owner, &doc);
f["effectivePpi"] = json!(ppi);
f["threshold"] = json!(min_ppi);
findings.push(f);
}
}
let checks = KINDS.map(|kind| {
let count = findings.iter().filter(|f| f["kind"] == kind).count();
let not_checked = if kind == "resolution" { resolution_unchecked } else { 0 };
let status = if count > 0 {
"failed"
} else if not_checked > 0 {
"notChecked"
} else {
"passed"
};
json!({ "kind": kind, "status": status, "count": count, "notChecked": not_checked })
});
Ok(json!({
"output": output, "minPpi": min_ppi, "artboards": indices, "checks": checks,
"findings": findings, "outputWarnings": context.warnings,
"limitations": ["These checks do not certify an exported file.", "Resolution inside symbols, patterns, brushes, opacity masks and placed documents is not checked."]
}))
}
fn finding(kind: &str, code: &str, id: NodeId, doc: &vectorcraft_doc::Document) -> Value {
json!({ "kind": kind, "code": code, "ids": [id.0], "name": doc.node(id).map(|n| n.display_name()).unwrap_or_else(|| id.0.to_string()) })
}
+11
View File
@@ -139,6 +139,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
p!("cornerRadius", "General", "", "Corner Radius", len(0.0, 1296.0, General)),
p!("pasteOffset", "General", "", "Paste Offset", len(0.0, 1296.0, General)),
p!("disableAutoAddDelete", "General", "Options", "Disable Auto Add/Delete", bool),
p!("interpolateControlPoints", "General", "Options", "Interpolate Control Points When Moving Anchors", bool),
p!("usePreciseCursors", "General", "Options", "Use Precise Cursors", bool),
p!("showToolTips", "General", "Options", "Show Tool Tips", bool),
p!("showExternalScriptWarning", "General", "Options", "Show External Script Warning", bool),
@@ -323,6 +324,14 @@ pub const PREF_SPECS: &[PrefSpec] = &[
p!("hyphenationExceptions", "Hyphenation", "", "Exceptions (comma separated)", text),
// Plug-ins & Scratch Disks
p!("pluginsFolder", "Plug-ins & Scratch Disks", "Plug-ins", "Additional Plug-ins Folder", text),
// The instructions each object filter run gets: Large gives at least 250 M besides those for each byte of input.
p!(
"pluginInstructionBudget",
"Plug-ins & Scratch Disks",
"Plug-ins",
"Plug-in Instruction Budget",
choice(&[("normal", "Normal"), ("large", "Large")])
),
p!("scratchPrimary", "Plug-ins & Scratch Disks", "Scratch Disks", "Primary", text),
p!("scratchSecondary", "Plug-ins & Scratch Disks", "Scratch Disks", "Secondary", text),
// User Interface
@@ -368,6 +377,8 @@ pub const PREF_SPECS: &[PrefSpec] = &[
p!("gpuPerformance", "Performance", "GPU Performance", "GPU Performance", bool),
p!("animatedZoom", "Performance", "GPU Performance", "Animated Zoom", bool),
p!("gpuPreference", "Performance", "GPU Performance", "Graphics Processor", choice(GPU_PREFERENCES)),
// Read by the desktop app at startup: the window presents without vsync, capped at 240 fps (#6013).
p!("lowLatencyDrawing", "Performance", "GPU Performance", "Low-Latency Drawing", bool),
p!("historyStates", "Performance", "", "History States", int(5, 1000)),
p!("realTimeDrawing", "Performance", "", "Real-time Drawing and Editing", bool),
p!("renderThreads", "Performance", "", "Render Threads (-1 = Automatic)", int(-1, 64)),
+26
View File
@@ -147,6 +147,32 @@ fn preview(s: &mut Session, p: &Value) -> Result<Value> {
Ok(v)
}
/// Reuse the Print dialog's saved settings and page geometry for production preflight, without
/// printing, writing a file or duplicating its type warnings.
pub(super) struct PreflightContext {
pub layers: PrintLayers,
pub pages: Vec<(Rect, Affine)>,
pub warnings: Vec<String>,
}
pub(super) fn preflight_context(s: &Session, indices: &[usize]) -> Result<PreflightContext> {
let settings =
json!({ "settings": { "artboards": "range", "range": indices.iter().map(|i| (i + 1).to_string()).collect::<Vec<_>>().join(",") } });
let set = preset_or_saved("document.preflight", s, &s.doc()?.doc, &settings)?;
super::printadvanced::flattener("document.preflight", &set, &s.prefs.flattener_presets)?;
let mut pv = vectorcraft_pdf::preview(&s.doc()?.doc, &set).map_err(|e| pdf_error("document.preflight", e))?;
let pages = pv
.sheets
.iter()
.filter_map(|p| {
let to_page = Affine::new(p.transform);
on_page(Rect::new(p.area[0], p.area[1], p.area[2], p.area[3]), to_page, (p.width, p.height)).map(|area| (area, to_page))
})
.collect();
pv.warnings.extend(pv.setting_notes);
Ok(PreflightContext { layers: set.print_layers, pages, warnings: pv.warnings })
}
/// The parts of the document (document space) that the pages of `pv` print.
fn areas(pv: &PrintPreview) -> Vec<Rect> {
pv.sheets
+17 -3
View File
@@ -34,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Recolor Artwork",
["Edit", "Edit Colors"],
None,
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null] (what `group` is rewritten with, a null removing the group's swatch at its place; default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null | \"keep\"] (what `group` is rewritten with, a null removing the group's swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the swatches it adds nothing; refused for a swatch that is not a colour); default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
has_doc,
apply
),
@@ -1680,12 +1680,26 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
Some(Value::Array(cs)) => Some(cs),
Some(_) => return Err(bad(C, "`groupColors` must be an array")),
};
// A null in groupColors removes the group's swatch at its place.
// A null in groupColors removes the group's swatch at its place, and "keep" leaves the swatch
// at its place its color, without the Global Adjust.
let own: Vec<Option<Color>> = match group {
Some(g) => {
s.doc()?.doc.swatch_groups.iter().find(|x| x.name == g).map(|g| g.swatches.iter().map(|w| w.paint.color()).collect()).unwrap_or_default()
}
None => vec![],
};
let new: Vec<Option<Color>> = match group_colors {
Some(cs) => cs
.iter()
.map(|v| match v {
.enumerate()
.map(|(i, v)| match v {
Value::Null => Ok(None),
// Past the group's swatches it adds nothing.
Value::String(k) if k == "keep" => match own.get(i) {
Some(Some(c)) => Ok(Some(*c)),
Some(None) => Err(bad(C, format!("the swatch at place {i} of groupColors is not a colour to keep"))),
None => Ok(None),
},
v => color_value(v)
.map(|c| adjust.apply(c))
.map(|c| Some(in_doc_model(palette.as_ref().map_or(c, |pl| pl.nearest(c)))))
File diff suppressed because one or more lines are too long
+57 -11
View File
@@ -375,6 +375,59 @@ fn is_selectable_within(d: &Document, iso: Option<NodeId>, locks: Option<&Locked
}
}
/// The object Next Object Above (`dir` > 0) or Next Object Below selects from `cur`: the nearest
/// sibling of `cur` in that direction that [`walk_selectable`] visits. Hidden and locked objects
/// and sublayers are passed over. Only the siblings are read, not the rest of the document.
fn step_target(d: &Document, iso: Option<NodeId>, cur: NodeId, dir: i64) -> Option<NodeId> {
let path = d.index_path(cur)?;
let (&idx, up) = path.split_last()?;
// The objects that hold `cur` and its siblings, from the top-level layer down.
let mut holders = Vec::with_capacity(up.len());
let mut siblings = &d.layers;
for &i in up {
let n = siblings.get(i)?;
holders.push(n.as_ref());
siblings = n.children()?;
}
let iso = iso.and_then(|i| d.node(i));
let locks = d.locked_artboards();
let visits = |n: &Node| walk_visits(&holders, n, iso, &locks);
let next = if dir > 0 { siblings.iter().skip(idx + 1).find(|n| visits(n)) } else { siblings.iter().take(idx).rev().find(|n| visits(n)) };
next.map(|n| n.id)
}
/// Whether [`walk_selectable`] visits `n`, read from the objects that hold it: `holders` are its
/// layer and the sublayers, groups and other containers inside it that hold `n`, outermost first
/// (its [`Document::ancestry`] without `n`). `iso` is the isolated object. Unlike
/// [`is_selectable`], it passes over sublayers and the ruler guides of a layer, which the walk
/// looks through or leaves out.
fn walk_visits(holders: &[&Node], n: &Node, iso: Option<&Node>, locks: &LockedArtboards) -> bool {
let len = holders.len() + 1;
let at = |i: usize| holders.get(i).copied().unwrap_or(n);
let open = |i: usize| at(i).visible && !at(i).locked;
let start = match iso {
Some(c) => {
let Some(p) = (0..len).find(|&i| at(i).id == c.id) else { return false };
if !(0..=p).all(|i| open(i) && !at(i).is_template()) {
return false;
}
// A single object isolated is all there is to select.
if !c.is_container() {
return p + 1 == len;
}
p + 1
}
None => 0,
};
// The object Select All takes: the first one that is not a layer, inside visible, unlocked
// layers and sublayers that are not template layers.
let Some(top) = (start..len).find(|&i| !at(i).is_layer()) else { return false };
(start..top).all(|i| open(i) && !at(i).is_template())
&& !at(top).is_ruler_guide()
&& (top..len).all(open)
&& (iso.is_some() || locks.is_empty() || !locks.holds(at(top)))
}
/// The first selected object, in selection order, that [`is_selectable`] accepts.
pub(crate) fn first_selectable(st: &DocState) -> Option<&Node> {
let locks = st.doc.locked_artboards();
@@ -475,17 +528,7 @@ fn inverse(s: &mut Session, _: &Value) -> Result<Value> {
fn step(s: &mut Session, dir: i64) -> Result<Value> {
let st = s.doc()?;
let Some(cur) = st.selection.objects.first().copied() else { return ok() };
let Some((par, idx, _)) = st.doc.position(cur) else { return ok() };
let Some(siblings) = st.doc.children(par) else { return ok() };
// The nearest sibling in that direction that `walk_selectable` visits: hidden and locked
// objects and sublayers are passed over.
let can = selectable_ids(&st.doc, st.isolation);
let next = if dir > 0 {
siblings.iter().skip(idx + 1).find(|n| can.contains(&n.id))
} else {
siblings.iter().take(idx).rev().find(|n| can.contains(&n.id))
};
let Some(id) = next.map(|n| n.id) else { return ok() };
let Some(id) = step_target(&st.doc, st.isolation, cur, dir) else { return ok() };
s.select(|_, sel| sel.set([id]))?;
ok()
}
@@ -1399,5 +1442,8 @@ fn not_pixel_aligned(s: &mut Session, _: &Value) -> Result<Value> {
#[cfg(test)]
mod same_tests;
#[cfg(test)]
mod step_tests;
#[cfg(test)]
mod tests;
+347
View File
@@ -0,0 +1,347 @@
//! Select > Next Object Above and Below through [`step_target`], which reads only the siblings of
//! the selected object, against a copy of the search that collected every object
//! [`walk_selectable`] visits on each step.
use std::sync::Arc;
use std::time::{Duration, Instant};
use serde_json::json;
use vectorcraft_doc::{Appearance, Document, LayerColor, Node, NodeId, NodeKind};
use vectorcraft_geom::{Rect, shapes};
use super::{selectable_ids, step_target, walk_visits};
use crate::Session;
/// The search as it was before it read only the siblings: the nearest sibling in that direction
/// that `walk_selectable` visits, from the set of every object it visits.
fn step_base(d: &Document, iso: Option<NodeId>, cur: NodeId, dir: i64) -> Option<NodeId> {
let (par, idx, _) = d.position(cur)?;
let siblings = d.children(par)?;
let can = selectable_ids(d, iso);
let next = if dir > 0 {
siblings.iter().skip(idx + 1).find(|n| can.contains(&n.id))
} else {
siblings.iter().take(idx).rev().find(|n| can.contains(&n.id))
};
next.map(|n| n.id)
}
/// A small xorshift generator, so that each seed gives the same document every run.
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
fn below(&mut self, n: u64) -> u64 {
self.next() % n
}
/// True `pct` times in 100.
fn chance(&mut self, pct: u64) -> bool {
self.below(100) < pct
}
}
fn rect_node(d: &mut Document, x: f64, y: f64) -> Node {
Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 40.0, y + 40.0)), Appearance::default())
}
fn layer_node(d: &mut Document, children: Vec<Node>) -> Node {
let mut l = Node::layer(d.alloc_id(), "Layer", LayerColor::Preset(0));
if let Some(ch) = l.children_mut() {
ch.extend(children.into_iter().map(Arc::new));
}
l
}
fn ruler_guide(d: &mut Document, pos: f64) -> Node {
Node::new(d.alloc_id(), NodeKind::RulerGuide { vertical: pos > 300.0, pos, artboard: None })
}
/// Up to six objects: rectangles on and off the artboard, guides made from paths, ruler guides,
/// groups, and sublayers, some hidden, locked or template layers. Groups and sublayers hold more
/// below `depth`. Sublayers and ruler guides also go inside groups, which the app does not make,
/// so that every shape of tree is compared.
fn objects(r: &mut Rng, d: &mut Document, depth: u32) -> Vec<Node> {
(0..r.below(7))
.map(|_| {
let (x, y) = (r.below(1400) as f64 - 300.0, r.below(1000) as f64 - 200.0);
let mut n = match r.below(if depth == 0 { 6 } else { 10 }) {
0..=3 => rect_node(d, x, y),
4 => {
let mut n = rect_node(d, x, y);
if let NodeKind::Path { guide, .. } = &mut n.kind {
*guide = true;
}
n
}
5 => ruler_guide(d, x),
6 | 7 => {
let kids = objects(r, d, depth - 1);
Node::group(d.alloc_id(), kids.into_iter().map(Arc::new).collect())
}
_ => {
let kids = objects(r, d, depth - 1);
layer_node(d, kids)
}
};
n.visible = !r.chance(10);
n.locked = r.chance(10);
if let NodeKind::Layer { template, .. } = &mut n.kind {
*template = r.chance(15);
}
n
})
.collect()
}
/// A document of one to three layers, some hidden, locked or template layers, holding
/// [`objects`], with its artboard locked in some seeds.
fn random_document(seed: u64) -> Document {
let mut r = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1);
let mut d = Document::new(800.0, 600.0);
let layers = (0..1 + r.below(3))
.map(|_| {
let kids = objects(&mut r, &mut d, 3);
let mut l = layer_node(&mut d, kids);
l.visible = !r.chance(10);
l.locked = r.chance(10);
if let NodeKind::Layer { template, .. } = &mut l.kind {
*template = r.chance(10);
}
Arc::new(l)
})
.collect();
d.layers = layers;
if let Some(a) = d.artboards.first_mut() {
a.locked = r.chance(40);
}
d
}
/// Every node of `d`, layers included, in tree order.
fn all_ids(d: &Document) -> Vec<NodeId> {
let mut ids = vec![];
d.walk(|n| ids.push(n.id));
ids
}
/// The objects that hold `id`, outermost first, and the node itself.
fn holders(d: &Document, id: NodeId) -> (Vec<&Node>, &Node) {
let a = d.ancestry(id).unwrap();
let (last, up) = a.split_last().unwrap();
(up.iter().map(|i| d.node(*i).unwrap()).collect(), d.node(*last).unwrap())
}
/// For every node of random documents, outside isolation mode and with each of several nodes
/// isolated, `walk_visits` says what the set of the objects `walk_selectable` visits says, and
/// Next Object Above and Below from it give what the search over that set gave.
#[test]
fn next_object_gives_what_the_search_over_every_selectable_object_gave() {
let (mut steps, mut moved, mut isolated) = (0, 0, 0);
for seed in 0..300 {
let d = random_document(seed);
let ids = all_ids(&d);
let mut r = Rng(seed + 7);
let mut isos = vec![None];
isos.extend((0..10).map(|_| Some(ids[r.below(ids.len() as u64) as usize])));
let locks = d.locked_artboards();
for iso in isos {
let can = selectable_ids(&d, iso);
let iso_node = iso.and_then(|i| d.node(i));
for &id in &ids {
let (up, n) = holders(&d, id);
assert_eq!(walk_visits(&up, n, iso_node, &locks), can.contains(&id), "seed {seed}, isolating {iso:?}, node {id:?}");
}
for &cur in &ids {
for dir in [1, -1] {
let want = step_base(&d, iso, cur, dir);
assert_eq!(step_target(&d, iso, cur, dir), want, "seed {seed}, isolating {iso:?}, from {cur:?}, direction {dir}");
steps += 1;
moved += usize::from(want.is_some());
isolated += usize::from(want.is_some() && iso.is_some());
}
}
}
}
// The documents give many steps that select something, inside isolation mode too.
eprintln!("{moved} of {steps} steps select an object, {isolated} of them in isolation mode");
assert!(moved > 5_000, "{moved} of {steps} steps select an object");
assert!(isolated > 500, "{isolated} steps select an object in isolation mode");
}
/// A session holding `d`, with `iso` isolated and `cur` selected.
fn session(d: Document, iso: Option<NodeId>, cur: NodeId) -> Session {
let mut s = Session::new();
s.add_document(d, None);
let st = s.doc_mut().unwrap();
st.isolation = iso;
st.selection.set([cur]);
s
}
fn selected(s: &Session) -> Vec<NodeId> {
s.doc().unwrap().selection.objects.to_vec()
}
/// In an isolated layer, Next Object Above and Below pass over a sublayer beside the selected object,
/// as the walk looks through it.
#[test]
fn next_object_passes_over_a_sublayer_in_an_isolated_layer() {
let mut d = Document::new(800.0, 600.0);
let a = rect_node(&mut d, 0.0, 0.0);
let inner = rect_node(&mut d, 100.0, 0.0);
let b = rect_node(&mut d, 200.0, 0.0);
let sub = layer_node(&mut d, vec![inner]);
let (a_id, b_id) = (a.id, b.id);
let l = layer_node(&mut d, vec![a, sub, b]);
let layer = l.id;
d.layers = vec![Arc::new(l)];
assert_eq!(step_base(&d, Some(layer), a_id, 1), Some(b_id));
let mut s = session(d, Some(layer), a_id);
s.execute("select.nextAbove", &json!({})).unwrap();
assert_eq!(selected(&s), vec![b_id]);
s.execute("select.nextBelow", &json!({})).unwrap();
assert_eq!(selected(&s), vec![a_id]);
}
/// Next Object Above passes over a ruler guide of the layer, which the walk leaves out, unless the
/// guide is the object isolated.
#[test]
fn next_object_passes_over_a_ruler_guide_of_the_layer() {
let mut d = Document::new(800.0, 600.0);
let a = rect_node(&mut d, 0.0, 0.0);
let b = rect_node(&mut d, 200.0, 0.0);
let guide = ruler_guide(&mut d, 100.0);
let (a_id, b_id, guide_id) = (a.id, b.id, guide.id);
let l = layer_node(&mut d, vec![a, b, guide]);
d.layers = vec![Arc::new(l)];
// Nothing above the rectangle but the guide: the selection stays.
assert_eq!(step_base(&d, None, b_id, 1), None);
let mut s = session(d.clone(), None, b_id);
s.execute("select.nextAbove", &json!({})).unwrap();
assert_eq!(selected(&s), vec![b_id]);
s.execute("select.nextBelow", &json!({})).unwrap();
assert_eq!(selected(&s), vec![a_id]);
// The guide isolated on its own is what there is to select.
assert_eq!(step_base(&d, Some(guide_id), b_id, 1), Some(guide_id));
assert_eq!(step_target(&d, Some(guide_id), b_id, 1), Some(guide_id));
}
/// The first selected object anchors the search even when it can no longer be selected itself.
#[test]
fn next_object_steps_from_a_hidden_first_selected_object() {
let mut d = Document::new(800.0, 600.0);
let mut a = rect_node(&mut d, 0.0, 0.0);
a.visible = false;
let b = rect_node(&mut d, 200.0, 0.0);
let (a_id, b_id) = (a.id, b.id);
let l = layer_node(&mut d, vec![a, b]);
d.layers = vec![Arc::new(l)];
assert_eq!(step_base(&d, None, a_id, 1), Some(b_id));
let mut s = session(d, None, a_id);
s.execute("select.nextAbove", &json!({})).unwrap();
assert_eq!(selected(&s), vec![b_id]);
}
/// 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()
}
}
}
/// A document of `groups` groups of `per` rectangles on one layer, or of `per` rectangles when
/// `groups` is 0 → the document and the object in the middle of the layer.
fn wide(groups: usize, per: usize) -> (Document, NodeId) {
let mut d = Document::new(800.0, 600.0);
let mut top = vec![];
if groups == 0 {
top.extend((0..per).map(|i| rect_node(&mut d, (i % 200) as f64 * 4.0, (i / 200 % 150) as f64 * 4.0)));
} else {
for g in 0..groups {
let kids: Vec<Arc<Node>> = (0..per).map(|i| Arc::new(rect_node(&mut d, (i % 20) as f64 * 4.0, (g % 150) as f64 * 4.0))).collect();
top.push(Node::group(d.alloc_id(), kids));
}
}
let mid = top[top.len() / 2].id;
let l = layer_node(&mut d, top);
d.layers = vec![Arc::new(l)];
(d, mid)
}
/// A search for the object Next Object Above or Below selects: [`step_base`] or [`step_target`].
type Step = fn(&Document, Option<NodeId>, NodeId, i64) -> Option<NodeId>;
/// Timings of Next Object Above and Below, stepping up and down from the object in the middle of
/// the layer, by the search over every selectable object (200 steps a run) and by the siblings
/// alone (200,000 steps a run, as one step takes too little time to measure), on 100,000
/// rectangles and on 1,000 groups of 100, run in turn on the same document, 7 runs each. Ignored by
/// default; it prints the median, fastest and slowest time per step and sets no bound on them:
/// `cargo test --release -p vectorcraft-engine --lib next_object_perf -- --ignored --nocapture`.
#[test]
#[ignore = "a benchmark: run with --ignored --nocapture"]
fn next_object_perf() {
const RUNS: usize = 7;
const OLD_STEPS: usize = 200;
const NEW_STEPS: usize = 200_000;
let per_step = |d: Duration, steps: usize| d.as_secs_f64() * 1e6 / steps as f64;
eprintln!("next_object_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" });
eprintln!("next_object_perf: {:<26} {:>32} {:>32}", "document", "every object µs/step (min-max)", "siblings µs/step (min-max)");
for (name, groups, per) in [("100,000 rectangles", 0, 100_000), ("1,000 groups of 100", 1_000, 100)] {
let (d, mid) = wide(groups, per);
let walk = |f: Step, steps: usize| {
let mut cur = mid;
let mut seen = Vec::with_capacity(steps);
for i in 0..steps {
cur = f(&d, None, cur, if i % 2 == 0 { 1 } else { -1 }).unwrap_or(cur);
seen.push(cur);
}
std::hint::black_box(seen)
};
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 = walk(step_base, OLD_STEPS)));
new.push(time(|| b = walk(step_target, NEW_STEPS)));
} else {
new.push(time(|| b = walk(step_target, NEW_STEPS)));
old.push(time(|| a = walk(step_base, OLD_STEPS)));
}
assert_eq!(a[..], b[..OLD_STEPS], "{name}");
assert_ne!(a[0], mid, "{name}: the first step selects another object");
}
old.sort();
new.sort();
eprintln!(
"next_object_perf: {name:<26} {:>12.3} ({:>8.3}-{:>9.3}) {:>12.3} ({:>8.3}-{:>9.3})",
per_step(old[RUNS / 2], OLD_STEPS),
per_step(old[0], OLD_STEPS),
per_step(old[RUNS - 1], OLD_STEPS),
per_step(new[RUNS / 2], NEW_STEPS),
per_step(new[0], NEW_STEPS),
per_step(new[RUNS - 1], NEW_STEPS),
);
}
}

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