Merge remote-tracking branch 'upstream/main' into feat/artistic-brush-library

This commit is contained in:
dotCooCoo
2026-11-17 21:56:40 -08:00
36 changed files with 1910 additions and 101 deletions
+73 -1
View File
@@ -187,8 +187,9 @@ impl Document {
/// [`Document::map_solid_paints`] limited to the art in the subtrees of `ids` (each paint
/// visited once even when an id is inside another).
pub fn map_solid_paints_in(&mut self, ids: &[NodeId], f: &mut LinkFn) -> usize {
let listed: HashSet<NodeId> = ids.iter().copied().collect();
let roots: Vec<NodeId> =
ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect();
ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| listed.contains(p)))).collect();
let mut n = 0;
let mut g = relink(f);
for id in roots {
@@ -844,6 +845,77 @@ mod tests {
assert_eq!(colors, [(Color::rgb(1.0, 0.0, 0.0), None)]);
}
/// [`Document::map_solid_paints_in`] with each ancestor searched for in `ids` rather than looked up in a set.
fn map_solid_paints_in_by_search(d: &mut Document, ids: &[NodeId], f: &mut LinkFn) -> usize {
let roots: 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();
let mut n = 0;
let mut g = relink(f);
for id in roots {
let Some(node) = d.node(id) else { continue };
if let Some((new, count)) = map_node(node, &mut g)
&& let Some(slot) = d.node_mut(id)
{
*slot = new;
n += count;
}
}
n
}
#[test]
fn mapping_within_ids_matches_a_search_of_the_ids() {
// Two layers: the first holds group `outer` (group `inner` with two rectangles, and a
// rectangle) and a rectangle; the second holds a rectangle. Each rectangle has its own color.
let mut d = Document::new(100.0, 100.0);
let first = d.layers[0].id;
let second = d.alloc_id();
d.insert(None, usize::MAX, Node::layer(second, "Second", crate::LayerColor::Preset(1))).unwrap();
let rect = |d: &mut Document, i: u8| {
let id = d.alloc_id();
let r = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0));
let color = Color::rgb(f32::from(i) / 8.0, 0.0, 0.0);
(id, Arc::new(Node::path(id, r, Appearance::basic(Paint::solid(color), Paint::solid(color), 1.0))))
};
let (r1, n1) = rect(&mut d, 1);
let (r2, n2) = rect(&mut d, 2);
let (r3, n3) = rect(&mut d, 3);
let (r4, n4) = rect(&mut d, 4);
let (r5, n5) = rect(&mut d, 5);
let (inner, outer) = (d.alloc_id(), d.alloc_id());
let outer_node = Node::group(outer, vec![Arc::new(Node::group(inner, vec![n1, n2])), n3]);
d.insert(Some(first), usize::MAX, outer_node).unwrap();
d.insert(Some(first), usize::MAX, Arc::unwrap_or_clone(n4)).unwrap();
d.insert(Some(second), usize::MAX, Arc::unwrap_or_clone(n5)).unwrap();
let missing = NodeId(u64::MAX);
let all = [first, second, outer, inner, r1, r2, r3, r4, r5, missing];
// Every list of up to three of them: nested ids in both orders, duplicates, a missing id and none.
let mut lists: Vec<Vec<NodeId>> = vec![vec![]];
let mut shorter: Vec<Vec<NodeId>> = vec![vec![]];
for _ in 0..3 {
shorter = shorter.iter().flat_map(|l| all.map(|id| [l.as_slice(), &[id]].concat())).collect();
lists.extend(shorter.iter().cloned());
}
assert_eq!(lists.len(), 1 + 10 + 100 + 1000);
for ids in &lists {
// A callback that changes every paint it visits, so a paint visited twice counts twice.
let run = |map: &dyn Fn(&mut Document, &[NodeId], &mut LinkFn) -> usize| {
let mut d = d.clone();
let mut visits = vec![];
let n = map(&mut d, ids, &mut |c, s, t| {
visits.push((*c, s.clone(), *t));
*s = Some(format!("{}", visits.len()));
*t *= 0.5;
true
});
(n, visits, d.layers)
};
let by_set = run(&|d, ids, f| d.map_solid_paints_in(ids, f));
let by_search = run(&|d, ids, f| map_solid_paints_in_by_search(d, ids, f));
assert_eq!(by_set, by_search, "{ids:?}");
}
}
/// The colors [`node_colors`] visits, in its order, by a [`Node::walk`] that reads the whole subtree.
fn full_walk(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) {
n.walk(&mut |m| {
+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);
}
}
+10 -3
View File
@@ -110,7 +110,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Rows",
[],
None,
"{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer, 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())));
+93 -1
View File
@@ -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");
}
}
+7 -1
View File
@@ -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)))
}
+39
View File
@@ -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]
-28
View File
@@ -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
+193
View File
@@ -4197,6 +4197,165 @@ fn images_that_cant_be_decoded_are_mid_gray_boxes() {
assert_eq!(paint(n.appearance.items[0].paint()), paint(&solid(Color::gray(0.5))));
}
/// A `w` × `h` RGB image whose pixels follow from `seed`, no two of its pixels gray.
fn seeded_png(seed: u32, (w, h): (u32, u32)) -> Vec<u8> {
let px = |x: u32, y: u32| {
let v = (x.wrapping_mul(73_856_093) ^ y.wrapping_mul(19_349_663) ^ seed.wrapping_mul(83_492_791)).to_le_bytes();
image::Rgb([v[0], v[1] | 1, v[2] & 0xfe])
};
png_of(image::DynamicImage::ImageRgb8(image::RgbImage::from_fn(w, h, px)))
}
/// A document placing `blobs` in turn on one layer, each `times` times: the first, the second and
/// so on, then the first again. Each blob is kept under `keys`' key at its index.
fn images_in_turn(blobs: &[ImageBlob], keys: &[&str], times: usize) -> Document {
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
for (blob, key) in blobs.iter().zip(keys) {
doc.images.insert((*key).to_string(), blob.clone());
}
for i in 0..times * blobs.len() {
let key = keys[i % blobs.len()].to_string();
let xf = Affine::translate((f64::from(u32::try_from(i).unwrap()), 10.0)) * Affine::scale(2.0);
let im = ImageObject { key, width: 4, height: 4, xf, link: None, placement: Default::default(), pixels: None };
let node = Node::new(doc.alloc_id(), NodeKind::Image(Box::new(im)));
doc.insert(Some(layer), usize::MAX, node).unwrap();
}
doc
}
/// `doc` written keeping the pixels of each image read (`last_only` false) or of the image read
/// last alone, and how many times an image's pixels were read.
fn export_reading(doc: &Document, last_only: bool) -> (AiEditingOutput, usize) {
writer::LAST_SAMPLES_ONLY.with(|l| l.set(last_only));
writer::SAMPLE_READS.with(|n| n.set(0));
let out = export_ai_editing(doc, &opts());
writer::LAST_SAMPLES_ONLY.with(|l| l.set(false));
(out.unwrap(), writer::SAMPLE_READS.with(std::cell::Cell::get))
}
/// `doc` written both ways ([`export_reading`]), the files and warnings compared whole, and the
/// reads of each way.
fn reads_for_the_same_file(doc: &Document) -> (usize, usize) {
let (kept, kept_reads) = export_reading(doc, false);
let (last, last_reads) = export_reading(doc, true);
assert!(kept.program == last.program, "the files differ");
assert_eq!(kept.header, last.header);
assert_eq!(kept.warnings, last.warnings);
(kept_reads, last_reads)
}
/// Two images placed one after the other 25 times each are each read once in a save, and the file
/// is the same as when only the image read last is kept.
#[test]
fn images_placed_in_turn_are_read_once_a_save() {
// GUARDS: each image was read again whenever the other was placed between its copies.
let blobs = [ImageBlob::png(seeded_png(1, (4, 4))), ImageBlob::png(seeded_png(2, (4, 4)))];
let doc = images_in_turn(&blobs, &["a", "b"], 25);
assert_eq!(reads_for_the_same_file(&doc), (2, 50));
let out = export_ai_editing(&doc, &opts()).unwrap();
assert_eq!(String::from_utf8_lossy(&out.program).matches("%AI5_BeginRaster").count(), 50);
}
/// A document of one image placed many times reads it once, and one without images reads none.
#[test]
fn one_image_is_read_once_and_no_image_never() {
let doc = images_in_turn(&[ImageBlob::png(seeded_png(3, (4, 4)))], &["a"], 10);
assert_eq!(reads_for_the_same_file(&doc), (1, 1));
assert_eq!(reads_for_the_same_file(&Document::new(200.0, 100.0)), (0, 0));
}
/// An image that can't be read, placed between copies of another, is read once too, and each copy
/// is still its gray outline with the same warning.
#[test]
fn an_image_that_cant_be_read_is_read_once_a_save() {
// GUARDS: an image that can't be read was read again whenever another image came between.
let blobs = [ImageBlob::png(b"not an image".to_vec()), ImageBlob::png(seeded_png(4, (4, 4)))];
let doc = images_in_turn(&blobs, &["bad", "good"], 3);
assert_eq!(reads_for_the_same_file(&doc), (2, 6));
let out = export_ai_editing(&doc, &opts()).unwrap();
assert_eq!(out.warnings, [writer::IMAGES]);
assert_eq!(String::from_utf8_lossy(&out.program).matches("%AI5_BeginRaster").count(), 3);
}
/// The same data under two MIME types is two images: each is read once, apart from the other.
#[test]
fn the_same_data_of_another_type_is_read_apart() {
let png = ImageBlob::png(seeded_png(5, (4, 4)));
let other = ImageBlob { mime: "image/x-other".into(), ..png.clone() };
assert!(Arc::ptr_eq(&png.bytes, &other.bytes));
let doc = images_in_turn(&[png, other], &["png", "other"], 3);
assert_eq!(reads_for_the_same_file(&doc), (2, 6));
}
/// Past the limits on the samples kept (bytes and images), an image is kept beside them in place
/// of the one before it, and the others are read again where they come: what is kept stays within
/// both limits, and the file is the same.
#[test]
fn images_past_the_limits_are_read_again_and_written_the_same() {
// Images of 48, 75 and 108 bytes of samples, then two of 48: 123 bytes and two images fit.
let sizes = [(4, 4), (5, 5), (6, 6), (4, 4), (4, 4)];
let blobs: Vec<_> = (0u32..).zip(sizes).map(|(i, s)| ImageBlob::png(seeded_png(10 + i, s))).collect();
let doc = images_in_turn(&blobs, &["a", "b", "c", "d", "e"], 3);
for (limits, kept_most, reads) in [((130, 8), (123, 2), 2 + 3 * 3), ((10_000, 3), (48 + 75 + 108, 3), 3 + 2 * 3)] {
writer::SAMPLE_LIMITS.with(|l| l.set(limits));
writer::SAMPLES_KEPT.with(|k| k.set((0, 0, false)));
let (kept_reads, last_reads) = reads_for_the_same_file(&doc);
let (bytes, images, beside) = writer::SAMPLES_KEPT.with(std::cell::Cell::get);
writer::SAMPLE_LIMITS.with(|l| l.set((256 << 20, 256)));
assert!(bytes <= limits.0 && images <= limits.1, "{limits:?}: kept {bytes} bytes of {images} images");
assert_eq!((bytes, images, beside), (kept_most.0, kept_most.1, true), "{limits:?}");
assert_eq!((kept_reads, last_reads), (reads, 15), "{limits:?}");
}
}
/// The time this thread has run, and how it was measured.
fn thread_time() -> (std::time::Duration, &'static str) {
if let Some(ns) = std::fs::read_to_string("/proc/thread-self/schedstat").ok().and_then(|s| s.split_whitespace().next()?.parse::<u64>().ok()) {
return (std::time::Duration::from_nanos(ns), "thread CPU time");
}
static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
(START.get_or_init(std::time::Instant::now).elapsed(), "wall-clock time")
}
/// The time to write two 2048 × 2048 images placed one after the other 25 times each, keeping the
/// pixels of each image read and of the image read last alone: the median of 7 runs of each,
/// alternating, with the files compared. Run with
/// `cargo test --release -p vectorcraft-eps --lib -- --ignored --nocapture images_placed_in_turn_are_written_quickly`.
#[test]
#[ignore = "timing"]
fn images_placed_in_turn_are_written_quickly() {
let blobs = [ImageBlob::png(seeded_png(1, (2048, 2048))), ImageBlob::png(seeded_png(2, (2048, 2048)))];
let doc = images_in_turn(&blobs, &["a", "b"], 25);
let mut times = [vec![], vec![]];
let mut files: [Option<Vec<u8>>; 2] = [None, None];
let mut reads = [0, 0];
let mut how = "";
for _ in 0..7 {
for (k, last_only) in [false, true].into_iter().enumerate() {
let (start, h) = thread_time();
let (out, n) = export_reading(&doc, last_only);
times[k].push(thread_time().0.saturating_sub(start));
how = h;
reads[k] = n;
files[k].get_or_insert(out.program);
}
}
assert!(files[0] == files[1], "the files differ");
assert_eq!(reads, [2, 50]);
for t in &mut times {
t.sort();
}
let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0;
println!("50 placements of two 2048 x 2048 images, median of 7 runs ({how}):");
println!("| pixels kept | images read | median (ms) | runs (ms) |");
println!("|---|---:|---:|---|");
for (k, label) in ["each image read", "the image read last"].into_iter().enumerate() {
let runs: Vec<String> = times[k].iter().map(|d| format!("{:.0}", ms(*d))).collect();
println!("| {label} | {} | {:.0} | {} |", reads[k], ms(times[k][3]), runs.join(", "));
}
}
#[test]
fn sixteen_bit_images_are_written_at_eight_bits() {
let mut doc = Document::new(200.0, 100.0);
@@ -10255,6 +10414,40 @@ fn brush_art_of_a_straight_line_comes_back_as_the_line() {
}
}
/// A Scatter brush's art is written turned over into its section (y up), so the side that is down the
/// page in the brush's copies is up in the section: a triangle with its point down comes out with
/// its point above its base, and comes back with its point down.
#[test]
fn a_scatter_brushs_art_is_written_turned_over() {
use vectorcraft_brush::{Brush, BrushKind, Scatter};
use vectorcraft_geom::{Point, SubPath};
let point_down = PathData { subpaths: vec![SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(40.0, 0.0), Point::new(20.0, 10.0)], true)] };
let art = Node::path(vectorcraft_doc::NodeId(1), point_down, Appearance::basic(black_fill(), Paint::None, 0.0));
let lib = vec![Brush { name: "Wedge".into(), kind: BrushKind::Scatter(Scatter { art, ..Scatter::default() }) }];
let mut doc = Document::new(300.0, 200.0);
vectorcraft_brush::store(&mut doc, &lib);
let text = program(&doc);
let start = text.find("%AI8_BeginBrushPattern").unwrap();
let end = start + text[start..].find("%AI8_EndBrushPattern").unwrap();
// The points of the frame and the triangle: the triangle's point is the one between the
// frame's left and right edges.
let points: Vec<(f64, f64)> = text[start..end]
.lines()
.filter_map(|l| l.strip_suffix(" m").or_else(|| l.strip_suffix(" L")))
.filter_map(|l| {
let mut n = l.split_whitespace().map(|v| v.parse::<f64>().ok());
Some((n.next()??, n.next()??))
})
.collect();
let (left, right) = points.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(l, r), p| (l.min(p.0), r.max(p.0)));
let bottom = points.iter().map(|p| p.1).fold(f64::INFINITY, f64::min);
let tip: Vec<f64> = points.iter().filter(|p| p.0 > left + 1e-3 && p.0 < right - 1e-3).map(|p| p.1).collect();
assert!(!tip.is_empty() && tip.iter().all(|y| (y - bottom - 10.0).abs() < 1e-3), "the point is 10 above the base in the section: {points:?}");
let back = vectorcraft_brush::library(&read_back(&doc));
let (BrushKind::Scatter(got), BrushKind::Scatter(want)) = (&back[0].kind, &lib[0].kind) else { panic!("{back:?}") };
assert!(same_tree(&art_tree(&got.art), &art_tree(&want.art)), "{:#?}", got.art);
}
/// Brush art of a path with several subpaths is written as a compound path, which the reader reads as
/// a compound path of one path for each subpath, and is weighed as the reader weighs that against the
/// art it copies into one file's brushes: of two Art brushes whose art is a path of 30,000 squares,
+5 -5
View File
@@ -42,7 +42,7 @@ pub(super) use texts::wraps_held;
pub(super) use images::PAYLOAD;
#[cfg(test)]
pub(super) use images::{IMAGE_DEPTH, IMAGES, LINKS_EMBEDDED};
pub(super) use images::{IMAGE_DEPTH, IMAGES, LAST_SAMPLES_ONLY, LINKS_EMBEDDED, SAMPLE_LIMITS, SAMPLE_READS, SAMPLES_KEPT};
#[cfg(test)]
pub(super) use paints::{
GRADIENT_DITHER, GRADIENT_HUE, GRADIENT_PERCEPTUAL, GRADIENT_SHAPES, GRADIENTS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name,
@@ -320,9 +320,9 @@ pub(super) struct Writer<'a> {
/// How many more envelopes and images with a Warp may be written live: as many as the reader
/// checks in one file ([`crate::import::ENVELOPE_CHECKS`]), which it spends on both.
checks_left: usize,
/// The image read last and its pixels ([`images::Samples::of`], `None` when they can't be
/// read): the pieces of a warped image, which follow one another, read them once.
last_samples: Option<(vectorcraft_doc::ImageBlob, Option<images::Read>)>,
/// The images read so far and their pixels: an image placed again, and each piece of a warped
/// image, is read once.
read_samples: images::SampleCache,
/// The images written whole so far, by the address of their data (which each entry keeps), each
/// with the index of its samples in [`Self::payloads`].
whole_images: HashMap<usize, (Arc<Vec<u8>>, usize)>,
@@ -422,7 +422,7 @@ impl<'a> Writer<'a> {
definition_links: 0,
definition_symbol_nodes: 0,
max_objects: crate::import::MAX_EDITING_OBJECTS,
last_samples: None,
read_samples: images::SampleCache::default(),
whole_images: HashMap::new(),
shown: vec![],
windowed: None,
+4 -3
View File
@@ -401,11 +401,12 @@ impl Writer<'_> {
fn brush_out(&mut self, b: &Brush) -> Option<BrushOut> {
let plugin = crate::import::brush_plugin_name(&b.kind);
let section = format!("Brush Art {}", self.brush_set.sections + 1);
// The art as the reader reads it: a section is read with y down, and an Art brush's art is
// turned over after that (its section's y up is the right of the path).
// The art as the reader reads it: a section is read with y down, and a Scatter or Art
// brush's art is turned over after that (its section's y up is down the page in each
// Scatter copy and the right of the path in Art).
let (params, art) = match &b.kind {
BrushKind::Calligraphic(c) => (calligraphic_params(c), None),
BrushKind::Scatter(s) => (scatter_params(s, &section)?, Some((s.art.clone(), Affine::FLIP_Y))),
BrushKind::Scatter(s) => (scatter_params(s, &section)?, Some((s.art.clone(), Affine::IDENTITY))),
BrushKind::Art(a) => (art_params(a, &section)?, Some((a.art.clone(), Affine::IDENTITY))),
BrushKind::Pattern(_) | BrushKind::Bristle(_) => return None,
};
+103 -8
View File
@@ -1,6 +1,9 @@
//! Images: embedded ones as a raster with its samples, linked ones as a placed file with a preview
//! (see [`crate::ai_editing`] for the form).
#[cfg(test)]
use std::cell::Cell;
use std::collections::HashMap;
use std::fmt::Write;
use std::sync::Arc;
@@ -30,6 +33,87 @@ pub(super) const SAMPLES_LINE: &str = "XI\u{1}";
/// An image's pixels as the data holds them, and whether it had 16 bits a channel ([`Samples::of`]).
pub(super) type Read = Arc<(Samples, bool)>;
/// The most bytes of samples a save keeps read ([`SampleCache`]): color and alpha together.
const KEPT_SAMPLE_BYTES: usize = 256 << 20;
/// The most images whose samples a save keeps read ([`SampleCache`]), those that can't be read
/// included.
const KEPT_IMAGES: usize = 256;
#[cfg(test)]
thread_local! {
/// How many times [`Samples::of`] has read an image on this thread.
pub(in crate::ai_editing) static SAMPLE_READS: Cell<usize> = const { Cell::new(0) };
/// Whether [`Writer::samples`] keeps only the image read last on this thread, to compare its
/// file with the one [`SampleCache`] gives.
pub(in crate::ai_editing) static LAST_SAMPLES_ONLY: Cell<bool> = const { Cell::new(false) };
/// The bytes of samples and the images [`SampleCache`] keeps at most on this thread.
pub(in crate::ai_editing) static SAMPLE_LIMITS: Cell<(usize, usize)> = const { Cell::new((KEPT_SAMPLE_BYTES, KEPT_IMAGES)) };
/// The most bytes of samples and images a [`SampleCache`] kept on this thread, and whether one
/// held an image beside them.
pub(in crate::ai_editing) static SAMPLES_KEPT: Cell<(usize, usize, bool)> = const { Cell::new((0, 0, false)) };
}
/// The bytes of samples and the images [`SampleCache`] keeps at most.
#[cfg(not(test))]
const fn sample_limits() -> (usize, usize) {
(KEPT_SAMPLE_BYTES, KEPT_IMAGES)
}
#[cfg(test)]
fn sample_limits() -> (usize, usize) {
SAMPLE_LIMITS.with(Cell::get)
}
/// The images read during a save and their pixels ([`Samples::of`], `None` when they can't be
/// read), so that an image placed again is read once: up to [`KEPT_IMAGES`] images and
/// [`KEPT_SAMPLE_BYTES`] of samples, and beside them the image read last that they have no room
/// for. An image is known by the address of its data and its MIME type; each entry keeps the
/// image, so no other data takes that address while the entry is kept.
#[derive(Default)]
pub(super) struct SampleCache {
/// By the address of the image's data, each image with that data and its pixels.
kept: HashMap<usize, Vec<(ImageBlob, Option<Read>)>>,
/// How many images `kept` holds.
images: usize,
/// The bytes of samples `kept` holds.
bytes: usize,
/// The image read last that `kept` had no room for, and its pixels.
last: Option<(ImageBlob, Option<Read>)>,
}
/// Whether `a` is the image `b`: the same data and MIME type.
fn same_image(a: &ImageBlob, b: &ImageBlob) -> bool {
Arc::ptr_eq(&a.bytes, &b.bytes) && a.mime == b.mime
}
impl SampleCache {
/// The pixels kept for `blob`, when it was read.
fn get(&self, blob: &ImageBlob) -> Option<Option<Read>> {
let kept = self.kept.get(&(Arc::as_ptr(&blob.bytes) as usize)).and_then(|v| v.iter().find(|(b, _)| same_image(b, blob)));
kept.or(self.last.as_ref().filter(|(b, _)| same_image(b, blob))).map(|(_, read)| read.clone())
}
/// Keep `read`, the pixels of `blob`: with the others while both limits allow, else beside them
/// in place of the image read last.
fn keep(&mut self, blob: &ImageBlob, read: Option<Read>) {
let size = read.as_deref().map_or(0, |(s, _)| s.color.len().saturating_add(s.alpha.as_ref().map_or(0, Vec::len)));
let (most_bytes, most_images) = sample_limits();
match self.bytes.checked_add(size).filter(|b| *b <= most_bytes) {
Some(bytes) if self.images < most_images => {
self.bytes = bytes;
self.images += 1;
self.kept.entry(Arc::as_ptr(&blob.bytes) as usize).or_default().push((blob.clone(), read));
}
_ => self.last = Some((blob.clone(), read)),
}
#[cfg(test)]
SAMPLES_KEPT.with(|k| {
let (b, n, last) = k.get();
k.set((b.max(self.bytes), n.max(self.images), last || self.last.is_some()));
});
}
}
/// A copy of an image written as the part of it that its regions show ([`Writer::image`]).
pub(super) struct Windowed {
/// Where its raster is in the body.
@@ -61,6 +145,8 @@ impl Samples {
/// or RGB samples, with an alpha channel when they need one. `None` when they can't be decoded or are more than
/// [`MAX_PIXELS`]; the flag is set when the image had 16 bits a channel.
fn of(blob: &ImageBlob) -> Option<(Samples, bool)> {
#[cfg(test)]
SAMPLE_READS.with(|n| n.set(n.get() + 1));
// The header's size is checked before the inks are decoded.
if blob.is_cmyk()
&& blob.header_size().is_some_and(|(w, h)| u64::from(w) * u64::from(h) <= MAX_PIXELS)
@@ -301,17 +387,26 @@ impl Writer<'_> {
);
}
/// The pixels of `blob` ([`Samples::of`]), read once for images that follow one another with
/// the same data.
/// The pixels of `blob` ([`Samples::of`]), read once in a save for each image the
/// [`SampleCache`] has room for.
fn samples(&mut self, blob: &ImageBlob) -> Option<Read> {
if let Some((last, read)) = &self.last_samples
&& Arc::ptr_eq(&last.bytes, &blob.bytes)
&& last.mime == blob.mime
{
return read.clone();
#[cfg(test)]
if LAST_SAMPLES_ONLY.with(Cell::get) {
if let Some((last, read)) = &self.read_samples.last
&& Arc::ptr_eq(&last.bytes, &blob.bytes)
&& last.mime == blob.mime
{
return read.clone();
}
let read = Samples::of(blob).map(Arc::new);
self.read_samples.last = Some((blob.clone(), read.clone()));
return read;
}
if let Some(read) = self.read_samples.get(blob) {
return read;
}
let read = Samples::of(blob).map(Arc::new);
self.last_samples = Some((blob.clone(), read.clone()));
self.read_samples.keep(blob, read.clone());
read
}
+11 -5
View File
@@ -63,7 +63,7 @@ use std::sync::Arc;
use kurbo::Affine;
use vectorcraft_brush::{ArtBrush, ArtScale, Bristle, Brush, BrushKind, Calligraphic, Colorization, Scatter, Variation};
use vectorcraft_color::Paint;
use vectorcraft_doc::{AppearanceItem, Node, NodeKind};
use vectorcraft_doc::{AppearanceItem, Node, NodeKind, Scaling};
use super::lex::{Lexer, Tok};
use super::obj::Names;
@@ -475,10 +475,11 @@ pub(super) fn parse_tool_object(kind: Tool, name: &str, params: &str) -> Result<
Ok(BrushDraft { name: name.to_string(), kind })
}
/// Turn `art` over (y for -y) with the art of all its opacity masks, those that don't move with
/// their objects too: the art changes the space it is in, and no object moves over its mask.
/// Turn `art` over (y for -y) with its pattern fills' tiles and the art of all its opacity masks,
/// those that don't move with their objects too: the art changes the space it is in, and no object
/// moves over its tiles or its mask.
pub(crate) fn turn_over(art: &mut Node) {
art.transform(Affine::scale_non_uniform(1.0, -1.0), false);
art.transform(Affine::scale_non_uniform(1.0, -1.0), Scaling { patterns: true, ..Scaling::default() });
turn_unlinked_masks(art);
}
@@ -574,7 +575,12 @@ pub(super) fn finish_brushes_within(
let kind = match d.kind {
_ if !kept => None,
DraftKind::Calligraphic(c) => Some(BrushKind::Calligraphic(c)),
DraftKind::Scatter { brush, art: name } => copy(&name).map(|a| BrushKind::Scatter(Scatter { art: a, ..brush })),
DraftKind::Scatter { brush, art: name } => copy(&name).map(|mut a| {
// Each copy is the section turned over: its side with y up draws down the page
// before the copy's rotation, and a brush draws art's y (down here) down the page.
turn_over(&mut a);
BrushKind::Scatter(Scatter { art: a, ..brush })
}),
DraftKind::Art { mut brush, art: name, settings } => copy(&name).map(|mut a| {
// The side of the section with y up draws on the right of the path, and a brush
// draws art's y (down here) on the left of the path.
+101 -4
View File
@@ -10483,11 +10483,11 @@ fn a_brushs_art_places_a_version_7_patterns_tiles_with_its_operands() {
};
let plain = placed("0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0]");
// The operands and the move they make from the plain placement (a b c d e f): those of
// `a_pattern_fill_applies_its_offset_scale_rotation_reflection_and_shear` with y down, as the
// art's space has it.
// `a_pattern_fill_applies_its_offset_scale_rotation_reflection_and_shear` in the file's own
// space (y up), since a Scatter brush's art is turned over with its tiles.
let cases = [
("10 15 1 1 0 0 0 0 0 [1 0 0 1 0 0]", [1.0, 0.0, 0.0, 1.0, 10.0, -15.0]),
("-5 7 2 .5 -45 0 0 -15 45 [1 0 0 1 0 0]", [1.793151, 0.353553, -1.035276, 0.353553, -5.0, -7.0]),
("10 15 1 1 0 0 0 0 0 [1 0 0 1 0 0]", [1.0, 0.0, 0.0, 1.0, 10.0, 15.0]),
("-5 7 2 .5 -45 0 0 -15 45 [1 0 0 1 0 0]", [1.793151, -0.353553, 1.035276, 0.353553, -5.0, 7.0]),
];
for (ops, want) in cases {
let got = (placed(ops) * plain.inverse()).as_coeffs();
@@ -11325,6 +11325,103 @@ fn type_with_an_art_brush_keeps_its_drawn_look() {
assert_eq!(brushed, 0, "{:?}", r.warnings);
}
/// Each copy a Scatter brush places is its section's art turned over before the copy's rotation:
/// the side of the section with y up goes down the page with the rotation at 0° to the page, and
/// to the right of the path's direction when the rotation follows the path. A rotation turns the
/// copy counterclockwise on the page, from the page or from the path's direction.
#[test]
fn a_scatter_brushs_copies_are_its_art_turned_over() {
// Size, spacing 100% and scatter 0%, fixed; the rotation 0° or 90°, to the page or following
// the path.
let still = "2 /Lopsided art/ 5 1 0 0 / 0 1 1 0 1 1 0 0 0 0 0 0 0 0 0";
let turned = "2 /Lopsided art/ 5 1 0 0 / 0 1 1 0 1 1 0 0 0 0 90 90 0 0 0";
let along = "2 /Lopsided art/ 5 1 0 0 / 0 1 1 0 1 1 0 0 0 0 0 0 0 1 0";
let def = format!(
"{}{}{}{}",
lopsided_art("Lopsided art"),
plugin_object(SCATTER, "Still", still),
plugin_object(SCATTER, "Turned", turned),
plugin_object(SCATTER, "Along", along)
);
let r = read_ok(&format!("{def}{}", layer(&(rect_path(0.0, 0.0, 10.0, 10.0) + "f\n"))));
let lib = vectorcraft_brush::library(&r.doc);
let stroke = vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::BLACK), 1.0);
// The art is 40 by 8, so copies are 40 apart along a line 100 long, centered at 20, 60 and 100
// from its start.
let pieces = |name: &str, from: (f64, f64), to: (f64, f64)| {
let b = lib.iter().find(|b| b.name == name).unwrap();
let line = kurbo::BezPath::from_vec(vec![kurbo::PathEl::MoveTo(Point::new(from.0, from.1)), kurbo::PathEl::LineTo(Point::new(to.0, to.1))]);
vectorcraft_brush::stroke_pieces(&r.doc, b, &line, &stroke)
};
let filled = |pieces: &[Node], x: f64, y: f64| {
pieces.iter().any(|n| {
let mut hit = false;
n.walk(&mut |c| hit |= c.path_data().is_some_and(|p| kurbo::Shape::winding(&p.to_bezpath(), Point::new(x, y)) != 0));
hit
})
};
let still = pieces("Still", (0.0, 0.0), (100.0, 0.0));
assert_eq!(still.len(), 3, "{still:#?}");
// The copy at 60 spans 40 to 80: the narrow block is its first 10, the wide block all of it.
assert!(filled(&still, 70.0, -2.0) && !filled(&still, 70.0, 2.0), "the wide block is above the line");
assert!(filled(&still, 45.0, 2.0), "the narrow block is below it");
// Turned 90° to the page, the copy at 60 stands across the line from 40 above it to 80 below
// it: the wide block on the left, the narrow block on the right at its bottom 10.
let turned = pieces("Turned", (0.0, 0.0), (100.0, 0.0));
assert_eq!(turned.len(), 3, "{turned:#?}");
assert!(filled(&turned, 58.0, 0.0) && !filled(&turned, 62.0, 0.0), "the wide block is left of the copy's middle");
assert!(filled(&turned, 62.0, 15.0) && !filled(&turned, 62.0, -15.0), "the narrow block is at its bottom");
// Right to left with the rotation following the path, the copy at 40 (20 to 60) is turned half
// way round: its narrow block is its last 10.
let along = pieces("Along", (100.0, 0.0), (0.0, 0.0));
assert_eq!(along.len(), 3, "{along:#?}");
assert!(filled(&along, 30.0, 2.0) && !filled(&along, 30.0, -2.0), "the wide block is below the line");
assert!(filled(&along, 55.0, -2.0), "the narrow block is above it, at the copy's other end");
// Up the page with the rotation following the path, the copy at y 40 (20 to 60) is turned a
// quarter round: the wide block on the left of the line, the narrow block on its right at its
// bottom 10, where the line starts.
let up = pieces("Along", (0.0, 100.0), (0.0, 0.0));
assert_eq!(up.len(), 3, "{up:#?}");
assert!(filled(&up, -2.0, 40.0) && !filled(&up, 2.0, 40.0), "the wide block is left of the line");
assert!(filled(&up, 2.0, 55.0) && !filled(&up, 2.0, 25.0), "the narrow block is right of it, at the copy's bottom");
}
/// A pattern fill in a Scatter or Art brush's art is turned over with the art: the tiles keep their
/// place on the art. The section fills a 40 by 8 rectangle with an 8-point tile placed with the
/// identity, so the tile's top left is at the rectangle's top left in the section (y up).
#[test]
fn a_pattern_fill_in_brush_art_turns_over_with_the_art() {
let still = "2 /Tiled art/ 5 1 0 0 / 0 1 1 0 1 1 0 0 0 0 0 0 0 0 0";
let ribbon = "2 / Tiled art/ / / / / 0 0/ 5 0 0 0 / 1 1 1 0 1 0 0 0 1 1 0 0 0 0 1";
let section = format!(
"%AI8_BeginBrushPattern\n(Tiled art)\n0 A\n(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n%AI8_EndBrushPattern\n",
rect_path(0.0, 0.0, 40.0, 8.0)
);
let def = format!("{DOTS}{section}{}{}", plugin_object(SCATTER, "Spray", still), plugin_object(ART_BRUSH, "Ribbon", ribbon));
let r = read_ok(&format!("{def}{}", layer(&(rect_path(0.0, 0.0, 10.0, 10.0) + "f\n"))));
let lib = vectorcraft_brush::library(&r.doc);
for name in ["Spray", "Ribbon"] {
let b = lib.iter().find(|b| b.name == name).unwrap_or_else(|| panic!("{name}: {lib:?}"));
let art = match &b.kind {
vectorcraft_brush::BrushKind::Scatter(s) => &s.art,
vectorcraft_brush::BrushKind::Art(a) => &a.art,
k => panic!("{name}: {k:?}"),
};
let mut found = None;
art.walk(&mut |n| {
if let (Some(_), Paint::Pattern { xf, .. }) = (n.path_data(), fill(n)) {
found = Some((n.geometric_bounds(), xf));
}
});
let Some((Some(bounds), xf)) = found else { panic!("{name}: {art:#?}") };
// The art is turned over (y up again): the tile's top left (0, 0) and its dot (4, 4), in
// the tile's space with y down, are at the rectangle's top left and 4 below it.
assert_eq!(bounds, Rect::new(0.0, 0.0, 40.0, 8.0), "{name}");
assert!((xf * Point::ZERO - Point::new(0.0, bounds.y1)).hypot() < 1e-9, "{name}: {xf:?}");
assert!((xf * Point::new(4.0, 4.0) - Point::new(4.0, bounds.y1 - 4.0)).hypot() < 1e-9, "{name}: {xf:?}");
}
}
use read::{GRAPH_PLAIN, GRAPH_UNENDED};
use vectorcraft_doc::{GraphKind, TickLength};
+4 -3
View File
@@ -171,10 +171,11 @@ impl<'a> Separator<'a> {
/// swatch link). Any ink above zero puts ink down, except on PostScript plates for a color that
/// counts as 100% black ([`vectorcraft_doc::overprint::is_black_ink`], as
/// [`vectorcraft_doc::overprint::OverprintBlack::default`] judges it) and is not linked to a
/// spot swatch, to Registration or to a swatch the document lacks: up to the half a percent of
/// another ink such a black may carry counts as none.
/// spot swatch or to Registration: up to the half a percent of another ink such a black may
/// carry counts as none. A link to a swatch the document lacks separates as the color's own
/// values, so such a black counts as unlinked.
fn no_ink(&self, plate: &str, p: &Paint) -> bool {
let process = |swatch: Option<&str>| swatch.is_none_or(|n| n != REGISTRATION && self.doc.swatch(n).is_some_and(|w| !w.spot));
let process = |swatch: Option<&str>| swatch.is_none_or(|n| n != REGISTRATION && self.doc.swatch(n).is_none_or(|w| !w.spot));
let none = |c: &Color, process: bool, ink: f32| ink <= 0.0 || (self.postscript && process && ink <= 0.005 && is_black_ink(c, 1.0, false));
match p {
Paint::Solid { color, swatch, tint } => {
+74
View File
@@ -829,6 +829,80 @@ fn overprint_black_keeps_the_cyan_under_near_and_freeform_blacks_on_postscript_p
assert_eq!((fills(&p.plates[0]), fills(&p.plates[3])), (1, 4), "the cyan plate, the Black plate");
}
#[test]
fn overprint_black_keeps_the_cyan_under_a_near_black_linked_to_a_missing_swatch_on_postscript_plates() {
// 0.4% cyan beside 100% K, linked to a swatch the document lacks: it separates from its own
// values and the option marks it to overprint, so it counts as black like an unlinked color.
let near = Paint::Solid { color: Color::cmyk(0.004, 0.0, 0.0, 1.0), swatch: Some("Missing".into()), tint: 1.0 };
let square =
Node::path(vectorcraft_doc::NodeId(0), shapes::rectangle(Rect::new(10.0, 15.0, 30.0, 35.0)), Appearance::basic(near, Paint::None, 0.0));
let d = over_cyan(vec![square]);
assert!(d.swatch("Missing").is_none());
let opts = PrintOptions {
settings: settings(json!({"output": {"mode": "separations", "overprintBlack": true}})),
postscript: true,
..Default::default()
};
let p = plan(&d, &opts).unwrap();
let fills = |doc: &Document| {
let mut count = 0;
doc.walk(|n| count += usize::from(n.appearance.fill().is_some_and(|f| !f.paint.is_none())));
count
};
assert_eq!((fills(&p.plates[0]), fills(&p.plates[3])), (1, 2), "the cyan plate, the Black plate");
}
#[test]
fn overprinting_near_blacks_linked_to_a_missing_swatch_keep_the_cyan_on_postscript_plates() {
// 0.4% cyan beside 100% K, linked to a swatch the document lacks and set to overprint, on a
// fill, a stroke, a character fill and a linear gradient's stops: a PostScript cyan plate draws
// it as nothing, as it does an unlinked black, and a PDF cyan plate draws it. A faint cyan that
// is not black, linked to the same name, stays on both.
let missing = |color: Color| Paint::Solid { color, swatch: Some("Missing".into()), tint: 1.0 };
let near = Color::cmyk(0.004, 0.0, 0.0, 1.0);
let faint = Color::cmyk(0.004, 0.5, 0.0, 0.0);
let square = |x: f64, fill: Paint, stroke: Paint| {
let mut n =
Node::path(vectorcraft_doc::NodeId(0), shapes::rectangle(Rect::new(x, 15.0, x + 20.0, 35.0)), Appearance::basic(fill, stroke, 2.0));
if let Some(f) = n.appearance.fill_mut() {
f.overprint = true;
}
if let Some(s) = n.appearance.stroke_mut() {
s.overprint = true;
}
n
};
let stop = |offset: f32| GradientStop { swatch: Some("Missing".into()), ..GradientStop::new(offset, near) };
let linear = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![stop(0.0), stop(1.0)]));
let style = vectorcraft_doc::CharStyle { fill: missing(near), overprint_fill: true, ..Default::default() };
let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(20.0, 60.0), "Hi", style);
let d = over_cyan(vec![
square(10.0, missing(near), Paint::None),
square(40.0, Paint::None, missing(near)),
square(70.0, Paint::Gradient(Box::new(linear)), Paint::None),
square(100.0, missing(faint), Paint::None),
Node::new(vectorcraft_doc::NodeId(0), NodeKind::Text(Box::new(text))),
]);
assert!(d.swatch("Missing").is_none());
// The fills, strokes and character fills plate `plate` draws.
let drawn = |postscript: bool, plate: usize| {
let opts = PrintOptions { settings: settings(json!({"output": {"mode": "separations"}})), postscript, ..Default::default() };
let p = plan(&d, &opts).unwrap();
let (mut fills, mut strokes, mut chars) = (0, 0, 0);
p.plates[plate].walk(|n| {
fills += usize::from(n.appearance.fill().is_some_and(|f| !f.paint.is_none()));
strokes += usize::from(n.appearance.stroke().is_some_and(|s| !s.paint.is_none()));
if let NodeKind::Text(t) = &n.kind {
chars += t.runs.iter().filter(|r| !r.style.fill.is_none()).count();
}
});
(fills, strokes, chars)
};
assert_eq!(drawn(true, 0), (2, 0, 0), "PostScript cyan plate: the cyan and the faint fill");
assert_eq!(drawn(false, 0), (4, 1, 1), "PDF cyan plate: the cyan, the fill, the gradient, the faint fill, the stroke and the type");
assert_eq!(drawn(true, 3), (3, 1, 1), "PostScript Black plate: every black, not the faint fill");
}
#[test]
fn an_overprinting_fill_keeps_its_faint_ink_on_pdf_plates() {
// 0.4% cyan beside 100% K, set to overprint: a PDF plate draws it with Darken, a PostScript
+4
View File
@@ -208,6 +208,7 @@ pub(crate) fn import_finding(
blends: fx::blends(&xml, &scan.markers),
filter_sources: fx::sources(&xml, &scan.markers, |h| files.data_href(h)),
files,
image_keys: HashMap::new(),
non_scaling: found.non_scaling,
data: found.data,
events: found.events,
@@ -371,6 +372,9 @@ struct Importer {
filter_sources: HashMap<String, fx::Source>,
/// The files `<image>` elements link to.
files: files::Files,
/// The image key of each raster image usvg got, by the address of its bytes, with the bytes
/// held so that the address isn't given to other bytes during the import.
image_keys: HashMap<usize, (Arc<Vec<u8>>, String)>,
/// Ids of the shapes whose strokes don't scale ([`vector_effect`]).
non_scaling: HashSet<String>,
/// The `data-*` attributes of elements, by id ([`user_data`]).
+264 -4
View File
@@ -780,6 +780,7 @@ impl Importer {
usvg::ImageKind::WEBP(d) => (d, "image/webp"),
usvg::ImageKind::SVG(tree) => return self.svg_image(tree, acc),
};
let source = bytes;
let size = i.size();
let (pw, ph) = vectorcraft_doc::header_size(bytes).unwrap_or((size.width().round().max(1.0) as u32, size.height().round().max(1.0) as u32));
// A turned CMYK image is stored as the CMYK TIFF of its inks, the size of the PNG usvg got.
@@ -792,10 +793,7 @@ impl Importer {
let linked = self.files.linked(i.kind());
let missing = linked.is_some_and(|l| l.missing);
let link = linked.map(|l| l.link.clone());
let key = match &link {
Some(l) => linked_key(bytes, &l.path),
None => format!("img-{:016x}", fnv1a(bytes)),
};
let key = self.image_key(source, bytes, link.as_ref().map(|l| l.path.as_str()));
self.doc.images.entry(key.clone()).or_insert_with(|| {
let blob = ImageBlob { mime: mime.into(), bytes: bytes.clone(), proxy: missing.then(|| bytes.clone()) };
if link.is_some() && !missing { blob.with_proxy() } else { blob }
@@ -813,6 +811,29 @@ impl Importer {
Some(node)
}
/// The image key of the raster image usvg got as `source`, stored as `bytes` (the CMYK TIFF
/// that replaces a turned CMYK image, else `source`), linked to `path` when it is linked. The
/// bytes are hashed for the first image that shows `source`; the images after it that show
/// the same bytes get the key kept for it.
fn image_key(&mut self, source: &Arc<Vec<u8>>, bytes: &[u8], path: Option<&str>) -> String {
let at = Arc::as_ptr(source) as usize;
#[cfg(test)]
let kept = !tests::UNKEPT.get();
#[cfg(not(test))]
let kept = true;
if kept && let Some((_, key)) = self.image_keys.get(&at) {
return key.clone();
}
#[cfg(test)]
tests::IMAGE_HASHES.set(tests::IMAGE_HASHES.get() + 1);
let key = match path {
Some(path) => linked_key(bytes, path),
None => format!("img-{:016x}", fnv1a(bytes)),
};
self.image_keys.insert(at, (source.clone(), key.clone()));
key
}
/// An SVG shown as an image (a data URL or a linked file) → its art, `acc` mapping its size.
/// Its ids are its own: they mean nothing in the SVG around it.
fn svg_image(&mut self, tree: &usvg::Tree, acc: Affine) -> Option<Node> {
@@ -870,6 +891,7 @@ mod tests {
blends: HashMap::new(),
filter_sources: HashMap::new(),
files: Files::default(),
image_keys: HashMap::new(),
non_scaling: HashSet::new(),
data: HashMap::new(),
events: HashMap::new(),
@@ -891,4 +913,242 @@ mod tests {
assert!(matches!(im.error, Some(SvgError::TooManyImages(crate::MAX_NESTED_SVG_IMAGES))));
assert_eq!(im.error.unwrap().to_string(), "the SVG expands to more than 256 nested SVG images");
}
thread_local! {
/// How many times this thread's imports hashed an image's bytes for its key.
pub(super) static IMAGE_HASHES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// When set, this thread's imports hash the bytes of every image for its key, without
/// the keys kept for earlier images.
pub(super) static UNKEPT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// `svg` imported on this thread with `opts`, with image keys kept or not, and how many times
/// image bytes were hashed for keys.
fn import_counting(svg: &str, opts: &crate::ImportOptions, kept: bool) -> (Document, Vec<String>, usize) {
UNKEPT.set(!kept);
IMAGE_HASHES.set(0);
let imported = crate::import::import(svg, opts, crate::MAX_NODES);
UNKEPT.set(false);
let (doc, warnings) = imported.unwrap();
(doc, warnings, IMAGE_HASHES.get())
}
/// The image objects of `doc` in paint order.
fn image_objects(doc: &Document) -> Vec<ImageObject> {
let mut out = vec![];
doc.walk(|n| {
if let NodeKind::Image(im) = &n.kind {
out.push((**im).clone());
}
});
out
}
fn svg_of(body: &str) -> String {
format!(r#"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200">{body}</svg>"#)
}
/// A `w` × `h` PNG of pixels made from `seed`.
fn png(w: u32, h: u32, seed: u32) -> Vec<u8> {
let mut state = seed.wrapping_mul(2_654_435_761).wrapping_add(1);
let img = image::RgbaImage::from_fn(w, h, |_, _| {
state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
let [r, g, b, _] = state.to_le_bytes();
image::Rgba([r, g, b, 255])
});
let mut out = vec![];
img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
out
}
fn data_url(mime: &str, bytes: &[u8]) -> String {
format!("data:{mime};base64,{}", crate::base64_encode(bytes))
}
/// A little-endian, uncompressed 1 × 1 CMYK TIFF of the inks `cmyk`.
fn cmyk_tiff(cmyk: [u8; 4]) -> Vec<u8> {
let entry = |tag: u16, kind: u16, count: u32, value: u32| {
[&tag.to_le_bytes()[..], &kind.to_le_bytes(), &count.to_le_bytes(), &value.to_le_bytes()].concat()
};
let entries = 11u16;
let bits_at = 8 + 2 + u32::from(entries) * 12 + 4;
let data_at = bits_at + 8;
let mut out = [b"II".as_slice(), &[0x2a, 0], &8u32.to_le_bytes(), &entries.to_le_bytes()].concat();
for e in [
entry(256, 4, 1, 1),
entry(257, 4, 1, 1),
entry(258, 3, 4, bits_at),
entry(259, 3, 1, 1),
entry(262, 3, 1, 5),
entry(273, 4, 1, data_at),
entry(274, 3, 1, 1),
entry(277, 3, 1, 4),
entry(278, 4, 1, 1),
entry(279, 4, 1, 4),
entry(284, 3, 1, 1),
] {
out.extend(e);
}
out.extend(0u32.to_le_bytes());
for _ in 0..4 {
out.extend(8u16.to_le_bytes());
}
assert_eq!(out.len(), data_at as usize);
out.extend(cmyk);
out
}
/// `svg` imported with `opts` hashes image bytes `hashes` times for keys, and once for each
/// image without kept keys; both imports give the same document and warnings.
fn same_as_hashing_every_image(svg: &str, opts: &crate::ImportOptions, hashes: usize) -> (Document, Vec<String>) {
let (doc, warnings, n) = import_counting(svg, opts, true);
let (every, every_warnings, every_n) = import_counting(svg, opts, false);
assert_eq!(every_n, image_objects(&every).len(), "without kept keys, each image is hashed");
assert_eq!(n, hashes, "image bytes hashed for keys");
assert_eq!(warnings, every_warnings);
assert_eq!(image_objects(&doc), image_objects(&every), "the same image objects");
assert_eq!(doc.images, every.images, "the same stored images");
assert!(doc == every, "the same document");
(doc, warnings)
}
/// Every `<use>` of one image, and every `<image>` with the same data URL, shows bytes usvg
/// got once: they are hashed once, and every image has the key of the image's bytes.
#[test]
fn an_image_shown_many_times_is_hashed_once() {
let png = png(3, 2, 1);
let href = data_url("image/png", &png);
let uses: String = (0..6).map(|i| format!(r##"<use href="#p" x="{}"/>"##, i * 10)).collect();
let inline: String = (0..6).map(|i| format!(r#"<image href="{href}" x="{}" width="3" height="2"/>"#, i * 10)).collect();
for body in [format!(r#"<defs><image id="p" href="{href}" width="3" height="2"/></defs>{uses}"#), inline] {
let (doc, warnings) = same_as_hashing_every_image(&svg_of(&body), &crate::ImportOptions::default(), 1);
assert!(warnings.is_empty(), "{warnings:?}");
let objects = image_objects(&doc);
assert_eq!(objects.len(), 6);
let key = format!("img-{:016x}", fnv1a(&png));
assert!(objects.iter().all(|o| o.key == key && o.link.is_none() && (o.width, o.height) == (3, 2)), "{objects:?}");
assert_eq!(doc.images.keys().collect::<Vec<_>>(), [&key]);
assert_eq!((doc.images[&key].mime.as_str(), &**doc.images[&key].bytes, doc.images[&key].proxy.is_none()), ("image/png", &png[..], true));
}
}
/// One image is hashed once; two images of different bytes twice, with keys of their own; two
/// data URLs written differently that hold the same bytes are hashed once each, and share the
/// key and the stored image of those bytes.
#[test]
fn each_buffer_of_image_bytes_is_hashed_once() {
let (a, b) = (png(2, 2, 1), png(2, 2, 2));
let image = |href: &str| format!(r#"<image href="{href}" width="2" height="2"/>"#);
let opts = crate::ImportOptions::default();
let (doc, _) = same_as_hashing_every_image(&svg_of(&image(&data_url("image/png", &a))), &opts, 1);
assert_eq!(image_objects(&doc)[0].key, format!("img-{:016x}", fnv1a(&a)));
let two = [image(&data_url("image/png", &a)), image(&data_url("image/png", &b)), image(&data_url("image/png", &a))].concat();
let (doc, _) = same_as_hashing_every_image(&svg_of(&two), &opts, 2);
let keys: Vec<String> = image_objects(&doc).into_iter().map(|o| o.key).collect();
assert_eq!(keys, [format!("img-{:016x}", fnv1a(&a)), format!("img-{:016x}", fnv1a(&b)), format!("img-{:016x}", fnv1a(&a))]);
assert_eq!(doc.images.len(), 2);
let spelled = [image(&data_url("image/png", &a)), image(&data_url("image/png;x=y", &a))].concat();
let (doc, _) = same_as_hashing_every_image(&svg_of(&spelled), &opts, 2);
let keys: Vec<String> = image_objects(&doc).into_iter().map(|o| o.key).collect();
assert_eq!(keys, [format!("img-{:016x}", fnv1a(&a)), format!("img-{:016x}", fnv1a(&a))]);
assert_eq!(doc.images.len(), 1);
}
/// Every image of one linked file, or of one missing file, is hashed once: the file is read
/// once, and every image has the key of its bytes and its path, with its link.
#[test]
fn a_linked_or_missing_file_shown_many_times_is_hashed_once() {
let png = png(4, 2, 3);
let reads = std::sync::atomic::AtomicUsize::new(0);
let read = |path: &str| {
reads.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
path.ends_with("a.png").then(|| (png.clone(), vectorcraft_doc::LinkInfo::new(path)))
};
let opts = crate::ImportOptions { folder: Some("/f"), read: Some(&read) };
for (name, missing) in [("a.png", false), ("gone.png", true)] {
let body: String = (0..5).map(|i| format!(r#"<image href="{name}" x="{}" width="4" height="2"/>"#, i * 10)).collect();
reads.store(0, std::sync::atomic::Ordering::Relaxed);
let (doc, warnings) = same_as_hashing_every_image(&svg_of(&body), &opts, 1);
assert_eq!(reads.load(std::sync::atomic::Ordering::Relaxed), 2, "{name}: one read for each of the two imports");
assert_eq!(warnings.iter().any(|w| w.contains(name)), missing, "{name}: {warnings:?}");
let objects = image_objects(&doc);
assert_eq!(objects.len(), 5);
let path = objects[0].link.as_ref().expect("linked").path.clone();
assert!(path.ends_with(name), "{path}");
let stored = doc.images[&objects[0].key].clone();
assert_eq!(objects[0].key, linked_key(&stored.bytes, &path), "{name}");
assert!(objects.iter().all(|o| o.key == objects[0].key && o.link.as_ref().is_some_and(|l| l.path == path)), "{name}");
assert_eq!(doc.images.len(), 1);
assert_eq!(*stored.bytes == png, !missing, "{name}: the file's bytes, or a placeholder");
assert_eq!(stored.is_proxy(), missing, "{name}");
}
}
/// A CMYK TIFF shown many times is stored as a CMYK TIFF and hashed once, its key that of the
/// stored TIFF.
#[test]
fn a_cmyk_image_shown_many_times_is_hashed_once() {
let tif = cmyk_tiff([255, 0, 0, 0]);
let href = data_url("image/tiff", &tif);
let uses: String = (0..4).map(|i| format!(r##"<use href="#p" x="{}"/>"##, i * 10)).collect();
let body = format!(r#"<defs><image id="p" href="{href}" width="10" height="10"/></defs>{uses}"#);
let (doc, _) = same_as_hashing_every_image(&svg_of(&body), &crate::ImportOptions::default(), 1);
let objects = image_objects(&doc);
assert_eq!(objects.len(), 4);
let blob = &doc.images[&objects[0].key];
assert_eq!(blob.mime, "image/tiff");
assert!(blob.cmyk().is_some(), "stored with its inks");
assert_eq!(objects[0].key, format!("img-{:016x}", fnv1a(&blob.bytes)));
assert!(objects.iter().all(|o| o.key == objects[0].key));
}
/// This thread's CPU time in seconds where the system reports it, else the time since a first
/// call.
fn cpu_seconds() -> f64 {
static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
let schedstat = std::fs::read_to_string("/proc/thread-self/schedstat").ok();
match schedstat.as_deref().and_then(|s| s.split_whitespace().next()?.parse::<f64>().ok()) {
Some(ns) => ns / 1e9,
None => START.get_or_init(std::time::Instant::now).elapsed().as_secs_f64(),
}
}
/// The import's time for one PNG data URL shown by many `<use>` elements, hashing every image
/// and keeping keys alternating in one process: `cargo test --release -p vectorcraft-svg --lib
/// importer::tests::image_key_timing -- --ignored --nocapture`.
#[test]
#[ignore = "timing, run by hand"]
fn image_key_timing() {
for (side, uses) in [(512, 100), (1024, 500)] {
let png = png(side, side, 7);
let refs: String = (0..uses).map(|i| format!(r##"<use href="#p" transform="translate({} {})"/>"##, i % 20, i / 20)).collect();
let svg = svg_of(&format!(r#"<defs><image id="p" href="{}" width="10" height="10"/></defs>{refs}"#, data_url("image/png", &png)));
let run = |kept: bool| {
let t = cpu_seconds();
let (doc, _, _) = import_counting(&svg, &crate::ImportOptions::default(), kept);
let spent = cpu_seconds() - t;
assert_eq!(image_objects(&doc).len(), uses);
spent
};
run(false);
run(true);
let (mut every, mut kept) = (vec![], vec![]);
for round in 0..7 {
if round % 2 == 0 {
every.push(run(false));
kept.push(run(true));
} else {
kept.push(run(true));
every.push(run(false));
}
}
let median = |v: &mut Vec<f64>| {
v.sort_by(f64::total_cmp);
v[v.len() / 2]
};
let ms = |v: &[f64]| v.iter().map(|s| format!("{:.1}", s * 1e3)).collect::<Vec<_>>().join(" ");
println!("{uses} uses of a {} byte PNG: every image {} ms, kept {} ms", png.len(), ms(&every), ms(&kept));
println!("{uses} uses: median every image {:.1} ms, kept {:.1} ms", median(&mut every) * 1e3, median(&mut kept) * 1e3);
}
}
}
+68 -1
View File
@@ -237,7 +237,15 @@ impl FreeTransformTool {
self.measure = cx.transform_tools_guides.then(|| (p, cx.size_label(nr.width(), nr.height())));
bx.conjugate(a)
}
Op::Shear(h) => bx.conjugate(shear_for_side(bx.rect, h, local, m.alt)),
Op::Shear(h) => {
let a = shear_for_side(bx.rect, h, local, m.alt);
// The shear's slope, read from the matrix the preview applies, labeled with the
// angle the Shear tool shows for the same slant.
let [_, vertical, horizontal, ..] = a.as_coeffs();
let k = if matches!(h, Handle::Top | Handle::Bottom) { horizontal } else { vertical };
self.measure = cx.transform_tools_guides.then(|| (p, format!("{:.1}°", 0.0 - k.atan().to_degrees())));
bx.conjugate(a)
}
Op::Rotate => {
let (a, deg) = rotate_for_drag(bx.center(), d.start, p, shift);
self.measure = cx.transform_tools_guides.then(|| (p, format!("{:.1}°", -deg)));
@@ -723,4 +731,63 @@ mod tests {
t.pointer(&cx(false), &ev(PointerKind::Drag, 220.0, 230.0));
assert!(t.overlays(&cx(false)).iter().all(|o| !matches!(o, Overlay::Measure { .. })));
}
/// The label a drag shows next to the pointer, and where.
fn shown_measure(t: &FreeTransformTool, cx: &ToolContext) -> Option<(Point, String)> {
t.overlays(cx).into_iter().find_map(|o| if let Overlay::Measure { p, text } = o { Some((p, text)) } else { None })
}
/// With Smart Guides' Transform Tools on, a Cmd side-handle shear shows its angle next to the
/// pointer, with the Shear tool's sign: the top side moved right and the right side moved down
/// by 20 pt on the 100 pt square slant 11.3° either way. Alt shears about the center.
#[test]
fn shear_drag_shows_its_angle_with_transform_tools_guides() {
let (d, id) = doc_with_rect();
let mut s = Selection::default();
s.add(id);
let p = paint();
let cx = |on: bool| ToolContext { transform_tools_guides: on, ..cx(&d, &s, &p) };
let cmd = Mods { cmd: true, ..Default::default() };
let shear = |c: &ToolContext, from: (f64, f64), to: (f64, f64), m: Mods| {
let mut t = FreeTransformTool::default();
t.pointer(c, &ev(PointerKind::Down, from.0, from.1).with_mods(m));
let a = t.pointer(c, &ev(PointerKind::Drag, to.0, to.1).with_mods(m));
assert_eq!(a[0], Action::Begin("Shear".into()));
let shown = shown_measure(&t, c);
assert_eq!(t.pointer(c, &ev(PointerKind::Up, to.0, to.1).with_mods(m)), vec![Action::Commit]);
assert_eq!(shown_measure(&t, c), None, "the label goes with the drag");
shown
};
let on = cx(true);
let off = Vec2::new(on.tol(12.0), on.tol(12.0));
assert_eq!(shear(&on, (150.0, 100.0), (170.0, 100.0), cmd), Some((Point::new(170.0, 100.0) + off, "11.3°".into())));
assert_eq!(shear(&on, (200.0, 150.0), (200.0, 170.0), cmd), Some((Point::new(200.0, 170.0) + off, "-11.3°".into())));
// About the center the lever is half as long: atan(20 / 50).
let alt = Mods { alt: true, ..cmd };
assert_eq!(shear(&on, (150.0, 100.0), (170.0, 100.0), alt).map(|m| m.1), Some("21.8°".into()));
// A drag straight away from the side, at right angles to it, shears nothing.
assert_eq!(shear(&on, (150.0, 100.0), (150.0, 90.0), cmd).map(|m| m.1), Some("0.0°".into()));
assert_eq!(shear(&cx(false), (150.0, 100.0), (170.0, 100.0), cmd), None);
}
/// A handle drag that turns into a shear, and back into a scale, labels only what it does now.
#[test]
fn a_handle_drag_that_changes_operation_relabels_it() {
let (d, id) = doc_with_rect();
let mut s = Selection::default();
s.add(id);
let p = paint();
let cx = ToolContext { transform_tools_guides: true, ..cx(&d, &s, &p) };
let cmd = Mods { cmd: true, ..Default::default() };
let mut t = FreeTransformTool::default();
t.pointer(&cx, &ev(PointerKind::Down, 150.0, 100.0));
t.pointer(&cx, &ev(PointerKind::Drag, 150.0, 90.0));
let size = cx.size_label(100.0, 110.0);
assert_eq!(shown_measure(&t, &cx).map(|m| m.1), Some(size.clone()));
let a = t.pointer(&cx, &ev(PointerKind::Drag, 170.0, 100.0).with_mods(cmd));
assert_eq!(a[..2], [Action::Cancel, Action::Begin("Shear".into())]);
assert_eq!(shown_measure(&t, &cx).map(|m| m.1), Some("11.3°".into()));
t.pointer(&cx, &ev(PointerKind::Drag, 150.0, 90.0));
assert_eq!(shown_measure(&t, &cx).map(|m| m.1), Some(size));
}
}
+2
View File
@@ -631,6 +631,8 @@ impl VectorcraftApp {
plugin_runs::show(self, &ctx);
trace_runs::show(self, &ctx);
opening::show(self, &ctx);
// After every window this pass may open, and before the palette's field takes the keyboard.
panel_docking::close_overlays_for_modal(self, &ctx);
palette::show(self, &ctx);
// After every panel had its chance to draw in this pass.
crate::panels::three_d::end_stale_drag(self, &ctx);
+13
View File
@@ -25,6 +25,8 @@ pub(crate) fn show_at<R>(ctx: &egui::Context, title: &str, id: Id, initial: Vec2
// Not focusable (`Sense::click()` is): Tab goes through the dialog's controls, not the backdrop.
ui.allocate_rect(ctx.content_rect(), egui::Sense::CLICK);
});
let pass = ctx.cumulative_pass_nr();
ctx.data_mut(|d| d.insert_temp(drawn_pass_id(), pass));
let shown = egui::Window::new(title)
.id(id)
.order(egui::Order::Foreground)
@@ -44,6 +46,17 @@ pub(crate) fn backdrop() -> egui::LayerId {
egui::LayerId::new(egui::Order::Middle, Id::unique("modal-dim"))
}
/// The key of the pass in which [`show_at`] last drew a modal window.
fn drawn_pass_id() -> Id {
Id::unique("modal-drawn-pass")
}
/// Whether [`show_at`] drew a modal window in this pass. Unlike the backdrop's visibility, which
/// also counts the last pass, it is false in the pass after the window closes.
pub(crate) fn drawn_this_pass(ctx: &egui::Context) -> bool {
ctx.data(|d| d.get_temp::<u64>(drawn_pass_id())) == Some(ctx.cumulative_pass_nr())
}
/// The dialog's heading, which also moves the window ([`drag_band`]).
pub(crate) fn heading(ui: &mut egui::Ui, text: &str) {
let t = Tokens::get(ui.ctx());
+189 -5
View File
@@ -564,8 +564,9 @@ pub(crate) fn recent_list_open(ctx: &egui::Context) -> bool {
pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
// The widget that had the keyboard focus when the palette opened takes it back when the palette
// closes, unless a pick opened a dialog, which focuses its own first field, or the press that
// closed it focused another widget, such as a field in a window above the backdrop.
// closes, unless a modal window is up (a pick opened a dialog, which focuses its own first
// field, or a window that opened closed the palette), or the press that closed it focused
// another widget, such as a field in a window above the backdrop.
let focus_id = egui::Id::unique("palette-focus-before");
let field_id = egui::Id::unique("palette-field");
if !app.ui.palette_open {
@@ -576,7 +577,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
});
let now = ctx.memory(|m| m.focused());
if let Some(Some(before)) = ctx.data_mut(|d| d.remove_temp::<Option<egui::Id>>(focus_id))
&& app.ui.dialog.is_none()
&& !crate::panel_docking::modal_window_up(app, ctx)
&& (now.is_none() || now == field)
{
ctx.memory_mut(|m| m.request_focus(before));
@@ -2303,6 +2304,38 @@ mod tests {
assert!(labels(&nodes).contains(&footer(n, n)), "{:?}", labels(&nodes));
}
/// When a modal window that is not a dialog, such as the About window, closes the palette, the
/// widget under the window's backdrop does not get the keyboard focus back.
#[test]
fn a_modal_window_that_closes_the_palette_keeps_the_focus_from_the_widget_under_it() {
let ctx = egui::Context::default();
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default());
let mut text = String::new();
let field = egui::Id::unique("other field");
let mut frame = |app: &mut VectorcraftApp, focus: bool| {
ctx.run_ui(egui::RawInput::default(), |ui| {
let r = ui.add(egui::TextEdit::singleline(&mut text).id(field));
if focus {
r.request_focus();
}
show(app, ui.ctx());
})
.textures_delta
.clear();
};
frame(&mut app, true);
frame(&mut app, false);
app.ui.palette_open = true;
frame(&mut app, false);
frame(&mut app, false);
// As `panel_docking::close_overlays_for_modal` does when the About window opens.
app.ui.about = true;
app.ui.palette_open = false;
frame(&mut app, false);
frame(&mut app, false);
assert_ne!(ctx.memory(|m| m.focused()), Some(field), "the field under the About window does not take the focus");
}
/// The widget that had the keyboard focus when the palette opened has it again once the
/// palette closes.
#[test]
@@ -2398,6 +2431,9 @@ mod tests {
/// app, as a progress window is drawn, and count its clicks.
above: Option<egui::Pos2>,
above_clicks: usize,
/// Draw a modal window over the backdrop before the app's windows, as a progress window
/// of a plug-in, trace or open run is drawn.
progress: bool,
}
impl Window {
@@ -2409,7 +2445,7 @@ mod tests {
assert!(!app.session.doc().unwrap().selection.is_empty());
let ctx = egui::Context::default();
ctx.enable_accesskit();
let mut window = Window { app, ctx, time: 0.0, above: None, above_clicks: 0 };
let mut window = Window { app, ctx, time: 0.0, above: None, above_clicks: 0, progress: false };
window.frame(vec![]);
window.frame(vec![]);
window
@@ -2421,9 +2457,13 @@ mod tests {
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, WINDOW);
let input = egui::RawInput { time: Some(self.time), screen_rect: Some(screen), events, ..Default::default() };
let app = &mut self.app;
let (above, clicks) = (self.above, &mut self.above_clicks);
let (above, clicks, progress) = (self.above, &mut self.above_clicks, self.progress);
let mut out = self.ctx.run_ui(input, |ui| {
app.logic(ui.ctx());
if progress {
let id = egui::Id::unique("test-progress");
crate::dialogs::modal::show_at(ui.ctx(), "Progress", id, egui::Vec2::ZERO, 12, |ui| ui.label("Working"));
}
app.ui(ui);
if let Some(at) = above {
let area = egui::Area::new(egui::Id::unique("test-above")).order(egui::Order::Foreground).fixed_pos(at);
@@ -2495,6 +2535,150 @@ mod tests {
assert_eq!(window.selection(), before, "the click does not reach the canvas");
}
/// #7906: a pick in the macOS menu bar that opens a dialog closes the palette, and the search
/// field does not keep the keyboard from the dialog.
#[test]
fn a_dialog_opened_from_the_system_menu_closes_the_palette() {
let mut window = Window::new();
window.app.ui.palette_open = true;
window.frame(vec![]);
window.frame(vec![]);
let field = window.ctx.data(|d| d.get_temp::<egui::Id>(egui::Id::unique("palette-field"))).expect("the search field is drawn");
assert_eq!(window.ctx.memory(|m| m.focused()), Some(field), "the search field has the keyboard");
menus::invoke_from_system_menu(&mut window.app, &window.ctx, "object.move", json!({}));
assert!(window.app.ui.dialog.is_some(), "Move… opens its dialog: {}", window.app.ui.status);
window.frame(vec![]);
assert!(!window.app.ui.palette_open, "the dialog closes the palette");
window.frame(vec![]);
assert!(window.app.ui.dialog.is_some(), "the dialog stays open");
assert_ne!(window.ctx.memory(|m| m.focused()), Some(field), "the search field does not keep the keyboard");
}
/// #7906: with the palette open, the About window that opens without a press closes the palette.
#[test]
fn the_about_window_closes_the_palette() {
let mut window = Window::new();
window.app.ui.palette_open = true;
window.frame(vec![]);
menus::invoke_from_system_menu(&mut window.app, &window.ctx, "help.about", json!({}));
assert!(window.app.ui.about, "About opens");
window.frame(vec![]);
assert!(!window.app.ui.palette_open, "the About window closes the palette");
}
/// #7906: a window drawn over the modal backdrop, as a plug-in, trace or open run's progress
/// window is, closes the palette in the pass it first draws.
#[test]
fn a_progress_window_closes_the_palette() {
let mut window = Window::new();
window.app.ui.palette_open = true;
window.frame(vec![]);
assert!(window.app.ui.palette_open, "the palette is open");
window.progress = true;
window.frame(vec![]);
assert!(!window.app.ui.palette_open, "the progress window closes the palette");
}
/// #7906: the palette opened from the macOS menu bar while a dialog is open closes again, and its
/// search field does not take the keyboard from the dialog.
#[test]
fn the_palette_opened_over_a_dialog_closes() {
let mut window = Window::new();
menus::invoke(&mut window.app, "object.move", json!({}));
assert!(window.app.ui.dialog.is_some(), "Move… opens its dialog: {}", window.app.ui.status);
window.frame(vec![]);
window.frame(vec![]);
let before = window.ctx.memory(|m| m.focused());
menus::invoke_from_system_menu(&mut window.app, &window.ctx, "help.commandPalette", json!({}));
assert!(window.app.ui.palette_open, "the command opens the palette");
window.frame(vec![]);
window.frame(vec![]);
assert!(!window.app.ui.palette_open, "the dialog keeps the palette closed");
assert!(window.app.ui.dialog.is_some(), "the dialog stays open");
let field = window.ctx.data(|d| d.get_temp::<egui::Id>(egui::Id::unique("palette-field")));
let now = window.ctx.memory(|m| m.focused());
assert!(field.is_none() || now != field, "the search field does not take the keyboard");
assert_eq!(now, before, "the dialog keeps its focus");
}
/// #7906 as reported: with the palette open, a click on the Effect menu in the window's menu bar
/// closes the palette, and a dialog opened afterwards is not under it.
#[test]
fn a_click_on_the_menu_bar_closes_the_palette_before_a_dialog_opens() {
let mut window = Window::new();
window.app.ui.palette_open = true;
let nodes = window.frame(vec![]);
window.click(button_at(&nodes, "Effect"));
assert!(!window.app.ui.palette_open, "the click on the menu bar closes the palette");
menus::invoke(&mut window.app, "object.move", json!({}));
assert!(window.app.ui.dialog.is_some(), "Move… opens its dialog: {}", window.app.ui.status);
window.frame(vec![]);
window.frame(vec![]);
assert!(!window.app.ui.palette_open, "the palette stays closed over the dialog");
}
/// Opens `overlay` ("flyout", "drawer" or "menu") in a new window, then opens Move… without a
/// press, as the macOS menu bar or an automation command does: whether the overlay is still open.
fn overlay_open_after_a_dialog_opens(overlay: &str) -> bool {
let mut window = Window::new();
match overlay {
"flyout" => {
window.app.ui.flyout = Some(0);
let tools = vec!["rectangle".to_string(), "ellipse".to_string()];
window.ctx.data_mut(|d| d.insert_temp(egui::Id::unique("flyout-tools"), tools));
}
"drawer" => window.app.ui.tools_drawer = true,
_ => {
let nodes = window.frame(vec![]);
window.click(button_at(&nodes, "Object"));
}
}
window.frame(vec![]);
let open = |w: &Window| w.app.ui.flyout.is_some() || w.app.ui.tools_drawer || egui::Popup::is_any_open(&w.ctx);
assert!(open(&window), "the {overlay} is open");
menus::invoke(&mut window.app, "object.move", json!({}));
assert!(window.app.ui.dialog.is_some(), "Move… opens its dialog: {}", window.app.ui.status);
window.frame(vec![]);
open(&window)
}
/// #7906: a dialog that opens without a press closes a tool group's flyout.
#[test]
fn a_dialog_opened_without_a_press_closes_a_flyout() {
assert!(!overlay_open_after_a_dialog_opens("flyout"), "the dialog closes the flyout");
}
/// #7906: a dialog that opens without a press closes the All Tools drawer.
#[test]
fn a_dialog_opened_without_a_press_closes_the_tools_drawer() {
assert!(!overlay_open_after_a_dialog_opens("drawer"), "the dialog closes the drawer");
}
/// #7906: a dialog that opens without a press closes an open menu.
#[test]
fn a_dialog_opened_without_a_press_closes_a_menu() {
assert!(!overlay_open_after_a_dialog_opens("menu"), "the dialog closes the menu");
}
/// The palette opened in the pass after a dialog closes stays open, and the next dialog to open,
/// one pass later, closes it.
#[test]
fn the_palette_opened_as_a_dialog_closes_stays_open_until_the_next_dialog() {
let mut window = Window::new();
menus::invoke(&mut window.app, "object.move", json!({}));
assert!(window.app.ui.dialog.is_some(), "Move… opens its dialog: {}", window.app.ui.status);
window.frame(vec![]);
window.frame(vec![]);
crate::dialogs::cancel(&mut window.app);
window.app.ui.palette_open = true;
window.frame(vec![]);
assert!(window.app.ui.palette_open, "the palette stays open");
menus::invoke(&mut window.app, "object.move", json!({}));
assert!(window.app.ui.dialog.is_some(), "Move… opens its dialog again: {}", window.app.ui.status);
window.frame(vec![]);
assert!(!window.app.ui.palette_open, "the next dialog closes the palette");
}
/// A click on another control outside the popup closes the popup and does not press the
/// control.
#[test]
+34
View File
@@ -1306,6 +1306,40 @@ pub(crate) fn modal_open(app: &VectorcraftApp, ctx: &egui::Context) -> bool {
|| ctx.memory(|m| m.areas().is_visible(&crate::dialogs::modal::backdrop()))
}
/// Is a modal window open in this pass: a dialog, the About window, a file dialog, the update
/// prompt, or a window such as a progress window drawn over the modal backdrop in this pass?
pub(crate) fn modal_window_up(app: &VectorcraftApp, ctx: &egui::Context) -> bool {
app.ui.dialog.is_some()
|| app.ui.about
|| app.file_dialog_open()
|| crate::updates_ui::blocks_input(app)
|| crate::dialogs::modal::drawn_this_pass(ctx)
}
/// The key of whether a modal window was up in the last pass ([`close_overlays_for_modal`]).
fn modal_window_up_id() -> egui::Id {
egui::Id::unique("modal-window-up")
}
/// While a modal window is up ([`modal_window_up`]), keeps the command palette closed, so a palette
/// opened over it from the macOS menu bar or by an automation command does not take the keyboard
/// from the window. In the pass the window opens, also closes a tool group's flyout, the All Tools
/// drawer and any open popup, whatever opened the window: a press in the window, a pick in the
/// macOS menu bar, an automation command or a run that ends in a dialog. Popups the window itself
/// opens later stay open. Called after every window of the pass has drawn.
pub(crate) fn close_overlays_for_modal(app: &mut VectorcraftApp, ctx: &egui::Context) {
let up = modal_window_up(app, ctx);
let was = ctx.data_mut(|d| std::mem::replace(d.get_temp_mut_or_default::<bool>(modal_window_up_id()), up));
if up {
app.ui.palette_open = false;
}
if up && !was {
app.ui.flyout = None;
app.ui.tools_drawer = false;
egui::Popup::close_all(ctx);
}
}
/// Keys, text and clipboard events that a floating panel's own OS window left over run the main
/// window's shortcuts, tool keys and clipboard on its next frame ([`VectorcraftApp::raw_input_hook`]).
/// craft-ui forwards nothing while a field in that window has the keyboard. A field of the main
+127 -2
View File
@@ -6,7 +6,9 @@
//! double-click opens Graphic Style Options. Dragging a style moves it in the list, applies it
//! to the art it is dropped on (`canvas::panel_drop`), or, dropped on New Graphic Style, adds a
//! copy of it and of the styles highlighted with it at the end of the list; art dragged off the
//! canvas or the Appearance panel's thumbnail dropped on the panel becomes a new style. Holding the right button on a style
//! canvas or the Appearance panel's thumbnail dropped on the panel becomes a new style, and
//! dropped on a style with Alt held replaces that style with its look (`graphicStyle.redefine`).
//! Holding the right button on a style
//! shows it large, on the selected object when there is one. The Control bar's Style picker lists
//! the same tiles ([`picker`]). Graphic style libraries open in library panels
//! ([`GraphicStyleLibraries`]).
@@ -364,6 +366,8 @@ struct Events {
moved: Option<(String, usize)>,
/// Art or an appearance dropped on the panel: a new style from this object.
new_from: Option<NodeId>,
/// Art or an appearance dropped on a style with Alt held: the style takes this object's look.
replaced: Option<(String, NodeId)>,
/// The style the right button is held on.
large: Option<usize>,
/// A style is dragged over a tile or row.
@@ -383,10 +387,26 @@ fn clicked(ui: &Ui, resp: &Response, name: &str) -> Option<Click> {
/// Clicks, drags and the right button on the tile or row `resp` of style `i` of `d` (`list`: rows
/// stack downwards). A drag from it carries the style ([`PanelDrag::GraphicStyle`]); a style
/// dragged over it lands before or after it by the pointer's half.
/// dragged over it lands before or after it by the pointer's half. Art (its first object) or the
/// Appearance panel's thumbnail held over it with Alt outlines it, and released there replaces the
/// style with that object's look; without Alt it is left to the list ([`zone_input`]).
fn cell_input(ui: &Ui, resp: &Response, d: &Document, i: usize, list: bool, ev: &mut Events) {
let name = &d.graphic_styles[i].name;
widgets::drag_source(ui, resp, || PanelDrag::GraphicStyle(name.clone()));
let source = resp.dnd_hover_payload::<PanelDrag>().and_then(|drag| match &*drag {
PanelDrag::Art(ids) => ids.first().copied(),
PanelDrag::Appearance(id) => Some(*id),
_ => None,
});
if let Some(id) = source
&& alt_held(ui)
{
ev.over = true;
widgets::drop_target_outline(ui, resp.rect);
if resp.dnd_release_payload::<PanelDrag>().is_some() {
ev.replaced = Some((name.clone(), id));
}
}
if let Some(drag) = resp.dnd_hover_payload::<PanelDrag>()
&& let PanelDrag::GraphicStyle(moving) = &*drag
{
@@ -505,6 +525,12 @@ fn act(app: &mut VectorcraftApp, ui: &Ui, s: &Shown, ev: Events, picker: bool) {
if let Some(id) = ev.new_from {
run(app, "graphicStyle.new", json!({ "id": id.0 }));
}
// An object that is linked to the style and still has its look leaves the style as it is.
if let Some((name, id)) = ev.replaced
&& !app.session.graphic_style_of(id).is_some_and(|(g, linked)| linked && g.name == name)
{
run(app, "graphicStyle.redefine", json!({ "name": name, "id": id.0 }));
}
match ev.click {
Some(Click::Pick(name, _)) if picker => {
app.run("graphicStyle.apply", json!({"name": name, "add": alt_held(ui)})).ok();
@@ -1432,6 +1458,105 @@ mod tests {
}
}
/// Art or the Appearance panel's thumbnail dropped on a style with Alt held replaces that style
/// with the object's look, in one undo step: the style keeps its name, its place and its id, the
/// objects still linked to it take the new look, and the object becomes linked. The style is
/// outlined while one is held over it with Alt. Without Alt the drop makes a new style; a style
/// dragged with Alt still only moves; an object linked to the style with its look, an empty art
/// drag and an object that is gone change nothing and record no undo step.
#[test]
fn art_or_an_appearance_dropped_on_a_style_with_alt_replaces_that_style() {
let mut app = app();
let rect = app.session.active().unwrap().doc.layers[0].children().unwrap()[0].id;
app.run("paint.setFill", json!({"color": "#ff0000", "ids": [rect.0]})).unwrap();
app.run("graphicStyle.new", json!({"name": "Red", "id": rect.0})).unwrap();
app.run("graphicStyle.move", json!({"name": "Red", "to": 0})).unwrap();
app.run("shape.ellipse", json!({"x": 60, "y": 60, "width": 20, "height": 20})).unwrap();
let oval = app.session.active().unwrap().selection.objects[0];
app.run("paint.setFill", json!({"color": "#00ff00", "ids": [oval.0]})).unwrap();
let ctx = egui::Context::default();
let screen = Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(260.0, 600.0)));
// One frame of the panel with `events` and `modifiers` held: whether a drop-target outline
// the size of one style's tile or row is drawn around `at`.
let frame_at = |app: &mut VectorcraftApp, at: egui::Pos2, events: Vec<egui::Event>, modifiers: egui::Modifiers| {
let events = std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect();
let mut out = ctx.run_ui(egui::RawInput { screen_rect: screen, events, ..Default::default() }, |ui| show(app, ui));
out.textures_delta.clear();
let accent = Tokens::get(&ctx).accent;
out.shapes.iter().any(|c| match &c.shape {
egui::Shape::Rect(r) => r.stroke.width == 1.5 && r.stroke.color == accent && r.rect.contains(at) && r.rect.height() < 45.0,
_ => false,
})
};
let release = |at: egui::Pos2, modifiers: egui::Modifiers| {
let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers };
vec![egui::Event::PointerMoved(at), up]
};
let (none, alt) = (egui::Modifiers::default(), egui::Modifiers::ALT);
let doc = |app: &VectorcraftApp| app.session.active().unwrap().doc.clone();
let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len();
let red = doc(&app).graphic_style("Red").unwrap().clone();
let green = doc(&app).node(oval).unwrap().appearance.fill_paint();
assert_ne!(red.appearance.fill_paint(), green);
// The first style: the top of the list's first row, or its first tile.
for (view, at) in [(View::SmallList, pos2(60.0, 9.0)), (View::Thumbnail, pos2(20.0, 20.0))] {
app.ui.graphic_styles_view = view;
frame_at(&mut app, at, vec![], none);
for payload in [PanelDrag::Art(vec![oval]), PanelDrag::Appearance(oval)] {
let n = names(&app);
let before = steps(&app);
// Held over the style with Alt it is outlined; without Alt it is not.
egui::DragAndDrop::set_payload(&ctx, payload.clone());
assert!(!frame_at(&mut app, at, vec![egui::Event::PointerMoved(at)], none), "{view:?} {payload:?}: no outline without Alt");
assert!(frame_at(&mut app, at, vec![egui::Event::PointerMoved(at)], alt), "{view:?} {payload:?}: outlined with Alt");
assert_eq!(names(&app), n, "{view:?} {payload:?}: holding it there changes nothing");
// Released there with Alt: Red takes the oval's look and keeps its name, place and id.
frame_at(&mut app, at, release(at, alt), alt);
let d = doc(&app);
assert_eq!(names(&app), n, "{view:?} {payload:?}");
let g = d.graphic_style("Red").unwrap();
assert_eq!((g.id, g.appearance.fill_paint()), (red.id, green.clone()), "{view:?} {payload:?}");
assert_eq!(d.node(rect).unwrap().appearance.fill_paint(), green, "{view:?} {payload:?}: the linked rectangle follows");
assert_eq!(d.node(rect).unwrap().extras().graphic_style, Some(red.id));
assert_eq!(d.node(oval).unwrap().extras().graphic_style, Some(red.id), "{view:?} {payload:?}: the oval is linked");
assert_eq!(steps(&app), before + 1, "{view:?} {payload:?}: one undo step");
app.run("edit.undo", json!({})).unwrap();
let d = doc(&app);
assert_eq!(d.graphic_style("Red").unwrap().appearance, red.appearance, "{view:?} {payload:?}: undo restores the style");
assert_eq!(d.node(oval).unwrap().extras().graphic_style, None);
assert_eq!(d.node(rect).unwrap().appearance.fill_paint(), red.appearance.fill_paint());
}
// Without Alt the oval becomes a new style at the end, and Red stays as it was.
let n = names(&app);
egui::DragAndDrop::set_payload(&ctx, PanelDrag::Art(vec![oval]));
frame_at(&mut app, at, release(at, none), none);
assert_eq!(names(&app).len(), n.len() + 1, "{view:?}");
assert_eq!(doc(&app).graphic_style("Red").unwrap().appearance, red.appearance, "{view:?}");
app.run("edit.undo", json!({})).unwrap();
// A style dragged onto Red with Alt moves and replaces nothing.
let last = n.last().unwrap().clone();
egui::DragAndDrop::set_payload(&ctx, PanelDrag::GraphicStyle(last.clone()));
frame_at(&mut app, at, release(at, alt), alt);
assert_eq!(names(&app)[0], last, "{view:?}");
assert_eq!(doc(&app).graphic_style("Red").unwrap().appearance, red.appearance, "{view:?}");
app.run("edit.undo", json!({})).unwrap();
assert_eq!(names(&app), n, "{view:?}");
// The rectangle that is linked to Red with its look, an empty drag of art and an object
// that is gone change nothing and record nothing.
let before = steps(&app);
for payload in [PanelDrag::Art(vec![rect]), PanelDrag::Appearance(rect), PanelDrag::Art(vec![]), PanelDrag::Art(vec![NodeId(9999)])] {
egui::DragAndDrop::set_payload(&ctx, payload.clone());
frame_at(&mut app, at, release(at, alt), alt);
assert_eq!(names(&app), n, "{view:?} {payload:?}");
assert_eq!(doc(&app).graphic_style("Red").unwrap().appearance, red.appearance, "{view:?} {payload:?}");
assert_eq!(steps(&app), before, "{view:?} {payload:?}");
}
}
}
#[test]
fn shift_click_selects_a_range_and_cmd_click_adds_or_removes_one_style() {
let mut app = app();
+4 -2
View File
@@ -330,15 +330,17 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
// The column drag: live while it lasts, one undo step when the button is released.
let released = ui.input(|i| i.pointer.any_released());
// Layers dragged into the empty space under the last row go below the bottom layer (there is
// no row there to take the drop).
// no row there to take the drop). The bottom layer itself goes there only as an Alt copy,
// which lands below it; moved, it would stay where it is (#8237).
let below = list_rect.top() - scrolled.inner.state.clamped_offset().y + list.len() as f32 * view.h;
let alt = ui.input(|i| i.modifiers.alt);
if query.is_empty()
&& !app.ui.layers_filter.is_on()
&& let Some(drag) = egui::DragAndDrop::payload::<LayersDrag>(ui.ctx())
&& let LayersDrag::Rows(ids) = &*drag
&& let Some(bottom) = doc.layers.first()
&& !ids.is_empty()
&& !ids.contains(&bottom.id)
&& (alt || !ids.contains(&bottom.id))
&& ids.iter().all(|i| doc.node(*i).is_some_and(Node::is_layer))
&& let Some(p) = ui.input(|i| i.pointer.hover_pos())
&& list_rect.contains(p)
+7 -2
View File
@@ -674,15 +674,20 @@ fn drop_target(ui: &Ui, view: &View, n: &Node, r: egui::Rect, indent: f32, open:
return;
}
};
// Never into itself or a row inside it.
// Never into itself or a row inside it. With Alt, rows held over one of their own rows copy
// beside it, above or below, as `layer.move` places a copy there (#8237).
let alt = ui.input(|i| i.modifiers.alt);
let beside_itself = alt && matches!(&*drag, LayersDrag::Rows(_)) && moving.contains(&n.id);
let around = doc.ancestry(n.id).unwrap_or_default();
if moving.is_empty() || moving.iter().any(|m| around.contains(m)) {
if moving.is_empty() || moving.iter().any(|m| around.contains(m) && !(beside_itself && *m == n.id)) {
return;
}
let Some(p) = ui.input(|i| i.pointer.hover_pos()) else { return };
let rel = (p.y - r.top()) / r.height().max(1.0);
let inside = takes(n, &drag, &moving, doc);
let place = match &*drag {
LayersDrag::Rows(_) if beside_itself && rel < 0.5 => Place::Above,
LayersDrag::Rows(_) if beside_itself => Place::Below,
LayersDrag::Art if inside => Place::Inside,
LayersDrag::Art => Place::Above,
LayersDrag::Rows(_) if inside && rel >= 0.25 && (rel <= 0.75 || open) => Place::Inside,
+51
View File
@@ -1462,6 +1462,57 @@ fn dragging_a_layer_into_the_empty_space_under_the_rows_moves_it_to_the_bottom()
assert_eq!(ids(&app), vec![top, bottom], "the top layer is now the bottom one");
}
/// #8237: with Alt, the top layer dropped on the top edge of its own row copies above itself, and
/// the bottom layer dropped in the empty space under the list copies below itself. Without Alt,
/// neither drop changes anything.
#[test]
fn alt_dragging_the_top_layer_up_or_the_bottom_layer_down_copies_it() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
app.session.execute("layer.new", &json!({"top": true})).unwrap();
let ids = |app: &VectorcraftApp| app.session.active().unwrap().doc.layers.iter().map(|l| l.id).collect::<Vec<_>>();
let [bottom, top] = ids(&app)[..] else { panic!("two layers") };
let ctx = egui::Context::default();
// Rows: the top layer, the bottom layer, then empty space.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 2);
let row = |y: f32| egui::pos2(150.0, y);
let top_edge = |y: f32| egui::pos2(150.0, y - ROW_MEDIUM * 0.4);
let under = |y: f32| egui::pos2(150.0, y + 3.0 * ROW_MEDIUM);
drag(&mut app, &ctx, row(circles[0].y), top_edge(circles[0].y), false);
drag(&mut app, &ctx, row(circles[1].y), under(circles[1].y), false);
assert_eq!(ids(&app), vec![bottom, top], "moved onto their own places, nothing changes");
drag(&mut app, &ctx, row(circles[0].y), top_edge(circles[0].y), true);
let after = ids(&app);
assert_eq!((after.len(), &after[..2]), (3, &[bottom, top][..]), "a copy above the top layer");
// Rows: the copy, the top layer, the bottom layer, then empty space.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 3);
drag(&mut app, &ctx, row(circles[2].y), under(circles[2].y), true);
let after = ids(&app);
assert_eq!((after.len(), after[1]), (4, bottom), "a copy below the bottom layer");
}
/// #8237: a document's only layer, Alt-dragged up onto its own row or down into the empty space,
/// is copied above or below itself.
#[test]
fn a_lone_layer_alt_dragged_up_or_down_is_copied() {
for (up, at) in [(true, 0), (false, 1)] {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let ids = |app: &VectorcraftApp| app.session.active().unwrap().doc.layers.iter().map(|l| l.id).collect::<Vec<_>>();
let [only] = ids(&app)[..] else { panic!("one layer") };
let ctx = egui::Context::default();
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 1);
let y = circles[0].y;
let to = if up { y - ROW_MEDIUM * 0.4 } else { y + 3.0 * ROW_MEDIUM };
drag(&mut app, &ctx, egui::pos2(150.0, y), egui::pos2(150.0, to), true);
let after = ids(&app);
assert_eq!((after.len(), after[at]), (2, only), "up: {up}");
}
}
#[test]
fn dragging_rows_moves_them_into_other_layers_and_alt_copies() {
let (mut app, [layer, sub, g, _, a, c]) = nested();
+13 -10
View File
@@ -5,16 +5,19 @@ use super::{
widgets,
};
/// The selected swatches and groups that can be deleted (all but None and Registration).
pub(super) fn deletable(sel: &[String]) -> Vec<String> {
sel.iter().filter(|n| !n.starts_with('[')).cloned().collect()
/// The selected swatches and groups that can be deleted: every color group in the document and
/// every swatch that `Swatch::is_reserved` does not reserve (None and Registration). Names the
/// document does not hold are left out.
pub(super) fn deletable(app: &VectorcraftApp, sel: &[String]) -> Vec<String> {
let Some(d) = app.session.active().map(|st| &st.doc) else { return vec![] };
sel.iter().filter(|n| d.swatch(n).map_or_else(|| d.swatch_groups.iter().any(|g| g.name == **n), |w| !w.is_reserved())).cloned().collect()
}
/// The selected swatch when exactly one swatch with an editor is selected (not None, Registration
/// or a group).
fn editable(app: &VectorcraftApp, sel: &[String]) -> Option<String> {
pub(super) fn editable(app: &VectorcraftApp, sel: &[String]) -> Option<String> {
match sel {
[n] if !n.starts_with('[') && app.session.active().is_some_and(|st| st.doc.swatch(n).is_some()) => Some(n.clone()),
[n] if app.session.active().and_then(|st| st.doc.swatch(n)).is_some_and(|w| !w.is_reserved()) => Some(n.clone()),
_ => None,
}
}
@@ -80,7 +83,7 @@ pub(super) fn bottom(app: &mut VectorcraftApp, ui: &mut Ui, sel: &[String]) {
}
ui.add_space((ui.available_width() - 3.0 * 28.0).max(0.0));
if widgets::icon_button(ui, "dc-folder", tl!("New Color Group"), false, 24.0).clicked() {
app.run("ui.newColorGroup", json!({"swatches": deletable(sel)})).ok();
app.run("ui.newColorGroup", json!({"swatches": deletable(app, sel)})).ok();
}
// Alt-click skips the dialog; Ctrl/Cmd-click makes a spot color, and Ctrl/Cmd+Shift-click
// makes a global process color.
@@ -89,7 +92,7 @@ pub(super) fn bottom(app: &mut VectorcraftApp, ui: &mut Ui, sel: &[String]) {
}
// Alt-click deletes without asking. Swatches or color groups dragged from the list can be
// dropped on it, also with nothing selected: the button is enabled while they are held.
let del = deletable(sel);
let del = deletable(app, sel);
let dragged = dragged_deletable(app, ui.ctx());
let trash = widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Swatch"), false, !del.is_empty() || !dragged.is_empty(), 24.0);
if trash.clicked() && !del.is_empty() {
@@ -111,7 +114,7 @@ fn dragged_deletable(app: &VectorcraftApp, ctx: &egui::Context) -> Vec<String> {
return vec![];
}
match egui::DragAndDrop::payload::<PanelDrag>(ctx).as_deref() {
Some(PanelDrag::Paint { rows: Some(r), .. }) => deletable(&r.names).into_iter().filter(|n| st.doc.swatch_name_taken(n)).collect(),
Some(PanelDrag::Paint { rows: Some(r), .. }) => deletable(app, &r.names).into_iter().filter(|n| st.doc.swatch_name_taken(n)).collect(),
_ => vec![],
}
}
@@ -164,7 +167,7 @@ pub(super) fn new_swatch(app: &mut VectorcraftApp, sel: &[String], m: egui::Modi
pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
let view = app.ui.swatches_view;
let selected = selection(app, ui);
let del = deletable(&selected);
let del = deletable(app, &selected);
let opts = editable(app, &selected);
if menu_item(ui, tl!("New Swatch…"), true, false) {
new_swatch(app, &selected, egui::Modifiers::NONE);
@@ -239,6 +242,6 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
ui.separator();
ui.menu_button(tl!("Open Swatch Library"), |ui| library_panel::library_menu::<SwatchLibraries>(app, ui));
if menu_item(ui, tl!("Save Swatch Library…"), true, false) {
app.run("ui.saveSwatchLibrary", json!({ "names": deletable(&selected) })).ok();
app.run("ui.saveSwatchLibrary", json!({ "names": deletable(app, &selected) })).ok();
}
}
@@ -142,7 +142,7 @@ impl LibraryKind for SwatchLibraries {
app.status(e);
}
if menu_item(ui, tl!("Save Swatch Library…"), app.session.active().is_some(), false) {
let names = deletable(&selection(app, ui));
let names = deletable(app, &selection(app, ui));
app.run("ui.saveSwatchLibrary", json!({ "names": names })).ok();
}
}
+21 -1
View File
@@ -281,7 +281,27 @@ fn delete_asks_then_removes_the_selection_and_unlinks_art() {
assert!(app.session.doc().unwrap().doc.swatch("Orange").is_some());
delete(&mut app, vec!["Orange".into()], true);
assert!(app.ui.dialog.is_none() && app.session.doc().unwrap().doc.swatch("Orange").is_none());
assert_eq!(deletable(&["[None]".into(), REGISTRATION.into(), "Grays".into()]), ["Grays"]);
assert_eq!(deletable(&app, &["[None]".into(), REGISTRATION.into(), "Grays".into()]), ["Grays"]);
}
/// Only None and Registration are reserved: a user swatch or color group whose name starts with
/// `[` can be deleted, the swatch can be edited, and names the document does not hold are left out.
#[test]
fn bracketed_user_swatches_and_groups_can_be_deleted_and_edited() {
let mut app = app();
app.run("swatch.new", json!({"name": "[Mine]", "color": "#336699"})).unwrap();
app.run("swatch.newGroup", json!({"name": "[Team]", "colors": ["#ff0000"]})).unwrap();
let names = |v: &[&str]| v.iter().map(|n| n.to_string()).collect::<Vec<String>>();
assert_eq!(deletable(&app, &names(&["[None]", REGISTRATION, "[Mine]", "[Team]", "Gone"])), ["[Mine]", "[Team]"]);
assert_eq!(actions::editable(&app, &names(&["[Mine]"])).as_deref(), Some("[Mine]"));
for name in ["[None]", REGISTRATION, "[Team]", "Gone"] {
assert_eq!(actions::editable(&app, &names(&[name])), None, "{name}");
}
let doomed = deletable(&app, &names(&["[Mine]"]));
delete(&mut app, doomed, false);
assert_eq!(app.ui.dialog.as_ref().map(|d| d.str("message")).as_deref(), Some("Delete “[Mine]”?"));
crate::dialogs::confirm(&mut app).unwrap();
assert!(app.session.doc().unwrap().doc.swatch("[Mine]").is_none());
}
/// The prompt for several swatches and groups gives the form the language's plural rule picks for the count.
+4 -2
View File
@@ -13,13 +13,15 @@ pub enum PanelDrag {
/// it is dropped.
Paint { paint: Paint, params: serde_json::Value, rows: Option<SwatchRows>, library: Option<(String, String)> },
/// The Appearance panel's thumbnail: art it is dropped on takes object `0`'s appearance
/// (`appearance.copyFrom`); the Graphic Styles panel makes a style of it.
/// (`appearance.copyFrom`); the Graphic Styles panel makes a style of it, or with Alt held
/// replaces the style it is dropped on with it (`graphicStyle.redefine`).
Appearance(vectorcraft_doc::NodeId),
/// A Graphic Styles panel style: art it is dropped on takes it (`graphicStyle.apply` with its
/// `ids`); the panel moves it to where it is dropped.
GraphicStyle(String),
/// The selected art, dragged off the canvas with the Selection tool: the Graphic Styles panel
/// makes a style of the first object (`graphicStyle.new`), the Symbols panel a symbol of it all
/// makes a style of the first object (`graphicStyle.new`), or with Alt held replaces the style
/// it is dropped on with that object's look (`graphicStyle.redefine`), the Symbols panel a symbol of it all
/// (`symbol.new`), the Swatches panel a pattern swatch of a copy (`object.pattern.make`) and the
/// Brushes panel an Art brush (`brush.new`).
Art(Vec<vectorcraft_doc::NodeId>),
File diff suppressed because one or more lines are too long
+10 -4
View File
@@ -4532,7 +4532,10 @@ A graphic style holds an appearance (fills, strokes, effects) plus opacity, blen
object's, type its characters'). `graphicStyle.apply {name, ids?}` gives the objects the style and links them;
`add: true` adds the style on top of the existing appearance instead. Linked objects stay linked while they keep the
style's look: editing their appearance or transparency breaks the link, and `graphicStyle.redefine {name?, id?}`
updates only the objects still linked. The art of a column or marker design in a graph series is never linked:
updates only the objects still linked. Art dragged off the canvas, or the Appearance panel's thumbnail, dropped on a
style in the Graphic Styles panel with Alt held runs `graphicStyle.redefine` with that style's `name` and the object's
`id` (the first object of the art); an object already linked to the style with its look changes nothing. The art of a
column or marker design in a graph series is never linked:
`graphicStyle.new` can make a style from it, and `graphicStyle.redefine` leaves its look as it was and unlinks it,
whether it is the source or a linked object. `graphicStyle.list` returns each style with the ids linked to it and the
style of the first selected object; `select.same.graphicStyle` selects an object's fellow users.
@@ -5666,7 +5669,10 @@ and `layerRows`, the rows highlighted in the panel.
layer, group or Intertwine group (on top of its contents), keeping their stacking order; `copy` (Alt-drag) moves
copies. Layers go only in layers or at the top level and objects in layers, groups and Intertwine groups (see
Intertwine for the members an Intertwine group takes; an object placed beside a top-level layer goes
inside it); a row never goes into itself or a row inside it, and a locked layer or group takes nothing. Dragging the
inside it); a row never goes into itself or a row inside it, and a locked layer or group takes nothing. With `copy`,
the target may be one of the rows copied: the copies go above or below it, as an Alt-drag onto a row's own row (or a
bottom layer's into the empty space under the list) places them, unless objects are copied with a top-level layer
that is the target, which would put them inside it (#8237). Dragging the
selected-art square is `layer.move` with the selected objects. `node.move {id, parent?, index}` is the low-level
form with the same nesting rules; unlike `layer.move`, it also moves a row into a locked layer or group.
- **Buttons**: `layer.new {name?, top?, below?, …options}` (above the current layer at its level; `top` with
@@ -7330,8 +7336,8 @@ Guides change where a snapped point lands:
- `anchorPathLabels` (on by default): off, no "anchor", "center", "path" or "align" label.
- `measurementLabels` (on by default): off, no size or offset readout while drawing, moving (Free Transform's move
too), dragging a ruler guide, drawing and resizing an artboard, or moving and resizing a slice.
- `transformToolsGuides` (on by default): off, no readout while scaling or rotating with the Selection tool, the
Free Transform tool or the Rotate, Scale, Shear and Reflect tools.
- `transformToolsGuides` (on by default): off, no readout while scaling, rotating or shearing with the Selection
tool, the Free Transform tool or the Rotate, Scale, Shear and Reflect tools.
- `objectHighlighting` (on by default; desktop app): off, the Selection tools no longer outline the object under the
pointer. The outline also needs View › Smart Guides on.
- `snappingTolerance` (0–40 px, 4 by default): how near an anchor, edge, centre or artboard edge pulls a drawn point,
+2 -1
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+3 -1
View File
@@ -1,6 +1,6 @@
# UI and interaction parity
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged)
>
> Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5).
>
@@ -58,6 +58,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard
| 2026-11-09 | minor | Document Setup and Character panel Language lists: Nepali, Konkani and Sindhi complete #4943; Assamese and Sanskrit are already present from #5946. Names in all 27 catalogs come from [CLDR locale language-name data](https://github.com/unicode-org/cldr/tree/main/common/main). The public [language assignment documentation](https://helpx.adobe.com/illustrator/using/spelling-language-dictionaries.html) describes the Character panel Language menu, but does not establish that these five languages are listed there; inclusion and a single Sindhi entry remain maintainer decisions. Scores unchanged |
| 2026-11-14 | minor | G5: Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. |
| 2026-11-14 | minor | Layers panel: right-clicking a layer/group/object row shows a context menu with Options…, Duplicate, Delete, Lock/Hide Others, Locate Object, and Collect for Export — matching standard desktop layer panel conventions. Scores unchanged. |
| 2026-11-16 | minor | Layers panel: an Alt-drag copies a row above or below its own place, so the top layer dragged up, the bottom layer dragged down and a document's only layer are copied (#8237). Scores and estimates unchanged. |
| 2026-11-16 | minor | Layers panel: rows or the selected-art square dragged over the list show the copy cursor while Alt is held, as the drop then copies, and the grabbing hand otherwise (#8217). Scores and estimates unchanged. |
| 2026-11-16 | minor | Gradient panel: the strip under the ramp, where a click adds a stop, shows the white arrow with a plus on Windows and X11, where the system copy cursor showed as the plain arrow (#8241). Scores and estimates unchanged. |
| 2026-11-13 | minor | Pencil cursors: the continuation cursor (a short rising line) shows over an open end of a selected path before any press, freehand too, and while a continuing stroke nears another selected path's open end it connects to; the straight-line cursor is a short level line; a continued path, a straight line too, shows the closing cursor and closes within Close Paths When Ends Are Within of its other end, and with Alt at the release. Scores and estimates unchanged. |
@@ -190,6 +191,7 @@ tools, never checked side by side) isn't captured row by row.
| Layers panel: a layer whose Layer Options › Print is off shows its name italic (#5739) | done | the panel row and its drag ghost; a printing layer stays upright, and Print on again restores it; `panels::layers` test `a_layer_that_does_not_print_has_its_name_italic` |
| Layers panel: Alt-drag shows the copy cursor (#8217) | done | rows and the selected-art square dragged over the list show the copy cursor while Alt is held and the grabbing hand otherwise, following Alt mid-drag; on Windows and X11 the copy cursor is the white arrow with a plus (the panels' add cursor, #8241); over the trash and New Layer, which ignore Alt, the hand stays; guide rows keep theirs; `alt_shows_the_copy_cursor_while_rows_are_dragged`, `drag_cursor_shows_a_copy_only_where_the_drop_copies` |
| Gradient panel: add-stop cursor under the ramp (#8241) | done | the white arrow with a plus (the Group Selection glyph) over the strip under the ramp, handed to the OS on Windows and X11 (winit shows the plain arrow for the system copy cursor there), the system copy cursor elsewhere; over the ramp itself the arrow stays; `panels::gradient` test `the_strip_under_the_ramp_shows_the_add_cursor` |
| Layers panel: Alt-drag copies a row beside itself (#8237) | done | with Alt, rows held over one of their own rows copy above or below it, and the bottom layer dropped in the empty space under the list copies below itself, so the top layer dragged up, the bottom one dragged down and a document's only layer are copied; a move onto its own place, or a copy inside itself, still does nothing; `panels::layers` tests `alt_dragging_the_top_layer_up_or_the_bottom_layer_down_copies_it`, `a_lone_layer_alt_dragged_up_or_down_is_copied`; engine test `a_copy_goes_above_or_below_a_row_it_copies` |
| Blend spine Anchor Point conversion and handle editing (#2544) | implemented | symmetric handles, independent drag/retraction, visible-handle policy and selection/stacking covered by tool and engine regressions; Windows native canvas checks and screenshots reviewed in PR #2643 |
| Several blend spine points picked and dragged together (#5285) | done | with Direct Selection, Shift-click picks more points of a selected blend's spine or takes one away, as on a path; dragging any picked point moves them all, and the key objects on them, in one undo step (`object.blend.spine.moveAnchor {with}`); a marquee picks the spine points inside it on the topmost selected blend, and with Shift adds or takes them away |
| Add/Delete/Anchor Point tools; Anchor Point tool drags segments to reshape | done | #2267: a click on a handle end retracts that handle and leaves the anchor a corner with the other one; Shift held at the press on an anchor moves it, handles and all (Shift kept down: at 45° steps) instead of pulling out handles |