Skip to content

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

Command lookup: index registered and shell command IDs (#1156)

Elvis33LEf4d489eb967b
diff --git a/crates/engine/examples/bench_command_lookup.rs b/crates/engine/examples/bench_command_lookup.rs
new file mode 100644
index 000000000..919297771
--- /dev/null
+++ b/crates/engine/examples/bench_command_lookup.rs
@@ -0,0 +1,31 @@
+//! Registry lookup cost, separate from command execution and canvas refresh.
+//! Run with `cargo run --release -p photocraft-engine --example bench_command_lookup`.
+use photocraft_engine::commands;
+use std::hint::black_box;
+use std::time::Instant;
+
+fn main() {
+ let specs = commands::command_specs();
+ let mut ids: Vec<_> = specs.iter().map(|s| s.id).collect();
+ ids.extend(std::iter::repeat_n("missing.command", 100));
+ for (name, indexed) in [("linear reference", false), ("commands::find", true)] {
+ let mut samples = Vec::new();
+ for _ in 0..31 {
+ let t = Instant::now();
+ for _ in 0..100 {
+ for id in &ids {
+ let id = black_box(*id);
+ black_box(if indexed { commands::find(id) } else { specs.iter().find(|s| s.id == id) });
+ }
+ }
+ samples.push(t.elapsed().as_secs_f64() * 10.0);
+ }
+ samples.sort_by(f64::total_cmp);
+ println!(
+ "{name}: {} ids/batch, p50={:.6} ms p95={:.6} ms",
+ ids.len(),
+ samples.get(15).copied().unwrap_or_default(),
+ samples.get(29).copied().unwrap_or_default()
+ );
+ }
+}
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index e877372d8..91d723f0f 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -114,12 +114,33 @@ macro_rules! cmd {
}
pub fn command_specs() -> &'static [CommandSpec] {
- static SPECS: std::sync::OnceLock<Vec<CommandSpec>> = std::sync::OnceLock::new();
- SPECS.get_or_init(build)
+ &registry().specs
}
pub fn find(id: &str) -> Option<&'static CommandSpec> {
- command_specs().iter().find(|c| c.id == id)
+ let registry = registry();
+ registry.by_id.get(id).and_then(|&index| registry.specs.get(index))
+}
+
+struct Registry {
+ specs: Vec<CommandSpec>,
+ by_id: std::collections::HashMap<&'static str, usize>,
+}
+
+impl Registry {
+ fn new(specs: Vec<CommandSpec>) -> Self {
+ let mut by_id = std::collections::HashMap::with_capacity(specs.len());
+ for (index, spec) in specs.iter().enumerate() {
+ // Preserve the linear lookup's first-match behavior if an id is duplicated.
+ by_id.entry(spec.id).or_insert(index);
+ }
+ Self { specs, by_id }
+ }
+}
+
+fn registry() -> &'static Registry {
+ static REGISTRY: std::sync::OnceLock<Registry> = std::sync::OnceLock::new();
+ REGISTRY.get_or_init(|| Registry::new(build()))
}
// ---------- param helpers ----------
@@ -1263,3 +1284,20 @@ pub(crate) fn layer_copy(doc: &Document, id: LayerId) -> Result<Layer> {
}
Ok(dup)
}
+
+#[cfg(test)]
+mod registry_tests {
+ use super::*;
+
+ #[test]
+ fn duplicate_ids_keep_the_first_spec_and_listing_order() {
+ let mut built = build().into_iter();
+ let first = built.next().unwrap();
+ let mut second = built.next().unwrap();
+ let id = first.id;
+ second.id = id;
+ let registry = Registry::new(vec![first, second]);
+ assert_eq!(registry.by_id.get(id), Some(&0));
+ assert_eq!(registry.specs.len(), 2);
+ }
+}
diff --git a/crates/engine/tests/command_lookup.rs b/crates/engine/tests/command_lookup.rs
new file mode 100644
index 000000000..d0baec0af
--- /dev/null
+++ b/crates/engine/tests/command_lookup.rs
@@ -0,0 +1,17 @@
+//! Index lookups must return the same spec, in the same order, as the registry's public slice.
+use photocraft_engine::commands;
+
+#[test]
+fn every_lookup_matches_the_first_linear_match() {
+ let specs = commands::command_specs();
+ for spec in specs {
+ let linear = specs.iter().find(|s| s.id == spec.id).unwrap();
+ assert!(std::ptr::eq(commands::find(spec.id).unwrap(), linear), "{}", spec.id);
+ // The id need not be a static string: control/MCP dispatch owns its input.
+ let owned = spec.id.to_string();
+ assert!(std::ptr::eq(commands::find(&owned).unwrap(), linear));
+ }
+ for id in ["", "missing.command", "FILE.NEW", "file.new\0", "💾"] {
+ assert!(commands::find(id).is_none(), "{id:?}");
+ }
+}
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index f9cb95cdb..9ee9cfd1d 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -654,8 +654,9 @@ pub struct MenuItem {
/// Is `id` implemented by the engine or the shell (a live menu item)? Shared by the menus and
/// the parity report ([`crate::parity`]).
pub fn is_live(id: &str) -> bool {
+ static UI_IDS: std::sync::OnceLock<std::collections::HashSet<&'static str>> = std::sync::OnceLock::new();
photocraft_engine::commands::find(id).is_some()
- || UI_COMMANDS.iter().any(|c| c.0 == id)
+ || UI_IDS.get_or_init(|| UI_COMMANDS.iter().map(|c| c.0).collect()).contains(id)
|| panel_alias(id).is_some()
|| workspace_name(id).is_some()
|| proof_preset(id).is_some()
@@ -1176,6 +1177,19 @@ pub fn apply_workspace(app: &mut PhotocraftApp) {
mod tests {
use super::*;
+ #[test]
+ fn live_lookup_finds_engine_and_shell_commands() {
+ for command in photocraft_engine::commands::command_specs() {
+ assert!(is_live(command.id), "{}", command.id);
+ }
+ for &(id, ..) in UI_COMMANDS {
+ assert!(is_live(id), "{id}");
+ }
+ for id in ["", "missing.command", "💾"] {
+ assert!(!is_live(id));
+ }
+ }
+
#[test]
fn select_menu_contains_every_selection_context_action_and_more() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());