Symbols: the panel reads the current symbol without running symbol.list

The Symbols panel and its panel menu asked for the current symbol on
every frame by running symbol.list, which builds a row per symbol and
walks the whole document once per symbol to count its instances. They
now read it from the active document with cmd::current_symbol, the
rule symbol.list itself uses for its `current`: the stored name while
a symbol has it, else the first symbol. symbol.sortByName,
symbol.place, symbol.options and text.insertInline use the same
function, and symbol.list's reply is unchanged.

An idle frame of the panel or its menu now runs no command, so on
macOS the native menu is not brought up to date on every frame while
the panel is open. In a document with 200 symbols and 50,000 objects
the read takes 0.035 us instead of 48.5 ms in a release build (thread
CPU time on Linux, median of 7 runs). The gain matters on large
documents; on small ones it is too small to notice.
This commit is contained in:
dotCooCoo
2026-11-16 05:29:31 -08:00
parent 7452b6f383
commit 75b02ea8df
7 changed files with 206 additions and 26 deletions
+4
View File
@@ -893,6 +893,10 @@ pub use buildcmds::live_paint_gaps;
/// Control bar enable it when it changes one).
pub use brushsym::reset_transformation_changes;
/// The Symbols panel's current symbol, as `symbol.list` answers it (the panel reads it on every
/// frame without running the command).
pub use brushsym::current_symbol;
/// The byte order of UTF-16 text without a byte-order mark, by Import Data Sets' rule (the Graph
/// Data window reads files by it too).
pub use variablecmds::utf16_order_without_mark;
+3
View File
@@ -27,6 +27,9 @@ use crate::EngineError;
/// Whether Reset Transformation changes a symbol instance.
pub use symbols::reset_transformation_changes;
/// The Symbols panel's current symbol, as `symbol.list` answers it.
pub use symbols::current_symbol;
mod brushes;
mod dynamic;
mod symbols;
+12 -11
View File
@@ -162,7 +162,7 @@ pub(super) fn symbol_sort(s: &mut Session, _: &Value) -> Result<Value> {
if d.symbols.is_sorted_by_key(key) {
return ok();
}
let current = current_symbol(d).or_else(|| symbol_names(d).into_iter().next());
let current = current_symbol(d);
s.edit("Sort by Name", |d, _| {
if let Some(name) = current {
d.unknown.insert(CURRENT_SYMBOL.into(), json!(name));
@@ -173,12 +173,15 @@ pub(super) fn symbol_sort(s: &mut Session, _: &Value) -> Result<Value> {
ok()
}
fn symbol_names(d: &Document) -> Vec<String> {
d.symbols.iter().map(|s| s.name.clone()).collect()
}
fn current_symbol(d: &Document) -> Option<String> {
d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str).filter(|n| d.symbols.iter().any(|s| s.name == *n)).map(str::to_string)
/// The Symbols panel's current symbol, as `symbol.list` answers it: the stored current symbol
/// while `d` has a symbol of that name, else the first symbol; `None` when `d` has no symbols.
pub fn current_symbol(d: &Document) -> Option<String> {
d.unknown
.get(CURRENT_SYMBOL)
.and_then(Value::as_str)
.filter(|n| d.symbols.iter().any(|s| s.name == *n))
.or_else(|| d.symbols.first().map(|s| s.name.as_str()))
.map(str::to_string)
}
pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result<Value> {
@@ -200,7 +203,7 @@ pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result<Value> {
})
})
.collect();
Ok(json!({ "symbols": list, "current": current_symbol(d).or_else(|| symbol_names(d).into_iter().next()) }))
Ok(json!({ "symbols": list, "current": current_symbol(d) }))
}
/// Store `art` ([`normalize`]d, of natural size `size`) as symbol `name`, which becomes the
@@ -398,9 +401,7 @@ fn resolve_symbol(d: &Document, p: &Value, cmd: &str) -> Result<String> {
match str_param(p, "name") {
Some(n) if d.symbols.iter().any(|s| s.name == n) => Ok(n.to_string()),
Some(n) => Err(bad(cmd, format!("no symbol named `{n}`"))),
None => {
current_symbol(d).or_else(|| symbol_names(d).into_iter().next()).ok_or_else(|| EngineError::Other("the document has no symbols".into()))
}
None => current_symbol(d).ok_or_else(|| EngineError::Other("the document has no symbols".into())),
}
}
+1 -10
View File
@@ -6,6 +6,7 @@ use vectorcraft_doc::text::INLINE_MAX_SCALE;
use vectorcraft_doc::{Document, InlineArt, NodeId, NodeKind, TextRun};
use vectorcraft_text::edit;
use super::brushsym::current_symbol;
use super::typecmd::refresh_bounds;
use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_doc, id_param, str_param};
@@ -97,13 +98,3 @@ fn insert_inline(s: &mut Session, p: &Value) -> Result<Value> {
}
Ok(json!({"id": id.0, "caret": caret}))
}
/// The Symbols panel's current symbol, else the first one.
fn current_symbol(d: &Document) -> Option<String> {
d.unknown
.get("currentSymbol")
.and_then(Value::as_str)
.filter(|n| d.symbols.iter().any(|s| s.name == *n))
.map(str::to_string)
.or_else(|| d.symbols.first().map(|s| s.name.clone()))
}
+47
View File
@@ -2599,3 +2599,50 @@ fn symbol_sort_by_name_orders_the_symbols_in_one_undo_step() {
s.execute("symbol.sortByName", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), before);
}
/// `cmd::current_symbol` answers what `symbol.list` answers as `current`, and what `rule` (the
/// stored name while a symbol has it, else the first of all the names) answers:
/// with no symbols, with no stored name, with a stored name that is not first, after the current
/// symbol is deleted, with a stored name no symbol has and with a stored value that is not text.
#[test]
fn current_symbol_is_the_current_symbol_list_answers() {
fn rule(d: &Document) -> Option<String> {
let names: Vec<String> = d.symbols.iter().map(|s| s.name.clone()).collect();
let stored = d.unknown.get("currentSymbol").and_then(Value::as_str).filter(|n| d.symbols.iter().any(|s| s.name == *n)).map(str::to_string);
stored.or_else(|| names.into_iter().next())
}
fn check(s: &mut Session, want: Option<&str>, case: &str) {
let listed = s.execute("symbol.list", &json!({})).unwrap()["current"].clone();
let d = &s.doc().unwrap().doc;
let helper = crate::cmd::current_symbol(d);
assert_eq!(helper.as_deref(), want, "{case}");
assert_eq!(json!(helper), listed, "{case}: symbol.list");
assert_eq!(helper, rule(d), "{case}: the rule");
}
fn store(s: &mut Session, v: Value) {
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).unknown.insert("currentSymbol".into(), v);
}
let mut s = session();
check(&mut s, None, "no symbols");
store(&mut s, json!("Gone"));
check(&mut s, None, "no symbols and a stored name");
for (i, name) in ["A", "B", "C"].into_iter().enumerate() {
rect(&mut s, 20.0 * i as f64, 0.0, 10.0, 10.0);
s.execute("symbol.new", &json!({"name": name})).unwrap();
}
check(&mut s, Some("C"), "the newest symbol is current");
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).unknown.remove("currentSymbol");
check(&mut s, Some("A"), "no stored name");
s.execute("symbol.setCurrent", &json!({"name": "B"})).unwrap();
check(&mut s, Some("B"), "a stored name that is not first");
s.execute("symbol.delete", &json!({"name": "B"})).unwrap();
check(&mut s, Some("A"), "the current symbol deleted");
store(&mut s, json!("Renamed"));
check(&mut s, Some("A"), "a stored name no symbol has");
store(&mut s, json!(3));
check(&mut s, Some("A"), "a stored number");
store(&mut s, json!(["C"]));
check(&mut s, Some("A"), "a stored list");
store(&mut s, json!("C"));
check(&mut s, Some("C"), "a stored name that is last");
}
+138 -5
View File
@@ -133,8 +133,10 @@ pub(crate) fn chip(ui: &Ui, doc: &Document, keys: &Thumbs, r: egui::Rect, name:
}
}
fn current(app: &mut VectorcraftApp) -> Option<String> {
app.run("symbol.list", json!({})).ok().and_then(|v| v["current"].as_str().map(str::to_string))
/// The active document's current symbol (`symbol.list`'s `current`), read without running a
/// command; `None` without a document or symbols.
fn current(app: &VectorcraftApp) -> Option<String> {
app.session.active().and_then(|st| vectorcraft_engine::cmd::current_symbol(&st.doc))
}
/// Does the selection hold (in it or in its groups) a symbol instance that `wanted` takes?
@@ -1189,7 +1191,7 @@ mod tests {
let tile = pos2(26.0, 26.0);
frame(&ctx, &mut app, vec![]);
frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile), button(tile, true), button(tile, false)]);
assert_eq!((editing(&app), current(&mut app)), (None, Some("Leaf".into())), "a click makes it current");
assert_eq!((editing(&app), current(&app)), (None, Some("Leaf".into())), "a click makes it current");
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
frame(&ctx, &mut app, vec![]);
@@ -1265,7 +1267,7 @@ mod tests {
let row = rows[2].1;
app.run("symbol.setCurrent", json!({"name": "ant"})).unwrap();
frame(&ctx, &mut app, vec![egui::Event::PointerMoved(row), button(row, true), button(row, false)]);
assert_eq!((editing(&app), current(&mut app)), (None, Some("Cat".into())), "{view}");
assert_eq!((editing(&app), current(&app)), (None, Some("Cat".into())), "{view}");
let ctx2 = egui::Context::default();
crate::theme::install_fonts(&ctx2);
frame(&ctx2, &mut app, vec![]);
@@ -1674,7 +1676,7 @@ mod tests {
app.run("edit.clear", json!({"ids": [id_b]})).unwrap();
// Currently "B" is the current symbol
assert_eq!(current(&mut app), Some("B".to_string()));
assert_eq!(current(&app), Some("B".to_string()));
let mut h = egui_kittest::Harness::builder().with_size(vec2(260.0, 400.0)).with_accessibility_check(false).build_ui_state(
|ui, app: &mut VectorcraftApp| {
@@ -1834,4 +1836,135 @@ mod tests {
let (left, reserve) = room.expect("the row was drawn");
assert!(left >= reserve, "{left} pt left after the symbol controls, {reserve} pt reserved");
}
/// The current symbol as `symbol.list` answers it, read by running the command.
fn listed_current(app: &mut VectorcraftApp) -> Option<String> {
app.run("symbol.list", json!({})).ok().and_then(|v| v["current"].as_str().map(str::to_string))
}
fn store_current(app: &mut VectorcraftApp, v: Value) {
Arc::make_mut(&mut app.session.doc_mut().unwrap().doc).unknown.insert("currentSymbol".into(), v);
}
/// The panel's current symbol is the one `symbol.list` answers: with no document, with no
/// symbols, with several symbols, with an instance of another symbol selected, and with a
/// stored name no symbol has.
#[test]
fn current_is_the_current_symbol_list_answers() {
fn check(app: &mut VectorcraftApp, want: Option<&str>, case: &str) {
let read = current(app);
assert_eq!(read.as_deref(), want, "{case}");
assert_eq!(read, listed_current(app), "{case}: symbol.list");
}
let mut app = VectorcraftApp::new(Session::new(), Default::default());
check(&mut app, None, "no document");
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
check(&mut app, None, "a document without symbols");
for (name, x) in [("Leaf", 10), ("Dot", 80), ("Star", 150)] {
app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 30, "height": 30})).unwrap();
app.run("symbol.new", json!({"name": name})).unwrap();
}
check(&mut app, Some("Star"), "several symbols, the newest current");
app.run("symbol.setCurrent", json!({"name": "Leaf"})).unwrap();
check(&mut app, Some("Leaf"), "the first symbol made current");
let dot = instance_of(&app, "Dot").expect("a Dot instance");
app.run("select.set", json!({"ids": [dot.0]})).unwrap();
check(&mut app, Some("Leaf"), "an instance of Dot selected");
app.run("symbol.setCurrent", json!({"name": "Dot"})).unwrap();
check(&mut app, Some("Dot"), "a symbol that is not first");
store_current(&mut app, json!("Gone"));
check(&mut app, Some("Leaf"), "a stored name no symbol has");
store_current(&mut app, json!(7));
check(&mut app, Some("Leaf"), "a stored value that is not a name");
}
/// Idle frames of the panel and of its open menu run no command (`symbol.list` included), so
/// they leave `run_count`, which the native menus watch, as it was.
#[test]
fn idle_frames_of_the_panel_and_its_menu_run_no_command() {
let mut app = leaf_and_dot();
let ctx = egui::Context::default();
frame(&ctx, &mut app, vec![]);
let commands = app.run_count;
frame(&ctx, &mut app, vec![]);
frame(&ctx, &mut app, vec![]);
assert_eq!(app.run_count, commands, "the panel");
let menu_ctx = egui::Context::default();
menu_frame(&menu_ctx, &mut app, vec![]);
menu_frame(&menu_ctx, &mut app, vec![]);
assert_eq!(app.run_count, commands, "the panel menu");
assert_eq!(current(&app).as_deref(), Some("Dot"));
}
/// CPU time of this thread in nanoseconds where the system reports it (Linux), else `None`.
fn thread_cpu_ns() -> Option<u128> {
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
}
/// Time reading the current symbol of a document with 200 symbols and 50,000 objects (5,000 of
/// them instances): by running `symbol.list` and by [`current`]. Per run,
/// `symbol.list` reads 20 times and `current` 200,000 times (so the thread's CPU clock, which
/// advances in steps of a few milliseconds, sees it); the two sides alternate, and the median
/// time per read of 7 runs is printed.
/// Run with `cargo test --release -p vectorcraft-ui-egui --lib current_symbol_read_timing -- --ignored --nocapture`.
#[test]
#[ignore = "manual timing probe; performance depends on machine load"]
fn current_symbol_read_timing() {
const SYMBOLS: usize = 200;
const OBJECTS: usize = 50_000;
const INSTANCES: usize = 5_000;
const LIST_READS: u32 = 20;
const READS: u32 = 200_000;
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 2000, "height": 2000})).unwrap();
for i in 0..SYMBOLS {
app.run("shape.rectangle", json!({"x": i % 40 * 40, "y": i / 40 * 40, "width": 30, "height": 30})).unwrap();
app.run("symbol.new", json!({"name": format!("S{i}")})).unwrap();
}
let rect = app.run("shape.rectangle", json!({"x": 0, "y": 400, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
let rect = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(rect)).cloned().unwrap();
app.session
.edit("Fill", |d, _| {
let layer = d.layers[0].id;
for i in 0..OBJECTS - SYMBOLS - 1 {
let id = d.alloc_id();
let node = if i < INSTANCES - SYMBOLS {
let at = vectorcraft_geom::Vec2::new((i % 100) as f64 * 20.0, 600.0 + (i / 100) as f64 * 20.0);
Node::new(id, NodeKind::SymbolInstance { symbol: format!("S{}", i % SYMBOLS), xf: vectorcraft_geom::Affine::translate(at) })
} else {
let mut n = rect.clone();
n.id = id;
n
};
d.insert(Some(layer), usize::MAX, node)?;
}
Ok(())
})
.unwrap();
app.run("symbol.setCurrent", json!({"name": "S7"})).unwrap();
let mut nodes = 0;
app.session.active().unwrap().doc.walk(|_| nodes += 1);
assert_eq!(listed_current(&mut app), current(&app));
let mut time = |reads: u32, f: &mut dyn FnMut(&mut VectorcraftApp) -> Option<String>| {
let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now());
for _ in 0..reads {
assert_eq!(f(&mut app).as_deref(), Some("S7"));
}
let ns = thread_cpu_ns().zip(cpu).map_or_else(|| wall.elapsed().as_nanos(), |(b, a)| b - a);
ns as f64 / f64::from(reads) / 1000.0
};
let (mut base, mut new) = (vec![], vec![]);
for _ in 0..7 {
base.push(time(LIST_READS, &mut listed_current));
new.push(time(READS, &mut |app| current(app)));
}
let median = |v: &mut Vec<f64>| {
v.sort_by(f64::total_cmp);
v[v.len() / 2]
};
let clock = if thread_cpu_ns().is_some() { "thread CPU time" } else { "wall-clock time" };
eprintln!("{SYMBOLS} symbols, {nodes} nodes; {clock} per read, median of 7 runs");
eprintln!("symbol.list ({LIST_READS} reads a run): {:>12.1} us {base:.1?}", median(&mut base));
eprintln!("current ({READS} reads a run): {:>12.4} us {new:.4?}", median(&mut new));
}
}
+1
View File
@@ -1054,6 +1054,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Symbols panel context menu** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): right-clicking a symbol in thumbnail view or list view displays a context menu with Place Symbol Instance (passes view center or artboard center), Edit Symbol, Duplicate Symbol, Delete Symbol, Break Link to Symbol (enabled when canvas selection includes instances of this symbol), and Select All Instances. Right-clicking an unselected symbol selects it first (`symbol.setCurrent`). Tests: `panels::symbols::tests::right_click_context_menu_in_symbols_panel_runs_actions`.
- **Symbols › Select All Unused** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), #4918): the Symbols panel menu's Select All Unused shows the symbols nothing places selected (`symbol.unused`): instances in the art (opacity masks included), graph designs, pattern tiles and brush art count, and so do instances in a used symbol's art. Delete Symbol, the button or the menu item, then asks "Delete the selected symbols?" once and deletes those still unused in one undo step (`symbol.delete {names}`); Alt-click on the button deletes them without asking, and a click on a symbol picks just it again. Tests: `tests::brushsym::symbol_unused_lists_the_symbols_nothing_places_and_delete_takes_several`, `panels::symbols::tests::select_all_unused_picks_the_unused_symbols_and_delete_deletes_them`, `dialogs::symbol_delete::tests::several_symbols_get_the_plural_question`.
- **Symbols › Sort by Name and the list views** ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Sort by Name puts the symbols in alphabetical order (`symbol.sortByName`), and its Thumbnail View, Small List View and Large List View show them as thumbnails, in a compact list or in a list with larger thumbnails. VectorCraft's own rules: the sort ignores case and keeps names that differ only in case in their order; it changes the document's order, which `symbol.list` reports, as one undo step, keeps the current symbol and adds no undo step when the symbols are already in order; Thumbnail View is the default, Small List View has 18-point rows with 14-point thumbnails and Large List View 26-point rows with 22-point thumbnails, and a click or double-click on a symbol does the same in every view. `ui.panelView` sets the view of the Symbols panel, and of the Swatches and Graphic Styles panels, as their panel menus do. Tests: `tests::brushsym::symbol_sort_by_name_orders_the_symbols_in_one_undo_step`, `panels::symbols::tests::sort_by_name_and_the_small_and_large_list_views`, `panels::symbols::tests::panel_view_sets_the_view_of_each_panel`.
- **The Symbols panel reads its current symbol from the document:** the Symbols panel and its panel menu read the current symbol on each frame without running `symbol.list`, which counts every symbol's instances by walking the whole document. The current symbol they show and act on is the one `symbol.list` reports, and an idle frame of the panel or its menu runs no command, so on macOS the native menu is not brought up to date on every frame while the panel is open. In a document with 200 symbols and 50,000 objects, the read takes 0.035 µs instead of 48.5 ms in a release build (thread CPU time on Linux, median of 7 runs); in a small document the difference is too small to notice. Tests: `tests::brushsym::current_symbol_is_the_current_symbol_list_answers`, `panels::symbols::tests::current_is_the_current_symbol_list_answers`, `panels::symbols::tests::idle_frames_of_the_panel_and_its_menu_run_no_command`; the timing probe is `panels::symbols::tests::current_symbol_read_timing`.
- **Expand of symbol instances:** Object › Expand turns selected symbol instances (without effects, not in perspective, in groups or placed documents too) into their art as Break Link to Symbol places it, one level deep, as one undo step; the Expand dialog's Fill and Stroke reach that art (`object.expand`, `crates/engine/src/tests/expand_symbols.rs`; estimated, score unchanged).
- **Reset Transformation** ([Transform symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/transform-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Reset Transformation and the Control bar's Reset, shown while symbol instances are selected, give the selected instances their symbol's own scale again, without rotation or shear, as one undo step (`symbol.instance.resetTransform`); an instance in perspective is left as it is. VectorCraft's own rules: each instance keeps the center of its bounding box in place, reflection is removed too, and the menu item and the button are enabled only while a selected instance would change. Tests: `tests::brushsym::reset_transformation_restores_the_symbols_scale_and_keeps_the_center`, `reset_transformation_keeps_the_center_of_art_away_from_the_origin`, `reset_transformation_ignores_a_stored_size_that_is_not_positive`, `reset_transformation_leaves_unchanged_instances_and_refuses_bad_ids`, `panels::symbols::tests::reset_transformation_is_enabled_for_a_transformed_instance_and_resets_it`.
- **Expand of dimensions:** Object › Expand, Expand Appearance, Create Outlines and Outline Stroke turn a dimension whose art they change into a plain group of that art, which stays as it is through later moves, scales and edits of what it measured; undo gives the live dimension back (`crates/engine/tests/it/dimensions.rs`; VectorCraft's own rule; estimated, score unchanged).