mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-27 04:38:29 +00:00
Merge remote-tracking branch 'upstream/main' into feat/artistic-brush-library
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
),
|
||||
@@ -774,9 +774,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();
|
||||
@@ -788,6 +790,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())));
|
||||
|
||||
@@ -220,8 +220,10 @@ fn own_stroke_or_leaves(s: &Session, p: &Value) -> Result<Vec<vectorcraft_doc::N
|
||||
})
|
||||
};
|
||||
let (mut out, rest): (Vec<_>, Vec<_>) = picked.into_iter().partition(own);
|
||||
// A leaf already listed is skipped; a set keeps this linear in the number of leaves.
|
||||
let mut seen: std::collections::HashSet<vectorcraft_doc::NodeId> = out.iter().copied().collect();
|
||||
for id in super::leaf_targets(s, &rest)? {
|
||||
if !out.contains(&id) {
|
||||
if seen.insert(id) {
|
||||
out.push(id);
|
||||
}
|
||||
}
|
||||
@@ -678,6 +680,7 @@ fn profile_list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vectorcraft_doc::NodeId;
|
||||
|
||||
#[test]
|
||||
fn weight_steps_follow_units_and_stop_at_their_bounds() {
|
||||
@@ -693,4 +696,93 @@ mod tests {
|
||||
assert!((step_weight(mm, Unit::Millimeters, true) - 2.0 * mm).abs() < 1e-9);
|
||||
assert!((step_weight(mm, Unit::Millimeters, false) - 0.75 * mm).abs() < 1e-9);
|
||||
}
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
|
||||
}
|
||||
|
||||
fn made(v: Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap_or_else(|| panic!("no id in {v}")))
|
||||
}
|
||||
|
||||
/// The targets of [`own_stroke_or_leaves`] merged by a linear search of the growing list.
|
||||
fn listed_merge(s: &Session, p: &Value) -> Vec<NodeId> {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let own = |id: &NodeId| {
|
||||
d.node(*id).is_some_and(|n| {
|
||||
matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !n.is_compound_shape() && n.appearance.stroke().is_some()
|
||||
})
|
||||
};
|
||||
let (mut out, rest): (Vec<_>, Vec<_>) = super::super::targets(s, p).unwrap().into_iter().partition(own);
|
||||
for id in super::super::leaf_targets(s, &rest).unwrap() {
|
||||
if !out.contains(&id) {
|
||||
out.push(id);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `stroke.set` with no `item` lists the same targets in the same order as a linear merge:
|
||||
/// groups and layers with a stroke of their own (repeats kept), the leaves of plain groups and
|
||||
/// layers, compound paths and compound shapes for their members, and each leaf once, also
|
||||
/// when it is named both directly and through its group.
|
||||
#[test]
|
||||
fn stroke_targets_match_the_listed_merge() {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 2000, "height": 400}));
|
||||
let base = s.doc().unwrap().doc.layers[0].id;
|
||||
let mut x = 0.0;
|
||||
let mut rect = |s: &mut Session| {
|
||||
x += 120.0;
|
||||
made(run(s, "shape.rectangle", json!({"x": x, "y": 100, "width": 100, "height": 100})))
|
||||
};
|
||||
let (a, b) = (rect(&mut s), rect(&mut s));
|
||||
let plain = made(run(&mut s, "object.group", json!({"ids": [a.0, b.0]})));
|
||||
let (c, d) = (rect(&mut s), rect(&mut s));
|
||||
let owned = made(run(&mut s, "object.group", json!({"ids": [c.0, d.0]})));
|
||||
run(&mut s, "appearance.addStroke", json!({"ids": [owned.0]}));
|
||||
let (e, f) = (rect(&mut s), rect(&mut s));
|
||||
run(&mut s, "select.set", json!({"ids": [e.0, f.0]}));
|
||||
let compound = made(run(&mut s, "object.compoundPath.make", json!({})));
|
||||
let (g, h) = (rect(&mut s), rect(&mut s));
|
||||
run(&mut s, "select.set", json!({"ids": [g.0, h.0]}));
|
||||
let shape = made(run(&mut s, "object.compoundShape.make", json!({})));
|
||||
let lone = rect(&mut s);
|
||||
let layer = made(run(&mut s, "layer.new", json!({})));
|
||||
let (j, k) = (rect(&mut s), rect(&mut s));
|
||||
run(&mut s, "appearance.addStroke", json!({"ids": [layer.0]}));
|
||||
{
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!((doc.parent_of(j), doc.parent_of(k)), (Some(layer), Some(layer)), "the new layer holds the last two");
|
||||
assert_eq!((doc.parent_of(e), doc.parent_of(g)), (Some(compound), Some(shape)));
|
||||
assert!(doc.node(owned).unwrap().appearance.stroke().is_some() && doc.node(layer).unwrap().appearance.stroke().is_some());
|
||||
}
|
||||
let named = json!({"ids": [plain.0, a.0, owned.0, owned.0, c.0, e.0, compound.0, g.0, lone.0, layer.0, j.0]});
|
||||
let cases = [
|
||||
named.clone(),
|
||||
json!({"ids": [j.0, h.0, f.0, b.0, plain.0, layer.0, owned.0, k.0, shape.0]}),
|
||||
json!({"ids": [base.0, layer.0, base.0]}),
|
||||
json!({"ids": [d.0, owned.0, base.0]}),
|
||||
json!({"ids": []}),
|
||||
];
|
||||
for p in &cases {
|
||||
assert_eq!(own_stroke_or_leaves(&s, p).unwrap(), listed_merge(&s, p), "{p}");
|
||||
}
|
||||
run(&mut s, "select.set", json!({"ids": [lone.0, owned.0, f.0, plain.0, b.0, layer.0]}));
|
||||
assert_eq!(own_stroke_or_leaves(&s, &json!({})).unwrap(), listed_merge(&s, &json!({})), "the selection");
|
||||
|
||||
// The edit reaches every listed target, counting a repeated one once, and leaves the other
|
||||
// member of the group with its own stroke alone.
|
||||
let want = listed_merge(&s, &named);
|
||||
assert_eq!(want.iter().filter(|id| **id == owned).count(), 2, "{want:?}");
|
||||
let distinct: std::collections::HashSet<_> = want.iter().collect();
|
||||
let before = s.doc().unwrap().doc.node(d).unwrap().clone();
|
||||
let r = run(&mut s, "stroke.set", json!({"ids": named["ids"], "weight": 3}));
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(r["objects"], distinct.len(), "{r} {want:?}");
|
||||
for id in &want {
|
||||
assert_eq!(doc.node(*id).unwrap().appearance.stroke().map(|st| st.width), Some(3.0), "{id:?}");
|
||||
}
|
||||
assert_eq!(doc.node(d), Some(&before), "a member reached only through its group's own stroke is left alone");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -318,8 +318,14 @@ impl Session {
|
||||
/// it is still linked (still has that style's look). A graph series group that holds nothing of its own stands
|
||||
/// for the topmost path directly inside it, which a style applied to the group links.
|
||||
pub fn selection_graphic_style(&self) -> Option<(&GraphicStyle, bool)> {
|
||||
self.graphic_style_of(*self.active()?.selection.subjects().first()?)
|
||||
}
|
||||
|
||||
/// The graphic style of object `id` of the active document, as [`Self::selection_graphic_style`]
|
||||
/// gives it for the first selected object.
|
||||
pub fn graphic_style_of(&self, id: NodeId) -> Option<(&GraphicStyle, bool)> {
|
||||
let st = self.active()?;
|
||||
let n = super::appearance::look_holder(&st.doc, st.doc.node(*st.selection.subjects().first()?)?);
|
||||
let n = super::appearance::look_holder(&st.doc, st.doc.node(id)?);
|
||||
let g = st.doc.graphic_style_by_id(n.extras().graphic_style?)?;
|
||||
Some((g, in_sync(n, g)))
|
||||
}
|
||||
|
||||
@@ -643,6 +643,45 @@ fn alt_drag_copies_rows_and_the_selected_art_moves_between_layers() {
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![a, g], "it stays selected");
|
||||
}
|
||||
|
||||
/// #8237: a copy may go above or below a row it copies, so a lone layer, the top layer dragged up
|
||||
/// and the bottom one dragged down can be copied. A move there, or a copy inside the row, is still
|
||||
/// refused.
|
||||
#[test]
|
||||
fn a_copy_goes_above_or_below_a_row_it_copies() {
|
||||
let mut s = session();
|
||||
let layers = |s: &Session| s.doc().unwrap().doc.layers.iter().map(|l| l.id).collect::<Vec<_>>();
|
||||
let [only] = layers(&s)[..] else { panic!("one layer") };
|
||||
for place in ["above", "below", "inside"] {
|
||||
assert!(s.execute("layer.move", &json!({"ids": [only.0], "target": only.0, "place": place})).is_err(), "a move {place} itself");
|
||||
}
|
||||
assert!(s.execute("layer.move", &json!({"ids": [only.0], "target": only.0, "place": "inside", "copy": true})).is_err());
|
||||
assert_eq!(layers(&s), vec![only], "nothing changed");
|
||||
let above = ids(&run(&mut s, "layer.move", json!({"ids": [only.0], "target": only.0, "place": "above", "copy": true})));
|
||||
assert_eq!(layers(&s), vec![only, above[0]], "the copy above the original");
|
||||
let below = ids(&run(&mut s, "layer.move", json!({"ids": [only.0], "target": only.0, "place": "below", "copy": true})));
|
||||
assert_eq!(layers(&s), vec![below[0], only, above[0]], "and one below it");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(layers(&s), vec![only, above[0]], "each copy is one undo step");
|
||||
}
|
||||
|
||||
/// #8237 review: rows that hold an object can't sit beside a top-level layer, so copied beside a
|
||||
/// top-level layer among them they would go inside it: a copy of that layer inside itself. Refused,
|
||||
/// and nothing changes.
|
||||
#[test]
|
||||
fn a_copy_with_objects_beside_a_copied_top_level_layer_is_refused() {
|
||||
let mut s = session();
|
||||
let bottom = s.doc().unwrap().doc.layers[0].id;
|
||||
let other = id(&run(&mut s, "layer.new", json!({})));
|
||||
let r = rect(&mut s, 0.0);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(r), Some(other), "the rectangle is in the other layer");
|
||||
let count = s.doc().unwrap().doc.node_count();
|
||||
for place in ["above", "below"] {
|
||||
let p = json!({"ids": [bottom.0, r.0], "target": bottom.0, "place": place, "copy": true});
|
||||
assert!(s.execute("layer.move", &p).is_err(), "{place}: the layer's copy would go inside it");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().doc.node_count(), count, "nothing copied");
|
||||
}
|
||||
|
||||
/// The selected art in rows dragged into a hidden layer or group is deselected, the key object
|
||||
/// included. Undo puts the rows back and selects the art again.
|
||||
#[test]
|
||||
|
||||
@@ -2542,34 +2542,6 @@ fn confined_screens_rows_check_the_artboard_each_file_holds() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A confined caller's single-file PDF with Preserve Editing of several assets carries the first
|
||||
/// asset's document alone, so only that document is checked: an image linked outside the read roots in a later asset does
|
||||
/// not refuse it, and one in the first asset does.
|
||||
#[test]
|
||||
fn confined_single_file_pdf_checks_the_document_it_carries() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let away = Folder::new("single-pdf-away");
|
||||
let home = Folder::new("single-pdf-home");
|
||||
let photo = away.file("photo.png");
|
||||
write(&photo, &png(60, 30, RED));
|
||||
let mut s = session();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
|
||||
let rect: vectorcraft_doc::NodeId = serde_json::from_value(r["id"].clone()).unwrap();
|
||||
let placed = place(&mut s, &photo);
|
||||
let mut assets = vec![];
|
||||
for id in [rect, placed] {
|
||||
assets.push(s.execute("assets.add", &json!({"ids": [id.0]})).unwrap()["assets"][0].as_u64().unwrap());
|
||||
}
|
||||
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
|
||||
let p = |ids: &[u64], folder: &str| json!({"assets": ids, "folder": home.file(folder), "pdfs": "single", "formats": [{"format": "pdf", "preserveEditing": true}]});
|
||||
let r = confine(roots.as_ref(), || s.execute("assets.export", &p(&assets, "first-plain"))).unwrap_or_else(|e| panic!("{e}"));
|
||||
assert_eq!(r["files"].as_array().map(Vec::len), Some(1), "{r}");
|
||||
let reversed = [assets[1], assets[0]];
|
||||
let e = confine(roots.as_ref(), || s.execute("assets.export", &p(&reversed, "first-linked"))).expect_err("first asset links outside").to_string();
|
||||
assert!(e.contains("a linked image file is outside the read roots"), "{e}");
|
||||
}
|
||||
|
||||
/// A confined caller's native outputs (a native file or template, an EPS or `.ai` file, a PDF with
|
||||
/// Preserve Editing, a package's document) carry the document without the Export for Screens
|
||||
/// folder when it is outside the read roots, with the other export settings and the art; the open
|
||||
|
||||
Reference in New Issue
Block a user