diff --git a/crates/ui-egui/examples/layers_panel_bench.rs b/crates/ui-egui/examples/layers_panel_bench.rs new file mode 100644 index 0000000000..7d1cf1b8e5 --- /dev/null +++ b/crates/ui-egui/examples/layers_panel_bench.rs @@ -0,0 +1,130 @@ +//! Per-frame CPU cost of the Layers panel with many groups (#13117): a group row that was scrolled +//! out of view used to paint its whole row (background, thumbnail, name, badges) every frame. This +//! is the before/after measure for that fix. +//! +//! ```sh +//! cargo run --release -p photocraft-ui-egui --example layers_panel_bench -- [--groups 300] [--frames 300] [--expanded] [--plain] [--json out.json] +//! ``` +//! +//! The document is built through Session commands on a tiny 64x48 canvas, so the canvas costs next +//! to nothing: `--groups N` top-level collapsed groups, each holding one pixel layer (`--expanded` +//! opens them all afterwards); `--plain` builds N plain pixel layers instead, a control whose rows +//! were already culled off-screen. The real `PhotocraftApp` runs in a plain CPU egui_kittest +//! harness (no wgpu), so a frame's time is the UI's own CPU work. After a warm-up, the row is the +//! median / p90 / max of `--frames` idle frames (`h.step()` each). + +use std::time::Instant; + +use egui_kittest::kittest::Queryable; +use photocraft_ui_egui::{PhotocraftApp, Services}; +use serde_json::{Value, json}; + +/// The app in an offscreen harness. +type H = egui_kittest::Harness<'static, PhotocraftApp>; + +/// The value after `name` on the command line, if any. +fn arg(args: &[String], name: &str) -> Option { + args.iter().position(|a| a == name).and_then(|i| args.get(i + 1).cloned()) +} + +/// Milliseconds since `t`. +fn ms(t: Instant) -> f64 { + t.elapsed().as_secs_f64() * 1000.0 +} + +/// One frame, timed. +fn frame(h: &mut H) -> f64 { + let t = Instant::now(); + h.step(); + ms(t) +} + +/// Result rows: name, then median, p90 and max frame time (ms). +struct Rows { + rows: Vec<(String, f64, f64, f64)>, +} + +impl Rows { + /// A row from frame times already taken. + fn add(&mut self, name: &str, v: Vec) { + let mut v: Vec = v.into_iter().filter(|t| t.is_finite()).collect(); + if v.is_empty() { + return; + } + v.sort_by(f64::total_cmp); + let (med, p90, max) = (v[v.len() / 2], v[(v.len() * 9 / 10).min(v.len() - 1)], v[v.len() - 1]); + println!("{name:<46} median {med:>8.3} ms p90 {p90:>8.3} max {max:>8.3}"); + self.rows.push((name.to_string(), med, p90, max)); + } +} + +/// `n` top-level collapsed groups (or plain layers), each group holding one pixel layer. +fn build(n: usize, plain: bool, expanded: bool) -> photocraft_engine::Session { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48})).expect("file.new"); + for i in 0..n { + s.execute("layer.new.layer", json!({"name": format!("Layer {i}")})).expect("layer.new.layer"); + if !plain { + // Group Layers makes a collapsed group; the next new layer lands above it, at the same level. + s.execute("layer.groupLayers", json!({"name": format!("Group {i}")})).expect("layer.groupLayers"); + } + } + if expanded && !plain { + s.execute("layer.setExpanded", json!({"all": true, "expanded": true})).expect("layer.setExpanded"); + } + s +} + +/// Builds the document, warms the app up, times idle frames and prints (and optionally writes) the row. +fn main() { + let args: Vec = std::env::args().collect(); + let groups: usize = arg(&args, "--groups").and_then(|v| v.parse().ok()).unwrap_or(300).max(1); + let frames: usize = arg(&args, "--frames").and_then(|v| v.parse().ok()).unwrap_or(300).max(3); + let expanded = args.iter().any(|a| a == "--expanded"); + let plain = args.iter().any(|a| a == "--plain"); + + let t = Instant::now(); + let session = build(groups, plain, expanded); + println!("built {groups} {} in {:.0} ms", if plain { "plain layers" } else { "groups" }, ms(t)); + + let mut h: H = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_pixels_per_point(1.0).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + PhotocraftApp::new(session, Services::default()) + }); + // Warm up. The layer made last is the top one and is active, so the panel is scrolled to the + // top and most rows are off-screen. + for _ in 0..30 { + h.step(); + } + + // How many group rows are on screen (their disclosure widgets, which every group row registers). + let window = h.ctx.content_rect(); + let (on_screen, total) = if plain { + (0, 0) + } else { + let all: Vec<_> = h.query_all_by_label_contains("group Group ").map(|n| n.rect()).collect(); + (all.iter().filter(|r| window.intersects(**r)).count(), all.len()) + }; + if !plain { + println!("group rows on screen: {on_screen} of {total} listed (document has {groups})"); + } + + let mut rows = Rows { rows: Vec::new() }; + let times: Vec = (0..frames).map(|_| frame(&mut h)).collect(); + let what = if plain { "plain layers" } else { "groups" }; + rows.add(&format!("idle frame, {groups} {what} (panel at top)"), times); + + if let Some(out) = arg(&args, "--json") { + let r: Vec = rows.rows.iter().map(|(n, med, p90, max)| json!({"name": n, "median_ms": med, "p90_ms": p90, "max_ms": max})).collect(); + let report = json!({ + "groups": groups, + "frames": frames, + "expanded": expanded, + "plain": plain, + "group_rows_on_screen": on_screen, + "group_rows_listed": total, + "rows": r, + }); + std::fs::write(&out, serde_json::to_string_pretty(&report).expect("json")).expect("write json"); + } +} diff --git a/crates/ui-egui/src/panels/layer_row.rs b/crates/ui-egui/src/panels/layer_row.rs index d0cd501ef8..e207b609e4 100644 --- a/crates/ui-egui/src/panels/layer_row.rs +++ b/crates/ui-egui/src/panels/layer_row.rs @@ -165,6 +165,26 @@ pub(super) fn paint_clipping_indicator(painter: &egui::Painter, at: Pos2, color: painter.add(egui::Shape::line(vec![at + vec2(2.0, 0.0), tip, at + vec2(8.0, 0.0)], stroke)); } +/// Where the row's disclosure triangle starts (after the eye column and the depth's indentation) and +/// the layer thumbnail's size, for a row `rect` with thumbnails of `base` (0 when off). The painted +/// row and an off-screen group's widget-only triangle share it, so the hit area is the same (#13117). +fn triangle_x_and_thumb_size(l: &Layer, depth: usize, rect: Rect, base: f32) -> (f32, f32) { + // Everything but the thumbnails, the indentation and the name, so a narrow panel squeezes + // the indentation first, then the thumbnails (a layer with two masks has three). + let others = 6.0 + + 28.0 + + if l.is_group() { crate::layer_tree_ui::TRIANGLE_W } else { 0.0 } + + if l.clipped { 12.0 } else { 0.0 } + + crate::layer_row_ui::reserved_width(l); + let ts = if base == 0.0 { 0.0 } else { crate::mask_thumbs_ui::thumb_size(l, base, rect.width() - others) }; + let fixed = others + if ts == 0.0 { 0.0 } else { ts + 6.0 + crate::mask_thumbs_ui::width(l, ts) }; + // A layer inside a group (or an artboard) indents one step more than its depth, past the + // triangle's column, so it sits right of its parent: with only its depth its thumbnail lined + // up under the group's, hiding the hierarchy. Top-level rows don't move. + let steps = if !l.is_group() && depth > 0 { depth + 1 } else { depth }; + (rect.left() + 6.0 + 28.0 + crate::layer_row_ui::indent(steps, rect.width(), fixed), ts) +} + /// Height of an artboard's row. Photoshop sets artboards apart from layers and groups in the /// Layers panel: a shorter row with the name in bold and no thumbnail (a board is a canvas, not a /// folder), so the boards read as headings over their layers (#10218). @@ -215,9 +235,14 @@ pub(super) fn layer_row( // Rows are painted: name them for screen readers and UI tests. resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, &l.name)); // A row scrolled out of view only keeps its place (#125): a layout's hundreds of rows would - // otherwise lay out names, icons and thumbnails every frame. Group rows stay whole: their - // disclosure triangle is a widget (accessibility, scroll-to). - if !ui.is_rect_visible(rect) && !l.is_group() && !resp.context_menu_opened() && crate::layer_row_ui::renaming(ctx) != Some(l.id.0) { + // otherwise lay out names, icons and thumbnails every frame. An off-screen group row keeps only + // its disclosure widget (accessibility, scroll-to) and paints nothing (#13117). A row whose + // menu (its own or the eye column's) is open, or that is being renamed, stays whole. + if !ui.is_rect_visible(rect) && !resp.context_menu_opened() && !eye_menu_open(ui, l) && crate::layer_row_ui::renaming(ctx) != Some(l.id.0) { + if l.is_group() { + let (x, _) = triangle_x_and_thumb_size(l, depth, rect, base); + crate::layer_tree_ui::disclosure_widget(ui, rect, x, l, actions); + } return rect; } let painter = ui.painter_at(rect.expand(1.0)); @@ -226,22 +251,8 @@ pub(super) fn layer_row( app.hover_layer = Some(l.id); } paint_row_background(&painter, &t, l, rect, selected, is_hovered); - let mut x = rect.left() + 6.0; let eye_resp = eye_column(app, ui, l, row, rect, actions); - // Everything but the thumbnails, the indentation and the name, so a narrow panel squeezes - // the indentation first, then the thumbnails (a layer with two masks has three). - let others = 6.0 - + 28.0 - + if l.is_group() { crate::layer_tree_ui::TRIANGLE_W } else { 0.0 } - + if l.clipped { 12.0 } else { 0.0 } - + crate::layer_row_ui::reserved_width(l); - let ts = if base == 0.0 { 0.0 } else { crate::mask_thumbs_ui::thumb_size(l, base, rect.width() - others) }; - let fixed = others + if ts == 0.0 { 0.0 } else { ts + 6.0 + crate::mask_thumbs_ui::width(l, ts) }; - // A layer inside a group (or an artboard) indents one step more than its depth, past the - // triangle's column, so it sits right of its parent: with only its depth its thumbnail lined - // up under the group's, hiding the hierarchy. Top-level rows don't move. - let steps = if !l.is_group() && depth > 0 { depth + 1 } else { depth }; - x += 28.0 + crate::layer_row_ui::indent(steps, rect.width(), fixed); + let (mut x, ts) = triangle_x_and_thumb_size(l, depth, rect, base); let toggled = crate::layer_tree_ui::disclosure(ui, rect, &mut x, l, actions); if l.clipped { paint_clipping_indicator(&painter, pos2(x, rect.center().y), t.text_faint); @@ -387,6 +398,18 @@ fn paint_row_background(painter: &egui::Painter, t: &Tokens, l: &Layer, rect: Re } } +/// The eye column's widget id. +fn eye_id(ui: &egui::Ui, l: &Layer) -> egui::Id { + ui.scope_id().with(("eye", l.id.0)) +} + +/// Whether the eye column's colour menu is open. It is the eye response's own context menu (egui +/// keys it `Popup::default_response_id`: the widget id with "popup"), not the row's, and egui closes +/// a popup that isn't shown in a frame, so a row with it open must not be culled. +fn eye_menu_open(ui: &egui::Ui, l: &Layer) -> bool { + egui::Popup::is_id_open(ui.ctx(), eye_id(ui, l).with("popup")) +} + /// The eye column: visibility toggle (⌥ shows only this layer), sweep-drag and its colour menu. fn eye_column(app: &mut PhotocraftApp, ui: &mut egui::Ui, l: &Layer, row: RowSel, rect: Rect, actions: &mut Vec<(String, Value)>) -> egui::Response { let ctx = &ui.ctx().clone(); @@ -395,7 +418,7 @@ fn eye_column(app: &mut PhotocraftApp, ui: &mut egui::Ui, l: &Layer, row: RowSel let eye_cell = eye_cell(rect); // The whole eye column takes drags too (so a drag starting on it never reorders the row): dragging down // the eyes gives every row swept over the visibility the first eye toggled to (#8467). - let eye_resp = ui.interact(eye_cell, ui.scope_id().with(("eye", l.id.0)), Sense::click_and_drag()); + let eye_resp = ui.interact(eye_cell, eye_id(ui, l), Sense::click_and_drag()); // A hidden layer's eye box is left empty (still clickable; the whole column takes the click, #8467). if l.visible { // Centre the drawing in the column while preserving the visibility hit area. diff --git a/crates/ui-egui/src/panels/layer_tree_ui.rs b/crates/ui-egui/src/panels/layer_tree_ui.rs index 1d7586f4c6..f6f36d4ae4 100644 --- a/crates/ui-egui/src/panels/layer_tree_ui.rs +++ b/crates/ui-egui/src/panels/layer_tree_ui.rs @@ -52,15 +52,33 @@ pub fn triangle_rect(row: Rect, x: f32) -> Rect { Rect::from_min_size(pos2(x - 2.0, row.top()), vec2(TRIANGLE_W + 2.0, row.height())) } -/// Paint and handle a group row's disclosure triangle at `*x` (advancing it). Returns true when -/// it was clicked this frame, so the row doesn't also treat the click as a selection. -pub fn disclosure(ui: &mut egui::Ui, row: Rect, x: &mut f32, l: &Layer, actions: &mut Vec<(String, Value)>) -> bool { +/// A group row's disclosure triangle as a widget only, at `x`: its hit area, the click that queues +/// `layer.setExpanded`, the tooltip and the accessibility label ("Expand group {name}" / "Collapse +/// group {name}"). Paints nothing, so a row scrolled out of view keeps the widget (accessibility, +/// scroll-to) without painting its row (#13117). `None` for a layer that is no group, or a frame. +pub fn disclosure_widget(ui: &mut egui::Ui, row: Rect, x: f32, l: &Layer, actions: &mut Vec<(String, Value)>) -> Option { if l.frame.is_some() { - return false; + return None; } + let LayerContent::Group(g) = &l.content else { return None }; + let resp = ui.interact(triangle_rect(row, x), ui.scope_id().with(("disclosure", l.id.0)), Sense::click()); + if resp.clicked() { + let all = ui.input(|i| i.modifiers.alt); + actions.push(("layer.setExpanded".into(), json!({"layer": l.id.0, "expanded": !g.expanded, "all": all}))); + } + let (verb, name) = (if g.expanded { tl!("Collapse") } else { tl!("Expand") }, l.name.clone()); + let tip = if g.expanded { tl!("Collapse group ({key}-click: all groups)") } else { tl!("Expand group ({key}-click: all groups)") }; + let resp = resp.on_hover_text(crate::i18n::fmt(tip, &[("key", &crate::shortcuts::pretty("Alt"))])); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("{verb} group {name}"))); + Some(resp) +} + +/// Paint and handle a group row's disclosure triangle at `*x` (advancing it): the widget of +/// [`disclosure_widget`] plus the triangle. Returns true when it was clicked this frame, so the row +/// doesn't also treat the click as a selection. +pub fn disclosure(ui: &mut egui::Ui, row: Rect, x: &mut f32, l: &Layer, actions: &mut Vec<(String, Value)>) -> bool { + let Some(resp) = disclosure_widget(ui, row, *x, l, actions) else { return false }; let LayerContent::Group(g) = &l.content else { return false }; - let hit = triangle_rect(row, *x); - let resp = ui.interact(hit, ui.scope_id().with(("disclosure", l.id.0)), Sense::click()); let t = Tokens::get(ui.ctx()); let c = pos2(*x + TRIANGLE_W / 2.0 - 1.0, row.center().y); let s = 3.5; @@ -72,16 +90,7 @@ pub fn disclosure(ui: &mut egui::Ui, row: Rect, x: &mut f32, l: &Layer, actions: let color = if resp.hovered() { t.text } else { t.icon }; ui.painter().add(Shape::convex_polygon(pts, color, Stroke::NONE)); *x += TRIANGLE_W; - let clicked = resp.clicked(); - if clicked { - let all = ui.input(|i| i.modifiers.alt); - actions.push(("layer.setExpanded".into(), json!({"layer": l.id.0, "expanded": !g.expanded, "all": all}))); - } - let (verb, name) = (if g.expanded { tl!("Collapse") } else { tl!("Expand") }, l.name.clone()); - let tip = if g.expanded { tl!("Collapse group ({key}-click: all groups)") } else { tl!("Expand group ({key}-click: all groups)") }; - let resp = resp.on_hover_text(crate::i18n::fmt(tip, &[("key", &crate::shortcuts::pretty("Alt"))])); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("{verb} group {name}"))); - clicked + resp.clicked() } #[cfg(test)] diff --git a/crates/ui-egui/src/panels/layer_tree_ui/tests.rs b/crates/ui-egui/src/panels/layer_tree_ui/tests.rs index dfc1f44fb0..0a0873e8cb 100644 --- a/crates/ui-egui/src/panels/layer_tree_ui/tests.rs +++ b/crates/ui-egui/src/panels/layer_tree_ui/tests.rs @@ -141,3 +141,91 @@ fn state_survives_psd_export_and_import_and_imported_groups_toggle() { click(&mut h, p, Modifiers::NONE); assert!(!group(&h, "outer").1); } + +/// Background, a collapsed group "Low Group" at the bottom of the list, 40 fillers above it (so it +/// sits below the Layers panel's fold) and a collapsed "High Group" on top (#13117). +fn long_list_with_groups() -> photocraft_engine::Session { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); + s.execute("layer.new.layer", json!({"name": "low child"})).unwrap(); + s.execute("layer.groupLayers", json!({"name": "Low Group"})).unwrap(); + for i in 0..40 { + s.execute("layer.new.layer", json!({"name": format!("Filler {i}")})).unwrap(); + } + s.execute("layer.new.layer", json!({"name": "high child"})).unwrap(); + s.execute("layer.groupLayers", json!({"name": "High Group"})).unwrap(); + s +} + +/// Every text painted in the harness's last frame, with its screen position. +fn painted_texts(h: &Harness<'_, PhotocraftApp>) -> Vec<(String, Pos2)> { + fn walk(s: &egui::Shape, out: &mut Vec<(String, Pos2)>) { + match s { + egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.pos)), + egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)), + _ => {} + } + } + let mut out = Vec::new(); + h.output().shapes.iter().for_each(|c| walk(&c.shape, &mut out)); + out +} + +/// #13117: a group row scrolled out of view paints nothing, like any other off-screen row; only +/// its disclosure widget stays (the next test). +#[test] +fn off_screen_group_paints_no_row() { + let h = harness_with(long_list_with_groups(), 1.0); + let window = h.ctx.content_rect(); + let low = h.get_by_label("Low Group").rect(); + let high = h.get_by_label("High Group").rect(); + assert!(low.top() >= window.bottom(), "Low Group sits below the fold: {low:?} vs {window:?}"); + assert!(window.contains_rect(high), "High Group shows: {high:?}"); + let named_in = |name: &str, row: egui::Rect| painted_texts(&h).iter().any(|(t, p)| t == name && p.y >= row.top() && p.y <= row.bottom()); + assert!(named_in("High Group", high), "the on-screen group's name is painted"); + assert!(!named_in("Low Group", low), "the off-screen group's row paints no name"); + // Nor any other text: no text shape lands in the off-screen row at all. + let in_low: Vec<_> = painted_texts(&h).into_iter().filter(|(_, p)| low.contains(*p)).collect(); + assert!(in_low.is_empty(), "the off-screen group's row adds no text shapes: {in_low:?}"); +} + +/// #13117: skipping the off-screen group's painting keeps its triangle a widget: it is listed for +/// accessibility, and scrolled to, it still toggles the group. +#[test] +fn off_screen_group_disclosure_stays_reachable() { + let mut h = harness_with(long_list_with_groups(), 1.0); + assert!(h.query_by_label("Expand group Low Group").is_some(), "the off-screen group keeps its disclosure widget"); + assert!(!group(&h, "Low Group").1); + let p = triangle(&mut h, "Low Group").expect("scrolled to the off-screen group's triangle"); + click(&mut h, p, Modifiers::NONE); + assert!(group(&h, "Low Group").1, "clicking it expands the group"); +} + +/// #13127 review: a group row whose eye-column colour menu is open stays whole when it scrolls +/// out of view. The menu is the eye's own popup, which egui closes if a frame doesn't show it. +#[test] +fn eye_menu_survives_its_group_scrolling_off_screen() { + let mut h = harness_with(long_list_with_groups(), 1.0); + let window = h.ctx.content_rect(); + let high = h.get_by_label("High Group").rect(); + assert!(window.contains_rect(high), "High Group shows: {high:?}"); + // Right-click High Group's eye column (the row's left 30 points): its colour menu opens. + let eye = egui::pos2(high.left() + 15.0, high.center().y); + h.hover_at(eye); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: eye, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: eye, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(3); + assert!(egui::Popup::is_any_open(&h.ctx), "the eye column's colour menu opened"); + // Scroll the list to its bottom group, taking High Group out of view, without a click. + h.query_by_label("Expand group Low Group").expect("Low Group's disclosure").scroll_to_me(); + h.run_steps(6); + let high = h.get_by_label("High Group").rect(); + let low = h.get_by_label("Low Group").rect(); + // Low Group is in view, and High Group sits more than a window's height above it, so it is + // outside the panel's (shorter) list. + assert!(window.contains_rect(low), "scrolled to Low Group: {low:?}"); + assert!(high.bottom() < low.top() - window.height(), "High Group is out of view: {high:?} vs {low:?}"); + assert!(egui::Popup::is_any_open(&h.ctx), "the colour menu stays open while its row is out of view"); +}