Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

macOS: Settings… is in the app menu

aiongg60f2c597a573
diff --git a/apps/designcraft/src/native_menu.rs b/apps/designcraft/src/native_menu.rs
index 8bf75b159..bc6189d00 100644
--- a/apps/designcraft/src/native_menu.rs
+++ b/apps/designcraft/src/native_menu.rs
@@ -6,7 +6,7 @@ use std::collections::HashMap;
use std::str::FromStr;
use designcraft_ui_egui::DesignApp;
-use designcraft_ui_egui::menus::{self, Item};
+use designcraft_ui_egui::menus::{self, AppMenuItem, Item};
use muda::accelerator::Accelerator;
use muda::{CheckMenuItem, Menu, MenuEvent, MenuItem, PredefinedMenuItem, Submenu};
use serde_json::Value;
@@ -30,32 +30,38 @@ fn accel(sc: &str) -> Option<Accelerator> {
Accelerator::from_str(&sc.replace("Cmd", "CMD").replace("Alt", "ALT").replace("Shift", "SHIFT").replace("Ctrl", "CTRL")).ok()
}
+/// A command's default shortcut, as the in-window menus show it.
+fn shortcut(id: &str) -> Option<&'static str> {
+ menus::ui_label(id).and_then(|(_, sc)| sc).or_else(|| designcraft_engine::find_command(id).and_then(|c| c.shortcut))
+}
+
impl NativeMenu {
pub fn install(app: &mut DesignApp) -> Self {
let menu = Menu::new();
let mut items = HashMap::new();
let mut counter = 0usize;
- // Application menu.
+ // Application menu: our own About splash (with the community links) instead of the stock
+ // panel, and Settings… (Edit › Preferences… on the other platforms).
let app_menu = Submenu::new("DesignCraft", true);
- // Our own About splash (with the community links) instead of the stock panel.
- let about = MenuItem::with_id("dc-about", "About DesignCraft", true, None);
- let discord = MenuItem::with_id("dc-discord", "Join the ArtCraft Discord…", true, None);
- let _ = app_menu.append_items(&[
- &about,
- &discord,
- &PredefinedMenuItem::separator(),
- &PredefinedMenuItem::services(None),
- &PredefinedMenuItem::separator(),
- &PredefinedMenuItem::hide(None),
- &PredefinedMenuItem::hide_others(None),
- &PredefinedMenuItem::show_all(None),
- &PredefinedMenuItem::separator(),
- &PredefinedMenuItem::quit(None),
- ]);
- items.insert("dc-about".into(), ("help.about".into(), serde_json::Value::Null, Handle::Plain(about)));
- items.insert("dc-discord".into(), ("help.discord".into(), serde_json::Value::Null, Handle::Plain(discord)));
+ for entry in menus::MAC_APP_MENU {
+ let _ = match *entry {
+ AppMenuItem::Cmd { id, label, command } => {
+ let sc = shortcut(command).and_then(accel);
+ let item = MenuItem::with_id(id, designcraft_ui_egui::i18n::tr(&app.ui.language, label), true, sc);
+ let appended = app_menu.append(&item);
+ items.insert(id.into(), (command.into(), Value::Null, Handle::Plain(item)));
+ appended
+ }
+ AppMenuItem::Sep => app_menu.append(&PredefinedMenuItem::separator()),
+ AppMenuItem::Services => app_menu.append(&PredefinedMenuItem::services(None)),
+ AppMenuItem::Hide => app_menu.append(&PredefinedMenuItem::hide(None)),
+ AppMenuItem::HideOthers => app_menu.append(&PredefinedMenuItem::hide_others(None)),
+ AppMenuItem::ShowAll => app_menu.append(&PredefinedMenuItem::show_all(None)),
+ AppMenuItem::Quit => app_menu.append(&PredefinedMenuItem::quit(None)),
+ };
+ }
let _ = menu.append(&app_menu);
- for (title, entries) in menus::menu_tree() {
+ for (title, entries) in menus::native_menu_tree() {
let sub = Submenu::new(designcraft_ui_egui::i18n::tr(&app.ui.language, title), true);
build(app, &sub, &entries, &mut items, &mut counter);
let _ = menu.append(&sub);
@@ -65,7 +71,7 @@ impl NativeMenu {
app.native_shortcuts = items
.values()
.filter_map(|(id, p, _)| {
- let sc = menus::ui_label(id).and_then(|(_, sc)| sc).or_else(|| designcraft_engine::find_command(id).and_then(|c| c.shortcut))?;
+ let sc = shortcut(id)?;
(p.is_null() && accel(sc).is_some()).then(|| id.clone())
})
.collect();
diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs
index e5e8a8d08..d823e91a6 100644
--- a/crates/ui-egui/src/i18n.rs
+++ b/crates/ui-egui/src/i18n.rs
@@ -62,6 +62,7 @@ const TABLE: &[(&str, [&str; 5])] = &[
("Find/Change…", ["Suchen/Ersetzen …", "Rechercher/Remplacer…", "Buscar/Cambiar…", "検索と置換…", "查找/更改…"]),
("Check Spelling…", ["Rechtschreibprüfung …", "Vérifier l'orthographe…", "Revisar ortografía…", "スペルチェック…", "拼写检查…"]),
("Preferences…", ["Voreinstellungen …", "Préférences…", "Preferencias…", "環境設定…", "首选项…"]),
+ ("Settings…", ["Einstellungen …", "Réglages…", "Ajustes…", "設定…", "设置…"]),
(
"Keyboard Shortcuts…",
["Tastaturbefehle …", "Raccourcis clavier…", "Métodos abreviados de teclado…", "キーボードショートカット…", "键盘快捷键…"],
diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs
index 10e393cd2..bf0a3efd3 100644
--- a/crates/ui-egui/src/i18n/ar.rs
+++ b/crates/ui-egui/src/i18n/ar.rs
@@ -39,6 +39,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Find/Change", "البحث/التغيير"),
("Check Spelling…", "تدقيق إملائي…"),
("Preferences…", "تفضيلات…"),
+ ("Settings…", "الإعدادات…"),
("Preferences", "تفضيلات"),
("Keyboard Shortcuts…", "اختصارات لوحة المفاتيح…"),
("Keyboard Shortcuts", "اختصارات لوحة المفاتيح"),
diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs
index c91afd6ba..9f12f3705 100644
--- a/crates/ui-egui/src/i18n/it.rs
+++ b/crates/ui-egui/src/i18n/it.rs
@@ -35,6 +35,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Find/Change…", "Trova/Sostituisci…"),
("Check Spelling…", "Controllo ortografico…"),
("Preferences…", "Preferenze…"),
+ ("Settings…", "Impostazioni…"),
("Keyboard Shortcuts…", "Scelte rapide da tastiera…"),
("Interface Language", "Lingua dell'interfaccia"),
("Pages", "Pagine"),
diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs
index be6e2c4da..30c4a3b0b 100644
--- a/crates/ui-egui/src/i18n/ja.rs
+++ b/crates/ui-egui/src/i18n/ja.rs
@@ -37,6 +37,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Find/Change…", "検索と置換…"),
("Check Spelling…", "スペルチェック…"),
("Preferences…", "環境設定…"),
+ ("Settings…", "設定…"),
("Keyboard Shortcuts…", "キーボードショートカット…"),
("Interface Language", "インターフェイスの言語"),
("Pages", "ページ"),
diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs
index d25717dc6..daf6aebbf 100644
--- a/crates/ui-egui/src/i18n/pt_br.rs
+++ b/crates/ui-egui/src/i18n/pt_br.rs
@@ -40,6 +40,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Find/Change", "Localizar/alterar"),
("Check Spelling…", "Verificar ortografia…"),
("Preferences…", "Preferências…"),
+ ("Settings…", "Ajustes…"),
("Preferences", "Preferências"),
("Keyboard Shortcuts…", "Atalhos de teclado…"),
("Keyboard Shortcuts", "Atalhos de teclado"),
diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs
index 9a9fb89ba..8e595fad2 100644
--- a/crates/ui-egui/src/i18n/uk.rs
+++ b/crates/ui-egui/src/i18n/uk.rs
@@ -38,6 +38,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Find/Change…", "Знайти й замінити…"),
("Check Spelling…", "Перевірити орфографію…"),
("Preferences…", "Налаштування…"),
+ ("Settings…", "Параметри…"),
("Keyboard Shortcuts…", "Клавіатурні скорочення…"),
("Interface Language", "Мова інтерфейсу"),
("Pages", "Сторінки"),
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 94e5c0971..c65f297e9 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -1721,6 +1721,76 @@ pub fn menu_tree() -> Vec<(&'static str, Vec<Item>)> {
MENUS.iter().map(|(m, e)| (*m, parse_entries(e))).collect()
}
+/// A row of the macOS application menu (the menu named after the app).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum AppMenuItem {
+ /// Runs `command` (no parameters); `id` is the native menu item id, `label` goes through `i18n::tr`.
+ Cmd {
+ id: &'static str,
+ label: &'static str,
+ command: &'static str,
+ },
+ Sep,
+ Services,
+ Hide,
+ HideOthers,
+ ShowAll,
+ Quit,
+}
+
+/// The macOS application menu. Settings… is `app.preferences`, which `native_menu_tree` leaves out of Edit.
+pub const MAC_APP_MENU: &[AppMenuItem] = &[
+ AppMenuItem::Cmd { id: "dc-about", label: "About DesignCraft", command: "help.about" },
+ AppMenuItem::Cmd { id: "dc-discord", label: "Join the ArtCraft Discord…", command: "help.discord" },
+ AppMenuItem::Sep,
+ AppMenuItem::Cmd { id: "dc-settings", label: "Settings…", command: "app.preferences" },
+ AppMenuItem::Sep,
+ AppMenuItem::Services,
+ AppMenuItem::Sep,
+ AppMenuItem::Hide,
+ AppMenuItem::HideOthers,
+ AppMenuItem::ShowAll,
+ AppMenuItem::Sep,
+ AppMenuItem::Quit,
+];
+
+/// The menu tree for the macOS menu bar: `menu_tree` without the commands `MAC_APP_MENU` holds,
+/// so each command (and its shortcut) appears once.
+pub fn native_menu_tree() -> Vec<(&'static str, Vec<Item>)> {
+ let in_app_menu = |id: &str| MAC_APP_MENU.iter().any(|m| matches!(m, AppMenuItem::Cmd { command, .. } if *command == id));
+ let mut tree = menu_tree();
+ for (_, entries) in &mut tree {
+ without_commands(entries, &in_app_menu);
+ }
+ tree
+}
+
+/// Drops the parameterless commands `drop` matches from `entries` (recursively), then any separator
+/// the removal left at an end or next to another.
+fn without_commands(entries: &mut Vec<Item>, drop: &dyn Fn(&str) -> bool) {
+ let before = entries.len();
+ entries.retain(|e| !matches!(e, Item::Cmd { id, params, .. } if params.is_null() && drop(id)));
+ for e in entries.iter_mut() {
+ if let Item::Sub(_, children) = e {
+ without_commands(children, drop);
+ }
+ }
+ if entries.len() == before {
+ return;
+ }
+ let mut tidy: Vec<Item> = Vec::with_capacity(entries.len());
+ for e in entries.drain(..) {
+ if matches!(e, Item::Sep) && tidy.last().is_none_or(|l| matches!(l, Item::Sep)) {
+ continue;
+ }
+ tidy.push(e);
+ }
+ if matches!(tidy.last(), Some(Item::Sep)) {
+ tidy.pop();
+ }
+ *entries = tidy;
+}
+
/// Check state of a toggle command (None = not a toggle).
pub fn checked(app: &DesignApp, id: &str, params: &Value) -> Option<bool> {
Some(match id {
@@ -3302,4 +3372,41 @@ mod tests {
let (_, Some((_, _, open))) = frame(500.0, vec![]) else { panic!("test menu remains open") };
assert!(!open, "an open submenu closes when its row becomes fully clipped");
}
+
+ #[test]
+ fn mac_settings_follow_about_in_the_app_menu_and_leave_edit() {
+ let pos = |command: &str| MAC_APP_MENU.iter().position(|m| matches!(m, AppMenuItem::Cmd { command: c, .. } if *c == command));
+ let (Some(about), Some(settings)) = (pos("help.about"), pos("app.preferences")) else { panic!("About and Settings are in the app menu") };
+ assert!(about < settings);
+ assert_eq!(MAC_APP_MENU.get(settings - 1), Some(&AppMenuItem::Sep));
+ assert_eq!(MAC_APP_MENU.get(settings + 1), Some(&AppMenuItem::Sep));
+ let label = |command: &str| {
+ MAC_APP_MENU.iter().find_map(|m| match m {
+ AppMenuItem::Cmd { label, command: c, .. } if *c == command => Some(*label),
+ _ => None,
+ })
+ };
+ assert_eq!(label("app.preferences"), Some("Settings…"));
+ assert_ne!(crate::i18n::tr("de", "Settings…"), "Settings…");
+ let ids = MAC_APP_MENU.iter().filter_map(|m| if let AppMenuItem::Cmd { id, .. } = m { Some(*id) } else { None }).collect::<Vec<_>>();
+ assert!(ids.iter().enumerate().all(|(i, id)| !ids[..i].contains(id)), "native ids are unique: {ids:?}");
+
+ let edit = |tree: Vec<(&'static str, Vec<Item>)>| {
+ let mut out = Vec::new();
+ walk(&tree.into_iter().find(|(t, _)| *t == "Edit").map(|(_, e)| e).unwrap_or_default(), &mut out);
+ out.into_iter().map(|(_, id, _)| id).collect::<Vec<_>>()
+ };
+ assert!(edit(menu_tree()).iter().any(|id| id == "app.preferences"), "the in-window Edit menu keeps Preferences");
+ let native = native_menu_tree();
+ let mut all = Vec::new();
+ for (_, entries) in &native {
+ walk(entries, &mut all);
+ }
+ assert!(!all.iter().any(|(_, id, _)| id == "app.preferences"), "the macOS menu bar has Settings only in the app menu");
+ assert!(edit(native_menu_tree()).iter().any(|id| id == "app.keyboardShortcuts"));
+ for (title, entries) in &native {
+ assert!(!matches!(entries.first(), Some(Item::Sep)) && !matches!(entries.last(), Some(Item::Sep)), "{title}: separator at an end");
+ assert!(entries.windows(2).all(|w| !matches!(w, [Item::Sep, Item::Sep])), "{title}: doubled separator");
+ }
+ }
}