Skip to content

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

Command palette: recently run commands on an empty query (#1824)

Reynold Hu4ed4faee5164
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index c5d13111c..37a9e9364 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -124,7 +124,12 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Va
if crate::discard_ui::intercept(app, id, &params) {
return Ok(Value::Null);
}
- invoke_unguarded(app, ctx, id, params)
+ let r = invoke_unguarded(app, ctx, id, params)?;
+ // The palette's empty-query list (UI-217-7); opening the palette isn't a command to recall.
+ if id != "edit.search" {
+ crate::palette::note_recent(ctx, id);
+ }
+ Ok(r)
}
/// [`invoke`] without the unsaved-changes prompt, for once the user has already answered it.
diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs
index 199ac9699..fa149827b 100644
--- a/crates/ui-egui/src/palette.rs
+++ b/crates/ui-egui/src/palette.rs
@@ -36,6 +36,57 @@ pub fn fuzzy_score(query: &str, text: &str) -> Option<i32> {
Some(score - (t.len() as i32 / 8))
}
+/// How many recently run commands the palette remembers.
+const RECENT_CAP: usize = 8;
+
+/// The id of the palette's recently-run list (egui temp data: session-scoped, like the query).
+fn recent_id() -> egui::Id {
+ egui::Id::new("palette-recent")
+}
+
+/// Remember `id` as the most recently run command: deduplicated, newest first, capped.
+pub(crate) fn note_recent(ctx: &egui::Context, id: &str) {
+ ctx.data_mut(|d| {
+ let mut list: Vec<String> = d.get_temp(recent_id()).unwrap_or_default();
+ push_recent(&mut list, id, RECENT_CAP);
+ d.insert_temp(recent_id(), list);
+ });
+}
+
+/// The palette's recently run commands, newest first (for tests).
+#[cfg(test)]
+pub(crate) fn recent_ids(ctx: &egui::Context) -> Vec<String> {
+ ctx.data(|d| d.get_temp(recent_id()).unwrap_or_default())
+}
+
+/// [`note_recent`]'s core: move `id` to the front, dropping the oldest past `cap`.
+fn push_recent(list: &mut Vec<String>, id: &str, cap: usize) {
+ list.retain(|x| x != id);
+ list.insert(0, id.to_string());
+ list.truncate(cap);
+}
+
+/// The empty-query hits: the recent commands as rows, newest first (UI-217-7). Ids that are
+/// no longer menu commands are skipped.
+fn recent_hits(recents: &[String], menus: &[crate::menus::MenuItem], lang: crate::i18n::Lang) -> Vec<(i32, String, String, Option<String>, bool)> {
+ recents
+ .iter()
+ .enumerate()
+ .filter_map(|(i, id)| {
+ let m = menus.iter().find(|m| &m.id == id)?;
+ let path = m.path.iter().map(|p| crate::i18n::tr(lang, p)).collect::<Vec<_>>().join(" › ");
+ let label = crate::i18n::tr_id(lang, &m.id, &m.label);
+ Some((
+ 1000 - i as i32,
+ m.id.clone(),
+ label.trim_end_matches('…').to_string(),
+ Some(path + &m.shortcut.as_ref().map(|s| format!(" {}", crate::shortcuts::pretty(s))).unwrap_or_default()),
+ m.enabled,
+ ))
+ })
+ .collect()
+}
+
pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
if !app.ui.palette_open {
return;
@@ -86,9 +137,14 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
crate::widgets::hairline(ui);
ui.add_space(6.0);
let lang = crate::i18n::Lang::from_pref(&app.session.prefs().interface.language);
- let mut hits: Vec<(i32, String, String, Option<String>, bool)> = crate::menus::menu_items(app)
- .into_iter()
- .filter_map(|m| {
+ let menus = crate::menus::menu_items(app);
+ let recents: Vec<String> = ui.data(|d| d.get_temp(recent_id()).unwrap_or_default());
+ let empty = q.trim().is_empty();
+ // An empty query lists the recently run commands (UI-217-7); with none (or a
+ // fresh session) it falls back to the full fuzzy list, as before.
+ let mut hits: Vec<(i32, String, String, Option<String>, bool)> = if empty { recent_hits(&recents, &menus, lang) } else { Vec::new() };
+ if !empty || hits.is_empty() {
+ hits.extend(menus.into_iter().filter_map(|m| {
let path_en = m.path.join(" › ");
let path = m.path.iter().map(|p| crate::i18n::tr(lang, p)).collect::<Vec<_>>().join(" › ");
let label = crate::i18n::tr_id(lang, &m.id, &m.label);
@@ -101,11 +157,11 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
Some(path + &m.shortcut.map(|s| format!(" {}", crate::shortcuts::pretty(&s))).unwrap_or_default()),
m.enabled,
))
- })
- .collect();
- for tool in crate::state::Tool::ALL {
- if let Some(s) = fuzzy_score(&q, &format!("{} {}", tl!(tool.label()), tool.label())) {
- hits.push((s + 2, format!("tool:{tool:?}"), tl!(tool.label()).into(), Some(format!("Tool {}", tool.key())), true));
+ }));
+ for tool in crate::state::Tool::ALL {
+ if let Some(s) = fuzzy_score(&q, &format!("{} {}", tl!(tool.label()), tool.label())) {
+ hits.push((s + 2, format!("tool:{tool:?}"), tl!(tool.label()).into(), Some(format!("Tool {}", tool.key())), true));
+ }
}
}
hits.sort_by(|a, b| b.0.cmp(&a.0).then(a.2.cmp(&b.2)));
@@ -184,7 +240,7 @@ mod tests {
use egui_kittest::Harness;
use serde_json::json;
- use super::fuzzy_score;
+ use super::{fuzzy_score, push_recent};
use crate::PhotocraftApp;
#[test]
@@ -206,6 +262,59 @@ mod tests {
assert_eq!(interrupts, [None, Some(false), Some(false), Some(false)]);
}
+ #[test]
+ fn push_recent_moves_to_the_front_and_caps() {
+ let mut l = Vec::new();
+ push_recent(&mut l, "b", 3);
+ push_recent(&mut l, "a", 3);
+ push_recent(&mut l, "c", 3);
+ assert_eq!(l, ["c", "a", "b"]);
+ push_recent(&mut l, "a", 3);
+ assert_eq!(l, ["a", "c", "b"], "re-running a command moves it to the front");
+ push_recent(&mut l, "d", 3);
+ assert_eq!(l, ["d", "a", "c"], "the oldest falls off the cap");
+ }
+
+ #[test]
+ fn the_palette_records_and_replays_recent_commands_on_an_empty_query() {
+ let mut h = Harness::builder().with_size(vec2(1200.0, 800.0)).with_max_steps(64).build_eframe(|cc| {
+ PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
+ PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default())
+ });
+ h.state_mut().run("file.new", json!({"width": 64, "height": 64})).unwrap();
+ h.state_mut().sync_views();
+ let ctx = h.ctx.clone();
+ // Run "Keyboard Shortcuts" through the palette: it becomes the recent command.
+ crate::menus::invoke(h.state_mut(), &ctx, "edit.search", json!({})).unwrap();
+ h.run_steps(2);
+ h.event(Event::Text("keyboard shortcuts".into()));
+ h.run_steps(2);
+ h.event(Event::Key { key: Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });
+ h.run_steps(3);
+ assert_eq!(super::recent_ids(&ctx).len(), 1, "the command the palette ran is remembered");
+ // Close its dialog, reopen the palette with an empty query and press Enter: the recent
+ // command is the first hit, so the same dialog opens again.
+ let dialog = h
+ .state()
+ .ui
+ .dialogs
+ .iter()
+ .find(|d| d.fields.get("__prefsui").and_then(|v| v.as_str()) == Some("shortcuts"))
+ .map(|d| d.id)
+ .expect("the shortcuts dialog");
+ h.state_mut().ui.close_dialog(dialog);
+ h.run_steps(2);
+ crate::menus::invoke(h.state_mut(), &ctx, "edit.search", json!({})).unwrap();
+ h.run_steps(2);
+ h.event(Event::Key { key: Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });
+ h.run_steps(3);
+ assert!(
+ h.state().ui.dialogs.iter().any(|d| d.fields.get("__prefsui").and_then(|v| v.as_str()) == Some("shortcuts")),
+ "the empty-query palette runs the recent command"
+ );
+ assert_eq!(super::recent_ids(&ctx).len(), 1, "re-running it moves it to the front, no duplicate");
+ }
+
#[test]
fn fuzzy_ranks_prefix_and_contiguous_higher() {
assert!(fuzzy_score("hue", "Hue/Saturation…").unwrap() > fuzzy_score("hue", "Channel Mixer Hue").unwrap_or(-99));
diff --git a/docs/scorecard.md b/docs/scorecard.md
index 291d66c60..10d41ba2c 100644
--- a/docs/scorecard.md
+++ b/docs/scorecard.md
@@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js
| [Performance](#performance) | 3 | 22 | 14 | 48 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 7 not run, 7 not measurable yet (baseline 2026-10-05) |
| [File compatibility](#file-compatibility) | 4 | 12 | 11 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 307/309; photoshop oracles: oracle ≥ 133/256, round trip ≥ 258/256 |
| [Tools](#tools) | 12 | 14 | 8 | |
-| [Workspace and UI](#workspace-and-ui) | 3 | 7 | 13 | settings that do nothing: 55 of 141 (target 0) |
+| [Workspace and UI](#workspace-and-ui) | 4 | 7 | 12 | settings that do nothing: 55 of 141 (target 0) |
| [Type](#type) | 0 | 3 | 6 | |
| [Automation](#automation) | 3 | 2 | 6 | 627 of 627 menu items live (100.0%) |
| [Reliability](#reliability) | 5 | 0 | 2 | never-crash lints on 28 of 28 crates; panic_hunt present |
@@ -171,7 +171,7 @@ Unread: `general.color_picker`, `general.beep_when_done`, `general.export_clipbo
| UI-217-4 | Preferences all take effect; recent files persist and honour recent_file_count (#204) | missing | [#217](https://github.com/storytold/photocraft/issues/217) | See the prefs audit and BUG-204-* |
| UI-217-5 | Panel groups can float (menu + drag out of the dock) and are restored at launch | missing | [#217](https://github.com/storytold/photocraft/issues/217) | No floating groups in dock.rs/panels.rs |
| UI-217-6 | Document tabs: overflow list, context menu (Close/Others/All/Reveal), drag to reorder | partial | [#217](https://github.com/storytold/photocraft/issues/217) | canvas.rs: Close/Others/All context menu with unsaved prompt; overflow, Reveal, drag reorder still missing |
-| UI-217-7 | Command palette shows recently run commands on an empty query | missing | [#217](https://github.com/storytold/photocraft/issues/217) | palette.rs:83-108 fuzzy hits only |
+| UI-217-7 | Command palette shows recently run commands on an empty query | done | [#217](https://github.com/storytold/photocraft/issues/217) | palette.rs: note_recent from menus::invoke keeps the last 8 commands (dedup, newest first); an empty query lists them via recent_hits; the_palette_records_and_replays_recent_commands_on_an_empty_query covers record -> empty query -> replay |
| UI-217-8 | Tool-specific canvas right-click menu; right-click spelling suggestions in text fields | partial | [#217](https://github.com/storytold/photocraft/issues/217) | paint_mouse.rs brush picker and canvas_tool_menu.rs selection actions; other tools and text spelling menus missing |
| UI-217-9 | UI scale presets 100/115/125/150/200 % through zoom_factor, remembered | missing | [#217](https://github.com/storytold/photocraft/issues/217) | prefs.rs:61 UiScale unused; input_tests.rs:71 asserts zoom_factor stays 1.0 |
| UI-217-10 | Appearance: animation toggle, canvas pattern toggle per theme, start-screen recents | missing | [#217](https://github.com/storytold/photocraft/issues/217) | No such prefs; start screen (canvas.rs:825) has no recents |
diff --git a/scorecard/ui.toml b/scorecard/ui.toml
index 444376f2e..6ddd33245 100644
--- a/scorecard/ui.toml
+++ b/scorecard/ui.toml
@@ -50,9 +50,9 @@ note = "canvas.rs: Close/Others/All context menu with unsaved prompt; overflow,
[[item]]
id = "UI-217-7"
target = "Command palette shows recently run commands on an empty query"
-status = "missing"
+status = "done"
issue = 217
-note = "palette.rs:83-108 fuzzy hits only"
+note = "palette.rs: note_recent from menus::invoke keeps the last 8 commands (dedup, newest first); an empty query lists them via recent_hits; the_palette_records_and_replays_recent_commands_on_an_empty_query covers record -> empty query -> replay"
[[item]]
id = "UI-217-8"