From 0ee110abfedad98cb72fd8c7b9e8d0c1e960ef75 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 10:19:28 -0800 Subject: [PATCH] Appearance: row edits look up written objects in a set appearance.setItem, appearance.duplicateItem and fill and stroke edits aimed at a row (`item`) keep, for graph labels and lines, the objects whose shown row the edit wrote. Each object was looked up in a list of the written objects, so that step took time that grows with the square of the number of objects. The written objects are now collected into a set first. The objects kept, their order and the rows a graph keeps are the same. crates/engine/examples/appearance_rows_bench.rs times both lookups on the same ids in one process and the whole commands. With 20,000 squares, each command given every square's id, the lookup takes 0.4 ms of thread CPU time on Linux against 57 ms, and appearance.setItem takes 96 ms against 158 ms. At 2,000 objects the difference is about 2 ms. --- .../engine/examples/appearance_rows_bench.rs | 164 ++++++++++++++++++ crates/engine/src/cmd/appearance.rs | 9 +- crates/engine/src/cmd/graph/tests.rs | 75 ++++++++ docs/target-app-parity.md | 1 + 4 files changed, 245 insertions(+), 4 deletions(-) create mode 100644 crates/engine/examples/appearance_rows_bench.rs diff --git a/crates/engine/examples/appearance_rows_bench.rs b/crates/engine/examples/appearance_rows_bench.rs new file mode 100644 index 0000000000..13606fb7e2 --- /dev/null +++ b/crates/engine/examples/appearance_rows_bench.rs @@ -0,0 +1,164 @@ +//! `cargo run --release -p vectorcraft-engine --example appearance_rows_bench` prints the time three Appearance row edits +//! take with every path of documents of 2,000, 10,000 and 20,000 squares selected, each square with one fill row and one +//! stroke row. For each size it first times the step that keeps the objects whose shown rows the edit wrote, on the same +//! ids, two ways: each id looked up in the list of written objects (a list of ids, and a list of ids with the kind of row, +//! as the commands held them), and each id looked up in a set built from that list. It checks that both ways keep the +//! same ids in the same order. Then it times the whole `appearance.setItem` (`index` 1, `weight` 2), +//! `appearance.duplicateItem` (`index` 0) and `stroke.set` (`item` 1, `weight` 2) commands, each on a fresh copy of the +//! document made before the clock starts. +//! 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. The two lookup +//! ways run in alternating order. +// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::HashSet; +use std::hint::black_box; +use std::time::Instant; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId}; +use vectorcraft_engine::Session; +use vectorcraft_geom::{Anchor, PathData, Point, SubPath}; + +fn iters() -> usize { + std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1) +} + +/// The thread's CPU time in ns, or `None` where `/proc/thread-self/schedstat` cannot be read. +fn cpu_ns() -> Option { + 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 { + v.sort_by(f64::total_cmp); + v[v.len() / 2] +} + +/// `n` closed 10 pt squares, each with a red fill row and a 1 pt black stroke row, and their ids in paint order. +fn document(n: usize) -> (Document, Vec) { + let mut doc = Document::new(4000.0, 4000.0); + let layer = doc.layers.first().map(|l| l.id); + let mut ids = Vec::with_capacity(n); + for i in 0..n { + let (x, y) = ((i % 200) as f64 * 12.0, (i / 200) as f64 * 12.0); + let corners = [(x, y), (x + 10.0, y), (x + 10.0, y + 10.0), (x, y + 10.0)]; + let path = PathData::single(SubPath::new(corners.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), true)); + let id = doc.alloc_id(); + let looks = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::BLACK), 1.0); + doc.insert(layer, usize::MAX, Node::path(id, path, looks)).unwrap(); + ids.push(id); + } + (doc, ids) +} + +/// The ids among `ids` that `wrote` holds, each looked up in the list: the lookup the row edits made. +fn in_list(ids: Vec, wrote: &[NodeId]) -> Vec { + ids.into_iter().filter(|id| wrote.contains(id)).collect() +} + +/// [`in_list`] with each id looked up in a set built from `wrote`. +fn in_set(ids: Vec, wrote: &[NodeId]) -> Vec { + let wrote: HashSet = wrote.iter().copied().collect(); + ids.into_iter().filter(|id| wrote.contains(id)).collect() +} + +/// The ids among `ids` that `edited` holds with either kind of row, each looked up in the list, as `appearance.setItem` +/// did. +fn in_kind_list(ids: Vec, edited: &[(NodeId, bool)]) -> Vec { + ids.into_iter().filter(|id| edited.iter().any(|(e, _)| e == id)).collect() +} + +/// [`in_kind_list`] with each id looked up in a set built from the ids of `edited`. +fn in_kind_set(ids: Vec, edited: &[(NodeId, bool)]) -> Vec { + let wrote: HashSet = edited.iter().map(|(id, _)| *id).collect(); + ids.into_iter().filter(|id| wrote.contains(id)).collect() +} + +fn row(name: &str, ms: f64) { + println!(" {name:<52} {ms:>10.3} ms"); +} + +/// The medians of `old` and `new` over [`iters`] runs, alternating which goes first; each run filters `ids` `reps` times +/// on copies made before the clock starts and gives the time of one. +fn time_both(ids: &[NodeId], wrote: &W, old: fn(Vec, &W) -> Vec, new: fn(Vec, &W) -> Vec) -> (f64, f64) { + let reps = (200_000 / ids.len()).max(1); + let run = |f: fn(Vec, &W) -> Vec| { + let mut work: Vec> = (0..reps).map(|_| ids.to_vec()).collect(); + ms(|| { + for it in &mut work { + black_box(f(black_box(std::mem::take(it)), wrote)); + } + }) / reps as f64 + }; + let (mut a, mut b) = (vec![], vec![]); + for i in 0..iters() { + if i % 2 == 0 { + a.push(run(old)); + b.push(run(new)); + } else { + b.push(run(new)); + a.push(run(old)); + } + } + (median(a), median(b)) +} + +fn bench(n: usize) { + println!("{n} squares, all selected"); + let (doc, ids) = document(n); + // Every object's topmost stroke row was written, as when every selected object takes the edit. + let edited: Vec<(NodeId, bool)> = ids.iter().map(|id| (*id, false)).collect(); + // A list missing every other id, so lookups that fail are timed too. + let half: Vec = ids.iter().copied().step_by(2).collect(); + for wrote in [&ids, &half] { + assert_eq!(in_list(ids.clone(), wrote), in_set(ids.clone(), wrote), "both ways keep the same ids"); + } + assert_eq!(in_kind_list(ids.clone(), &edited), in_kind_set(ids.clone(), &edited), "both ways keep the same ids"); + let (old, new) = time_both(&ids, ids.as_slice(), in_list, in_set); + row("keep written ids, every id in the list", old); + row("keep written ids, every id in a set", new); + let (old, new) = time_both(&ids, half.as_slice(), in_list, in_set); + row("keep written ids, half the ids in the list", old); + row("keep written ids, half the ids in a set", new); + let (old, new) = time_both(&ids, edited.as_slice(), in_kind_list, in_kind_set); + row("keep written ids, (id, kind) list", old); + row("keep written ids, (id, kind) set", new); + + let all: Vec = ids.iter().map(|id| id.0).collect(); + let commands: [(&str, Value); 3] = [ + ("appearance.setItem", json!({"ids": all, "index": 1, "weight": 2})), + ("appearance.duplicateItem", json!({"ids": all, "index": 0})), + ("stroke.set", json!({"ids": all, "item": 1, "weight": 2})), + ]; + for (cmd, p) in &commands { + let runs = (0..iters()) + .map(|_| { + let mut s = Session::new(); + s.add_document(doc.clone(), None); + let t = ms(|| drop(black_box(s.execute(cmd, p).unwrap()))); + drop(black_box(s)); + t + }) + .collect(); + row(&format!("{cmd}, whole command"), median(runs)); + } +} + +fn main() { + println!("{}", if cpu_ns().is_some() { "thread CPU time, median of runs" } else { "wall time, median of runs" }); + for n in [2_000, 10_000, 20_000] { + bench(n); + } +} diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 84596eb53c..1b14e25391 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -772,7 +772,7 @@ fn edit_items_writing_then( // The objects whose rows `f` edited: on type, no row means its characters. let mut rows = Vec::new(); // The objects where `f` wrote the topmost visible row of its kind. - let mut wrote = Vec::new(); + let mut wrote = HashSet::new(); // The row of each object `f` wrote: its index, else the topmost row of the kind. let mut written = Vec::new(); for (id, item) in ids.iter().zip(&per) { @@ -785,7 +785,7 @@ fn edit_items_writing_then( rows.push(*id); } if index.is_none_or(|i| is_top_shown(n, i)) { - wrote.push(*id); + wrote.insert(*id); } written.extend(index.or_else(|| n.appearance.items.iter().rposition(|it| it.is_fill() == fill)).map(|at| (*id, at))); } @@ -1341,7 +1341,8 @@ fn set_item(s: &mut Session, p: &Value) -> Result { let mut rows = top_paint_changed(&before, d, &ids); rows.extend(painted_rows(d, written)); let painted = super::graph::capture_series_top_paints(d, &rows); - let reached = shown_rows_edited(&before, d, reached, |id| edited.iter().any(|(e, _)| *e == id)); + let wrote: HashSet = edited.iter().map(|(id, _)| *id).collect(); + let reached = shown_rows_edited(&before, d, reached, |id| wrote.contains(&id)); let labels = capture_row_edits(&before, d, &reached); // A graph line keeps what was written to its topmost visible row, also when it already showed it. let tops: Vec<(NodeId, usize)> = ids.iter().zip(&per).filter_map(|(id, at)| Some((*id, *at.first()?))).collect(); @@ -1503,7 +1504,7 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result { } super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids)); let mut rows = top_paint_changed(&before, d, &ids); - let top_copies: Vec = added.iter().map(|(id, _)| *id).collect(); + let top_copies: HashSet = added.iter().map(|(id, _)| *id).collect(); rows.extend(painted_rows(d, added)); super::graph::capture_series_top_paints(d, &rows); capture_row_edits(&before, d, &shown_rows_edited(&before, d, reached, |id| top_copies.contains(&id))); diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index b74dd97454..5d50fb9c39 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -7406,6 +7406,81 @@ fn the_last_label_of_a_kind_edited_together_sets_what_it_keeps() { assert_eq!(kept(&s), "#ff0000"); } +/// A column graph, a 10 pt square with one red fill row, and the category labels Q1, Q2 and Q3: Q1 and Q3 have one red +/// fill row, Q2 a hidden red fill row under a green one, and Q1's row is then painted blue, which the kind keeps. +/// Returns the graph, the square and the three labels. +fn labels_with_hidden_and_shown_rows(s: &mut Session) -> (NodeId, NodeId, [NodeId; 3]) { + use vectorcraft_doc::{AppearanceItem, FillLayer}; + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(s, "column"); + let square = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + let labels = ["Q1", "Q2", "Q3"].map(|t| text_id(s, id, "Axes", t)); + let fill = |hex: &str, visible: bool| { + AppearanceItem::Fill(FillLayer { visible, ..FillLayer::new(Paint::solid(vectorcraft_color::Color::from_hex(hex).unwrap())) }) + }; + s.edit("Rows", |d, _| { + for (l, items) in [ + (square, vec![fill("#ff0000", true)]), + (labels[0], vec![fill("#ff0000", true)]), + (labels[1], vec![fill("#ff0000", false), fill("#00ff00", true)]), + (labels[2], vec![fill("#ff0000", true)]), + ] { + d.node_mut(l).unwrap().appearance.items = items; + } + Ok(()) + }) + .unwrap(); + s.execute("appearance.setItem", &json!({"ids": [labels[0].0], "index": 0, "color": "#0000ff"})).unwrap(); + assert_eq!(kept_category_fill(s, id), Some("#0000ff".into())); + (id, square, labels) +} + +/// The fill of the category label rows graph `id` keeps, as a hex color. +fn kept_category_fill(s: &Session, id: NodeId) -> Option { + spec(s, id).label_styles.categories_rows.and_then(|r| r.paint.fill).and_then(|p| p.color()).map(|c| c.to_hex()) +} + +/// Row edits on several labels at once, with a plain object among them, keep for the kind what the last label whose shown +/// row the edit wrote shows, also when that row comes out as it was; a label whose hidden row the edit wrote is left out. +/// One undo takes it back. Covers `appearance.setItem`, `appearance.duplicateItem` and `paint.setFill` with `item`. +#[test] +fn row_edits_on_several_labels_keep_the_last_written_shown_row() { + let edits = [ + ("appearance.setItem", json!({"index": 0, "color": "#ff0000"})), + ("appearance.duplicateItem", json!({"index": 0})), + ("paint.setFill", json!({"item": 0, "color": "#ff0000"})), + ]; + for (cmd, mut p) in edits { + let mut s = Session::new(); + let (id, square, [_, q2, q3]) = labels_with_hidden_and_shown_rows(&mut s); + // Q3 shows red before and after the edit; Q2 shows green over the hidden row the edit writes. + p["ids"] = json!([q3.0, square.0, q2.0]); + s.execute(cmd, &p).unwrap(); + assert_eq!(kept_category_fill(&s, id), Some("#ff0000".into()), "{cmd}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(kept_category_fill(&s, id), Some("#0000ff".into()), "{cmd}: undo"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(kept_category_fill(&s, id), Some("#ff0000".into()), "{cmd}: redo"); + s.execute("edit.undo", &json!({})).unwrap(); + // Only the hidden row of a label: the kind keeps blue. + let steps = s.doc().unwrap().history.undo.len(); + p["ids"] = json!([square.0, q2.0]); + s.execute(cmd, &p).unwrap(); + assert_eq!(kept_category_fill(&s, id), Some("#0000ff".into()), "{cmd}: hidden row only"); + while s.doc().unwrap().history.undo.len() > steps { + s.execute("edit.undo", &json!({})).unwrap(); + } + // Q2's shown green row, written as it was: the kind keeps green. + p["ids"] = json!([q2.0]); + p[if cmd == "paint.setFill" { "item" } else { "index" }] = json!(1); + if cmd != "appearance.duplicateItem" { + p["color"] = json!("#00ff00"); + } + s.execute(cmd, &p).unwrap(); + assert_eq!(kept_category_fill(&s, id), Some("#00ff00".into()), "{cmd}: the shown row written as it was"); + } +} + /// A label's object opacity and blend mode set without a row (`transparency.set` without `item`) are kept for its kind. #[test] fn a_labels_object_opacity_and_blend_mode_are_kept_for_its_kind() { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..49f469ae2d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1815,6 +1815,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The [About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) page describes up to five Pattern brush tiles: sides, inner corner, outer corner, beginning and end. The archived [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page says to add pattern tiles to the Swatches panel and select a swatch from the scroll list for each tile. Pattern Brush Options offers document pattern swatches in all five tile menus, including swatches named like built-in choices. The brush copies each swatch's whole art and tile frame. Side requires art; explicit None on a corner prevents fallback to the other corner's art. After a swatch is deleted, the brush keeps drawing its copied art and shows it as Original. The cited pages do not describe copying the whole art, requiring Side, suppressing corner fallback after explicit None, or showing deleted swatch art as Original. `brush.options` accepts swatch names and an object form for names that match built-in choices, and rejects unknown patterns before editing. Evidence: `tests::brushsym::pattern_tile_choices_copy_whole_swatch_art_and_reject_invalid_side` and `tests::brushsym::pattern_tile_object_selects_reserved_swatch_names` (vectorcraft-engine), `tests::pattern_corner_source_none_leaves_that_kind_of_corner_empty` (vectorcraft-brush), and `dialogs::brush_options::tests::pattern_tile_menus_use_document_patterns_and_side_none_keeps_dialog_open`, `dialogs::brush_options::tests::pattern_options_borrowed_swatch_corner_keeps_its_frame`, and `dialogs::brush_options::tests::pattern_options_selects_swatches_with_reserved_names` (vectorcraft-ui-egui). - **Appearance:** the Appearance panel's selected row drives every paint, stroke, gradient and transparency edit (`item` on the commands); effects apply to one fill or stroke; per-item Opacity popups, whose blend-mode list and opacity slider stay open inside them (#430; the Control bar's Stroke popover too); Mixed Appearances, Layers target dots and basic-appearance rules. Effects can be reordered, moved between items and copied by dragging; Show All Hidden Attributes; clicking an effect edits it in place; the object thumbnail drags onto art; effects render on type, images, symbols, blends, envelopes, meshes and repeats, and per-item raster effects export. Groups, layers and type have their own fills, strokes and effects (Contents and Characters rows); the Layers panel's target circles target layers, groups and objects; Expand Appearance turns fills, strokes, effects and brushes into objects. Fill and stroke paint (Fill, Stroke, None, Apply Last Color and Apply Last Gradient, also on characters selected with the Type tool), the Stroke panel's options, gradient and freeform point edits, Swap Fill and Stroke, Default Fill and Stroke, the Eyedropper, and the Appearance panel's item edits, Clear Appearance, Reduce to Basic Appearance, Remove Item, item reordering and Move Appearance record no undo step when they change nothing. + The Appearance panel's row edits (`appearance.setItem`), Duplicate Item (`appearance.duplicateItem`) and fill and stroke edits aimed at a row (`item`) look up which objects had their shown row written in a set, so that step takes time in step with the number of objects. With 20,000 squares, each with one fill and one stroke row and each command given every square's id, that step takes 0.4 ms of thread CPU time on Linux instead of 57 to 63 ms, and the whole `appearance.setItem` command takes 96 ms instead of 158 ms; at 2,000 objects the difference is about 2 ms (`crates/engine/examples/appearance_rows_bench.rs`; `cmd::graph::tests::row_edits_on_several_labels_keep_the_last_written_shown_row`). A Layers panel target circle dropped on the panel's Delete Selection button reduces that layer, group or object to basic appearance (`appearance.reduceToBasic`) in one undo step and deletes nothing, as the [Appearance attributes](https://helpx.adobe.com/illustrator/using/appearance-attributes.html) help page describes for that drag. Which fill and stroke stay (the topmost visible ones), that a layer or group keeps only the rows it had, and that the object's opacity and blend mode stay are VectorCraft's own rules (`panels::layers` test `dropping_a_target_circle_on_the_trash_reduces_it_to_basic_appearance`). The Add New Effect popup (Appearance panel, Properties), the Appearance panel's swatch picker, the Gradient panel's gradient swatches menu and the Image Trace button's list of presets stop at the bottom of a short window, and the mouse wheel or the scroll bar reaches their last rows. A list that fits does not scroll (`a_long_swatch_picker_scrolls_inside_a_short_window`). An image's own fills and strokes draw the shape that a Convert to Shape or Outline Object effect on them gives them (the image's box, or the outline of the image's opaque area or its frame, reshaped by the effects after it), under or over the image as its Contents row says, on the canvas, in exports and through Expand Appearance; new fills and strokes on an image go under it. Without one of those effects they draw nothing, and Use Preview Bounds then measures an image by its frame.