diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 6b1d8ac3f2..cef27dab18 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -10,12 +10,12 @@ use std::collections::HashMap; use std::sync::Arc; use super::grid::LineLook; -use super::outline::{c32, node_outline, stroke_path, too_many_anchors}; +use super::outline::{c32, node_outline, to_screen_path, too_many_anchors}; use super::view::fit_zoom; use super::{ - Affine, CacheKey, Point, Rect, RulerScale, Sense, Stroke, StrokeKind, Tokens, Ui, VectorcraftApp, View, Xf, artboard_edges, backdrop, cache_key, - dim_on_canvas, frame_options, frame_ppp, frame_view, grid, guides_of, json, paint_paper, pixel_region, placed_key, plugin_key, pos2, rulers, - shows_artboards, textured_quad, vec2, view_rects, + Affine, BezPath, CacheKey, Point, Rect, RulerScale, Sense, Stroke, StrokeKind, Tokens, Ui, VectorcraftApp, View, Xf, artboard_edges, backdrop, + cache_key, dim_on_canvas, frame_options, frame_ppp, frame_view, grid, guides_of, json, paint_paper, pixel_region, placed_key, plugin_key, pos2, + rulers, shows_artboards, textured_quad, vec2, view_rects, }; use crate::doc_windows::Win; use crate::thumb_worker::ThumbWorker; @@ -46,6 +46,29 @@ pub struct Panes { /// By slot: the size of the view's area its view was last fitted to in a pane, and the zoom and /// center the fit gave. fits: HashMap, + /// By slot: the outlines of the selected objects the pane drew last, and what they show. + outlines: HashMap, + /// How many times a pane's outlines were made. + outlines_made: u64, +} + +/// A pane's selected-object outlines as screen shapes, and the document revision, document, +/// selection and screen mapping they were made for. +struct Outlines { + revision: u64, + /// A weak reference to the document: while it exists, no other document can take the + /// allocation's address. + doc: std::sync::Weak, + selection: Vec, + affine: [f64; 6], + shapes: Vec, +} + +impl Outlines { + /// Whether these outlines show `st`'s selection through the screen mapping `affine`. + fn shows(&self, st: &vectorcraft_engine::DocState, affine: &[f64; 6]) -> bool { + self.revision == st.revision && self.doc.ptr_eq(&Arc::downgrade(&st.doc)) && self.affine == *affine && self.selection == st.selection.objects + } } impl Panes { @@ -56,6 +79,7 @@ impl Panes { self.last.clear(); self.last_slots.clear(); self.fits.clear(); + self.outlines.clear(); } /// Upload `img`, the render `key` describes, for `slot`. @@ -311,6 +335,9 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { app.canvas.panes.clear(); } app.canvas.panes.last.clear(); + // Only the floating windows draw panes now. + let floating = &app.ui.floating; + app.canvas.panes.outlines.retain(|(u, n), _| floating.iter().any(|w| w.uid == *u && w.view == *n)); app.canvas.panes.last_slots.clear(); return false; } @@ -326,6 +353,7 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { app.canvas.panes.shown.retain(|s, _| live.contains(s)); app.canvas.panes.pending.retain(|s, _| live.contains(s)); app.canvas.panes.fits.retain(|s, _| live.contains(s)); + app.canvas.panes.outlines.retain(|s, _| live.contains(s)); // A window that moved to another pane fits it, and so does a window whose pane changed place or // size because a window opened, closed, floated or docked, or because the panes came back from // one window. A window that keeps its pane keeps its zoom and scroll, as when a tab brings its @@ -563,7 +591,9 @@ fn draw_pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> boo guides_of(app, st, (&painter, &xf, &t), rect); } if app.ui.view.edges { - selected_objects(st, &painter, &xf); + selected_objects(&mut app.canvas.panes, slot, st, &painter, &xf); + } else { + app.canvas.panes.outlines.remove(&slot); } if app.ui.view.rulers && app.ui.screen_mode < 3 { rulers(ui, full, &xf, None, RulerScale::document(app.session.general_unit(), st.doc.ruler_origin_for(v.artboard)), &t); @@ -581,23 +611,45 @@ fn draw_pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> boo resp.contains_pointer() && ui.input(|inp| inp.pointer.any_pressed()) } -/// The outlines of the objects selected in `st`, in their layers' colors; their bounds when they -/// have too many points to outline. -fn selected_objects(st: &vectorcraft_engine::DocState, painter: &egui::Painter, xf: &Xf) { +/// Draw the outlines of the objects selected in `st` ([`outline_shapes`]) in `slot`'s pane, from +/// the outlines `panes` kept for the slot while they show the same revision, document, selection +/// and screen mapping, and made again otherwise. +fn selected_objects(panes: &mut Panes, slot: Slot, st: &vectorcraft_engine::DocState, painter: &egui::Painter, xf: &Xf) { + let affine = xf.affine().as_coeffs(); + if !panes.outlines.get(&slot).is_some_and(|o| o.shows(st, &affine)) { + let shapes = outline_shapes(st, xf); + let kept = Outlines { revision: st.revision, doc: Arc::downgrade(&st.doc), selection: st.selection.objects.clone(), affine, shapes }; + panes.outlines.insert(slot, kept); + panes.outlines_made += 1; + } + for shape in panes.outlines.get(&slot).map_or(&[][..], |o| &o.shapes) { + painter.add(shape.clone()); + } +} + +/// The outlines of the objects selected in `st` as lines on the screen through `xf`, in their +/// layers' colors; their bounds when they have too many points to outline. +fn outline_shapes(st: &vectorcraft_engine::DocState, xf: &Xf) -> Vec { + let mut shapes = vec![]; + if st.selection.objects.is_empty() { + return shapes; + } let symbols = st.doc.symbol_boxes(); let nodes: Vec<(vectorcraft_doc::NodeId, &vectorcraft_doc::Node)> = st.selection.objects.iter().filter_map(|id| Some((*id, st.doc.node(*id)?))).collect(); let color = |id: vectorcraft_doc::NodeId| Stroke::new(1.0, c32(st.doc.layer_color(id))); + let mut stroke = |bp: &BezPath, s: Stroke| shapes.extend(to_screen_path(bp, xf).into_iter().map(|line| egui::Shape::line(line, s))); if too_many_anchors(nodes.iter().map(|(_, n)| *n)) { let bounds = nodes.iter().filter_map(|(_, n)| n.geometric_bounds_with(&symbols)).reduce(|a, b| a.union(b)); if let (Some(b), Some((id, _))) = (bounds, nodes.first()) { - stroke_path(painter, &vectorcraft_geom::shapes::rectangle(b).to_bezpath(), xf, color(*id)); + stroke(&vectorcraft_geom::shapes::rectangle(b).to_bezpath(), color(*id)); } - return; + return shapes; } for (id, n) in nodes { - stroke_path(painter, &node_outline(n, &symbols), xf, color(id)); + stroke(&node_outline(n, &symbols), color(id)); } + shapes } #[cfg(test)] diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index 6c7a8cf755..15e5e138d3 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -875,6 +875,149 @@ fn other_panes_draw_their_guides_and_selected_objects() { assert_ne!(layer, Color32::TRANSPARENT); } +/// The selected objects' outlines as the panes made them on every frame before they kept them, +/// to hold the kept outlines against. +fn outlines_made_each_frame(st: &vectorcraft_engine::DocState, xf: &Xf) -> Vec { + let mut shapes = vec![]; + let symbols = st.doc.symbol_boxes(); + let nodes: Vec<(vectorcraft_doc::NodeId, &vectorcraft_doc::Node)> = + st.selection.objects.iter().filter_map(|id| Some((*id, st.doc.node(*id)?))).collect(); + let color = |id: vectorcraft_doc::NodeId| Stroke::new(1.0, c32(st.doc.layer_color(id))); + let mut stroke_path = |bp: &BezPath, s: Stroke| { + for line in to_screen_path(bp, xf) { + shapes.push(Shape::line(line, s)); + } + }; + if too_many_anchors(nodes.iter().map(|(_, n)| *n)) { + let bounds = nodes.iter().filter_map(|(_, n)| n.geometric_bounds_with(&symbols)).reduce(|a, b| a.union(b)); + if let (Some(b), Some((id, _))) = (bounds, nodes.first()) { + stroke_path(&vectorcraft_geom::shapes::rectangle(b).to_bezpath(), color(*id)); + } + return shapes; + } + for (id, n) in nodes { + stroke_path(&node_outline(n, &symbols), color(id)); + } + shapes +} + +/// The first document's pane in a tiled pair: the outlines it keeps, after checking that they +/// equal the outlines made afresh through its view and that the frame `drawn` holds them in order. +fn kept_outlines<'a>(app: &'a VectorcraftApp, ctx: &egui::Context, drawn: &[Shape]) -> &'a [Shape] { + let pane = panes(app).1[0]; + let xf = Xf::new(view_rects(app, pane, ctx.pixels_per_point()).1, &app.views[0]); + let slot = (app.session.documents()[0].uid, 1); + let kept = &app.canvas.panes.outlines.get(&slot).expect("the pane keeps its outlines").shapes; + assert_eq!(kept, &outlines_made_each_frame(&app.session.documents()[0], &xf), "the kept outlines are the ones made afresh"); + assert!(kept.is_empty() || drawn.windows(kept.len()).any(|w| w == kept.as_slice()), "the pane draws the kept outlines"); + kept +} + +/// Run `cmd` on the first document of a tiled pair, then make the second current again. +fn in_first(app: &mut VectorcraftApp, cmd: &str, args: serde_json::Value) -> serde_json::Value { + app.run("document.activate", json!({"index": 0})).unwrap(); + let out = app.session.execute(cmd, &args).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + out +} + +#[test] +fn kept_outlines_do_not_show_for_a_new_document_that_takes_a_freed_documents_address() { + let affine = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + let st = vectorcraft_engine::DocState::new(vectorcraft_doc::Document::new(400.0, 300.0), None); + let kept = Outlines { revision: st.revision, doc: Arc::downgrade(&st.doc), selection: vec![], affine, shapes: vec![] }; + assert!(kept.shows(&st, &affine), "the outlines show the document they were made for"); + let freed = Arc::as_ptr(&st.doc); + drop(st); + let mut reused = false; + for _ in 0..64 { + let other = vectorcraft_engine::DocState::new(vectorcraft_doc::Document::new(400.0, 300.0), None); + reused |= Arc::as_ptr(&other.doc) == freed; + assert!(!kept.shows(&other, &affine), "a different document with the same revision, selection and mapping is not the one shown"); + } + assert!(!reused, "the weak reference keeps the freed document's address from being taken"); +} + +#[test] +fn other_panes_keep_their_selected_outlines_until_the_document_selection_or_view_changes() { + let mut app = app_with(2); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("window.arrange.tile", json!({})).unwrap(); + let ctx = egui::Context::default(); + let rect = in_first(&mut app, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 80}))["id"].clone(); + let ellipse = in_first(&mut app, "shape.ellipse", json!({"x": 200, "y": 100, "width": 90, "height": 60}))["id"].clone(); + in_first(&mut app, "select.set", json!({"ids": [rect, ellipse]})); + frame(&mut app, &ctx, vec![]); + let drawn = frame(&mut app, &ctx, vec![]); + assert!(kept_outlines(&app, &ctx, &drawn).len() >= 2, "the rectangle and the ellipse are outlined"); + let made = app.canvas.panes.outlines_made; + let drawn = frame(&mut app, &ctx, vec![]); + kept_outlines(&app, &ctx, &drawn); + assert_eq!(app.canvas.panes.outlines_made, made, "an unchanged frame draws the kept outlines"); + let changed = |app: &mut VectorcraftApp, what: &str| { + let made = app.canvas.panes.outlines_made; + let drawn = frame(app, &ctx, vec![]); + kept_outlines(app, &ctx, &drawn); + assert_eq!(app.canvas.panes.outlines_made, made + 1, "{what} makes the outlines again, once"); + let drawn = frame(app, &ctx, vec![]); + kept_outlines(app, &ctx, &drawn); + assert_eq!(app.canvas.panes.outlines_made, made + 1, "the frame after {what} draws the kept outlines"); + }; + in_first(&mut app, "select.set", json!({"ids": [ellipse]})); + changed(&mut app, "a new selection"); + in_first(&mut app, "object.move", json!({"dx": 30, "dy": -10})); + changed(&mut app, "a move"); + let layer = app.session.documents()[0].doc.layers[0].id.0; + in_first(&mut app, "layer.setProps", json!({"id": layer, "color": "#20a040"})); + changed(&mut app, "a new layer color"); + app.views[0].center.x += 25.0; + changed(&mut app, "a pan"); + app.views[0].zoom *= 1.5; + app.views[0].rotation = 20.0; + changed(&mut app, "a zoom and a turn"); + app.ui.view.edges = false; + frame(&mut app, &ctx, vec![]); + assert!(app.canvas.panes.outlines.is_empty(), "with Edges off no outlines are kept"); + app.ui.view.edges = true; + changed(&mut app, "Edges on again"); + in_first(&mut app, "select.none", json!({})); + changed(&mut app, "an empty selection"); + let drawn = frame(&mut app, &ctx, vec![]); + assert!(kept_outlines(&app, &ctx, &drawn).is_empty()); + // 30,000 rectangles have more points than the outlines are made for: the pane keeps the bounds. + let st = &app.session.documents()[0]; + let rect = st.doc.node(vectorcraft_doc::NodeId(rect.as_u64().unwrap())).cloned().unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.session + .edit("Fill", |d, _| { + let layer = d.layers[0].id; + for _ in 0..30_000 { + let mut n = rect.clone(); + n.id = d.alloc_id(); + d.insert(Some(layer), usize::MAX, n)?; + } + Ok(()) + }) + .unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + changed(&mut app, "selecting more points than are outlined"); + let drawn = frame(&mut app, &ctx, vec![]); + assert_eq!(kept_outlines(&app, &ctx, &drawn).len(), 1, "one rectangle around the bounds"); + app.run("window.arrange.consolidateAllWindows", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert!(app.canvas.panes.outlines.is_empty(), "Consolidate All Windows forgets the outlines"); + // Panes that stop showing before their render arrives keep no outlines either. + app.run("window.arrange.tile", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert_eq!(app.canvas.panes.outlines.len(), 1); + app.ui.tiled = false; + app.canvas.panes.shown.clear(); + app.canvas.panes.last.clear(); + frame(&mut app, &ctx, vec![]); + assert!(app.canvas.panes.outlines.is_empty(), "no pane shows, so no outlines are kept"); +} + #[test] fn opening_a_document_while_tiled_fits_each_document_to_its_new_pane() { let mut app = app_with(2); @@ -1209,3 +1352,82 @@ fn tiled_documents_blend_translucent_art_over_their_own_paper_before_display_con assert!(differs(want, blend(s, front_paper)), "the front document's paper blends to another color"); assert!(differs(got, over(plain(s), under)), "the art converted alone shows another color"); } + +fn thread_cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() +} + +/// Time a pane's selected-object outlines with every object of a document selected: 2,000 and +/// 20,000 rectangles, 20,000 ellipses, and 150,000 rectangles (more points than are outlined, so +/// the pane draws their bounds). Each frame is a whole egui pass that draws the outlines and the +/// tessellation of what it drew, made afresh on every frame ([`outlines_made_each_frame`]) or +/// drawn from the kept outlines ([`selected_objects`]). The sides alternate, and the median time +/// per frame of 7 runs is printed. +/// Run with `cargo test --release -p vectorcraft-ui-egui --lib pane_outlines_timing -- --ignored --nocapture`. +#[test] +#[ignore = "manual timing probe; performance depends on machine load"] +fn pane_outlines_timing() { + const FRAMES: u32 = 20; + let clock = if thread_cpu_ns().is_some() { "thread CPU time" } else { "wall-clock time" }; + eprintln!("{clock} per frame, median of 7 runs of {FRAMES} frames"); + for (count, shape) in [(2_000, "shape.rectangle"), (20_000, "shape.rectangle"), (20_000, "shape.ellipse"), (150_000, "shape.rectangle")] { + let mut app = app_with(1); + let id = app.run(shape, json!({"x": 20, "y": 20, "width": 60, "height": 40})).unwrap()["id"].as_u64().unwrap(); + let node = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).cloned().unwrap(); + app.session + .edit("Fill", |d, _| { + let layer = d.layers[0].id; + for _ in 1..count { + let mut n = node.clone(); + n.id = d.alloc_id(); + d.insert(Some(layer), usize::MAX, n)?; + } + Ok(()) + }) + .unwrap(); + app.run("select.all", json!({})).unwrap(); + let st = app.session.active().unwrap(); + assert_eq!(st.selection.objects.len(), count); + let ctx = egui::Context::default(); + let area = egui::Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0)); + let xf = Xf { rect: area, zoom: 4.0, center: Point::new(50.0, 40.0), rot: 0.0 }; + let mut kept = Panes::default(); + let slot = (st.uid, 1); + let mut pass = |fresh: bool| { + let raw = egui::RawInput { screen_rect: Some(area), ..Default::default() }; + let out = ctx.run_ui(raw, |ui| { + let painter = ui.painter_at(area); + if fresh { + for s in outlines_made_each_frame(st, &xf) { + painter.add(s); + } + } else { + selected_objects(&mut kept, slot, st, &painter, &xf); + } + }); + ctx.tessellate(out.shapes, out.pixels_per_point).len() + }; + assert_eq!(pass(true), pass(false), "both sides draw as much"); + let mut time = |fresh: bool| { + let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now()); + for _ in 0..FRAMES { + pass(fresh); + } + let ns = thread_cpu_ns().zip(cpu).map_or_else(|| wall.elapsed().as_nanos(), |(b, a)| b - a); + ns as f64 / f64::from(FRAMES) / 1e6 + }; + let (mut fresh, mut cached) = (vec![], vec![]); + for _ in 0..7 { + fresh.push(time(true)); + cached.push(time(false)); + } + let median = |v: &mut Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + let shapes = kept.outlines.get(&slot).map_or(0, |o| o.shapes.len()); + eprintln!("{count} x {shape} ({shapes} lines drawn)"); + eprintln!(" made every frame: {:>9.3} ms {fresh:.3?}", median(&mut fresh)); + eprintln!(" kept: {:>9.3} ms {cached:.3?}", median(&mut cached)); + } +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4c9cb308f7..36884752f9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2362,6 +2362,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Control bar and task bar on large paths:** the Control bar and the contextual task bar read the first selected object in place each frame instead of copying it; the task bar copies the object only when it is a basic shape, for its Shape Properties. With one selected open path of 200,000 anchors, an idle frame with both bars shown takes 3.8 ms in a release build instead of 8.0 ms (medians of five interleaved runs). Tests: `the_control_bar_label_follows_edits_undo_documents_and_selection`, `the_task_bar_follows_the_active_document`, `the_task_bar_follows_edits_and_undo`. - **Panels on large selections:** the Properties, Transform, Brushes, Appearance, Transparency and Image Trace panels read the selected object where the document holds it each frame instead of copying it, and the Transparency panel removes the mask from a copy of the object only when it draws the object's thumbnail again. With one selected open path of 200,000 anchors, an idle repaint uses 72.9 µs of CPU time in a release build instead of 88.4 µs for the Properties panel, 27.5 µs instead of 37.2 µs for the Appearance panel and 19.6 µs instead of 29.8 µs for the Transparency panel with its thumbnails shown (medians of seven interleaved runs). Tests: `first_selected_is_the_node_the_document_holds`, `first_subject_is_the_node_the_document_holds`, `panels_show_the_selected_object_after_an_edit_and_after_undo`, `state_holds_the_documents_node_and_the_object_thumbnail_leaves_out_the_mask`. - **Paste of many objects:** Paste leaves pasted copies as they are when no resource has another name or color in the document and the objects link no graphic style. It looks up the pasted type in one walk of the tree. A paste and undo of 20,000 rectangles in 200 groups uses 49.2 ms of CPU time in a release build instead of 59.4 ms, and of 5,000 point type objects 25.3 ms instead of 29.4 ms (medians of seven interleaved rounds, each round the CPU time of a 61-paste run minus a 1-paste run, divided by 60). Tests: `crates/engine/tests/it/paste_many.rs`. +- **Selected objects in other panes:** under Window › Arrange › Tile and in floating document windows, each pane other than the current document's keeps the outlines of its selected objects between frames, and makes them again when its document, its selection or its view changes; with View › Edges off it keeps none. The outlines drawn are the same as before. With every object selected, a frame of a pane's outlines, tessellation included, takes 28.9 ms of CPU time in a release build instead of 40.1 ms for 20,000 rectangles, 116.7 ms instead of 197.2 ms for 20,000 ellipses, and 0.05 ms instead of 32.0 ms for 150,000 rectangles, which the pane draws as their bounds (medians of seven interleaved runs of 20 frames). Tests: `canvas::panes::tests::other_panes_keep_their_selected_outlines_until_the_document_selection_or_view_changes`; timing: `pane_outlines_timing`. - **Type drawn as glyph outlines:** under a geometry effect, in EMF and WMF export, in DXF export when it is written as outlines, flattened with Convert All Text to Outlines, and inside an envelope, type keeps its underline and strikethrough, the weight and dashes of its character strokes when it is scaled, and the placement of its gradients and patterns, as the canvas draws it. A group's or layer's own fills and strokes also paint the underline and strikethrough of the type in it.