Skip to content

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

Help › Search: find any menu command by name (#815)

jason4shorta20c63521d16
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 0c3f6991f..28d269918 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -795,7 +795,15 @@ pub fn menu_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> f32 {
if mine.is_empty() {
ui.weak(crate::i18n::tr(lang, "(coming soon)"));
}
- render_level(ui, &mine, 1, &mut clicked, &mut nav);
+ if top == "Help" {
+ // The search field scrolls with the rows, as part of the menu's content.
+ crate::menu_nav::level(ui, 1, &mut nav, |ui, nav| {
+ help_search(ui, items, &mut clicked, nav);
+ render_level_rows(ui, &mine, 1, &mut clicked, nav);
+ });
+ } else {
+ render_level(ui, &mine, 1, &mut clicked, &mut nav);
+ }
});
buttons.push(title);
}
@@ -875,6 +883,98 @@ fn switch_on_hover(ctx: &egui::Context, buttons: &[egui::Response]) {
}
}
+/// Most results the Help menu search lists.
+const HELP_SEARCH_MAX: usize = 15;
+
+/// How well `query` (lowercase) matches a menu item: its label starting with it, then a word of
+/// the label starting with it, then anywhere in the label, then anywhere in its menu path.
+/// `None` when it doesn't match at all.
+pub fn search_rank(query: &str, label: &str, path: &[String]) -> Option<u8> {
+ let l = label.to_lowercase();
+ if l.starts_with(query) {
+ Some(0)
+ } else if l.split(|c: char| !c.is_alphanumeric()).any(|w| w.starts_with(query)) {
+ Some(1)
+ } else if l.contains(query) {
+ Some(2)
+ } else if path.iter().any(|p| p.to_lowercase().contains(query)) {
+ Some(3)
+ } else {
+ None
+ }
+}
+
+/// Menu items matching `query`, best first (Photoshop order within a rank). Both the English
+/// labels and their `lang` translations match, so a search works in the UI language and in
+/// English; untranslated strings are simply their English text.
+pub fn search_items<'a>(items: &'a [MenuItem], query: &str, lang: crate::i18n::Lang) -> Vec<&'a MenuItem> {
+ let q = query.trim().to_lowercase();
+ if q.is_empty() {
+ return Vec::new();
+ }
+ let rank = |it: &MenuItem| {
+ let english = search_rank(&q, &it.label, &it.path);
+ let path: Vec<String> = it.path.iter().map(|p| crate::i18n::tr(lang, p).to_string()).collect();
+ let local = search_rank(&q, crate::i18n::tr_id(lang, &it.id, &it.label), &path);
+ english.into_iter().chain(local).min()
+ };
+ let mut hits: Vec<(u8, usize, &MenuItem)> =
+ items.iter().enumerate().filter(|(_, it)| it.label != "---").filter_map(|(i, it)| rank(it).map(|r| (r, i, it))).collect();
+ hits.sort_by_key(|(r, i, _)| (*r, *i));
+ let mut seen = std::collections::HashSet::new();
+ hits.into_iter().filter(|(_, _, it)| seen.insert(it.id.as_str())).take(HELP_SEARCH_MAX).map(|(_, _, it)| it).collect()
+}
+
+/// Help › Search : a field at the top of the Help menu that finds any menu command
+/// by name. Results show their menu path; click, ↓ then ↩, or ↩ in the field runs one.
+fn help_search(ui: &mut egui::Ui, items: &[MenuItem], clicked: &mut Option<String>, nav: &mut crate::menu_nav::Nav) {
+ let ctx = ui.ctx().clone();
+ let lang = crate::i18n::current();
+ let text_id = egui::Id::new("help-menu-search");
+ let pass_id = text_id.with("pass");
+ // A fresh opening of the Help menu starts empty, with the field focused.
+ let pass = ctx.cumulative_pass_nr();
+ let reopened = ctx.data(|d| d.get_temp::<u64>(pass_id)).is_none_or(|p| p + 1 < pass);
+ ctx.data_mut(|d| d.insert_temp(pass_id, pass));
+ let mut query: String = if reopened { String::new() } else { ctx.data(|d| d.get_temp(text_id)).unwrap_or_default() };
+ let field = ui.add(egui::TextEdit::singleline(&mut query).id(text_id.with("field")).hint_text(crate::i18n::tr(lang, "Search menus")).desired_width(220.0));
+ if reopened {
+ field.request_focus();
+ }
+ let results = search_items(items, &query, lang);
+ if field.lost_focus()
+ && ui.input(|i| i.key_pressed(egui::Key::Enter))
+ && let Some(it) = results.iter().find(|it| it.enabled)
+ {
+ *clicked = Some(it.id.clone());
+ ui.close();
+ }
+ ctx.data_mut(|d| d.insert_temp(text_id, query.clone()));
+ if !query.trim().is_empty() {
+ if results.is_empty() {
+ ui.weak(crate::i18n::tr(lang, "No matching commands"));
+ }
+ for it in results {
+ let mut trail: Vec<&str> = it.path.iter().map(|p| crate::i18n::tr(lang, p)).collect();
+ trail.push(crate::i18n::tr_id(lang, &it.id, &it.label));
+ let mut b = egui::Button::new(trail.join(" › "));
+ if let Some(sc) = &it.shortcut {
+ b = b.shortcut_text(crate::shortcuts::pretty(sc));
+ }
+ let hit = nav.row(ui, 0, it.enabled, Some(&it.id), |ui, _| {
+ let r = ui.add_enabled(it.enabled, b);
+ let hit = r.clicked() || released_on(ui, &r);
+ (r, hit)
+ });
+ if hit {
+ *clicked = Some(it.id.clone());
+ ui.close();
+ }
+ }
+ }
+ ui.separator();
+}
+
fn render_level(ui: &mut egui::Ui, items: &[&MenuItem], depth: usize, clicked: &mut Option<String>, nav: &mut crate::menu_nav::Nav) {
// Menu popups can be taller than the window: each level stays on screen and scrolls (wheel,
// scroll arrows, keyboard), like a native menu on a small display.
@@ -1105,6 +1205,36 @@ mod tests {
assert!(harness.query_by_label_contains("Duplicate…").is_some(), "Image menu should open on hover");
}
+ #[test]
+ fn help_search_finds_commands_by_any_word() {
+ let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ let items = menu_items(&app);
+ let ids = |q: &str| search_items(&items, q, crate::i18n::Lang::EN).iter().map(|i| i.id.clone()).collect::<Vec<_>>();
+ let di = ids("DI");
+ assert!(di.contains(&"edit.transform.distort".to_string()), "{di:?}");
+ assert!(di.len() <= HELP_SEARCH_MAX);
+ // A word inside the label matches too, and a label match outranks a path-only match.
+ assert!(ids("selection").contains(&"select.transformSelection".to_string()));
+ assert_eq!(search_rank("dis", "Distort", &[]), Some(0));
+ assert_eq!(search_rank("sel", "Transform Selection", &[]), Some(1));
+ assert_eq!(search_rank("orm", "Transform Selection", &[]), Some(2));
+ assert_eq!(search_rank("trans", "Distort", &["Edit".into(), "Transform".into()]), Some(3));
+ assert!(ids(" ").is_empty());
+ assert!(ids("zzzzqqq").is_empty());
+ }
+
+ /// In another UI language both the translated and the English names match.
+ #[test]
+ fn help_search_matches_the_ui_language_and_english() {
+ let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ let items = menu_items(&app);
+ let Some(fr) = crate::i18n::Lang::from_code("fr") else { return };
+ let ids = |q: &str| search_items(&items, q, fr).iter().map(|i| i.id.clone()).collect::<Vec<_>>();
+ assert!(!ids("calque").is_empty(), "French menu name");
+ assert!(ids("distort").contains(&"edit.transform.distort".to_string()), "English still matches");
+ assert!(ids("zzzzqqq").is_empty());
+ }
+
#[test]
fn dropdown_items_have_room() {
use egui_kittest::{Harness, kittest::Queryable};