diff --git a/assets/locales/pending/settings-profiles.json b/assets/locales/pending/settings-profiles.json new file mode 100644 index 000000000..7b11ef0e2 --- /dev/null +++ b/assets/locales/pending/settings-profiles.json @@ -0,0 +1,170 @@ +{ + "en": { + "cmd.settings_profile_apply": "Apply Settings Profile", + "cmd.settings_profile_delete": "Delete Settings Profile", + "cmd.settings_profile_export": "Export Settings Profile", + "cmd.settings_profile_import": "Import Settings Profile", + "cmd.settings_profile_list": "Settings Profiles", + "cmd.settings_profile_rename": "Rename Settings Profile", + "cmd.settings_profile_save": "Save Settings Profile", + "prefs.profile_active": "Active profile", + "prefs.profile_applied": "Profile applied.", + "prefs.profile_changed": "Settings changed since the profile was saved. Save keeps them in it.", + "prefs.profile_deleted": "Profile deleted.", + "prefs.profile_export": "Export…", + "prefs.profile_exported": "Profile exported.", + "prefs.profile_imported": "Profile imported. Choose it under Active profile to switch to it.", + "prefs.profile_name_hint": "Profile name, e.g. Laptop", + "prefs.profile_rename": "Rename", + "prefs.profile_renamed": "Profile renamed.", + "prefs.profile_save": "Save", + "prefs.profile_saved": "Current settings saved to the profile.", + "prefs.profile_skipped": "Profile applied; {n} setting(s) kept their current value (see the log).", + "prefs.profiles": "Settings profiles", + "prefs.profiles_note": "Shortcuts, the toolbar, navigation, the radial menu and interface settings, kept together under a name and switched at once." + }, + "de": { + "cmd.settings_profile_apply": "Einstellungsprofil anwenden", + "cmd.settings_profile_delete": "Einstellungsprofil löschen", + "cmd.settings_profile_export": "Einstellungsprofil exportieren", + "cmd.settings_profile_import": "Einstellungsprofil importieren", + "cmd.settings_profile_list": "Einstellungsprofile", + "cmd.settings_profile_rename": "Einstellungsprofil umbenennen", + "cmd.settings_profile_save": "Einstellungsprofil speichern", + "prefs.profile_active": "Aktives Profil", + "prefs.profile_applied": "Profil angewendet.", + "prefs.profile_changed": "Die Einstellungen wurden seit dem Speichern des Profils geändert. „Speichern“ übernimmt sie ins Profil.", + "prefs.profile_deleted": "Profil gelöscht.", + "prefs.profile_export": "Exportieren…", + "prefs.profile_exported": "Profil exportiert.", + "prefs.profile_imported": "Profil importiert. Unter „Aktives Profil“ auswählen, um dazu zu wechseln.", + "prefs.profile_name_hint": "Profilname, z. B. Laptop", + "prefs.profile_rename": "Umbenennen", + "prefs.profile_renamed": "Profil umbenannt.", + "prefs.profile_save": "Speichern", + "prefs.profile_saved": "Aktuelle Einstellungen im Profil gespeichert.", + "prefs.profile_skipped": "Profil angewendet; {n} Einstellung(en) behielten ihren aktuellen Wert (siehe Protokoll).", + "prefs.profiles": "Einstellungsprofile", + "prefs.profiles_note": "Tastenkürzel, Werkzeugleiste, Navigation, Radialmenü und Oberflächeneinstellungen, gemeinsam unter einem Namen gespeichert und auf einmal umgeschaltet." + }, + "ja": { + "cmd.settings_profile_apply": "設定プロファイルを適用", + "cmd.settings_profile_delete": "設定プロファイルを削除", + "cmd.settings_profile_export": "設定プロファイルをエクスポート", + "cmd.settings_profile_import": "設定プロファイルをインポート", + "cmd.settings_profile_list": "設定プロファイル", + "cmd.settings_profile_rename": "設定プロファイルの名前を変更", + "cmd.settings_profile_save": "設定プロファイルを保存", + "prefs.profile_active": "使用中のプロファイル", + "prefs.profile_applied": "プロファイルを適用しました。", + "prefs.profile_changed": "プロファイルの保存後に設定が変更されています。「保存」でプロファイルに反映されます。", + "prefs.profile_deleted": "プロファイルを削除しました。", + "prefs.profile_export": "エクスポート…", + "prefs.profile_exported": "プロファイルをエクスポートしました。", + "prefs.profile_imported": "プロファイルをインポートしました。切り替えるには「使用中のプロファイル」で選択してください。", + "prefs.profile_name_hint": "プロファイル名(例: ノートPC)", + "prefs.profile_rename": "名前を変更", + "prefs.profile_renamed": "プロファイルの名前を変更しました。", + "prefs.profile_save": "保存", + "prefs.profile_saved": "現在の設定をプロファイルに保存しました。", + "prefs.profile_skipped": "プロファイルを適用しました。{n} 件の設定は現在の値のままです(ログを参照)。", + "prefs.profiles": "設定プロファイル", + "prefs.profiles_note": "ショートカット、ツールバー、ナビゲーション、ラジアルメニュー、インターフェース設定を名前を付けてまとめて保存し、一度に切り替えます。" + }, + "zh": { + "cmd.settings_profile_apply": "应用设置配置文件", + "cmd.settings_profile_delete": "删除设置配置文件", + "cmd.settings_profile_export": "导出设置配置文件", + "cmd.settings_profile_import": "导入设置配置文件", + "cmd.settings_profile_list": "设置配置文件", + "cmd.settings_profile_rename": "重命名设置配置文件", + "cmd.settings_profile_save": "保存设置配置文件", + "prefs.profile_active": "当前配置文件", + "prefs.profile_applied": "已应用配置文件。", + "prefs.profile_changed": "保存配置文件后设置已更改。“保存”会将其写入配置文件。", + "prefs.profile_deleted": "已删除配置文件。", + "prefs.profile_export": "导出…", + "prefs.profile_exported": "已导出配置文件。", + "prefs.profile_imported": "已导入配置文件。在“当前配置文件”中选择它即可切换。", + "prefs.profile_name_hint": "配置文件名称,例如 笔记本", + "prefs.profile_rename": "重命名", + "prefs.profile_renamed": "已重命名配置文件。", + "prefs.profile_save": "保存", + "prefs.profile_saved": "已将当前设置保存到配置文件。", + "prefs.profile_skipped": "已应用配置文件;{n} 项设置保留了当前值(见日志)。", + "prefs.profiles": "设置配置文件", + "prefs.profiles_note": "将快捷键、工具栏、导航、径向菜单和界面设置一起以名称保存,并一次切换。" + }, + "ar": { + "cmd.settings_profile_apply": "تطبيق ملف تعريف الإعدادات", + "cmd.settings_profile_delete": "حذف ملف تعريف الإعدادات", + "cmd.settings_profile_export": "تصدير ملف تعريف الإعدادات", + "cmd.settings_profile_import": "استيراد ملف تعريف الإعدادات", + "cmd.settings_profile_list": "ملفات تعريف الإعدادات", + "cmd.settings_profile_rename": "إعادة تسمية ملف تعريف الإعدادات", + "cmd.settings_profile_save": "حفظ ملف تعريف الإعدادات", + "prefs.profile_active": "ملف التعريف النشط", + "prefs.profile_applied": "تم تطبيق ملف التعريف.", + "prefs.profile_changed": "تغيّرت الإعدادات منذ حفظ ملف التعريف. «حفظ» يضيفها إليه.", + "prefs.profile_deleted": "تم حذف ملف التعريف.", + "prefs.profile_export": "تصدير…", + "prefs.profile_exported": "تم تصدير ملف التعريف.", + "prefs.profile_imported": "تم استيراد ملف التعريف. اختره في «ملف التعريف النشط» للتبديل إليه.", + "prefs.profile_name_hint": "اسم ملف التعريف، مثل: حاسوب محمول", + "prefs.profile_rename": "إعادة تسمية", + "prefs.profile_renamed": "تمت إعادة تسمية ملف التعريف.", + "prefs.profile_save": "حفظ", + "prefs.profile_saved": "تم حفظ الإعدادات الحالية في ملف التعريف.", + "prefs.profile_skipped": "تم تطبيق ملف التعريف؛ احتفظ {n} من الإعدادات بقيمته الحالية (راجع السجل).", + "prefs.profiles": "ملفات تعريف الإعدادات", + "prefs.profiles_note": "الاختصارات وشريط الأدوات والتنقل والقائمة الدائرية وإعدادات الواجهة، محفوظة معًا تحت اسم واحد وتُبدَّل دفعة واحدة." + }, + "he": { + "cmd.settings_profile_apply": "החלת פרופיל הגדרות", + "cmd.settings_profile_delete": "מחיקת פרופיל הגדרות", + "cmd.settings_profile_export": "ייצוא פרופיל הגדרות", + "cmd.settings_profile_import": "ייבוא פרופיל הגדרות", + "cmd.settings_profile_list": "פרופילי הגדרות", + "cmd.settings_profile_rename": "שינוי שם פרופיל הגדרות", + "cmd.settings_profile_save": "שמירת פרופיל הגדרות", + "prefs.profile_active": "פרופיל פעיל", + "prefs.profile_applied": "הפרופיל הוחל.", + "prefs.profile_changed": "ההגדרות השתנו מאז שהפרופיל נשמר. „שמירה“ מכניסה אותן לפרופיל.", + "prefs.profile_deleted": "הפרופיל נמחק.", + "prefs.profile_export": "ייצוא…", + "prefs.profile_exported": "הפרופיל יוצא.", + "prefs.profile_imported": "הפרופיל יובא. בחרו בו תחת „פרופיל פעיל“ כדי לעבור אליו.", + "prefs.profile_name_hint": "שם הפרופיל, למשל מחשב נייד", + "prefs.profile_rename": "שינוי שם", + "prefs.profile_renamed": "שם הפרופיל שונה.", + "prefs.profile_save": "שמירה", + "prefs.profile_saved": "ההגדרות הנוכחיות נשמרו בפרופיל.", + "prefs.profile_skipped": "הפרופיל הוחל; {n} הגדרות שמרו על ערכן הנוכחי (ראו ביומן).", + "prefs.profiles": "פרופילי הגדרות", + "prefs.profiles_note": "קיצורי מקלדת, סרגל הכלים, ניווט, התפריט המעגלי והגדרות הממשק, נשמרים יחד תחת שם אחד ומוחלפים בבת אחת." + }, + "vi": { + "cmd.settings_profile_apply": "Áp dụng hồ sơ cài đặt", + "cmd.settings_profile_delete": "Xóa hồ sơ cài đặt", + "cmd.settings_profile_export": "Xuất hồ sơ cài đặt", + "cmd.settings_profile_import": "Nhập hồ sơ cài đặt", + "cmd.settings_profile_list": "Hồ sơ cài đặt", + "cmd.settings_profile_rename": "Đổi tên hồ sơ cài đặt", + "cmd.settings_profile_save": "Lưu hồ sơ cài đặt", + "prefs.profile_active": "Hồ sơ đang dùng", + "prefs.profile_applied": "Đã áp dụng hồ sơ.", + "prefs.profile_changed": "Cài đặt đã thay đổi kể từ khi lưu hồ sơ. “Lưu” sẽ ghi chúng vào hồ sơ.", + "prefs.profile_deleted": "Đã xóa hồ sơ.", + "prefs.profile_export": "Xuất tệp…", + "prefs.profile_exported": "Đã xuất hồ sơ.", + "prefs.profile_imported": "Đã nhập hồ sơ. Chọn hồ sơ trong “Hồ sơ đang dùng” để chuyển sang.", + "prefs.profile_name_hint": "Tên hồ sơ, ví dụ Laptop", + "prefs.profile_rename": "Đổi tên", + "prefs.profile_renamed": "Đã đổi tên hồ sơ.", + "prefs.profile_save": "Lưu", + "prefs.profile_saved": "Đã lưu cài đặt hiện tại vào hồ sơ.", + "prefs.profile_skipped": "Đã áp dụng hồ sơ; {n} cài đặt giữ nguyên giá trị hiện tại (xem nhật ký).", + "prefs.profiles": "Hồ sơ cài đặt", + "prefs.profiles_note": "Phím tắt, thanh công cụ, điều hướng, menu dạng vòng và cài đặt giao diện, được lưu cùng nhau dưới một tên và chuyển đổi cùng lúc." + } +} diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index fe99d0957..747073d5a 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -67,6 +67,7 @@ mod parts; mod point_cloud; mod script; mod section; +pub mod settings; pub(crate) use measure_sel::{measure_items, shape_of}; pub(crate) use measure_shape::Shape; #[cfg(test)] @@ -336,6 +337,7 @@ pub fn command_specs() -> Vec<&'static CommandSpec> { v.extend(section::COMMANDS.iter()); v.extend(view_navigation::COMMANDS.iter()); v.extend(view_dxf::COMMANDS.iter()); + v.extend(settings::COMMANDS.iter()); v.extend(diagnostics::COMMANDS.iter()); v.extend(render::COMMANDS.iter()); v.extend(render_ui::COMMANDS.iter()); diff --git a/crates/engine/src/cmd/settings.rs b/crates/engine/src/cmd/settings.rs new file mode 100644 index 000000000..94b58fc06 --- /dev/null +++ b/crates/engine/src/cmd/settings.rs @@ -0,0 +1,166 @@ +//! Settings profiles (#6237): named sets of the input and interface preferences, kept by the +//! app. The engine holds no preferences, so these commands only check and echo their +//! parameters; the desktop and web apps act on the echo (`settings_profiles` in the UI crate). +//! Run without an app (CLI, scripts), they do nothing else. + +use serde_json::{Map, Value, json}; + +use super::CommandSpec; +use crate::params::{bad, str_}; +use crate::{Result, Session}; + +/// Most characters in a profile's name. +pub const MAX_PROFILE_NAME: usize = 64; +/// Most bytes in a path given to Export or Import. +const MAX_PATH: usize = 4096; + +pub static COMMANDS: &[CommandSpec] = &[ + CommandSpec::new("settings.profile.list", "Settings Profiles", list) + .icon("list") + .noundo() + .doc_only() + .params("→ profiles: [name], active: name|null; handled by the app"), + CommandSpec::new("settings.profile.save", "Save Settings Profile", save) + .icon("save") + .noundo() + .doc_only() + .params("name: 1..64 characters → name; keeps the current input and interface settings under `name` (replacing a profile of that name) and makes it the active one"), + CommandSpec::new("settings.profile.apply", "Apply Settings Profile", apply) + .icon("settings") + .noundo() + .doc_only() + .params("name → name, applied, skipped: [preference]; switches every setting the profile holds at once"), + CommandSpec::new("settings.profile.rename", "Rename Settings Profile", rename) + .icon("rename") + .noundo() + .doc_only() + .params("name, to: 1..64 characters → name"), + CommandSpec::new("settings.profile.delete", "Delete Settings Profile", delete) + .icon("delete") + .noundo() + .doc_only() + .params("name → deleted"), + CommandSpec::new("settings.profile.export", "Export Settings Profile", export) + .icon("export") + .noundo() + .doc_only() + .params("name, path?: file → profile (a `solidcraft-profile/1` document), written to `path` when given; never opens a dialog"), + CommandSpec::new("settings.profile.import", "Import Settings Profile", import) + .icon("import") + .noundo() + .doc_only() + .params("path: file | profile: `solidcraft-profile/1` document, name?: 1..64 characters → name; adds the profile without switching to it"), +]; + +/// A profile name as given: trimmed, 1 to [`MAX_PROFILE_NAME`] characters, no control characters. +pub fn profile_name(name: &str) -> Option<&str> { + let name = name.trim(); + (!name.is_empty() && name.chars().count() <= MAX_PROFILE_NAME && !name.chars().any(char::is_control)).then_some(name) +} + +fn name_param<'a>(cmd: &str, p: &'a Value, key: &str) -> Result<&'a str> { + str_(p, key) + .and_then(profile_name) + .ok_or_else(|| bad(cmd, format!("`{key}` must be 1 to {MAX_PROFILE_NAME} characters, without control characters"))) +} + +fn path_param<'a>(cmd: &str, p: &'a Value) -> Result> { + match p.get("path") { + None | Some(Value::Null) => Ok(None), + Some(Value::String(path)) if !path.trim().is_empty() && path.len() <= MAX_PATH => Ok(Some(path)), + Some(_) => Err(bad(cmd, format!("`path` must be a file path of at most {MAX_PATH} bytes"))), + } +} + +fn list(_s: &mut Session, _p: &Value) -> Result { + Ok(json!({})) +} + +fn save(_s: &mut Session, p: &Value) -> Result { + Ok(json!({ "name": name_param("settings.profile.save", p, "name")? })) +} + +fn apply(_s: &mut Session, p: &Value) -> Result { + Ok(json!({ "name": name_param("settings.profile.apply", p, "name")? })) +} + +fn rename(_s: &mut Session, p: &Value) -> Result { + let cmd = "settings.profile.rename"; + Ok(json!({ "name": name_param(cmd, p, "name")?, "to": name_param(cmd, p, "to")? })) +} + +fn delete(_s: &mut Session, p: &Value) -> Result { + Ok(json!({ "name": name_param("settings.profile.delete", p, "name")? })) +} + +fn export(_s: &mut Session, p: &Value) -> Result { + let cmd = "settings.profile.export"; + let mut out = Map::new(); + out.insert("name".into(), json!(name_param(cmd, p, "name")?)); + if let Some(path) = path_param(cmd, p)? { + out.insert("path".into(), json!(path)); + } + Ok(Value::Object(out)) +} + +fn import(_s: &mut Session, p: &Value) -> Result { + let cmd = "settings.profile.import"; + let mut out = Map::new(); + let (key, value) = match (path_param(cmd, p)?, p.get("profile")) { + (Some(path), None) => ("path", json!(path)), + (None, Some(profile)) if profile.is_object() => ("profile", profile.clone()), + _ => return Err(bad(cmd, "give either `path` or `profile` (a `solidcraft-profile/1` document)")), + }; + out.insert(key.into(), value); + if p.get("name").is_some_and(|name| !name.is_null()) { + out.insert("name".into(), json!(name_param(cmd, p, "name")?)); + } + Ok(Value::Object(out)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn run(id: &str, p: Value) -> std::result::Result { + let mut s = Session::default(); + s.execute(id, &p).map_err(|e| e.to_string()) + } + + #[test] + fn names_are_trimmed_and_bounded() { + assert_eq!(run("settings.profile.save", json!({"name":" Laptop "})).unwrap(), json!({"name":"Laptop"})); + for name in [json!(""), json!(" "), json!("a\nb"), json!("x".repeat(65)), json!(3), Value::Null] { + assert!(run("settings.profile.save", json!({ "name": name })).is_err(), "{name}"); + } + assert!(run("settings.profile.save", json!({"name":"é".repeat(64)})).is_ok()); + assert!(run("settings.profile.rename", json!({"name":"A"})).is_err()); + } + + #[test] + fn import_takes_a_path_or_a_document_but_not_both() { + assert_eq!(run("settings.profile.import", json!({"path":"/tmp/p.json"})).unwrap(), json!({"path":"/tmp/p.json"})); + let doc = json!({"format":"solidcraft-profile/1"}); + assert_eq!(run("settings.profile.import", json!({"profile":doc, "name":"B"})).unwrap(), json!({"profile":doc, "name":"B"})); + assert!(run("settings.profile.import", json!({"path":"/tmp/p.json", "profile":doc})).is_err()); + assert!(run("settings.profile.import", json!({"profile":"text"})).is_err()); + assert!(run("settings.profile.import", json!({})).is_err()); + assert!(run("settings.profile.export", json!({"name":"A", "path":"x".repeat(5000)})).is_err()); + } + + #[test] + fn profile_commands_leave_the_design_and_its_history_alone() { + let mut s = Session::default(); + let doc = s.doc.to_json(); + for (id, p) in [ + ("settings.profile.save", json!({"name":"A"})), + ("settings.profile.apply", json!({"name":"A"})), + ("settings.profile.list", json!({})), + ("settings.profile.delete", json!({"name":"A"})), + ] { + s.execute(id, &p).unwrap(); + } + assert_eq!(s.doc.to_json(), doc); + assert!(s.undo.is_empty()); + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 799ae5886..470e4faf7 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -44,6 +44,7 @@ use serde_json::Value; use solidcraft_doc::{Document, Model, ModelState}; use solidcraft_geom::Vec3; +pub use cmd::settings::{MAX_PROFILE_NAME, profile_name}; pub use cmd::{ Addition, CommandInfo, CommandSpec, addition, auto_operation, command_specs, dimension_roles, extrude_reach, find_command, resolve_design_links, shown_scope, standard_view, diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index e8f78d78a..b97d075be 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -251,6 +251,7 @@ fn execute(app: &mut SolveApp, id: &str, params: Value) -> Result | "browser.expand_all" | "browser.collapse_all" ) + && !id.starts_with("settings.") && app.session.active_sketch.is_none() && app.session.world_state().bodies.len() == 1 && app.session.undo.len() <= 2 diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index 421ca0a8b..220c20ef7 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -181,19 +181,7 @@ impl Keymap { /// One key is saved as a string, as before a command could have several, so older versions /// still read it. pub fn prefs(&self) -> Value { - Value::Object( - self.custom - .iter() - .map(|(id, keys)| { - let v = match keys.as_slice() { - [] => json!(""), - [key] => json!(key), - _ => json!(keys), - }; - (id.clone(), v) - }) - .collect(), - ) + Value::Object(self.custom.iter().map(|(id, keys)| (id.clone(), keys_value(keys))).collect()) } pub fn load(&mut self, v: &Value) { self.custom = v.as_object().map(|o| o.iter().take(2000).filter_map(|(k, v)| Some((k.clone(), saved_keys(v)?))).collect()).unwrap_or_default(); @@ -207,8 +195,17 @@ impl Keymap { } } +/// A command's keys as they are saved: `""` (none), one key, or a list of them. +pub(crate) fn keys_value(keys: &[String]) -> Value { + match keys { + [] => json!(""), + [key] => json!(key), + _ => json!(keys), + } +} + /// A command's saved keys: `""` (none), one key, or a list of them. -fn saved_keys(v: &Value) -> Option> { +pub(crate) fn saved_keys(v: &Value) -> Option> { match v { Value::String(key) if key.is_empty() => Some(Vec::new()), Value::String(key) => Some(vec![key.clone()]), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index bb3885fc7..04edf708c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -225,6 +225,9 @@ pub mod scenario; pub(crate) mod scene_palette; pub mod select_other; pub mod selection; +pub mod settings_profiles; +#[cfg(test)] +mod settings_profiles_tests; pub mod shell; #[cfg(test)] mod shell_face_sketch_ui_tests; @@ -514,6 +517,8 @@ pub struct SolveApp { pub install_steps: Option, /// Toolbar buttons the user pinned, removed or reordered. pub toolbar_custom: toolbar_custom::ToolbarCustom, + /// Named settings profiles (#6237). + pub settings_profiles: settings_profiles::Profiles, /// Preferences kept between runs, and their window. pub preferences: prefs::Prefs, pub prefs_window: prefs::PrefsWindow, @@ -736,6 +741,7 @@ impl SolveApp { updater: update::Updater::default(), install_steps: None, toolbar_custom: toolbar_custom::ToolbarCustom::default(), + settings_profiles: settings_profiles::Profiles::default(), preferences: prefs::Prefs::default(), prefs_window: prefs::PrefsWindow::default(), slicer_menu: dialogs_save_mesh::SlicerMenu::default(), @@ -938,6 +944,7 @@ impl SolveApp { "shortcut_box": self.sbox.prefs(), "shortcuts": self.keymap.prefs(), "toolbar": self.toolbar_custom.prefs(), + "settings_profiles": self.settings_profiles.prefs(), "autosave_minutes": self.autosave_minutes, "ground_shadow": self.ui.ground_shadow, "agent_cursor": self.ui.agent_cursor, @@ -1006,6 +1013,9 @@ impl SolveApp { if let Some(t) = v.get("toolbar") { self.toolbar_custom.load(t); } + if let Some(p) = v.get("settings_profiles") { + self.settings_profiles.load(p); + } if let Some(mut p) = v.get("preferences").filter(|p| p.is_object()).map(prefs::lenient) { if !prefs::MSAA.contains(&p.msaa) { p.msaa = prefs::Prefs::default().msaa; @@ -1283,6 +1293,11 @@ impl SolveApp { // Curves drawn in construction (or centerline) mode take that line type. sketch_palette::apply_mode(self, id, v); } + // Settings profiles live in the app: the engine only checked the parameters. + let r = match r { + Ok(v) if id.starts_with("settings.profile.") => settings_profiles::command(self, id, &v), + r => r, + }; self.finish_command(id, &r); if render_workspace::active(self) && matches!(id, "appearance.assign" | "appearance.paste") @@ -1540,6 +1555,11 @@ impl SolveApp { let _ = self.run(id, json!({})); return; } + // Profiles are named and picked in Preferences. + if id.starts_with("settings.profile.") { + prefs::open_at(self, prefs::PAGE_GENERAL); + return; + } if id == "view.ambient_occlusion" { let _ = self.run(id, json!({"enabled": !self.preferences.ambient_occlusion})); return; diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index d9a886f22..d0f6d7e07 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -826,6 +826,9 @@ macro_rules! preference_settings { fn default() -> Self { Self { $($field: $default,)* } } } + /// Every stored field and the page whose Defaults resets it (`None`: no page). + pub(crate) const FIELD_PAGES: &[(&str, Option)] = &[$((stringify!($field), preference_settings!(@page $($page)?)),)*]; + fn reset_preferences(p: &mut Prefs, page: usize) { let d = Prefs::default(); $($(if page == $page { p.$field = d.$field; })?)* @@ -843,6 +846,8 @@ macro_rules! preference_settings { })?)* } }; + (@page) => { None }; + (@page $page:expr) => { Some($page) }; (@control $app:ident, $ui:ident, $field:ident, check($label:literal $(, $help:literal)?)) => { ui_kit::checkbox($ui, crate::i18n::tr_label($label), &mut $app.preferences.$field) $(.on_hover_text(crate::i18n::tr_label($help)))? @@ -1476,6 +1481,10 @@ struct Snapshot { autosave: f64, auto_project: bool, keys: std::collections::BTreeMap>, + /// What a settings profile also switches: the toolbar, the S box favourites and which profile is active. + toolbar: serde_json::Value, + favourites: Vec, + profile: Option, } impl Snapshot { @@ -1495,6 +1504,9 @@ impl Snapshot { autosave: app.autosave_minutes, auto_project: app.session.auto_project, keys: app.keymap.custom.clone(), + toolbar: app.toolbar_custom.prefs(), + favourites: app.sbox.pinned.clone(), + profile: app.settings_profiles.active.clone(), } } fn restore(self, app: &mut SolveApp) { @@ -1522,6 +1534,9 @@ impl Snapshot { set_autosave(app); app.session.auto_project = self.auto_project; app.keymap.custom = self.keys; + app.toolbar_custom.load(&self.toolbar); + app.sbox.pinned = self.favourites; + app.settings_profiles.active = self.profile.filter(|name| app.settings_profiles.names().contains(name)); if (app.preferences.msaa, app.preferences.window_system.clone(), app.preferences.graphics_adapter.clone()) != graphics { save_graphics(app); } @@ -1545,6 +1560,9 @@ impl Snapshot { autosave, auto_project, keys, + toolbar, + favourites, + profile, } = self; *prefs == app.preferences && *dark == app.ui.dark @@ -1560,6 +1578,9 @@ impl Snapshot { && *autosave == app.autosave_minutes && *auto_project == app.session.auto_project && *keys == app.keymap.custom + && *toolbar == app.toolbar_custom.prefs() + && *favourites == app.sbox.pinned + && *profile == app.settings_profiles.active } } diff --git a/crates/ui-egui/src/prefs/general.rs b/crates/ui-egui/src/prefs/general.rs index 0182da829..d0f2f7e78 100644 --- a/crates/ui-egui/src/prefs/general.rs +++ b/crates/ui-egui/src/prefs/general.rs @@ -20,6 +20,7 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) { }); }); }); + crate::settings_profiles::section(app, ui, labels); ui_kit::settings_section(ui, "saving", app.tr("prefs.saving"), |ui| { ui_kit::settings_block_hint(ui, app.tr("ui.autosave_every"), crate::i18n::tr_label("0 turns it off"), labels, |ui| { ui.horizontal(|ui| { diff --git a/crates/ui-egui/src/settings_profiles.rs b/crates/ui-egui/src/settings_profiles.rs new file mode 100644 index 000000000..25df84320 --- /dev/null +++ b/crates/ui-egui/src/settings_profiles.rs @@ -0,0 +1,481 @@ +//! Settings profiles (#6237): the input and interface settings kept together under a name, such +//! as "Laptop" and "Large monitor", and switched at once. A profile holds the preferences of the +//! Interface, Navigation and Sketch pages and the language, the keyboard shortcuts, the toolbar +//! and the S box favourites, and the imported theme it uses. Machine-specific settings stay out: +//! the 3D mouse, graphics, recent files and the AI pages. +//! +//! A profile is kept, exported and imported as one `solidcraft-profile/1` document. Every +//! document is checked by [`sanitize`] first: unknown keys are dropped, sizes are capped, and a +//! preference this version can't read is left out. Applying one sets each preference through +//! [`prefs::set`], so it is checked again and has the same effects as a change in Preferences; +//! one that is refused there (an interface font this computer lacks) keeps its current value. +//! +//! The `settings.profile.*` commands reach the profiles; the engine only checks their +//! parameters, and [`command`] does the rest after `SolveApp::run`. + +use serde_json::{Map, Value, json}; +use solidcraft_engine::{MAX_PROFILE_NAME, profile_name}; + +use crate::{SolveApp, prefs, theme_files, ui_kit}; + +/// The format tag of a profile document. +pub const FORMAT: &str = "solidcraft-profile/1"; +/// Most profiles kept. +pub const MAX_PROFILES: usize = 32; +/// Most bytes read from a profile file. +const MAX_FILE_BYTES: u64 = 4 * 1024 * 1024; +/// Most bytes in one checked profile document. +const MAX_PROFILE_BYTES: usize = 1024 * 1024; +const MAX_SHORTCUTS: usize = 2000; +const MAX_FAVOURITES: usize = 64; +/// Most imported themes one profile carries (the one it uses). +const MAX_THEMES: usize = 4; +/// Most characters in a command id or a key name. +const MAX_ID: usize = 200; + +/// The Preferences pages whose settings a profile holds. +const PAGES: [usize; 3] = [prefs::PAGE_INTERFACE, prefs::PAGE_NAVIGATION, prefs::PAGE_SKETCH]; +/// Settings a profile holds from other pages. +const ALSO: [&str; 1] = ["language"]; + +/// Settings of those pages that belong to the computer, not the person: the 3D mouse (its +/// calibration, driver and axes) and the cursor flag older releases saved. +fn machine_specific(key: &str) -> bool { + key.starts_with("space_mouse_") || key == "orbit_cursor" +} + +/// The preferences a profile holds, by their stored key. +pub fn keys() -> impl Iterator { + prefs::FIELD_PAGES + .iter() + .filter(|(key, page)| ALSO.contains(key) || page.is_some_and(|page| PAGES.contains(&page))) + .map(|(key, _)| *key) + .filter(|key| !machine_specific(key)) +} + +/// The kept profiles, which one was applied or saved last, and the Preferences section's state. +#[derive(Default)] +pub struct Profiles { + /// Checked `solidcraft-profile/1` documents, in the order they were added. + pub list: Vec, + /// The profile applied or saved last, while it exists. + pub active: Option, + /// The name typed in Preferences. + draft: String, + /// The last action's outcome in Preferences. + message: Option, +} + +/// What a profile action in Preferences reports. Kept untranslated: applying a profile can +/// change the language, and the report is shown in the new one. +enum Outcome { + /// It worked: the message id. + Done(&'static str), + /// A profile applied with this many settings refused. + Skipped(usize), + Failed(String), +} + +impl Profiles { + /// What the app keeps between runs. + pub fn prefs(&self) -> Value { + json!({ "active": self.active, "profiles": self.list }) + } + + /// Back from [`Profiles::prefs`]: profiles that fail the checks, and repeated names, are dropped. + pub fn load(&mut self, v: &Value) { + self.list.clear(); + for doc in v.get("profiles").and_then(Value::as_array).into_iter().flatten().take(MAX_PROFILES) { + match sanitize(doc) { + Ok(doc) if self.find(name_of(&doc)).is_none() => self.list.push(doc), + Ok(_) => {} + Err(e) => log::warn!("settings profiles: one is dropped: {e}"), + } + } + self.active = v.get("active").and_then(Value::as_str).filter(|name| self.find(name).is_some()).map(str::to_string); + } + + /// The profile names, in order. + pub fn names(&self) -> Vec { + self.list.iter().map(|doc| name_of(doc).to_string()).collect() + } + + fn find(&self, name: &str) -> Option { + self.list.iter().position(|doc| name_of(doc) == name) + } + + fn get(&self, name: &str) -> Result<&Value, String> { + self.find(name).and_then(|i| self.list.get(i)).ok_or_else(|| format!("no settings profile `{name}`")) + } + + /// `name`, or the first of `name 2`, `name 3`… no profile has yet. + fn free_name(&self, name: &str) -> String { + if self.find(name).is_none() { + return name.to_string(); + } + (2..=MAX_PROFILES + 1) + .map(|n| { + let suffix = format!(" {n}"); + let base: String = name.chars().take(MAX_PROFILE_NAME - suffix.chars().count()).collect(); + format!("{}{suffix}", base.trim_end()) + }) + .find(|candidate| self.find(candidate).is_none()) + .unwrap_or_else(|| name.to_string()) + } +} + +fn name_of(doc: &Value) -> &str { + doc.get("name").and_then(Value::as_str).unwrap_or_default() +} + +fn set_name(doc: &mut Value, name: &str) { + if let Some(o) = doc.as_object_mut() { + o.insert("name".into(), json!(name)); + } +} + +/// The current settings as a profile called `name`. +pub fn capture(app: &SolveApp, name: &str) -> Value { + let all = serde_json::to_value(&app.preferences).unwrap_or_default(); + let preferences: Map = keys().filter_map(|key| Some((key.to_string(), all.get(key)?.clone()))).collect(); + let themes: Vec = app.preferences.custom_themes.iter().filter(|t| t.id == app.preferences.theme).map(theme_document).collect(); + json!({ + "format": FORMAT, + "name": name, + "preferences": preferences, + "shortcuts": app.keymap.prefs(), + "favourites": app.sbox.pinned, + "toolbar": app.toolbar_custom.prefs(), + "themes": themes, + }) +} + +/// An imported theme as a theme file that also keeps the id the profile's `theme` names. +fn theme_document(theme: &theme_files::ThemeFile) -> Value { + let mut v = serde_json::to_value(theme).unwrap_or_default(); + if let Some(o) = v.as_object_mut() { + o.insert("format".into(), json!(theme_files::FORMAT)); + } + v +} + +/// A theme id as a profile may name one: lower-case letters, digits and dashes. +fn theme_id(id: &str) -> Option<&str> { + (!id.is_empty() && id.len() <= MAX_PROFILE_NAME && id.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')).then_some(id) +} + +/// A profile document checked and cut down to what this version keeps: the format and a usable +/// name are required; unknown keys, preferences this version can't read, and themes that fail +/// their checks are dropped; lists and texts are capped. +pub fn sanitize(v: &Value) -> Result { + let o = v.as_object().ok_or("not a SolidCraft settings profile")?; + if o.get("format").and_then(Value::as_str) != Some(FORMAT) { + return Err(format!("not a SolidCraft settings profile: `format` must be \"{FORMAT}\"")); + } + let name = o + .get("name") + .and_then(Value::as_str) + .and_then(profile_name) + .ok_or_else(|| format!("`name` must be 1 to {MAX_PROFILE_NAME} characters, without control characters"))?; + let mut preferences = Map::new(); + if let Some(src) = o.get("preferences") { + let src = src.as_object().ok_or("`preferences` must be an object")?; + let defaults = serde_json::to_value(prefs::Prefs::default()).map_err(|e| e.to_string())?; + for key in keys() { + let Some(value) = src.get(key) else { continue }; + let mut probe = defaults.clone(); + if let Some(p) = probe.as_object_mut() { + p.insert(key.to_string(), value.clone()); + } + if serde_json::from_value::(probe).is_ok() { + preferences.insert(key.to_string(), value.clone()); + } else { + log::warn!("settings profile `{name}`: `{key}` is not understood by this version; left out"); + } + } + } + let text = |v: &Value| v.as_str().filter(|s| !s.is_empty() && s.chars().count() <= MAX_ID).map(str::to_string); + let shortcuts: Map = o + .get("shortcuts") + .and_then(Value::as_object) + .into_iter() + .flatten() + .filter(|(id, _)| id.chars().count() <= MAX_ID) + .filter_map(|(id, keys)| Some((id.clone(), shortcut_keys(keys)?))) + .take(MAX_SHORTCUTS) + .collect(); + let favourites: Vec = o.get("favourites").and_then(Value::as_array).into_iter().flatten().filter_map(text).take(MAX_FAVOURITES).collect(); + let mut toolbar = crate::toolbar_custom::ToolbarCustom::default(); + if let Some(t) = o.get("toolbar") { + toolbar.load(t); + } + let mut themes = Vec::new(); + for t in o.get("themes").and_then(Value::as_array).into_iter().flatten().take(MAX_THEMES) { + match theme_files::from_value(t) { + Ok(mut theme) => { + if let Some(id) = t.get("id").and_then(Value::as_str).and_then(theme_id) { + theme.id = id.to_string(); + } + themes.push(theme_document(&theme)); + } + Err(e) => log::warn!("settings profile `{name}`: a theme is left out: {e}"), + } + } + let doc = json!({ + "format": FORMAT, + "name": name, + "preferences": preferences, + "shortcuts": shortcuts, + "favourites": favourites, + "toolbar": toolbar.prefs(), + "themes": themes, + }); + if doc.to_string().len() > MAX_PROFILE_BYTES { + return Err(format!("a settings profile is at most {} KiB", MAX_PROFILE_BYTES / 1024)); + } + Ok(doc) +} + +/// A command's keys in a profile, as the keymap saves them (`""`, one key or a list of them), or +/// `None` when they can't be read or a key name is too long. +fn shortcut_keys(v: &Value) -> Option { + let keys = crate::keymap::saved_keys(v)?; + keys.iter().all(|k| k.chars().count() <= MAX_ID).then(|| crate::keymap::keys_value(&keys)) +} + +/// Apply a checked profile: its themes, each preference (through [`prefs::set`]), the +/// shortcuts, the favourites and the toolbar. Returns the preferences that were refused. +fn apply(app: &mut SolveApp, doc: &Value) -> Vec { + let mut theme_ids = std::collections::BTreeMap::new(); + for t in doc.get("themes").and_then(Value::as_array).into_iter().flatten() { + let Ok(mut theme) = theme_files::from_value(t) else { continue }; + let wanted = t.get("id").and_then(Value::as_str).and_then(theme_id).unwrap_or(&theme.id).to_string(); + theme.id = wanted.clone(); + if let Ok(id) = theme_files::add(&mut app.preferences.custom_themes, theme) { + theme_ids.insert(wanted, id); + } + } + let mut skipped = Vec::new(); + for (key, value) in doc.get("preferences").and_then(Value::as_object).into_iter().flatten() { + let value = match value.as_str().and_then(|id| theme_ids.get(id)) { + Some(id) if key == "theme" => json!(id), + _ => value.clone(), + }; + if let Err(e) = prefs::set(app, &json!({ key: value })) { + log::warn!("settings profile: `{key}` keeps its current value: {e}"); + skipped.push(key.clone()); + } + } + if let Some(s) = doc.get("shortcuts") { + app.keymap.load(s); + } + if let Some(f) = doc.get("favourites").and_then(Value::as_array) { + app.sbox.pinned = f.iter().filter_map(|x| x.as_str().map(str::to_string)).collect(); + } + if let Some(t) = doc.get("toolbar") { + app.toolbar_custom.load(t); + } + skipped +} + +/// A profile file read and checked, refusing one too large to be a profile. +fn read_file(path: &str) -> Result { + let size = std::fs::metadata(path).map_err(|e| format!("{path}: {e}"))?.len(); + if size > MAX_FILE_BYTES { + return Err(format!("{path}: a settings profile file is at most {} MiB", MAX_FILE_BYTES / 1024 / 1024)); + } + let text = std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?; + serde_json::from_str(&text).map_err(|e| format!("{path}: not a settings profile: {e}")) +} + +/// Add a checked profile under its name, or `name` when given, made unique; never switches to it. +fn add(app: &mut SolveApp, doc: &Value, name: Option<&str>) -> Result { + let mut doc = sanitize(doc)?; + if app.settings_profiles.list.len() >= MAX_PROFILES { + return Err(format!("at most {MAX_PROFILES} settings profiles; delete one first")); + } + let name = app.settings_profiles.free_name(name.unwrap_or(name_of(&doc))); + set_name(&mut doc, &name); + app.settings_profiles.list.push(doc); + Ok(name) +} + +/// The rest of a `settings.profile.*` command, after the engine checked its parameters (`v`, its echo). +pub fn command(app: &mut SolveApp, id: &str, v: &Value) -> Result { + let name = v.get("name").and_then(Value::as_str).unwrap_or_default(); + match id { + "settings.profile.list" => Ok(json!({ "profiles": app.settings_profiles.names(), "active": app.settings_profiles.active })), + "settings.profile.save" => { + let doc = capture(app, name); + match app.settings_profiles.find(name) { + Some(i) => { + if let Some(old) = app.settings_profiles.list.get_mut(i) { + *old = doc; + } + } + None if app.settings_profiles.list.len() >= MAX_PROFILES => { + return Err(format!("at most {MAX_PROFILES} settings profiles; delete one first")); + } + None => app.settings_profiles.list.push(doc), + } + app.settings_profiles.active = Some(name.to_string()); + Ok(json!({ "name": name })) + } + "settings.profile.apply" => { + let doc = app.settings_profiles.get(name)?.clone(); + let skipped = apply(app, &doc); + app.settings_profiles.active = Some(name.to_string()); + let applied = doc.get("preferences").and_then(Value::as_object).map_or(0, |p| p.len().saturating_sub(skipped.len())); + Ok(json!({ "name": name, "applied": applied, "skipped": skipped })) + } + "settings.profile.rename" => { + let to = v.get("to").and_then(Value::as_str).unwrap_or_default(); + let i = app.settings_profiles.find(name).ok_or_else(|| format!("no settings profile `{name}`"))?; + if to != name && app.settings_profiles.find(to).is_some() { + return Err(format!("another settings profile is called `{to}`")); + } + if let Some(doc) = app.settings_profiles.list.get_mut(i) { + set_name(doc, to); + } + if app.settings_profiles.active.as_deref() == Some(name) { + app.settings_profiles.active = Some(to.to_string()); + } + Ok(json!({ "name": to })) + } + "settings.profile.delete" => { + let i = app.settings_profiles.find(name).ok_or_else(|| format!("no settings profile `{name}`"))?; + app.settings_profiles.list.remove(i); + if app.settings_profiles.active.as_deref() == Some(name) { + app.settings_profiles.active = None; + } + Ok(json!({ "deleted": name })) + } + "settings.profile.export" => { + let doc = app.settings_profiles.get(name)?.clone(); + if let Some(path) = v.get("path").and_then(Value::as_str) { + let text = serde_json::to_string_pretty(&doc).map_err(|e| e.to_string())?; + std::fs::write(path, text).map_err(|e| format!("{path}: {e}"))?; + return Ok(json!({ "profile": doc, "path": path })); + } + Ok(json!({ "profile": doc })) + } + "settings.profile.import" => { + let doc = match v.get("path").and_then(Value::as_str) { + Some(path) => read_file(path)?, + None => v.get("profile").cloned().unwrap_or_default(), + }; + let name = add(app, &doc, v.get("name").and_then(Value::as_str))?; + Ok(json!({ "name": name })) + } + _ => Err(format!("`{id}` is not a settings profile command")), + } +} + +/// Run a profile command from Preferences and show its outcome there. +fn act(app: &mut SolveApp, id: &str, params: Value, done: &'static str) { + let result = app.run(id, params); + app.settings_profiles.message = Some(match result { + Ok(v) => match v.get("skipped").and_then(Value::as_array).map_or(0, Vec::len) { + 0 => Outcome::Done(done), + skipped => Outcome::Skipped(skipped), + }, + Err(e) => Outcome::Failed(e), + }); +} + +/// The Settings profiles section of the General page: the active profile (choosing one applies +/// it), a name to save the current settings under, and Rename, Delete, Export… and Import…. +pub(crate) fn section(app: &mut SolveApp, ui: &mut egui::Ui, labels: f32) { + let t = crate::theme::Tokens::get(); + if app.settings_profiles.draft.is_empty() + && let Some(active) = &app.settings_profiles.active + { + app.settings_profiles.draft = active.clone(); + } + ui_kit::settings_section(ui, "profiles", app.tr("prefs.profiles"), |ui| { + ui_kit::text(ui, app.tr("prefs.profiles_note"), ui_kit::Text::Hint("profiles")); + ui_kit::settings_form(ui, labels, |ui| { + let names = app.settings_profiles.names(); + let current = app.settings_profiles.active.clone().unwrap_or_else(|| crate::i18n::tr_label("None").to_string()); + let mut chosen = None; + ui_kit::row(ui, app.tr("prefs.profile_active"), |ui| { + ui_kit::settings_control_width(ui, t.form_card_width - t.space_4, |ui| { + ui_kit::dropdown_menu(ui, "pref_profile", ¤t, |ui| { + for name in &names { + if ui_kit::list_picker(ui, name, name, app.settings_profiles.active.as_ref() == Some(name)).clicked() { + chosen = Some(name.clone()); + } + } + }); + }); + }); + if let Some(name) = chosen { + app.settings_profiles.draft = name.clone(); + act(app, "settings.profile.apply", json!({ "name": name }), "prefs.profile_applied"); + } + if let Some(active) = app.settings_profiles.active.clone() + && app.settings_profiles.get(&active).is_ok_and(|doc| *doc != capture(app, &active)) + { + ui_kit::text(ui, app.tr("prefs.profile_changed"), ui_kit::Text::Note("profile_changed")); + } + ui_kit::row(ui, crate::i18n::tr_label("Name"), |ui| { + let mut draft = std::mem::take(&mut app.settings_profiles.draft); + let (enter, _) = ui_kit::text_field(ui, &mut draft, app.tr("prefs.profile_name_hint")); + app.settings_profiles.draft = draft; + if enter { + let name = app.settings_profiles.draft.clone(); + act(app, "settings.profile.save", json!({ "name": name }), "prefs.profile_saved"); + } + }); + }); + let draft = app.settings_profiles.draft.trim().to_string(); + let active = app.settings_profiles.active.clone(); + ui.horizontal_wrapped(|ui| { + if ui_kit::button(ui, app.tr("prefs.profile_save"), ui_kit::Button::Enabled(profile_name(&draft).is_some())).clicked() { + act(app, "settings.profile.save", json!({ "name": draft }), "prefs.profile_saved"); + } + let renamable = active.as_ref().is_some_and(|a| *a != draft) && profile_name(&draft).is_some(); + if ui_kit::button(ui, app.tr("prefs.profile_rename"), ui_kit::Button::Enabled(renamable)).clicked() + && let Some(name) = &active + { + act(app, "settings.profile.rename", json!({ "name": name, "to": draft }), "prefs.profile_renamed"); + } + if ui_kit::button(ui, crate::i18n::tr_label("Delete"), ui_kit::Button::Enabled(active.is_some())).clicked() + && let Some(name) = &active + { + act(app, "settings.profile.delete", json!({ "name": name }), "prefs.profile_deleted"); + app.settings_profiles.draft.clear(); + } + if ui_kit::button(ui, app.tr("prefs.profile_export"), ui_kit::Button::Enabled(active.is_some())).clicked() + && let Some(name) = active.clone() + { + app.pick_save(&format!("{name}.solidcraft-profile.json"), &["json"], move |app, path| { + if let Some(path) = path { + act(app, "settings.profile.export", json!({ "name": name, "path": path }), "prefs.profile_exported"); + } + }); + } + if ui_kit::button(ui, crate::i18n::tr_label("Import…"), ui_kit::Button::Normal).clicked() { + app.pick_open_for(&["json"], |app, path| { + if let Some(path) = path { + act(app, "settings.profile.import", json!({ "path": path }), "prefs.profile_imported"); + } + }); + } + }); + let locale = crate::i18n::Locale::for_language(&app.preferences.language); + match &app.settings_profiles.message { + Some(Outcome::Done(id)) => { + ui_kit::text(ui, locale.text(id), ui_kit::Text::Note("profile_message")); + } + Some(Outcome::Skipped(n)) => { + let text = locale.format("prefs.profile_skipped", &[("n", &n.to_string())]); + ui_kit::text(ui, &text, ui_kit::Text::Error("profile_message")); + } + Some(Outcome::Failed(e)) => { + ui_kit::text(ui, e, ui_kit::Text::Error("profile_message")); + } + None => {} + } + }); +} diff --git a/crates/ui-egui/src/settings_profiles_tests.rs b/crates/ui-egui/src/settings_profiles_tests.rs new file mode 100644 index 000000000..d6efe1981 --- /dev/null +++ b/crates/ui-egui/src/settings_profiles_tests.rs @@ -0,0 +1,268 @@ +use serde_json::{Value, json}; + +use crate::scenario::Harness; +use crate::settings_profiles::{FORMAT, MAX_PROFILES, capture, keys, sanitize}; + +fn run(h: &mut Harness, id: &str, params: Value) -> Value { + let out = h.call("engine.execute", json!({ "command": id, "params": params })); + assert!(out["error"].is_null(), "{id}: {out}"); + out["result"].clone() +} + +fn error(h: &mut Harness, id: &str, params: Value) -> String { + let out = h.call("engine.execute", json!({ "command": id, "params": params })); + out["error"].as_str().map(str::to_string).unwrap_or_else(|| panic!("{id} should fail: {out}")) +} + +#[test] +fn a_profile_holds_input_and_interface_settings_but_not_the_machine() { + let keys: Vec<&str> = keys().collect(); + for key in [ + "nav", + "mouse_gestures", + "radial_context_menu", + "zoom_reverse", + "theme", + "ui_scale", + "ui_font", + "navigator_style", + "language", + "suppress_sketch_snap", + ] { + assert!(keys.contains(&key), "{key} belongs in a profile"); + } + for key in [ + "space_mouse_calibrations", + "space_mouse_driver", + "space_mouse_speed", + "msaa", + "window_system", + "default_units", + "update", + "agents", + "custom_themes", + "orbit_cursor", + ] { + assert!(!keys.contains(&key), "{key} stays out of a profile"); + } + let h = Harness::new(); + let doc = capture(&h.app, "Laptop"); + assert_eq!(doc["format"], FORMAT); + assert_eq!(sanitize(&doc).unwrap(), doc, "a captured profile passes its own checks unchanged"); +} + +#[test] +fn switching_profiles_applies_every_setting_at_once() { + let mut h = Harness::new(); + h.app.preferences.ui_scale = 1.0; + h.app.preferences.nav = "fusion".into(); + assert_eq!(run(&mut h, "settings.profile.save", json!({"name": "Laptop"})), json!({"name": "Laptop"})); + + h.app.preferences.ui_scale = 1.5; + h.app.preferences.nav = "solidworks".into(); + h.app.preferences.mouse_gestures.enabled = true; + h.app.preferences.radial_context_menu = true; + h.app.keymap.custom.insert("solid.extrude".into(), vec!["E".into(), "Shift+E".into()]); + h.app.sbox.pinned = vec!["solid.fillet".into()]; + h.app.toolbar_custom.panels.insert("DESIGN/SOLID/CREATE".into(), vec!["solid.box".into()]); + run(&mut h, "settings.profile.save", json!({"name": "Large monitor"})); + assert_eq!(run(&mut h, "settings.profile.list", json!({})), json!({"profiles": ["Laptop", "Large monitor"], "active": "Large monitor"})); + + let out = run(&mut h, "settings.profile.apply", json!({"name": "Laptop"})); + assert_eq!((out["name"].as_str(), out["skipped"].as_array().map(Vec::len)), (Some("Laptop"), Some(0)), "{out}"); + assert_eq!((h.app.preferences.ui_scale, h.app.preferences.nav.as_str()), (1.0, "fusion")); + assert!(!h.app.preferences.mouse_gestures.enabled && !h.app.preferences.radial_context_menu); + assert!(h.app.keymap.custom.is_empty() && h.app.sbox.pinned.is_empty() && h.app.toolbar_custom.panels.is_empty()); + assert_eq!(h.app.settings_profiles.active.as_deref(), Some("Laptop")); + + run(&mut h, "settings.profile.apply", json!({"name": "Large monitor"})); + assert_eq!((h.app.preferences.ui_scale, h.app.preferences.nav.as_str()), (1.5, "solidworks")); + assert!(h.app.preferences.mouse_gestures.enabled && h.app.preferences.radial_context_menu); + assert_eq!(h.app.keymap.custom.get("solid.extrude").map(Vec::as_slice), Some(&["E".to_string(), "Shift+E".to_string()][..])); + assert_eq!(h.app.sbox.pinned, ["solid.fillet"]); + assert_eq!(h.app.toolbar_custom.panels.get("DESIGN/SOLID/CREATE"), Some(&vec!["solid.box".to_string()])); + + assert!(error(&mut h, "settings.profile.apply", json!({"name": "Desk"})).contains("no settings profile")); +} + +#[test] +fn rename_and_delete_follow_the_active_profile() { + let mut h = Harness::new(); + run(&mut h, "settings.profile.save", json!({"name": "A"})); + run(&mut h, "settings.profile.save", json!({"name": "B"})); + assert!(error(&mut h, "settings.profile.rename", json!({"name": "B", "to": "A"})).contains("another settings profile")); + run(&mut h, "settings.profile.rename", json!({"name": "B", "to": "Desk"})); + assert_eq!(h.app.settings_profiles.active.as_deref(), Some("Desk")); + assert_eq!(run(&mut h, "settings.profile.delete", json!({"name": "Desk"})), json!({"deleted": "Desk"})); + assert_eq!(run(&mut h, "settings.profile.list", json!({})), json!({"profiles": ["A"], "active": null})); +} + +#[test] +fn profiles_and_the_active_one_are_kept_between_runs() { + let mut h = Harness::new(); + h.app.preferences.ui_scale = 1.25; + run(&mut h, "settings.profile.save", json!({"name": "Laptop"})); + let mut other = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + other.load_prefs(&h.app.prefs()); + assert_eq!(other.settings_profiles.names(), ["Laptop"]); + assert_eq!(other.settings_profiles.active.as_deref(), Some("Laptop")); + assert_eq!(other.settings_profiles.list, h.app.settings_profiles.list); +} + +#[test] +fn export_and_import_go_through_one_file_and_import_never_switches() { + let dir = std::env::temp_dir().join(format!("solidcraft-profile-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("laptop.json"); + let path = path.to_str().unwrap(); + let mut h = Harness::new(); + h.app.preferences.zoom_reverse = true; + run(&mut h, "settings.profile.save", json!({"name": "Laptop"})); + let out = run(&mut h, "settings.profile.export", json!({"name": "Laptop", "path": path})); + assert_eq!(out["profile"]["format"], FORMAT); + let written: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap(); + assert_eq!(written, out["profile"]); + + h.app.preferences.zoom_reverse = false; + run(&mut h, "settings.profile.save", json!({"name": "Desk"})); + assert_eq!(run(&mut h, "settings.profile.import", json!({"path": path})), json!({"name": "Laptop 2"})); + assert_eq!(h.app.settings_profiles.active.as_deref(), Some("Desk"), "an import doesn't switch"); + assert!(!h.app.preferences.zoom_reverse); + run(&mut h, "settings.profile.apply", json!({"name": "Laptop 2"})); + assert!(h.app.preferences.zoom_reverse); + assert_eq!(run(&mut h, "settings.profile.import", json!({"profile": written, "name": "Travel"})), json!({"name": "Travel"})); + + let big = dir.join("big.json"); + std::fs::write(&big, " ".repeat(5 * 1024 * 1024)).unwrap(); + assert!(error(&mut h, "settings.profile.import", json!({"path": big.to_str().unwrap()})).contains("at most")); + assert!(error(&mut h, "settings.profile.import", json!({"path": dir.join("missing.json").to_str().unwrap()})).contains("missing.json")); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn hostile_profiles_are_refused_or_cut_down_without_panicking() { + let mut h = Harness::new(); + let refused = [ + json!(null), + json!("text"), + json!({"format": "solidcraft-shortcuts/1", "name": "A"}), + json!({"format": FORMAT}), + json!({"format": FORMAT, "name": ""}), + json!({"format": FORMAT, "name": "x".repeat(65)}), + json!({"format": FORMAT, "name": "A\u{0}"}), + json!({"format": FORMAT, "name": "A", "preferences": []}), + ]; + for doc in refused { + assert!(sanitize(&doc).is_err(), "{doc}"); + error(&mut h, "settings.profile.import", json!({"profile": doc})); + } + let shortcuts: serde_json::Map = (0..5000).map(|i| (format!("cmd.{i}"), json!("F1"))).collect(); + let doc = sanitize(&json!({ + "format": FORMAT, + "name": "A", + "unknown": 1, + "preferences": {"ui_scale": "big", "msaa": 8, "nav": "solidworks", "space_mouse_speed": 9.0, "no_such": true, "zoom_reverse": true}, + "shortcuts": Value::Object(shortcuts), + "favourites": (0..500).map(|i| json!(format!("f{i}"))).chain([json!(3), json!("x".repeat(300))]).collect::>(), + "themes": [{"format": "solidcraft-theme/1", "name": "Bad", "base": "grey"}], + })) + .unwrap(); + assert!(doc.get("unknown").is_none()); + assert_eq!(doc["preferences"], json!({"nav": "solidworks", "zoom_reverse": true}), "unknown, unreadable and machine settings are left out"); + assert_eq!(doc["shortcuts"].as_object().map(serde_json::Map::len), Some(2000)); + assert_eq!(doc["favourites"].as_array().map(Vec::len), Some(64)); + assert_eq!(doc["themes"], json!([])); + + // Readable but refused when applied: the setting keeps its value and is reported. + let before = h.app.preferences.ui_scale; + let doc = json!({"format": FORMAT, "name": "Odd", "preferences": {"ui_scale": 99.0, "zoom_reverse": true}}); + run(&mut h, "settings.profile.import", json!({"profile": doc})); + let out = run(&mut h, "settings.profile.apply", json!({"name": "Odd"})); + assert_eq!((out["applied"].as_u64(), out["skipped"].clone()), (Some(1), json!(["ui_scale"])), "{out}"); + assert_eq!(h.app.preferences.ui_scale, before); + assert!(h.app.preferences.zoom_reverse); + + for i in h.app.settings_profiles.list.len()..MAX_PROFILES { + run(&mut h, "settings.profile.save", json!({ "name": format!("P{i}") })); + } + assert!(error(&mut h, "settings.profile.save", json!({"name": "One more"})).contains("at most")); + let one_more = capture(&h.app, "One more"); + assert!(error(&mut h, "settings.profile.import", json!({"profile": one_more})).contains("at most")); +} + +#[test] +fn a_command_with_several_keys_keeps_them_all_in_a_profile() { + let doc = sanitize(&json!({ + "format": FORMAT, + "name": "A", + "shortcuts": {"solid.extrude": ["E", "Shift+E"], "sketch.line": "L", "sketch.circle": "", "bad": 3, "long": ["E", "x".repeat(300)]}, + })) + .unwrap(); + assert_eq!(doc["shortcuts"], json!({"solid.extrude": ["E", "Shift+E"], "sketch.line": "L", "sketch.circle": ""})); + let mut h = Harness::new(); + h.app.keymap.custom.insert("solid.extrude".into(), vec!["E".into(), "Shift+E".into()]); + let doc = capture(&h.app, "Laptop"); + assert_eq!(doc["shortcuts"]["solid.extrude"], json!(["E", "Shift+E"])); + assert_eq!(sanitize(&doc).unwrap(), doc, "several keys pass the profile's own checks"); +} + +#[test] +fn a_profile_brings_its_imported_theme_along() { + let mut h = Harness::new(); + let file = json!({"format": "solidcraft-theme/1", "name": "Paper", "base": "light", "colors": {"panel": "#fffdf0"}}); + h.call("ui.prefs", json!({"theme_import": file})); + assert_eq!(h.app.preferences.theme, "paper"); + run(&mut h, "settings.profile.save", json!({"name": "Bright"})); + h.call("ui.prefs", json!({"theme_remove": "paper"})); + assert!(h.app.preferences.custom_themes.is_empty()); + run(&mut h, "settings.profile.apply", json!({"name": "Bright"})); + assert_eq!(h.app.preferences.theme, "paper"); + assert_eq!(h.app.preferences.custom_themes.len(), 1); + assert!(!h.app.ui.dark); +} + +#[test] +fn cancel_in_preferences_takes_a_switch_back() { + let mut h = Harness::new(); + run(&mut h, "settings.profile.save", json!({"name": "Plain"})); + h.app.preferences.ui_scale = 1.5; + h.app.keymap.custom.insert("solid.extrude".into(), vec!["E".into(), "Shift+E".into()]); + h.app.sbox.pinned = vec!["solid.fillet".into()]; + run(&mut h, "settings.profile.save", json!({"name": "Big"})); + h.call("ui.prefs", json!({"open": "General"})); + run(&mut h, "settings.profile.apply", json!({"name": "Plain"})); + assert_eq!(h.app.preferences.ui_scale, 1.0); + h.call("ui.prefs", json!({"button": "cancel"})); + assert_eq!(h.app.preferences.ui_scale, 1.5); + assert_eq!(h.app.keymap.custom.get("solid.extrude").map(Vec::as_slice), Some(&["E".to_string(), "Shift+E".to_string()][..])); + assert_eq!(h.app.sbox.pinned, ["solid.fillet"]); + assert_eq!(h.app.settings_profiles.active.as_deref(), Some("Big")); +} + +#[test] +fn starting_a_profile_command_opens_preferences_instead_of_failing() { + let mut h = Harness::new(); + h.app.start("settings.profile.save"); + assert!(h.app.prefs_window.open); + assert_eq!(h.app.prefs_window.section, crate::prefs::PAGE_GENERAL); + h.frames(2); + assert!(h.app.prefs_window.open); +} + +#[test] +fn choosing_a_profile_in_preferences_applies_it() { + let mut h = Harness::new(); + run(&mut h, "settings.profile.save", json!({"name": "Laptop"})); + h.app.preferences.zoom_reverse = true; + run(&mut h, "settings.profile.save", json!({"name": "Large monitor"})); + run(&mut h, "settings.profile.apply", json!({"name": "Laptop"})); + assert!(!h.app.preferences.zoom_reverse); + h.call("ui.prefs", json!({"open": "General"})); + h.frames(3); + h.step(&json!({"click": {"handle": "dialog:Active profile"}})).unwrap(); + h.frames(3); + h.step(&json!({"click": {"handle": "dialog:list:Large monitor"}})).unwrap(); + h.frames(3); + assert_eq!(h.app.settings_profiles.active.as_deref(), Some("Large monitor")); + assert!(h.app.preferences.zoom_reverse); +} diff --git a/docs/book/src/guide/ui-tour.md b/docs/book/src/guide/ui-tour.md index 775e38908..fd16d16ef 100644 --- a/docs/book/src/guide/ui-tour.md +++ b/docs/book/src/guide/ui-tour.md @@ -301,6 +301,35 @@ or turn on **Frame rate details**, for the performance overlay: While the readout is on, the view redraws every frame. With vertical sync the frame rate tops out at the display's refresh rate; the interface time and the GPU counts still show the work. +### Settings profiles + +General › **Settings profiles** keeps the input and interface settings together under a name, +for example "Laptop" and "Large monitor", and switches them at once. A profile holds: + +- the Interface, Navigation and Sketch pages: theme, interface scale and font, layout, mouse + mode and the other navigation options, the radial menu and mouse gestures with every studio's + command lists, and the sketch modifier keys; +- the interface language; +- the keyboard shortcuts, the toolbar and the S box favourites; +- the imported theme it uses, so it travels with an exported profile. + +Settings that belong to the computer stay out: the 3D mouse (calibration, driver, speeds and +buttons), graphics, units and decimals, the AI page, recent files and window positions. + +- **Active profile** lists the profiles; choosing one applies it. While its settings differ from + what was saved, a note says so. +- **Save** keeps the current settings under the typed name, replacing a profile of that name, + and makes it the active one. +- **Rename** and **Delete** act on the active profile. +- **Export…** saves the active profile as one `solidcraft-profile/1` file; **Import…** adds one + without switching to it (a name already taken gets a number). + +Switching, like any other change in Preferences, is taken back by Cancel. A setting a profile +holds but this computer refuses (an interface font that isn't installed) keeps its current value, +and the message says how many did. Import ignores unknown keys, leaves out values this version +can't read, and refuses files over 4 MiB. Scripts and agents reach the same actions with the +`settings.profile.*` commands (`save`, `apply`, `rename`, `delete`, `list`, `export`, `import`). + Navigation › **Smooth wheel zoom** is on by default. Turn it off to apply each wheel or trackpad event immediately, with no smoothing tail. It is independent of **Animate view changes**, which controls axis views, Look At, Home and Fit. Re-enabling smoothing during diff --git a/docs/book/src/reference/glossary.md b/docs/book/src/reference/glossary.md index ae0c6f733..8371981e4 100644 --- a/docs/book/src/reference/glossary.md +++ b/docs/book/src/reference/glossary.md @@ -353,6 +353,24 @@ are kept, not deleted. - **For translators:** "history" is the undo history, not the timeline. French had three names for this marker while English did. +### settings profile + +A named set of input and interface preferences that can be switched, exported and imported as +one. + +A settings profile holds the Interface, Navigation and Sketch preferences, the interface +language, keyboard shortcuts, the toolbar and the S box favourites. Settings that belong to one +computer (the 3D mouse, graphics, units) stay out. It is an app setting, not part of a design. + +- **In SolidCraft:** `settings.profile.list`, `settings.profile.save`, `settings.profile.apply`, + `settings.profile.rename`, `settings.profile.delete`, `settings.profile.export`, + `settings.profile.import`; the `settings_profiles` key of the stored preferences; the + `solidcraft-profile/1` file format. +- **Don't use:** preset, configuration, workspace (for the set of settings). +- **Elsewhere:** settings profile, user profile, preferences set. +- **For translators:** not a sketch profile and not a frame profile (see *Words with more than + one meaning*, "Profile"), and not a design configuration. + ### sketch A set of points and curves, with their constraints, on one plane, that features use as profiles, @@ -436,6 +454,9 @@ share a catalogue entry. Each meaning below gets its own term and, in time, its | Part | a standard part | *standard part* | `parts.*` | | | a body, an occurrence or the design | *body*, *occurrence*, *design* | catalogue texts that say "part" | | | a design property | *part number* | Design Properties | +| Profile | a closed region of a sketch that a feature uses | profile | `solid.extrude`, `solid.revolve` | +| | the cross-section a frame member follows | frame profile | `frame.profile.*` | +| | a named set of preferences | *settings profile* | `settings.profile.*`, Preferences › General | | Gap | the space a hem leaves | hem gap | the Hem dialog's Gap row | | | an open end in the sketch continuity legend | open end | the sketch continuity legend | | Clearance | the Clearance command | clearance check | `inspect.clearance` |