Merge main into fix/shortcut-row-names-translated

This commit is contained in:
dotCooCoo
2026-11-16 11:57:36 -08:00
52 changed files with 3158 additions and 184 deletions
+1 -3
View File
@@ -1189,9 +1189,7 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id)));
}
if is_explicit {
for id in &ids {
sel.remove(*id);
}
sel.remove_all(ids.iter().copied());
sel.prune(d);
} else {
sel.clear();
+83 -10
View File
@@ -1238,6 +1238,69 @@ fn expand_node_except(
}
}
/// Replace `n`, a group or layer whose Transform effect's copies each carry the raster effects
/// listed before it ([`effects::outer_effects`]), with its art ([`effects::evaluate_container`]):
/// the copies become groups of their own with those effects, and they and what they hold get ids
/// of their own, so they expand as its members do; the raster effects after the Transform effect
/// stay on `n`. A copy that repeats an id ([`repeats_an_id`]) and holds a random Transform effect
/// ([`has_seeded`]) expands before its ids change ([`expand_in_place`]), as [`expand_pieces`] does,
/// and `members` gets what that expansion lists, by the copy's new id. `kept` gets the new id of
/// each copy of an object `skip` lists, and `out` gets `n` unless `listed` says it is there.
/// Returns whether `n` changed; any other object stays as it is. `Err`, with `n` as it is, when
/// such a copy still holds a random Transform effect after the raster budget left part of it as
/// it is: its new ids would give that effect another seed.
fn copies_carrying_raster(
d: &mut Document,
n: &mut Node,
(brushes, skip): (&[vectorcraft_brush::Brush], &[NodeId]),
kept: &mut Vec<NodeId>,
members: &mut std::collections::HashMap<NodeId, Vec<Listed>>,
(out, listed): (&mut Vec<Listed>, &mut bool),
raster: &mut RasterBudget,
) -> std::result::Result<bool, OverBudget> {
if !carries_copies(n) {
return Ok(false);
}
let Some(mut m) = effects::evaluate_container(Some(&*d), n) else { return Ok(false) };
let mut seen = std::collections::HashSet::from([n.id]);
for c in m.children_mut().into_iter().flatten().filter(|c| !c.is_ruler_guide()) {
let c = Arc::make_mut(c);
let left = raster.left;
let mut expanded = (has_seeded(c) && repeats_an_id(c, &seen)).then(|| expand_in_place(d, c, brushes, skip, raster));
if expanded.is_some() && raster.left > left && has_seeded(c) {
return Err(OverBudget);
}
let mut was = vec![];
if !skip.is_empty() {
c.walk(&mut |n| was.push(n.id));
}
fresh_ids_listed(d, c, &mut seen, expanded.as_deref_mut().unwrap_or_default());
// A copy of an object `skip` lists is left as it is too.
let mut at = 0;
c.walk(&mut |n| {
if was.get(at).is_some_and(|old| *old != n.id && skip.contains(old)) {
kept.push(n.id);
}
at += 1;
});
if let Some(expanded) = expanded {
members.insert(c.id, expanded);
}
}
if !*listed {
out.push((n.id, 0));
*listed = true;
}
*n = m;
Ok(true)
}
/// Is `n` a group or layer whose Transform effect's copies each carry the raster effects listed
/// before it ([`copies_carrying_raster`])?
fn carries_copies(n: &Node) -> bool {
is_container(n) && effects::outer_effects(n).len() != n.appearance.effects.len()
}
/// [`expand_node`] of `n`, which need not be in `d`: `n` with its appearance expanded, `None` when
/// it has nothing to expand. `out` gets the objects whose appearance expands, by places in the walk
/// of the expanded `n`, `n`'s first when its own does. The objects `skip` lists are not expanded.
@@ -1267,10 +1330,13 @@ fn expanded_node(
}
_ => None,
};
// The embedded images before the adjustment, when the raster budget may yet leave `n` as it
// is: the recolored copies the adjustment adds then go again.
let images_before = (effects::has_adjustment(&n) && !rasterfx::raster_fx(&n).is_empty())
// The embedded images before the adjustment and the expansions of the copies
// ([`copies_carrying_raster`]), when the raster budget may yet leave `n` as it is: the
// recolored copies and the images those add then go again.
let images_before = ((effects::has_adjustment(&n) && !rasterfx::raster_fx(&n).is_empty()) || carries_copies(&n))
.then(|| d.images.keys().cloned().collect::<std::collections::HashSet<_>>());
// What the raster budget had left before those expansions: it gets back what they took.
let budget_before = (raster.images, raster.pixels);
if effects::has_adjustment(&n)
&& let Some(m) = effects::adjust_in_document(d, &n, symbol_art)
{
@@ -1316,23 +1382,30 @@ fn expanded_node(
}
return Some(m);
}
// New ids of the copies of objects `skip` lists among the members.
let mut kept = vec![];
// Members of a group or layer that `expand_pieces` or `copies_carrying_raster` expanded, by id,
// with what their expansion lists.
let mut members = std::collections::HashMap::new();
let copies = copies_carrying_raster(d, &mut n, (brushes, skip), &mut kept, &mut members, (out, &mut listed_n), raster);
// Raster effects whose image would go past the budget stay: so does the object, with what is
// inside it and its color adjustments (a symbol instance stays an instance of its symbol).
let Ok(image) = raster_image(d, &n, raster) else {
// inside it and its color adjustments (a symbol instance stays an instance of its symbol), and
// so does a group or layer whose copies keep a random Transform effect the budget left.
let Ok(image) = copies.and_then(|copied| {
changed |= copied;
raster_image(d, &n, raster)
}) else {
out.truncate(listed_before);
if let Some(keys) = images_before {
d.images.retain(|k, _| keys.contains(k));
}
(raster.images, raster.pixels) = budget_before;
return None;
};
let mut v = n.clone();
rasterfx::strip_raster(&mut v, false);
let mut stroke_art =
|d: &mut Document, path: &PathData, rule: FillRule, st: &StrokeLayer| super::pathops::outlined_stroke(d, brushes, path, rule, st);
// Members of a group or layer that `expand_pieces` expanded, by id, with what their expansion lists.
let mut members = std::collections::HashMap::new();
// New ids of the copies of objects `skip` lists among those members.
let mut kept = vec![];
let expanded = match image {
// Blur, feather and inner glow change the object itself: it becomes the image (a layer
// keeps it as its only member).
@@ -1344,7 +1417,7 @@ fn expanded_node(
} else if container {
// A group's or layer's own fills and strokes become art among its members.
effects::evaluate_container(Some(&*d), &v).map(|mut m| {
members = expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art, raster);
members.extend(expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art, raster));
m
})
} else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
+39
View File
@@ -1150,3 +1150,42 @@ fn an_image_past_the_pixels_left_stays_unmade() {
let mut budget = super::RasterBudget { images: 0, pixels, left: 0 };
assert!(super::raster_image(&mut d, &n, &mut budget).is_err(), "no image is left");
}
/// A group whose Transform effect's copies each carry the drop shadow listed before it, with a
/// symbol instance whose random Transform effect takes its seed from the instance's id, stays as it
/// is when the raster budget has no image left for a copy's shadow, with none left or with one for
/// the first copy's: the copies keep the ids their random moves are drawn with, the group draws as
/// before, and the document holds no image the first copy's expansion made, nor the budget its
/// charge.
#[test]
fn copies_the_raster_budget_leaves_keep_their_random_moves() {
let (mut s, id) = session_with_rect();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let id = NodeId(s.execute("symbol.new", &json!({"name": "Box"})).unwrap()["id"].as_u64().unwrap());
let random = json!({"moveH": 40, "moveV": 40, "random": true});
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "distort.transform", "params": random})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let shadow = json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"});
s.execute("effect.apply", &json!({"ids": [g.0], "effect": "stylize.dropShadow", "params": shadow})).unwrap();
s.execute("effect.apply", &json!({"ids": [g.0], "effect": "distort.transform", "params": {"moveV": 150, "copies": 1}})).unwrap();
let draw = |d: &vectorcraft_doc::Document| {
vectorcraft_render::Renderer::new().render(d, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels
};
for images in [0, 1] {
let mut d = s.doc().unwrap().doc.as_ref().clone();
let before = d.node(g).cloned().unwrap();
assert!(effects::outer_effects(&before).len() < before.appearance.effects.len(), "each copy carries the shadow");
let (drawn, keys) = (draw(&d), d.images.keys().cloned().collect::<Vec<_>>());
let mut budget = super::RasterBudget { images, pixels: u64::MAX, left: 0 };
let mut out = vec![];
super::expand_node(&mut d, g, &[], &mut out, &mut budget);
assert!(budget.left > 0, "{images}: a copy's shadow is left");
assert!(out.is_empty(), "{images}: nothing expands: {out:?}");
assert_eq!(d.node(g), Some(&before), "{images}: the group stays as it is");
assert!(draw(&d) == drawn, "{images}: the group draws as before");
assert_eq!(d.images.keys().cloned().collect::<Vec<_>>(), keys, "{images}: no image is added");
assert_eq!((budget.images, budget.pixels), (images, u64::MAX), "{images}: the budget gets back what the copies took");
}
}
+17 -9
View File
@@ -286,16 +286,24 @@ fn editing_copy(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions) -> Option<
/// A `.ai`, or a PDF saved with the editing data, whose PDF part can't be read (`e`, the import's
/// error) from the editor's own copy of its art alone, as a file saved without PDF compatibility
/// is read, its first note saying why: `None` when pages are picked, layers or the editing data
/// are off, or the file has no editing data that reads. Its type is outlines when `opts` asks.
fn without_pdf_part(bytes: &[u8], opts: &LoadOptions, e: &EngineError) -> Option<(Document, Vec<String>)> {
/// is read, its first note saying why. Else `e`: as it is when pages are picked, layers or the
/// editing data are off, or the file has no editing data, and followed by why when the file has
/// editing data that can't be read. Its type is outlines when `opts` asks.
fn without_pdf_part(bytes: &[u8], opts: &LoadOptions, e: EngineError) -> Result<(Document, Vec<String>)> {
if opts.pages.is_some() || !opts.layers || !opts.editing_data {
return None;
return Err(e);
}
let read = vectorcraft_pdf::read_illustrator_data_without_pdf_part(bytes, opts.password.as_deref())
.and_then(|private| private.map(|p| vectorcraft_eps::ai_alone_on_page(&p.data, p.trim, p.user_unit, opts.legacy_names)).transpose());
match read {
Ok(Some((doc, warnings))) => {
let notes =
std::iter::once(format!("the PDF part couldn't be read ({e}): the file opened from its editing data")).chain(warnings).collect();
Ok(outlined_if_asked(doc, notes, opts))
}
Ok(None) => Err(e),
Err(why) => Err(err(format!("{e}; its editing data couldn't be read either ({why})"))),
}
let private = vectorcraft_pdf::illustrator_data_without_pdf_part(bytes, opts.password.as_deref())?;
let (doc, warnings) = vectorcraft_eps::ai_alone_on_page(&private.data, private.trim, private.user_unit, opts.legacy_names).ok()?;
let notes = std::iter::once(format!("the PDF part couldn't be read ({e}): the file opened from its editing data")).chain(warnings).collect();
Some(outlined_if_asked(doc, notes, opts))
}
/// Is `w` a note on the PDF part as a page, which says nothing was skipped: that the art off the
@@ -497,7 +505,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
.inspect(|_| editing_data = true),
// A PDF part that can't be read (a stream the import refuses): the editing copy
// alone where it reads, else the error.
Err(e) => without_pdf_part(bytes, opts, &e).inspect(|_| editing_data = true).ok_or(e),
Err(e) => without_pdf_part(bytes, opts, e).inspect(|_| editing_data = true),
}
})?;
// The File Info of a file read from its pages or its editing copy.
+17 -2
View File
@@ -799,7 +799,7 @@ fn unread_pdf_part(e: &str) -> String {
/// #4366: a `.ai`, or a PDF saved with the editing data, whose PDF part can't be read opens from
/// its editing data, with a first note saying why. Pages picked, layers off or the editing data
/// off keep the error, and so does editing data that can't be read.
/// off keep the error. Editing data that can't be read keeps it too, followed by why.
#[test]
fn a_file_whose_pdf_part_cant_be_read_opens_from_its_editing_data() {
let mut s = Session::new();
@@ -817,10 +817,25 @@ fn a_file_whose_pdf_part_cant_be_read_opens_from_its_editing_data() {
}
for (name, file) in refused_files(b"%AI12_CompressedData not zlib", ai::page_pdf()) {
let plain = open(&mut s, name, &file, json!({"editingData": false})).unwrap_err().to_string();
assert_eq!(open(&mut s, name, &file, json!({})).unwrap_err().to_string(), plain, "{name}");
let both = format!("{plain}; its editing data couldn't be read either (its zlib compression is damaged)");
assert_eq!(open(&mut s, name, &file, json!({})).unwrap_err().to_string(), both, "{name}");
for p in [json!({"pages": "1"}), json!({"layers": false})] {
assert_eq!(open(&mut s, name, &file, p.clone()).unwrap_err().to_string(), plain, "{name}: {p}");
}
}
}
/// #4366: editing data stored in a form the reader doesn't take, beside a PDF part that can't be
/// read, is named in the error.
#[test]
fn the_error_says_why_the_editing_data_couldnt_be_read() {
let mut s = Session::new();
let file = ai::ai_with_private_streams(&compressed(&ai::sample_data()), ai::page_pdf(), REFUSED_CONTENT, "/Filter /Bogus ");
let plain = open(&mut s, "art.ai", &file, json!({"editingData": false})).unwrap_err().to_string();
let e = open(&mut s, "art.ai", &file, json!({})).unwrap_err().to_string();
assert_eq!(e, format!("{plain}; its editing data couldn't be read either (it is stored in a form that isn't read)"));
}
/// A file saved in units of 10 points (`/UserUnit 10`, as in
/// `an_ai_file_with_a_user_unit_opens_at_its_size_in_points`) whose PDF part can't be read opens
/// from its editing data at its size in points.
+140 -44
View File
@@ -4,7 +4,7 @@ use std::collections::BTreeSet;
use serde_json::{Value, json};
use vectorcraft_color::Paint;
use vectorcraft_doc::{Document, LockedArtboards, Node, NodeId, NodeKind};
use vectorcraft_doc::{AnchorRef, Document, LockedArtboards, Node, NodeId, NodeKind, Selection};
use vectorcraft_tools::builder::is_live_paint;
use super::object::can_align;
@@ -930,52 +930,145 @@ fn anchors_many(s: &mut Session, p: &Value) -> Result<Value> {
None if bool_or(p, "add", false) => "add",
None => "set",
};
s.select(|d, sel| {
if mode == "set" {
sel.clear();
}
for (id, refs) in items {
// A segment pick's endpoints aren't selected anchors: start from none of them.
let segment_pick = sel.segments.remove(&id).is_some();
let all: BTreeSet<(usize, usize)> =
d.node(id).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, i, _)| (s, i)).collect()).unwrap_or_default();
// Anything but a path is selected, toggled or deselected as a whole.
if all.is_empty() {
match mode {
"toggle" => sel.toggle(id),
"subtract" => sel.remove(id),
_ => sel.add(id),
}
continue;
}
// From the anchors selected now (all of them for a path selected as a whole).
let now = match sel.partial(id) {
_ if segment_pick => BTreeSet::new(),
Some(a) => a.clone(),
None if sel.contains(id) => all.clone(),
None => BTreeSet::new(),
};
let refs: BTreeSet<(usize, usize)> = refs.intersection(&all).copied().collect();
let next: BTreeSet<(usize, usize)> = match mode {
"toggle" => now.symmetric_difference(&refs).copied().collect(),
"subtract" => now.difference(&refs).copied().collect(),
_ => now.union(&refs).copied().collect(),
};
if next.is_empty() {
sel.remove(id);
continue;
}
sel.add(id);
if next.len() < all.len() {
sel.anchors.insert(id, next);
} else {
sel.anchors.remove(&id);
}
}
})?;
s.select(|d, sel| select_anchor_items(d, sel, items, mode))?;
ok()
}
/// `select.anchorsMany`'s change to `sel`: each item in order, with the selected objects kept in a
/// [`Members`] map while the items run, so that an item's membership check and change don't go
/// through `sel.objects`.
fn select_anchor_items(d: &Document, sel: &mut Selection, items: Vec<(NodeId, BTreeSet<AnchorRef>)>, mode: &str) {
if mode == "set" {
sel.clear();
}
if items.is_empty() {
return;
}
let mut members = Members::of(sel);
for (id, refs) in items {
// A segment pick's endpoints aren't selected anchors: start from none of them.
let segment_pick = sel.segments.remove(&id).is_some();
let all: BTreeSet<AnchorRef> =
d.node(id).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, i, _)| (s, i)).collect()).unwrap_or_default();
// Anything but a path is selected, toggled or deselected as a whole.
if all.is_empty() {
match mode {
"toggle" => members.toggle(sel, id),
"subtract" => members.remove(sel, id),
_ => members.add(sel, id),
}
continue;
}
// From the anchors selected now (all of them for a path selected as a whole).
let now = match sel.partial(id) {
_ if segment_pick => BTreeSet::new(),
Some(a) => a.clone(),
None if members.contains(id) => all.clone(),
None => BTreeSet::new(),
};
let refs: BTreeSet<AnchorRef> = refs.intersection(&all).copied().collect();
let next: BTreeSet<AnchorRef> = match mode {
"toggle" => now.symmetric_difference(&refs).copied().collect(),
"subtract" => now.difference(&refs).copied().collect(),
_ => now.union(&refs).copied().collect(),
};
if next.is_empty() {
members.remove(sel, id);
continue;
}
members.add(sel, id);
if next.len() < all.len() {
sel.anchors.insert(id, next);
} else {
sel.anchors.remove(&id);
}
}
members.finish(sel);
}
/// The selected objects of a [`Selection`] while [`select_anchor_items`] changes them. Each
/// selected id maps to the activation that selected it: 0 for the objects selected before, and
/// a new number for each later [`Members::add`] of an unselected id, which `added` lists in order.
/// [`Members::finish`] writes them back to `objects`.
struct Members {
live: std::collections::HashMap<NodeId, usize>,
added: Vec<(NodeId, usize)>,
removed: bool,
}
impl Members {
fn of(sel: &Selection) -> Self {
count_objects_walk();
Self { live: sel.objects.iter().map(|id| (*id, 0)).collect(), added: Vec::new(), removed: false }
}
fn contains(&self, id: NodeId) -> bool {
self.live.contains_key(&id)
}
/// [`Selection::add`]: clears what any selection change clears, and selects `id` at the end
/// unless it is selected.
fn add(&mut self, sel: &mut Selection, id: NodeId) {
sel.target = None;
sel.slices.clear();
sel.symbol_part = None;
sel.on_path_member = None;
if let std::collections::hash_map::Entry::Vacant(e) = self.live.entry(id) {
let activation = self.added.len() + 1;
e.insert(activation);
self.added.push((id, activation));
}
}
/// [`Selection::remove`]: clears what any selection change clears, and deselects `id` with
/// its anchors, segments, and the key or key anchor it is.
fn remove(&mut self, sel: &mut Selection, id: NodeId) {
sel.target = None;
sel.slices.clear();
sel.symbol_part = None;
sel.on_path_member = None;
if self.live.remove(&id).is_some() {
self.removed = true;
}
sel.anchors.remove(&id);
sel.segments.remove(&id);
if sel.key == Some(id) {
sel.key = None;
}
if sel.key_anchor.is_some_and(|(k, _)| k == id) {
sel.key_anchor = None;
}
}
/// [`Selection::toggle`].
fn toggle(&mut self, sel: &mut Selection, id: NodeId) {
if self.contains(id) { self.remove(sel, id) } else { self.add(sel, id) }
}
/// Writes the selected objects to `sel.objects`: the slots of the objects selected before and
/// still selected by that activation, in their order, then the ids selected since and still
/// selected by the activation that added them, in the order they were added.
fn finish(self, sel: &mut Selection) {
if self.removed {
count_objects_walk();
sel.objects.retain(|id| self.live.get(id) == Some(&0));
}
sel.objects.extend(self.added.into_iter().filter(|(id, n)| self.live.get(id) == Some(n)).map(|(id, _)| id));
}
}
#[cfg(test)]
thread_local! {
/// Tests: how many walks [`select_anchor_items`] made over the selected objects on this thread.
pub(crate) static OBJECTS_WALKS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Tests: count one walk over the selected objects.
fn count_objects_walk() {
#[cfg(test)]
OBJECTS_WALKS.set(OBJECTS_WALKS.get() + 1);
}
/// Select › Same › Fill/Stroke Color: is `a` the same colour as `b`? Tints of one global or spot
/// swatch are, unless `tint` (General › Select Same Tint %) asks for the same tint too.
pub(crate) fn same_paint(a: &Paint, b: &Paint, tint: bool) -> bool {
@@ -1287,3 +1380,6 @@ fn not_pixel_aligned(s: &mut Session, _: &Value) -> Result<Value> {
s.select(|_, sel| sel.set(ids))?;
Ok(json!({ "count": s.doc()?.selection.objects.len() }))
}
#[cfg(test)]
mod tests;
+286
View File
@@ -0,0 +1,286 @@
//! `select.anchorsMany`'s item loop ([`select_anchor_items`]) against a loop that changes the
//! selection one item at a time through [`Selection::add`], [`Selection::remove`] and
//! [`Selection::toggle`].
use std::collections::{BTreeSet, HashSet};
use std::sync::Arc;
use std::time::{Duration, Instant};
use vectorcraft_color::Color;
use vectorcraft_doc::{AnchorRef, Document, NodeId, Selection, SymbolPart};
use vectorcraft_geom::Rect;
use vectorcraft_testkit::fixtures::DocBuilder;
use super::{OBJECTS_WALKS, select_anchor_items};
type Items = Vec<(NodeId, BTreeSet<AnchorRef>)>;
const MODES: [&str; 4] = ["set", "add", "toggle", "subtract"];
/// The item loop through `Selection`'s own methods, each of which goes through `objects`.
fn item_by_item(d: &Document, sel: &mut Selection, items: Items, mode: &str) {
if mode == "set" {
sel.clear();
}
for (id, refs) in items {
let segment_pick = sel.segments.remove(&id).is_some();
let all: BTreeSet<AnchorRef> =
d.node(id).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, i, _)| (s, i)).collect()).unwrap_or_default();
if all.is_empty() {
match mode {
"toggle" => sel.toggle(id),
"subtract" => sel.remove(id),
_ => sel.add(id),
}
continue;
}
let now = match sel.partial(id) {
_ if segment_pick => BTreeSet::new(),
Some(a) => a.clone(),
None if sel.contains(id) => all.clone(),
None => BTreeSet::new(),
};
let refs: BTreeSet<AnchorRef> = refs.intersection(&all).copied().collect();
let next: BTreeSet<AnchorRef> = match mode {
"toggle" => now.symmetric_difference(&refs).copied().collect(),
"subtract" => now.difference(&refs).copied().collect(),
_ => now.union(&refs).copied().collect(),
};
if next.is_empty() {
sel.remove(id);
continue;
}
sel.add(id);
if next.len() < all.len() {
sel.anchors.insert(id, next);
} else {
sel.anchors.remove(&id);
}
}
}
/// A document with `n` four-anchor rectangles and, after them, a group of two more → the
/// rectangles' ids and the group's.
fn doc(n: usize) -> (Document, Vec<NodeId>, NodeId) {
let mut b = DocBuilder::new(2000.0, 2000.0);
let rects = (0..n)
.map(|i| {
let (x, y) = ((i % 200) as f64 * 10.0, (i / 200) as f64 * 10.0);
b.rect(Rect::new(x, y, x + 5.0, y + 5.0), Color::rgb(0.2, 0.4, 0.6), |_| {})
})
.collect();
let black = Color::rgb(0.0, 0.0, 0.0);
let kids = vec![b.rect_node(Rect::new(0.0, 0.0, 1.0, 1.0), black), b.rect_node(Rect::new(2.0, 0.0, 3.0, 1.0), black)];
let group = b.group(kids, false);
(b.build(), rects, group)
}
fn anchors(refs: &[(usize, usize)]) -> BTreeSet<AnchorRef> {
refs.iter().copied().collect()
}
/// A selection with every field set: rectangles 0 to 4 and the group, rectangle 2 listed twice,
/// partial anchors on 1 and 3, a segment pick on 4, rectangle 1 the key, a key anchor on 3, and a
/// target, slices, guides, a key guide, new art, a symbol part and an on-path member.
fn seeded(r: &[NodeId], group: NodeId) -> Selection {
let mut s = Selection { objects: vec![r[0], r[1], r[2], r[3], group, r[2], r[4]], ..Selection::default() };
s.anchors.insert(r[1], anchors(&[(0, 0), (0, 1)]));
s.anchors.insert(r[3], anchors(&[(0, 2)]));
s.anchors.insert(r[4], anchors(&[(0, 0), (0, 1)]));
s.segments.insert(r[4], anchors(&[(0, 0)]));
s.key = Some(r[1]);
s.key_anchor = Some((r[3], (0, 2)));
s.target = Some(r[0]);
s.slices = vec![r[5]];
s.guides = vec![r[6]];
s.key_guide = Some(r[6]);
s.new_art = Arc::new(HashSet::from([r[2]]));
s.symbol_part = Some(SymbolPart { instance: r[0], path: vec![0] });
s.on_path_member = Some(r[7]);
s
}
/// Item lists with repeated ids, removals followed by additions, the group, anchors outside a
/// path, items that empty a path, and the empty list, then pseudo-random lists.
fn item_streams(r: &[NodeId], group: NodeId) -> Vec<Items> {
let all = [(0, 0), (0, 1), (0, 2), (0, 3)];
let mut streams: Vec<Items> = vec![
vec![],
vec![(r[2], anchors(&[(0, 0)]))],
vec![(r[2], anchors(&all)), (r[2], anchors(&all))],
vec![(r[2], anchors(&all)), (r[5], anchors(&[(0, 1)])), (r[2], anchors(&[(0, 3)]))],
vec![(group, anchors(&[])), (group, anchors(&[(0, 0)])), (group, anchors(&[]))],
vec![(r[6], anchors(&[(0, 0)])), (r[6], anchors(&[(0, 0)])), (r[7], anchors(&[(0, 9), (3, 0)]))],
vec![(r[1], anchors(&[(0, 0), (0, 1)])), (r[3], anchors(&[(0, 2)])), (r[1], anchors(&all)), (r[3], anchors(&all))],
vec![(r[4], anchors(&[])), (r[4], anchors(&[(0, 2)]))],
vec![(r[1], anchors(&all)), (r[3], anchors(&all)), (r[1], anchors(&[(0, 0)])), (r[3], anchors(&[(0, 2)]))],
vec![(r[8], anchors(&[(0, 0)])), (r[0], anchors(&all)), (r[8], anchors(&all)), (r[0], anchors(&[(0, 1)]))],
];
let pool: Vec<NodeId> = r.iter().copied().chain([group]).collect();
let mut x: u64 = 0x9e37_79b9_7f4a_7c15;
let mut next = move || {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
x
};
for len in [3, 9, 25, 80, 200] {
let items = (0..len)
.map(|_| {
let id = pool[(next() % pool.len() as u64) as usize];
// Bits 0 to 4 of a draw pick anchors 0 to 3 and one past the end.
let bits = next();
let refs = (0..5).filter(|i| (bits >> i) & 1 == 1).map(|i| (0, i)).collect();
(id, refs)
})
.collect();
streams.push(items);
}
streams
}
/// Starting selections: the seeded one, none, every rectangle whole, and every rectangle with
/// one anchor.
fn starts(r: &[NodeId], group: NodeId) -> Vec<Selection> {
let mut whole = Selection::default();
whole.set(r.iter().copied().chain([group]));
let mut partial = whole.clone();
for id in r {
partial.anchors.insert(*id, anchors(&[(0, 1)]));
}
vec![seeded(r, group), Selection::default(), whole, partial]
}
#[test]
fn anchor_items_do_what_the_item_by_item_loop_does() {
let (d, r, group) = doc(12);
for start in starts(&r, group) {
for items in item_streams(&r, group) {
for mode in MODES {
let mut expected = start.clone();
item_by_item(&d, &mut expected, items.clone(), mode);
let mut got = start.clone();
select_anchor_items(&d, &mut got, items.clone(), mode);
assert_eq!(got, expected, "mode {mode}, items {items:?}, from {start:?}");
assert_eq!(got.new_art, expected.new_art);
}
}
}
}
#[test]
fn a_path_deselected_and_selected_again_goes_last_without_its_key() {
let (d, r, group) = doc(12);
let all = anchors(&[(0, 0), (0, 1), (0, 2), (0, 3)]);
let mut s = seeded(&r, group);
// Toggling the selected anchors of 1 and 3 deselects them; toggling again selects them again.
let items = vec![(r[1], anchors(&[(0, 0), (0, 1)])), (r[3], anchors(&[(0, 2)])), (r[1], anchors(&[(0, 0)])), (r[3], all)];
select_anchor_items(&d, &mut s, items, "toggle");
assert_eq!(s.objects, [r[0], r[2], group, r[2], r[4], r[1], r[3]]);
assert_eq!(s.anchors.get(&r[1]), Some(&anchors(&[(0, 0)])));
assert_eq!(s.anchors.get(&r[3]), None);
assert_eq!((s.key, s.key_anchor), (None, None));
}
/// Every rectangle with one anchor, as a Direct Selection marquee sends them.
fn marquee(r: &[NodeId]) -> Items {
r.iter().map(|id| (*id, anchors(&[(0, 0)]))).collect()
}
/// Every rectangle with all four anchors, which deselects each in subtract mode.
fn every_anchor(r: &[NodeId]) -> Items {
r.iter().map(|id| (*id, anchors(&[(0, 0), (0, 1), (0, 2), (0, 3)]))).collect()
}
#[test]
fn anchor_items_walk_the_selected_objects_at_most_twice() {
let (d, r, group) = doc(2000);
let mut all = Selection::default();
all.set(r.iter().copied().chain([group]));
for (start, items, mode) in [
(Selection::default(), marquee(&r), "set"),
(all.clone(), marquee(&r), "toggle"),
(all.clone(), every_anchor(&r), "subtract"),
(all.clone(), every_anchor(&r).into_iter().chain(marquee(&r)).collect(), "toggle"),
] {
let mut s = start;
OBJECTS_WALKS.set(0);
select_anchor_items(&d, &mut s, items, mode);
let walks = OBJECTS_WALKS.get();
assert!(walks <= 2, "{mode}: {walks} walks over the selected objects");
}
}
/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere.
fn thread_cpu() -> Option<Duration> {
let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?;
stat.split_whitespace().next()?.parse().ok().map(Duration::from_nanos)
}
/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock.
fn time(f: impl FnOnce()) -> Duration {
match thread_cpu() {
Some(before) => {
f();
thread_cpu().map_or(Duration::ZERO, |after| after.saturating_sub(before))
}
None => {
let start = Instant::now();
f();
start.elapsed()
}
}
}
fn ms(d: Duration) -> f64 {
d.as_secs_f64() * 1000.0
}
/// Timings of the item loop and the item-by-item loop on 2,000, 20,000 and 50,000 rectangles, run
/// in turn on clones of the same selection, 7 runs each. Ignored by default; it prints the median,
/// fastest and slowest run and sets no bound on them:
/// `cargo test --release -p vectorcraft-engine --lib anchor_items_perf -- --ignored --nocapture`.
#[test]
#[ignore = "a benchmark: run with --ignored --nocapture"]
fn anchor_items_perf() {
const RUNS: usize = 7;
eprintln!("anchor_items_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" });
eprintln!("anchor_items_perf: {:>6} {:<26} {:>28} {:>28}", "paths", "case", "item by item ms (min-max)", "item loop ms (min-max)");
for n in [2_000, 20_000, 50_000] {
let (d, r, group) = doc(n);
let mut all = Selection::default();
all.set(r.iter().copied().chain([group]));
for (case, start, items, mode) in [
("set, marquee", Selection::default(), marquee(&r), "set"),
("add, marquee", Selection::default(), marquee(&r), "add"),
("toggle, Select All", all.clone(), marquee(&r), "toggle"),
("subtract every anchor", all.clone(), every_anchor(&r), "subtract"),
] {
let (mut old, mut new) = (Vec::new(), Vec::new());
for run in 0..RUNS {
let (mut a, mut b) = (start.clone(), start.clone());
let (ia, ib) = (items.clone(), items.clone());
// The two loops take turns going first.
if run % 2 == 0 {
old.push(time(|| item_by_item(&d, &mut a, ia, mode)));
new.push(time(|| select_anchor_items(&d, &mut b, ib, mode)));
} else {
new.push(time(|| select_anchor_items(&d, &mut b, ib, mode)));
old.push(time(|| item_by_item(&d, &mut a, ia, mode)));
}
assert_eq!(a, b, "{n} paths, {case}");
}
old.sort();
new.sort();
eprintln!(
"anchor_items_perf: {n:>6} {case:<26} {:>10.3} ({:>7.3}-{:>8.3}) {:>10.3} ({:>7.3}-{:>8.3})",
ms(old[RUNS / 2]),
ms(old[0]),
ms(old[RUNS - 1]),
ms(new[RUNS / 2]),
ms(new[0]),
ms(new[RUNS - 1]),
);
}
}
}
+10 -2
View File
@@ -53,7 +53,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
style_delete
),
cmd!("graphicStyle.duplicate", "Duplicate Graphic Style", ["Window", "Graphic Styles"], None, "{name} → {name}", has_doc, style_duplicate),
cmd!(
"graphicStyle.duplicate",
"Duplicate Graphic Style",
["Window", "Graphic Styles"],
None,
"{name} a copy of the style at the end of the list, named `<name> copy` (`<name> copy 2`… when that is taken); no object is linked to it → {name}",
has_doc,
style_duplicate
),
cmd!(
query "graphicStyle.list",
"List Graphic Styles",
@@ -431,7 +439,7 @@ fn style_duplicate(s: &mut Session, p: &Value) -> Result<Value> {
let pos = style_index(d, &name)?;
let nm = unique_name(&format!("{name} copy"), |n| d.graphic_style(n).is_some());
let g = GraphicStyle { name: nm.clone(), id: d.next_graphic_style_id(), ..d.graphic_styles[pos].clone() };
d.graphic_styles.insert(pos + 1, g);
d.graphic_styles.push(g);
Ok(nm)
})?;
Ok(json!({"name": new}))
+130
View File
@@ -302,6 +302,136 @@ fn each_copys_fill_shadow_expands_as_the_canvas_draws_it() {
}
}
/// Each copy of a group's Transform effect draws the drop shadow listed before the effect under
/// itself, of both its squares together and scaled with it, and Expand Appearance keeps those
/// shadows: the squares (20..40 together) have their shadow 20 pt to their right, and their copy
/// scaled 200 % and moved 80 pt down (10..50 across, 90..130 down) has its own 40 pt to its right.
/// A copy moved 30 pt right (50..70) lies under the squares' shadow (40..60), which still paints
/// over it once expanded. The expanded art has no effects left, and each object in it an id of its
/// own.
#[test]
fn each_copys_shadow_on_a_group_expands_as_the_canvas_draws_it() {
let cases = [
(json!({"scaleH": 200, "scaleV": 200, "moveV": 80, "copies": 1}), (80, 110), "the copy's shadow"),
(json!({"moveH": 30, "copies": 1}), (55, 30), "the squares' shadow over the copy"),
];
for (params, (x, y), what) in cases {
let mut s = session();
let mut ids = vec![];
for x in [20, 30] {
ids.push(run(&mut s, "shape.rectangle", json!({"x": x, "y": 20, "width": 10, "height": 20}))["id"].as_u64().unwrap());
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
run(&mut s, "paint.setStroke", json!({"none": true}));
}
run(&mut s, "select.set", json!({"ids": ids}));
run(&mut s, "object.group", json!({}));
let shadow = json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"});
run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": shadow}));
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": params}));
let before = render(&s);
assert_eq!(before.pixel(x, y), [0, 255, 0, 255], "{params}: {what}");
run(&mut s, "effect.expandAppearance", json!({}));
let after = render(&s);
let diff = differing(&before, &after, 64);
assert_eq!(diff, 0, "{params}: {diff} pixels differ");
let doc = &s.doc().unwrap().doc;
let (mut seen, mut count, mut effects) = (std::collections::HashSet::new(), 0, 0);
for l in &doc.layers {
l.walk(&mut |n| {
seen.insert(n.id);
count += 1;
effects += n.appearance.effects.len();
});
}
assert_eq!(seen.len(), count, "{params}: each object has an id of its own");
assert_eq!(effects, 0, "{params}: no effects are left");
}
}
/// A member's random Transform effect takes its seed from the member's id, and the canvas draws
/// every copy of the group with that id: Expand Appearance of a group with a stroke of its own, a
/// shadow and a copying Transform effect gives each copy's symbol instance the same random move, so
/// the copies, 60 pt apart, still draw alike.
#[test]
fn each_copys_random_member_expands_as_the_canvas_draws_it() {
let mut s = session();
let mut ids = vec![];
for x in [20, 50] {
ids.push(run(&mut s, "shape.rectangle", json!({"x": x, "y": 20, "width": 20, "height": 20}))["id"].as_u64().unwrap());
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
run(&mut s, "paint.setStroke", json!({"none": true}));
}
run(&mut s, "select.set", json!({"ids": [ids[0]]}));
ids[0] = run(&mut s, "symbol.new", json!({"name": "Box"}))["id"].as_u64().unwrap();
run(&mut s, "select.set", json!({"ids": [ids[0]]}));
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"moveH": 16, "moveV": 16, "random": true}}));
run(&mut s, "select.set", json!({"ids": ids}));
let g = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap();
run(&mut s, "select.set", json!({"ids": [g]}));
run(&mut s, "appearance.addStroke", json!({}));
assert!(node(&s, NodeId(g)).appearance.items.iter().any(|i| i.visible()), "the group has a stroke of its own");
let shadow = json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"});
run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": shadow}));
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"moveV": 60, "copies": 2}}));
// The pixels of each copy's 60 pt band that differ from the first copy's by more than 64.
let unlike = |r: &vectorcraft_render::Rendered| {
let px = |x: usize, y: usize| {
let i = (y * r.width as usize + x) * 4;
r.pixels.get(i..i + 4).map(<[u8]>::to_vec).unwrap_or_default()
};
let mut n = 0;
for k in [60, 120] {
for y in 0..60 {
for x in 0..r.width as usize {
n += usize::from(px(x, y).iter().zip(px(x, y + k)).any(|(a, b)| a.abs_diff(b) > 64));
}
}
}
n
};
let before = render(&s);
assert_eq!(unlike(&before), 0, "the canvas draws the copies alike");
let art = vectorcraft_render::effects::evaluate_container(Some(&s.doc().unwrap().doc), &node(&s, NodeId(g))).unwrap();
let mut live = 0;
art.walk(&mut |n| live += n.appearance.effects.iter().filter(|e| e.id == "distort.transform").count());
assert_eq!(live, 3, "each copy's instance keeps its random effect live");
run(&mut s, "effect.expandAppearance", json!({}));
let after = render(&s);
assert_eq!(unlike(&after), 0, "the expanded copies draw alike");
assert!(differing(&before, &after, 64) < 200, "the copies stay where they are drawn");
}
/// A member's own Offset Path applies before the copying Transform effect of its group, which has
/// a stroke of its own, whether or not a shadow is listed before that Transform effect: the copy
/// scaled 200 % draws the offset square scaled, with or without a shadow at 0 % opacity.
#[test]
fn a_members_offset_path_applies_before_its_painted_groups_copies() {
let draw = |shadow: bool| {
let mut s = session();
let mut ids = vec![];
for x in [20, 40] {
ids.push(run(&mut s, "shape.rectangle", json!({"x": x, "y": 20, "width": 10, "height": 10}))["id"].as_u64().unwrap());
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
run(&mut s, "paint.setStroke", json!({"none": true}));
}
run(&mut s, "select.set", json!({"ids": [ids[0]]}));
run(&mut s, "effect.apply", json!({"effect": "path.offsetPath", "params": {"offset": 5}}));
run(&mut s, "select.set", json!({"ids": ids}));
let g = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap());
run(&mut s, "appearance.addStroke", json!({}));
if shadow {
let fx = json!({"x": 10, "y": 0, "blur": 0, "opacity": 0, "mode": "normal", "color": "#00ff00"});
run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": fx}));
}
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"scaleH": 200, "scaleV": 200, "moveV": 60, "copies": 1}}));
let n = node(&s, g);
assert_eq!(vectorcraft_render::effects::outer_effects(&n).len() < n.appearance.effects.len(), shadow, "each copy carries the shadow");
render(&s)
};
let diff = differing(&draw(false), &draw(true), 64);
assert_eq!(diff, 0, "{diff} pixels differ");
}
/// Each copy of type's Transform effect draws the drop shadow listed before the effect under
/// itself, scaled with it, and Expand Appearance keeps those shadows: the type's copy, scaled 200 %
/// and moved 80 pt down, has its shadow 40 pt to the right of its letters rather than the type's
+39
View File
@@ -224,6 +224,45 @@ fn shadows_and_glows_keep_their_blend_modes() {
assert_eq!(modes, [vectorcraft_color::BlendMode::Multiply, vectorcraft_color::BlendMode::Screen]);
}
/// Each copy of a group's Transform effect has its own image of the shadow listed before the
/// effect, under that copy: the squares' shadow (40..60) paints over their copy moved 30 pt right
/// (50..70), as on the canvas, and the copies' objects have ids of their own.
#[test]
fn each_copys_shadow_on_a_group_flattens_under_that_copy() {
let mut d = Document::new(200.0, 200.0);
let members = [20.0, 30.0].map(|x| Arc::new(rect(&mut d, Rect::new(x, 40.0, x + 10.0, 60.0), Color::rgb(1.0, 0.0, 0.0))));
let mut g = Node::group(d.alloc_id(), members.to_vec());
g.appearance.effects = vec![
Effect {
id: "stylize.dropShadow".into(),
params: json!({"x": 20.0, "y": 0.0, "blur": 0.0, "opacity": 100.0, "mode": "normal", "color": "#00ff00"}),
visible: true,
},
Effect { id: "distort.transform".into(), params: json!({"moveH": 30.0, "copies": 1}), visible: true },
];
add(&mut d, g);
let canvas = render(&d);
let flat = crate::flatten_raster_effects(&d).unwrap();
let back = render(&flat);
let at = |r: &Rendered, x: usize| {
let i = (50 * r.width as usize + x) * 4;
(r.pixels[i], r.pixels[i + 1], r.pixels[i + 2])
};
for x in [55, 65, 85] {
let (want, got) = (at(&canvas, x), at(&back, x));
assert!(want.0.abs_diff(got.0) < 32 && want.1.abs_diff(got.1) < 32 && want.2.abs_diff(got.2) < 32, "x {x}: {want:?} {got:?}");
}
assert!(at(&back, 55).1 > 200 && at(&back, 55).0 < 60, "the squares' shadow over the copy: {:?}", at(&back, 55));
let (mut seen, mut count) = (std::collections::HashSet::new(), 0);
for l in &flat.layers {
l.walk(&mut |n| {
seen.insert(n.id);
count += 1;
});
}
assert_eq!(seen.len(), count, "each object has an id of its own");
}
#[test]
fn pdf_resolution_cap_warns_once_for_original_object_when_appearance_items_split() {
let mut d = Document::new(300.0, 300.0);
+26
View File
@@ -151,6 +151,32 @@ fn style_names_are_unique() {
assert_ne!(style(&s, "Y copy").id, style(&s, "Y").id);
}
#[test]
fn duplicate_puts_the_copy_at_the_end_of_the_list_in_one_undo_step() {
let mut s = session();
let a = rect(&mut s, 10.0);
run(&mut s, "graphicStyle.new", json!({"name": "S"}));
let names = |s: &Session| s.doc().unwrap().doc.graphic_styles.iter().map(|g| g.name.clone()).collect::<Vec<_>>();
let before = names(&s);
// A style that is not last: the copy still goes after every other style.
let first = before[0].clone();
assert_ne!(first, *before.last().unwrap());
assert_eq!(run(&mut s, "graphicStyle.duplicate", json!({"name": first}))["name"], format!("{first} copy"));
let after = names(&s);
assert_eq!(after[..before.len()], before[..]);
assert_eq!(after.last(), Some(&format!("{first} copy")));
let (src, copy) = (style(&s, &first), style(&s, &format!("{first} copy")));
assert_eq!(copy.appearance, src.appearance);
assert_ne!(copy.id, src.id);
// Nothing is linked to the copy, and the source keeps its links.
assert!(linked(&mut s, &format!("{first} copy")).is_empty());
assert_eq!(linked(&mut s, "S"), vec![a.0]);
run(&mut s, "edit.undo", json!({}));
assert_eq!(names(&s), before);
assert!(s.execute("graphicStyle.duplicate", &json!({"name": "nope"})).is_err());
assert_eq!(names(&s), before);
}
/// Three rectangles: `a` (the source of style "S"), `b` and `c`, all linked to "S".
fn linked_three(s: &mut Session) -> (NodeId, NodeId, NodeId) {
let a = rect(s, 10.0);