diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index e3d2a13d64..c256c17a3c 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -90,6 +90,7 @@ impl VectorcraftApp { selection_bounds: None, content_bounds: None, pixel_aligned: None, + symbol_instances: None, plugin_keys: Default::default(), placed_keys: Default::default(), cursors: Default::default(), diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 6dc036fcf2..c2fd1de1d8 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -64,6 +64,9 @@ pub struct CanvasCache { /// The Transform panel's Align to Pixel Grid state (on, off or mixed, and whether every /// selected object can be aligned) for (document uid, revision). pub pixel_aligned: Option<((u64, u64), Option)>, + /// The symbol instances in the selection and its groups, for (document uid, revision): the + /// Properties and Symbols panels read them every frame. + pub symbol_instances: Option<((u64, u64), SymbolInstances)>, /// [`CacheKey::plugins`] by document uid, with the plug-in revision /// ([`vectorcraft_render::effects::plugin_revision`]) it was last checked at. pub plugin_keys: std::collections::HashMap, @@ -115,6 +118,18 @@ pub type LivePaintGapsCache = ((u64, u64), std::sync::Arc, bool); +/// [`CanvasCache::symbol_instances`]: the symbol instances in the selection and its groups. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SymbolInstances { + /// Each instance's id, in the order the selection's subtrees list them. + pub ids: Vec, + /// One of them has appearance changes of its own (`symbol_overrides`). + pub changed: bool, + /// One of them has a scale, rotation or shear that Reset Transformation would change; measured + /// on the first read. + pub transformed: Option, +} + /// [`CanvasCache::print_tiling`]: the print tiling of (document uid, revision). pub type PrintTilingCache = ((u64, u64), std::sync::Arc>); diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index 0be9e7111c..6b500e6b3a 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -19,6 +19,7 @@ use super::library_panel::{self, LibraryKind, LibraryRef, Row}; use super::memo::Memo; use super::{pstate, set_pstate}; use crate::VectorcraftApp; +use crate::caches::SymbolInstances; use crate::menus::Item; use crate::theme::Tokens; use crate::widgets::{self, PanelDrag, menu_item}; @@ -139,21 +140,37 @@ fn current(app: &VectorcraftApp) -> Option { 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? -fn instance_selected(app: &VectorcraftApp, wanted: impl Fn(&Node) -> bool) -> bool { - app.session.active().is_some_and(|st| { - st.selection.objects.iter().any(|id| { - let mut any = false; - if let Some(n) = st.doc.node(*id) { - n.walk(&mut |c| any |= matches!(c.kind, NodeKind::SymbolInstance { .. }) && wanted(c)); - } - any - }) - }) +#[cfg(test)] +thread_local! { + /// How many times [`selected_instances`] walked the selection on this thread. + static INSTANCE_SCANS: std::cell::Cell = const { std::cell::Cell::new(0) }; } -fn has_instances_selected(app: &VectorcraftApp) -> bool { - instance_selected(app, |_| true) +/// The symbol instances in the selection and in its groups, found in one walk of the selected +/// subtrees per (document uid, revision) ([`crate::caches::CanvasCache::symbol_instances`]); +/// `None` without a document. +fn selected_instances(app: &mut VectorcraftApp) -> Option<&mut SymbolInstances> { + let st = app.session.active()?; + let key = (st.uid, st.revision); + if app.canvas.symbol_instances.as_ref().is_none_or(|(k, _)| *k != key) { + #[cfg(test)] + INSTANCE_SCANS.with(|n| n.set(n.get() + 1)); + let mut found = SymbolInstances::default(); + for n in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) { + n.walk(&mut |c| { + if matches!(c.kind, NodeKind::SymbolInstance { .. }) { + found.changed |= !c.extras().symbol_overrides.is_empty(); + found.ids.push(c.id); + } + }); + } + app.canvas.symbol_instances = Some((key, found)); + } + app.canvas.symbol_instances.as_mut().map(|(_, found)| found) +} + +fn has_instances_selected(app: &mut VectorcraftApp) -> bool { + selected_instances(app).is_some_and(|found| !found.ids.is_empty()) } /// Collect the IDs of selected instances of symbol `name` (including inside groups). @@ -221,15 +238,19 @@ fn item_context_menu(app: &mut VectorcraftApp, ui: &mut Ui, name: &str) { /// Does the selection hold a symbol instance with appearance changes of its own (a dynamic /// symbol's), which Reset drops? -pub(crate) fn changed_instances_selected(app: &VectorcraftApp) -> bool { - instance_selected(app, |c| !c.extras().symbol_overrides.is_empty()) +pub(crate) fn changed_instances_selected(app: &mut VectorcraftApp) -> bool { + selected_instances(app).is_some_and(|found| found.changed) } /// Does the selection hold a symbol instance whose scale, rotation or shear differs from its /// symbol's, which Reset Transformation restores? -fn transformed_instances_selected(app: &VectorcraftApp) -> bool { +fn transformed_instances_selected(app: &mut VectorcraftApp) -> bool { let Some(doc) = app.session.active().map(|st| st.doc.clone()) else { return false }; - instance_selected(app, |c| vectorcraft_engine::cmd::reset_transformation_changes(&doc, c)) + let Some(found) = selected_instances(app) else { return false }; + let ids = &found.ids; + *found + .transformed + .get_or_insert_with(|| ids.iter().filter_map(|id| doc.node(*id)).any(|n| vectorcraft_engine::cmd::reset_transformation_changes(&doc, n))) } /// The symbols of the selected objects when every one is a symbol instance; `None` otherwise. @@ -1008,6 +1029,134 @@ mod tests { assert_eq!(app.run("symbol.list", json!({})).unwrap()["symbols"][0]["alignToPixelGrid"], false); } + /// Does the selection hold a symbol instance that `wanted` takes, found by walking every + /// selected subtree on each call: what the cached flags must match. + fn walked(app: &VectorcraftApp, wanted: impl Fn(&Node) -> bool) -> bool { + app.session.active().is_some_and(|st| { + st.selection.objects.iter().any(|id| { + let mut any = false; + if let Some(n) = st.doc.node(*id) { + n.walk(&mut |c| any |= matches!(c.kind, NodeKind::SymbolInstance { .. }) && wanted(c)); + } + any + }) + }) + } + + /// Any instance, one with appearance changes, one Reset Transformation changes: walked again. + fn walked_flags(app: &VectorcraftApp) -> [bool; 3] { + let Some(doc) = app.session.active().map(|st| st.doc.clone()) else { return [false; 3] }; + [ + walked(app, |_| true), + walked(app, |c| !c.extras().symbol_overrides.is_empty()), + walked(app, |c| vectorcraft_engine::cmd::reset_transformation_changes(&doc, c)), + ] + } + + fn cached_flags(app: &mut VectorcraftApp) -> [bool; 3] { + [has_instances_selected(app), changed_instances_selected(app), transformed_instances_selected(app)] + } + + fn scans() -> usize { + INSTANCE_SCANS.with(std::cell::Cell::get) + } + + /// The Symbols and Properties panels' instance flags (Break Link, Reset Symbol Instance and the + /// Properties panel's Reset, Reset Transformation) are those a walk of the selection gives, for + /// plain, changed, scaled and grouped instances, several selected objects, nothing selected, + /// Undo and another document; the selection is walked once per document revision, however + /// often they are read. + #[test] + fn instance_flags_are_found_once_per_revision_and_match_a_walk_of_the_selection() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let id = |v: Value| v["id"].as_u64().unwrap(); + let rect = id(app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()); + let second = id(app.run("shape.rectangle", json!({"x": 60, "y": 10, "width": 40, "height": 40})).unwrap()); + let other = id(app.run("shape.rectangle", json!({"x": 300, "y": 10, "width": 40, "height": 40})).unwrap()); + // Reads every flag several times; the walk runs only when the revision changed. + let check = |app: &mut VectorcraftApp, want: [bool; 3], what: &str| { + let before = scans(); + for _ in 0..3 { + assert_eq!(cached_flags(app), want, "{what}"); + } + assert_eq!(walked_flags(app), want, "{what}: a walk of the selection agrees"); + assert!(scans() - before <= 1, "{what}: walked {} times", scans() - before); + }; + app.run("select.set", json!({"ids": [rect]})).unwrap(); + check(&mut app, [false; 3], "no instance"); + // Two objects, so the instance's art is a group whose first object can be painted. + let inst = id(app.run("symbol.new", json!({"name": "S", "ids": [rect, second], "type": "dynamic"})).unwrap()); + app.run("select.set", json!({"ids": [inst]})).unwrap(); + check(&mut app, [true, false, false], "a plain instance"); + app.run("symbol.instance.setAppearance", json!({"id": inst, "path": [0], "fill": "#ff0000"})).unwrap(); + app.run("select.set", json!({"ids": [inst]})).unwrap(); + check(&mut app, [true, true, false], "an instance with appearance changes"); + let scaled = id(app.run("symbol.place", json!({"name": "S", "x": 200, "y": 100})).unwrap()); + app.run("select.set", json!({"ids": [scaled]})).unwrap(); + app.run("object.scale", json!({"sx": 150, "sy": 50})).unwrap(); + check(&mut app, [true, false, true], "a scaled instance"); + app.run("select.set", json!({"ids": [scaled, other]})).unwrap(); + let group = id(app.run("object.group", json!({})).unwrap()); + app.run("select.set", json!({"ids": [group]})).unwrap(); + check(&mut app, [true, false, true], "an instance in a selected group"); + app.run("select.set", json!({"ids": [inst, group]})).unwrap(); + check(&mut app, [true, true, true], "several selected objects"); + app.run("select.set", json!({"ids": [other]})).unwrap(); + check(&mut app, [false; 3], "select.set to a path"); + app.run("select.none", json!({})).unwrap(); + check(&mut app, [false; 3], "nothing selected"); + // Undo takes the group apart again. + app.run("edit.undo", json!({})).unwrap(); + let undone = walked_flags(&app); + check(&mut app, undone, "after Undo"); + // At one revision the walk runs once; a new revision walks again. + app.run("select.set", json!({"ids": [inst, scaled]})).unwrap(); + let before = scans(); + cached_flags(&mut app); + cached_flags(&mut app); + assert_eq!(scans(), before + 1); + app.run("select.set", json!({"ids": [inst]})).unwrap(); + cached_flags(&mut app); + assert_eq!(scans(), before + 2); + // Another document has its own uid, so its flags are found again. + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let plain = id(app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()); + app.run("select.set", json!({"ids": [plain]})).unwrap(); + check(&mut app, [false; 3], "another document"); + } + + /// The Properties panel (its Reset quick action) and the Symbols panel (Break Link) share one + /// walk of the selection while the document does not change. + #[test] + fn properties_and_symbols_panels_walk_the_selection_once_per_revision() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let rect = |app: &mut VectorcraftApp, x: f64| { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap() + }; + let ids = [rect(&mut app, 10.0), rect(&mut app, 60.0)]; + let inst = app.run("symbol.new", json!({"name": "S", "ids": ids, "type": "dynamic"})).unwrap()["id"].as_u64().unwrap(); + app.run("symbol.instance.setAppearance", json!({"id": inst, "path": [0], "fill": "#ff0000"})).unwrap(); + app.run("select.set", json!({"ids": [inst]})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let before = scans(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::properties::show(&mut app, ui)); + out.textures_delta.clear(); + assert_eq!(scans(), before + 1, "the Properties panel reads the flags"); + for _ in 0..3 { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + super::super::properties::show(&mut app, ui); + show(&mut app, ui); + }); + out.textures_delta.clear(); + } + assert_eq!(scans(), before + 1, "one walk for both panels over four frames"); + assert_eq!(cached_flags(&mut app), [true, true, false]); + assert_eq!(scans(), before + 1); + } + /// F8 is Symbol Options… (`ui.symbolOptions`) by default, on every platform. Shift+F8 and Cmd+F8 /// are still the Transform and Info panels' keys, and Cmd+Shift+F8 is still Edit Pattern's. No /// other command, tool or panel has F8 by default. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ef83de54ad..1c16a48e04 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1103,6 +1103,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **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`. + - **The Symbols and Properties panels find selected symbol instances once per revision:** whether the selection or its groups hold a symbol instance (Break Link to Symbol), one with appearance changes of its own (Reset Symbol Instance and the Properties panel's Reset), or one Reset Transformation would change is worked out in one walk of the selected objects for each document revision, and later frames reuse it. The buttons and menu items are enabled as before. With one selected group of 300,000 paths, the two panels' reads took a median 5.1 to 5.7 ms of thread CPU time per frame; the first read after a change now takes about 3 ms and later frames about 5 ns (Linux, opt-level 3, median of 7 runs). In a small document the difference is too small to notice. Tests: `panels::symbols::tests::instance_flags_are_found_once_per_revision_and_match_a_walk_of_the_selection`, `properties_and_symbols_panels_walk_the_selection_once_per_revision`. - **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). - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol; Ink and Wash adds ink and wash brushes (the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) lists an Ink brush library of strokes with varied thickness and texture; the names, shapes and opacities are VectorCraft's own): Tapered Ink, an art brush broad near its start that thins to a fine tip; Brush Pen, a calligraphic brush whose size follows the pen pressure; and Soft Wash and Pooling Wash, art brushes of translucent gray layers that take the stroke color as tints; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag); Energy Beams adds laser and plasma art brushes (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); Dry Media adds grainy art brushes (Chalk Grain, Graphite Pencil, Wax Crayon, Charcoal Dust). A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. - **Bristle Brushes library** ([What's new](https://helpx.adobe.com/illustrator/desktop/new-features/whats-new.html), [About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Bristle Brushes holds ten bristle brushes, one for each tip shape (Fine Liner, Pointed Flat, Stubby Round, Dry Scrub, Soft Dome, Filbert, Angled Round, Angled Flat, Fan Blender, Grass Fan). The brushes, their names and their values are VectorCraft's own, and every value lies inside the range the bristle brush keeps (`brush.libraries`, `brush.addFromLibrary`; `the_bristle_brushes_library_covers_every_tip_shape_within_the_bristle_ranges`).