Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

fix(ui): keep menus responsive on documents with thousands of layers (#2454)

Manuel Montoto0140ffdf9def
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index 1cc8502f0..5d6ce28f6 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -937,7 +937,18 @@ impl Document {
}
pub fn path_of(&self, id: LayerId) -> Option<LayerPath> {
- self.walk().into_iter().find(|(_, _, l)| l.id == id).map(|(p, _, _)| p)
+ fn rec(layers: &[Layer], id: LayerId, path: &mut LayerPath) -> bool {
+ for (i, l) in layers.iter().enumerate() {
+ path.push(i);
+ if l.id == id || l.children().is_some_and(|ch| rec(ch, id, path)) {
+ return true;
+ }
+ path.pop();
+ }
+ false
+ }
+ let mut path = Vec::new();
+ rec(&self.layers, id, &mut path).then_some(path)
}
/// The locks in force on the layer at `path`: its own and those of every group around it,
@@ -952,8 +963,10 @@ impl Document {
}
pub fn layer(&self, id: LayerId) -> Option<&Layer> {
- let path = self.path_of(id)?;
- self.layer_at(&path)
+ fn rec(layers: &[Layer], id: LayerId) -> Option<&Layer> {
+ layers.iter().find_map(|l| if l.id == id { Some(l) } else { l.children().and_then(|ch| rec(ch, id)) })
+ }
+ rec(&self.layers, id)
}
pub fn layer_mut(&mut self, id: LayerId) -> Option<&mut Layer> {
@@ -1198,6 +1211,27 @@ mod tests {
assert_eq!(d.layer_count(), 4);
}
+ /// `layer` and `path_of` search the tree directly (no `walk`): they must agree with it at
+ /// every depth, and miss cleanly.
+ #[test]
+ fn layer_lookup_agrees_with_walk() {
+ let mut d = doc();
+ let format = d.pixel_format();
+ let leaf = |n: &str| Layer::raster(n, format);
+ let deep = Layer::group("A", vec![leaf("a0"), Layer::group("B", vec![leaf("b0"), Layer::group("C", vec![leaf("c0")]), leaf("b2")]), leaf("a2")]);
+ d.insert_above(None, deep);
+ d.insert_above(None, leaf("top"));
+ let walk: Vec<(LayerPath, LayerId)> = d.walk().into_iter().map(|(p, _, l)| (p, l.id)).collect();
+ assert_eq!(walk.len(), 10);
+ for (path, id) in &walk {
+ assert_eq!(d.path_of(*id).as_ref(), Some(path));
+ assert_eq!(d.layer(*id).map(|l| l.id), Some(*id));
+ assert_eq!(d.layer_mut(*id).map(|l| l.id), Some(*id));
+ }
+ let missing = Layer::raster("elsewhere", d.pixel_format()).id;
+ assert!(d.path_of(missing).is_none() && d.layer(missing).is_none() && d.layer_mut(missing).is_none());
+ }
+
#[test]
fn a_locked_group_locks_its_contents() {
let mut d = doc();
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index fd2c2b4e7..7beb0d37c 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -408,6 +408,8 @@ pub struct PhotocraftApp {
live_stroke: Option<canvas::LiveStroke>,
/// Footprint trail of a retouching drag (see `stroke_trail`).
trail: Option<stroke_trail::Trail>,
+ /// The open menus' items, reused between frames (`menus::ItemCache`).
+ pub(crate) menu_cache: Option<menus::ItemCache>,
/// Move tool drag shown live (`move_ui`).
pub(crate) move_preview: Option<move_ui::MovePreview>,
/// A blend mode hovered in the Layers panel, shown live (`blend_preview`).
@@ -610,6 +612,7 @@ impl PhotocraftApp {
tool_override: None,
live_stroke: None,
trail: None,
+ menu_cache: None,
move_preview: None,
blend_preview: None,
patch_preview: None,
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 03db139ca..54c30ab4f 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -915,11 +915,29 @@ fn menu_tint(name: &str) -> Option<egui::Color32> {
})
}
+/// The open menus' items, kept between frames: building them asks every command whether it can
+/// run, which on a document with thousands of layers costs far more than a frame.
+pub(crate) struct ItemCache {
+ /// [`crate::native_menu::state_hash`] of the state the items were built from.
+ state: u64,
+ items: Vec<MenuItem>,
+}
+
+impl ItemCache {
+ /// The items, while they still describe `state`. A frame with a click or key press rebuilds
+ /// them, which covers state the hash doesn't list.
+ fn reuse(self, state: u64, input: bool) -> Option<Vec<MenuItem>> {
+ (!input && self.state == state).then_some(self.items)
+ }
+}
+
/// Draws the menu bar; returns the right edge of the last menu title (the bar itself fills the row).
pub fn menu_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> f32 {
// Built only while a menu is open: every item's enabled/checked state scales with the
- // document (layer lookups), which cost milliseconds per frame on large layouts (#125).
- let items: std::cell::OnceCell<Vec<MenuItem>> = std::cell::OnceCell::new();
+ // document (layer lookups), which cost milliseconds per frame on large layouts (#125). While
+ // one stays open, the items are reused until what they depend on changes.
+ let kept = std::cell::Cell::new(app.menu_cache.take());
+ let built: std::cell::OnceCell<ItemCache> = std::cell::OnceCell::new();
let app_ref: &PhotocraftApp = app;
let mut right = ui.cursor().left();
let lang = crate::i18n::current();
@@ -964,7 +982,14 @@ pub fn menu_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> f32 {
.style(config.style.clone())
.info(egui::UiStackInfo::new(egui::UiKind::Menu).with_tag_value(egui::containers::menu::MenuConfig::MENU_CONFIG_TAG, config))
.show(|ui| {
- let items = items.get_or_init(|| menu_items(app_ref));
+ let items = &built
+ .get_or_init(|| {
+ let state = crate::native_menu::state_hash(app_ref, None);
+ let input = crate::native_menu::had_input(ui.ctx());
+ let items = kept.take().and_then(|c| c.reuse(state, input)).unwrap_or_else(|| menu_items(app_ref));
+ ItemCache { state, items }
+ })
+ .items;
let mine: Vec<&MenuItem> = items.iter().filter(|i| i.path.first().map(String::as_str) == Some(top)).collect();
ui.set_min_width(220.0);
if mine.is_empty() {
@@ -989,6 +1014,8 @@ pub fn menu_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> f32 {
});
});
nav.store(ui.ctx());
+ // No menu open this frame: nothing is kept.
+ app.menu_cache = built.into_inner();
// The press-drag gesture ends with the button (its release was handled by the rows above).
if ui.input(|i| i.pointer.primary_released() || !i.pointer.primary_down()) {
ui.ctx().data_mut(|d| d.remove::<bool>(press_gesture_id()));
@@ -1484,6 +1511,42 @@ mod tests {
assert!(harness.query_by_label_contains("Duplicate…").is_some(), "Image menu should open on hover");
}
+ /// An open menu reuses its items between frames (building them costs far more than a frame on
+ /// a document with thousands of layers), rebuilds them when the state changes under it, and
+ /// keeps nothing once it closes.
+ #[test]
+ fn an_open_menu_reuses_its_items_until_the_state_changes() {
+ use egui_kittest::{Harness, kittest::Queryable};
+
+ let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ let mut harness = Harness::builder().with_size(egui::vec2(1200.0, 700.0)).build_ui_state(
+ |ui, app| {
+ menu_bar(app, ui);
+ },
+ app,
+ );
+ PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]);
+ harness.run_steps(3);
+ assert!(harness.state().menu_cache.is_none(), "no menu open, nothing built");
+ harness.get_by_label("File").click();
+ harness.run_steps(3);
+ // The same allocation frame after frame: the items were not rebuilt.
+ let built = |app: &PhotocraftApp| app.menu_cache.as_ref().map(|c| c.items.as_ptr());
+ let close = |app: &PhotocraftApp| app.menu_cache.as_ref().and_then(|c| c.items.iter().find(|i| i.id == "file.close")).map(|i| i.enabled);
+ let first = built(harness.state());
+ assert!(first.is_some());
+ assert_eq!(close(harness.state()), Some(false));
+ harness.run_steps(3);
+ assert_eq!(built(harness.state()), first);
+ // A document opened under the open menu (a job ending, an agent): the items follow.
+ harness.state_mut().run("file.new", json!({"width": 8, "height": 8})).unwrap();
+ harness.run_steps(1);
+ assert_eq!(close(harness.state()), Some(true));
+ harness.key_press(egui::Key::Escape);
+ harness.run_steps(3);
+ assert!(harness.state().menu_cache.is_none(), "closed, nothing kept");
+ }
+
#[test]
fn help_search_finds_commands_by_any_word() {
let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
diff --git a/crates/ui-egui/src/native_menu.rs b/crates/ui-egui/src/native_menu.rs
index 847217e98..6b6101d9e 100644
--- a/crates/ui-egui/src/native_menu.rs
+++ b/crates/ui-egui/src/native_menu.rs
@@ -683,8 +683,7 @@ pub fn run(app: &mut PhotocraftApp, ctx: &egui::Context) {
/// every command's enabled state, so it doesn't run on frames that only animate or scroll.
pub fn sync(app: &mut PhotocraftApp, ctx: &egui::Context) {
let Some(menu) = app.services.native_menu.as_ref() else { return };
- let input = ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Key { pressed: true, .. } | egui::Event::PointerButton { pressed: false, .. })));
- let state = state_hash(app, input.then_some(app.frame));
+ let state = state_hash(app, had_input(ctx).then_some(app.frame));
if menu.state == Some(state) && !menu.dirty {
return;
}
@@ -706,16 +705,23 @@ pub fn sync(app: &mut PhotocraftApp, ctx: &egui::Context) {
menu.dirty = false;
}
+/// A click or key press this frame: it may have changed state [`state_hash`] doesn't list.
+pub(crate) fn had_input(ctx: &egui::Context) -> bool {
+ ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Key { pressed: true, .. } | egui::Event::PointerButton { pressed: false, .. })))
+}
+
/// What the menus' rows depend on, cheaply: commands run, the documents and their revisions,
/// selection, recent files, panels and view state, the language. `input` forces a change on
/// frames with a click or key press, which covers state the hash doesn't list.
-fn state_hash(app: &PhotocraftApp, input: Option<u64>) -> u64 {
+pub(crate) fn state_hash(app: &PhotocraftApp, input: Option<u64>) -> u64 {
let mut h = DefaultHasher::new();
input.hash(&mut h);
let s = &app.session;
s.journal.len().hash(&mut h);
s.active_index().hash(&mut h);
s.clipboard.is_some().hash(&mut h);
+ // A running job greys the commands that would change its document.
+ s.has_jobs().hash(&mut h);
if let Some(d) = s.active() {
(d.doc.id.0, d.revision, d.active_layer.map(|l| l.0), d.selected_layers.len(), d.isolated_layers.len()).hash(&mut h);
}