Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Follow a theme file and reload it when it changes (#7573) (#7574)

raykholod2f0627421d3
diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rs
index 74d835da51..4045f1f738 100644
--- a/apps/solidcraft/src/main.rs
+++ b/apps/solidcraft/src/main.rs
@@ -750,11 +750,14 @@ fn main() -> eframe::Result {
let mut control_port: Option<u16> = solidcraft_engine::geom::env::var("CONTROL_PORT").and_then(|p| p.parse().ok());
let mut files = Vec::new();
let mut sample = false;
+ // `--theme-file PATH`: follow that theme file for this run without saving it (#7573).
+ let mut theme_file: Option<String> = None;
let mut args = std::env::args().skip(1);
while let Some(a) = args.next() {
match a.as_str() {
"--control" => control_port = args.next().and_then(|p| p.parse().ok()),
"--sample" => sample = true,
+ "--theme-file" => theme_file = args.next(),
"--safe-mode" => safe_mode = true,
"--version" | "-V" => {
println!("solidcraft {}", env!("CARGO_PKG_VERSION"));
@@ -774,7 +777,9 @@ fn main() -> eframe::Result {
return Ok(());
}
"--help" | "-h" => {
- println!("usage: solidcraft [--control PORT] [--sample] [--crash-log] [--safe-mode] [design.solidcraft | part.step]");
+ println!(
+ "usage: solidcraft [--control PORT] [--sample] [--theme-file THEME.json] [--crash-log] [--safe-mode] [design.solidcraft | part.step]"
+ );
return Ok(());
}
_ => files.push(a),
@@ -926,6 +931,11 @@ fn main() -> eframe::Result {
if let Some(p) = cc.storage.and_then(|s| solidcraft_ui_egui::prefs::stored(|k| s.get_string(k))).filter(|_| !safe_mode) {
app.load_prefs(&p);
}
+ if let Some(path) = &theme_file
+ && let Err(e) = solidcraft_ui_egui::prefs::follow_theme_file_for_run(&mut app, path)
+ {
+ app.set_status(format!("--theme-file: {e}"), true);
+ }
mark("app state and prefs");
let gpu = cc.wgpu_render_state.as_ref().map(|rs| LostWatch {
lost: rs.device_lost.clone(),
diff --git a/assets/locales/pending/theme-follow.json b/assets/locales/pending/theme-follow.json
new file mode 100644
index 0000000000..134e0d649f
--- /dev/null
+++ b/assets/locales/pending/theme-follow.json
@@ -0,0 +1,226 @@
+{
+ "en": {
+ "prefs.theme_follow": "Follow a theme file",
+ "prefs.theme_follow_error": "Not applied: {error}. The last good theme stays on.",
+ "prefs.theme_follow_launch": "Followed for this run only (--theme-file); reloaded whenever another tool rewrites it.",
+ "prefs.theme_follow_note": "Reloaded whenever another tool rewrites it. Choosing a theme stops following it.",
+ "prefs.theme_follow_off": "Off",
+ "prefs.theme_follow_stop": "Stop following"
+ },
+ "ar": {
+ "prefs.theme_follow": "اتباع ملف سمة",
+ "prefs.theme_follow_error": "لم يُطبّق: {error}. تبقى آخر سمة سليمة مفعّلة.",
+ "prefs.theme_follow_launch": "يُتّبع لهذه الجلسة فقط (--theme-file)؛ يُعاد تحميله كلما أعادت أداة أخرى كتابته.",
+ "prefs.theme_follow_note": "يُعاد تحميله كلما أعادت أداة أخرى كتابته. اختيار سمة يوقف اتباعه.",
+ "prefs.theme_follow_off": "إيقاف",
+ "prefs.theme_follow_stop": "إيقاف الاتباع"
+ },
+ "cs": {
+ "prefs.theme_follow": "Sledovat soubor motivu",
+ "prefs.theme_follow_error": "Nepoužito: {error}. Zůstává poslední funkční motiv.",
+ "prefs.theme_follow_launch": "Sledování jen pro toto spuštění (--theme-file); načte se znovu při každém přepsání jiným nástrojem.",
+ "prefs.theme_follow_note": "Načte se znovu při každém přepsání jiným nástrojem. Výběr motivu sledování ukončí.",
+ "prefs.theme_follow_off": "Vypnuto",
+ "prefs.theme_follow_stop": "Ukončit sledování"
+ },
+ "da": {
+ "prefs.theme_follow": "Følg en temafil",
+ "prefs.theme_follow_error": "Ikke anvendt: {error}. Det seneste gyldige tema bevares.",
+ "prefs.theme_follow_launch": "Følges kun denne gang (--theme-file); genindlæses, når et andet værktøj overskriver filen.",
+ "prefs.theme_follow_note": "Genindlæses, når et andet værktøj overskriver filen. Valg af et tema stopper dette.",
+ "prefs.theme_follow_off": "Fra",
+ "prefs.theme_follow_stop": "Stop med at følge"
+ },
+ "de": {
+ "prefs.theme_follow": "Einer Designdatei folgen",
+ "prefs.theme_follow_error": "Nicht angewendet: {error}. Das letzte gültige Design bleibt aktiv.",
+ "prefs.theme_follow_launch": "Nur für diesen Start (--theme-file); wird neu geladen, sobald ein anderes Werkzeug die Datei überschreibt.",
+ "prefs.theme_follow_note": "Wird neu geladen, sobald ein anderes Werkzeug die Datei überschreibt. Die Auswahl eines Designs beendet das Folgen.",
+ "prefs.theme_follow_off": "Aus",
+ "prefs.theme_follow_stop": "Nicht mehr folgen"
+ },
+ "es": {
+ "prefs.theme_follow": "Seguir un archivo de tema",
+ "prefs.theme_follow_error": "No aplicado: {error}. Se mantiene el último tema válido.",
+ "prefs.theme_follow_launch": "Solo en esta sesión (--theme-file); se recarga cada vez que otra herramienta reescribe el archivo.",
+ "prefs.theme_follow_note": "Se recarga cada vez que otra herramienta reescribe el archivo. Elegir un tema deja de seguirlo.",
+ "prefs.theme_follow_off": "Desactivado",
+ "prefs.theme_follow_stop": "Dejar de seguir"
+ },
+ "fr": {
+ "prefs.theme_follow": "Suivre un fichier de thème",
+ "prefs.theme_follow_error": "Non appliqué : {error}. Le dernier thème valide reste actif.",
+ "prefs.theme_follow_launch": "Suivi pour cette session uniquement (--theme-file) ; rechargé dès qu’un autre outil réécrit le fichier.",
+ "prefs.theme_follow_note": "Rechargé dès qu’un autre outil réécrit le fichier. Choisir un thème arrête le suivi.",
+ "prefs.theme_follow_off": "Désactivé",
+ "prefs.theme_follow_stop": "Arrêter le suivi"
+ },
+ "gl": {
+ "prefs.theme_follow": "Seguir un ficheiro de tema",
+ "prefs.theme_follow_error": "Non aplicado: {error}. Mantense o último tema válido.",
+ "prefs.theme_follow_launch": "Só nesta sesión (--theme-file); vólvese cargar cando outra ferramenta reescribe o ficheiro.",
+ "prefs.theme_follow_note": "Vólvese cargar cando outra ferramenta reescribe o ficheiro. Escoller un tema detén o seguimento.",
+ "prefs.theme_follow_off": "Desactivado",
+ "prefs.theme_follow_stop": "Deixar de seguir"
+ },
+ "he": {
+ "prefs.theme_follow": "מעקב אחר קובץ ערכת נושא",
+ "prefs.theme_follow_error": "לא הוחל: {error}. ערכת הנושא התקינה האחרונה נשארת פעילה.",
+ "prefs.theme_follow_launch": "מעקב להפעלה זו בלבד (--theme-file); נטען מחדש בכל פעם שכלי אחר משכתב את הקובץ.",
+ "prefs.theme_follow_note": "נטען מחדש בכל פעם שכלי אחר משכתב את הקובץ. בחירת ערכת נושא מפסיקה את המעקב.",
+ "prefs.theme_follow_off": "כבוי",
+ "prefs.theme_follow_stop": "הפסקת המעקב"
+ },
+ "hu": {
+ "prefs.theme_follow": "Témafájl követése",
+ "prefs.theme_follow_error": "Nem alkalmazható: {error}. Az utolsó érvényes téma marad aktív.",
+ "prefs.theme_follow_launch": "Követés csak erre a futásra (--theme-file); újratöltés, ha más eszköz felülírja a fájlt.",
+ "prefs.theme_follow_note": "Újratöltés, ha más eszköz felülírja a fájlt. Téma választása leállítja a követést.",
+ "prefs.theme_follow_off": "Ki",
+ "prefs.theme_follow_stop": "Követés leállítása"
+ },
+ "id": {
+ "prefs.theme_follow": "Ikuti file tema",
+ "prefs.theme_follow_error": "Tidak diterapkan: {error}. Tema valid terakhir tetap aktif.",
+ "prefs.theme_follow_launch": "Diikuti hanya untuk sesi ini (--theme-file); dimuat ulang setiap kali alat lain menulis ulang file.",
+ "prefs.theme_follow_note": "Dimuat ulang setiap kali alat lain menulis ulang file. Memilih tema menghentikan pengikutan.",
+ "prefs.theme_follow_off": "Nonaktif",
+ "prefs.theme_follow_stop": "Berhenti mengikuti"
+ },
+ "it": {
+ "prefs.theme_follow": "Segui un file di tema",
+ "prefs.theme_follow_error": "Non applicato: {error}. Resta attivo l’ultimo tema valido.",
+ "prefs.theme_follow_launch": "Seguito solo per questa sessione (--theme-file); ricaricato quando un altro strumento riscrive il file.",
+ "prefs.theme_follow_note": "Ricaricato quando un altro strumento riscrive il file. Scegliere un tema interrompe il monitoraggio.",
+ "prefs.theme_follow_off": "Disattivato",
+ "prefs.theme_follow_stop": "Smetti di seguire"
+ },
+ "ja": {
+ "prefs.theme_follow": "テーマファイルに従う",
+ "prefs.theme_follow_error": "適用できません: {error}。最後に正常に適用されたテーマを維持します。",
+ "prefs.theme_follow_launch": "今回の起動時のみ有効です (--theme-file)。別のツールがファイルを書き換えるたびに再読み込みします。",
+ "prefs.theme_follow_note": "別のツールがファイルを書き換えるたびに再読み込みします。テーマを選ぶと追従を停止します。",
+ "prefs.theme_follow_off": "オフ",
+ "prefs.theme_follow_stop": "追従を停止"
+ },
+ "ko": {
+ "prefs.theme_follow": "테마 파일 따르기",
+ "prefs.theme_follow_error": "적용되지 않음: {error}. 마지막으로 적용된 정상 테마를 유지합니다.",
+ "prefs.theme_follow_launch": "이번 실행에만 적용됩니다 (--theme-file). 다른 도구가 파일을 다시 쓸 때마다 다시 불러옵니다.",
+ "prefs.theme_follow_note": "다른 도구가 파일을 다시 쓸 때마다 다시 불러옵니다. 테마를 선택하면 따르기를 중지합니다.",
+ "prefs.theme_follow_off": "끄기",
+ "prefs.theme_follow_stop": "따르기 중지"
+ },
+ "ms": {
+ "prefs.theme_follow": "Ikut fail tema",
+ "prefs.theme_follow_error": "Tidak digunakan: {error}. Tema sah terakhir kekal aktif.",
+ "prefs.theme_follow_launch": "Diikuti untuk sesi ini sahaja (--theme-file); dimuat semula setiap kali alat lain menulis semula fail.",
+ "prefs.theme_follow_note": "Dimuat semula setiap kali alat lain menulis semula fail. Memilih tema menghentikan ikutan.",
+ "prefs.theme_follow_off": "Mati",
+ "prefs.theme_follow_stop": "Berhenti mengikuti"
+ },
+ "nb": {
+ "prefs.theme_follow": "Følg en temafil",
+ "prefs.theme_follow_error": "Ikke brukt: {error}. Det siste gyldige temaet forblir aktivt.",
+ "prefs.theme_follow_launch": "Følges bare denne kjøringen (--theme-file); lastes inn på nytt når et annet verktøy skriver om filen.",
+ "prefs.theme_follow_note": "Lastes inn på nytt når et annet verktøy skriver om filen. Valg av et tema stopper dette.",
+ "prefs.theme_follow_off": "Av",
+ "prefs.theme_follow_stop": "Slutt å følge"
+ },
+ "nl": {
+ "prefs.theme_follow": "Een themabestand volgen",
+ "prefs.theme_follow_error": "Niet toegepast: {error}. Het laatste geldige thema blijft actief.",
+ "prefs.theme_follow_launch": "Alleen deze sessie gevolgd (--theme-file); opnieuw geladen zodra een ander hulpmiddel het bestand overschrijft.",
+ "prefs.theme_follow_note": "Opnieuw geladen zodra een ander hulpmiddel het bestand overschrijft. Een thema kiezen stopt het volgen.",
+ "prefs.theme_follow_off": "Uit",
+ "prefs.theme_follow_stop": "Volgen stoppen"
+ },
+ "pl": {
+ "prefs.theme_follow": "Śledź plik motywu",
+ "prefs.theme_follow_error": "Nie zastosowano: {error}. Ostatni poprawny motyw pozostaje aktywny.",
+ "prefs.theme_follow_launch": "Śledzenie tylko w tej sesji (--theme-file); plik jest wczytywany ponownie po każdym nadpisaniu przez inne narzędzie.",
+ "prefs.theme_follow_note": "Plik jest wczytywany ponownie po każdym nadpisaniu przez inne narzędzie. Wybór motywu kończy śledzenie.",
+ "prefs.theme_follow_off": "Wyłączone",
+ "prefs.theme_follow_stop": "Zakończ śledzenie"
+ },
+ "pt-BR": {
+ "prefs.theme_follow": "Seguir um arquivo de tema",
+ "prefs.theme_follow_error": "Não aplicado: {error}. O último tema válido continua ativo.",
+ "prefs.theme_follow_launch": "Seguido apenas nesta sessão (--theme-file); recarregado sempre que outra ferramenta reescreve o arquivo.",
+ "prefs.theme_follow_note": "Recarregado sempre que outra ferramenta reescreve o arquivo. Escolher um tema interrompe o acompanhamento.",
+ "prefs.theme_follow_off": "Desativado",
+ "prefs.theme_follow_stop": "Parar de seguir"
+ },
+ "ro": {
+ "prefs.theme_follow": "Urmărește un fișier de temă",
+ "prefs.theme_follow_error": "Nu s-a aplicat: {error}. Ultima temă validă rămâne activă.",
+ "prefs.theme_follow_launch": "Urmărit doar în această sesiune (--theme-file); reîncărcat când alt instrument rescrie fișierul.",
+ "prefs.theme_follow_note": "Reîncărcat când alt instrument rescrie fișierul. Alegerea unei teme oprește urmărirea.",
+ "prefs.theme_follow_off": "Dezactivat",
+ "prefs.theme_follow_stop": "Oprește urmărirea"
+ },
+ "ru": {
+ "prefs.theme_follow": "Следить за файлом темы",
+ "prefs.theme_follow_error": "Не применено: {error}. Последняя рабочая тема остаётся активной.",
+ "prefs.theme_follow_launch": "Только для этого запуска (--theme-file); перезагружается, когда другой инструмент перезаписывает файл.",
+ "prefs.theme_follow_note": "Перезагружается, когда другой инструмент перезаписывает файл. Выбор темы прекращает отслеживание.",
+ "prefs.theme_follow_off": "Выкл.",
+ "prefs.theme_follow_stop": "Прекратить отслеживание"
+ },
+ "sv": {
+ "prefs.theme_follow": "Följ en temafil",
+ "prefs.theme_follow_error": "Inte tillämpat: {error}. Det senaste giltiga temat förblir aktivt.",
+ "prefs.theme_follow_launch": "Följs endast denna körning (--theme-file); läses in igen när ett annat verktyg skriver om filen.",
+ "prefs.theme_follow_note": "Läses in igen när ett annat verktyg skriver om filen. Att välja ett tema avslutar detta.",
+ "prefs.theme_follow_off": "Av",
+ "prefs.theme_follow_stop": "Sluta följa"
+ },
+ "tr": {
+ "prefs.theme_follow": "Bir tema dosyasını takip et",
+ "prefs.theme_follow_error": "Uygulanmadı: {error}. Son geçerli tema etkin kalır.",
+ "prefs.theme_follow_launch": "Yalnızca bu çalıştırmada takip edilir (--theme-file); başka bir araç dosyayı yeniden yazdığında yeniden yüklenir.",
+ "prefs.theme_follow_note": "Başka bir araç dosyayı yeniden yazdığında yeniden yüklenir. Tema seçmek takibi durdurur.",
+ "prefs.theme_follow_off": "Kapalı",
+ "prefs.theme_follow_stop": "Takibi durdur"
+ },
+ "uk": {
+ "prefs.theme_follow": "Стежити за файлом теми",
+ "prefs.theme_follow_error": "Не застосовано: {error}. Остання робоча тема залишається активною.",
+ "prefs.theme_follow_launch": "Лише для цього запуску (--theme-file); перезавантажується, коли інший інструмент перезаписує файл.",
+ "prefs.theme_follow_note": "Перезавантажується, коли інший інструмент перезаписує файл. Вибір теми припиняє відстеження.",
+ "prefs.theme_follow_off": "Вимк.",
+ "prefs.theme_follow_stop": "Припинити відстеження"
+ },
+ "vi": {
+ "prefs.theme_follow": "Theo dõi tệp chủ đề",
+ "prefs.theme_follow_error": "Chưa áp dụng: {error}. Chủ đề hợp lệ gần nhất vẫn được giữ.",
+ "prefs.theme_follow_launch": "Chỉ theo dõi trong lần chạy này (--theme-file); tải lại mỗi khi công cụ khác ghi lại tệp.",
+ "prefs.theme_follow_note": "Tải lại mỗi khi công cụ khác ghi lại tệp. Chọn chủ đề sẽ dừng theo dõi.",
+ "prefs.theme_follow_off": "Tắt",
+ "prefs.theme_follow_stop": "Dừng theo dõi"
+ },
+ "zh": {
+ "prefs.theme_follow": "跟随主题文件",
+ "prefs.theme_follow_error": "未应用:{error}。保留上次有效的主题。",
+ "prefs.theme_follow_launch": "仅本次运行跟随 (--theme-file);其他工具改写文件时会重新加载。",
+ "prefs.theme_follow_note": "其他工具改写文件时会重新加载。选择主题将停止跟随。",
+ "prefs.theme_follow_off": "关闭",
+ "prefs.theme_follow_stop": "停止跟随"
+ },
+ "zh-TW": {
+ "prefs.theme_follow": "跟隨主題檔案",
+ "prefs.theme_follow_error": "未套用:{error}。保留上次有效的主題。",
+ "prefs.theme_follow_launch": "僅本次執行跟隨 (--theme-file);其他工具改寫檔案時會重新載入。",
+ "prefs.theme_follow_note": "其他工具改寫檔案時會重新載入。選擇主題將停止跟隨。",
+ "prefs.theme_follow_off": "關閉",
+ "prefs.theme_follow_stop": "停止跟隨"
+ },
+ "en-GB": {
+ "prefs.theme_follow": "Follow a theme file",
+ "prefs.theme_follow_error": "Not applied: {error}. The last good theme stays on.",
+ "prefs.theme_follow_launch": "Followed for this run only (--theme-file); reloaded whenever another tool rewrites it.",
+ "prefs.theme_follow_note": "Reloaded whenever another tool rewrites it. Choosing a theme stops following it.",
+ "prefs.theme_follow_off": "Off",
+ "prefs.theme_follow_stop": "Stop following"
+ }
+}
diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs
index 74c11d6141..887fdd1c65 100644
--- a/crates/ui-egui/src/prefs.rs
+++ b/crates/ui-egui/src/prefs.rs
@@ -629,6 +629,9 @@ preference_settings! {
viewport_theme: crate::theme::ViewportTheme = crate::theme::ViewportTheme::Theme, PAGE_INTERFACE;
/// Imported theme files (`theme_files`), kept here so they also work in the browser.
custom_themes: Vec<crate::theme_files::ThemeFile> = Vec::new();
+ /// Desktop: a `solidcraft-theme/1` file another tool writes, followed as the theme and
+ /// reloaded when it changes (#7573). Empty (the default): no file is followed.
+ theme_follow: String = String::new(), PAGE_INTERFACE;
/// Interface language (a registered locale ID).
language: String = "en".into(), 0;
/// Shared workspace composition; system windows and popups retain their purpose.
@@ -856,6 +859,80 @@ pub struct PrefsWindow {
font_filter: String,
/// Search text on the Plugins page.
pub(crate) plugin_query: String,
+ /// The followed theme file's state (#7573): its last good theme and why a read failed.
+ pub(crate) follow: crate::theme_files::Follow,
+}
+
+/// Following a theme file needs the file system: the desktop app only (#7573).
+const FOLLOW_AVAILABLE: bool = cfg!(not(target_arch = "wasm32"));
+
+/// Follow `path` as the theme for this run (the `--theme-file` launch flag), without saving it.
+pub fn follow_theme_file_for_run(app: &mut SolveApp, path: &str) -> Result<(), String> {
+ if !FOLLOW_AVAILABLE {
+ return Err(FOLLOW_UNAVAILABLE.into());
+ }
+ let path = crate::theme_files::follow_path(path)?;
+ app.prefs_window.follow.launch = (!path.is_empty()).then_some(path);
+ Ok(())
+}
+
+const FOLLOW_UNAVAILABLE: &str = "`theme_follow` is not available in the browser: it follows a file on this computer; import the theme instead";
+
+/// Stop following a theme file: the preference and this run's launch flag. The chosen theme
+/// takes over again, with its own dark or light.
+fn stop_following(app: &mut SolveApp) {
+ let following = !app.prefs_window.follow.path(&app.preferences.theme_follow).is_empty();
+ app.preferences.theme_follow.clear();
+ app.prefs_window.follow.launch = None;
+ if following {
+ let theme = app.preferences.theme.clone();
+ select_theme(app, &theme);
+ }
+}
+
+/// Look at the followed theme file (#7573): every second while the app runs and whenever the
+/// window gains the focus. A new failure is reported once in the status bar; a recovery too.
+fn follow_theme_file(app: &mut SolveApp, ctx: &egui::Context) {
+ if !FOLLOW_AVAILABLE {
+ return;
+ }
+ let (now, focused) = ctx.input(|i| (i.time, i.focused));
+ let follow = &mut app.prefs_window.follow;
+ let gained_focus = focused && !follow.focused;
+ follow.focused = focused;
+ let path = follow.path(&app.preferences.theme_follow).to_string();
+ let had_error = follow.error().is_some();
+ match follow.poll(&path, now, gained_focus) {
+ crate::theme_files::FollowChange::None => {}
+ crate::theme_files::FollowChange::Loaded(name) => {
+ if had_error {
+ app.set_status(format!("Theme file loaded again: {name}"), false);
+ }
+ }
+ crate::theme_files::FollowChange::Failed(e) => app.set_status(format!("Theme file not applied: {e} (the last good theme stays on)"), true),
+ }
+ if !path.is_empty() {
+ ctx.request_repaint_after(std::time::Duration::from_secs_f64(crate::theme_files::FOLLOW_INTERVAL));
+ }
+}
+
+/// `ui.prefs` `theme_follow`: a path follows that file (read at once, so the reply has any
+/// error), `""` stops following.
+fn set_theme_follow(app: &mut SolveApp, value: &serde_json::Value, available: bool) -> Result<(), String> {
+ if !available {
+ return Err(FOLLOW_UNAVAILABLE.into());
+ }
+ let path = value.as_str().ok_or("`theme_follow` must be a theme file's path, or \"\" to stop following")?;
+ let path = crate::theme_files::follow_path(path)?;
+ if path.is_empty() {
+ stop_following(app);
+ return Ok(());
+ }
+ app.prefs_window.follow.launch = None;
+ app.preferences.theme_follow = path.clone();
+ // Read now, so the reply has any error; the next frame's look then follows on as usual.
+ let _ = app.prefs_window.follow.poll(&path, f64::NEG_INFINITY, true);
+ Ok(())
}
/// Open the dialog at a page.
@@ -934,6 +1011,8 @@ impl Snapshot {
/// and Remove (an imported theme). Like the other preferences, a choice applies at once.
fn theme_row(app: &mut SolveApp, ui: &mut egui::Ui) {
let mut choices = theme_choices(app);
+ // While a file is followed (#7573) it is the theme, so no tile shows as chosen.
+ let following = !app.prefs_window.follow.path(&app.preferences.theme_follow).is_empty();
choices.sort_by_key(|(id, _)| match id.as_str() {
"light" => 0,
"dark" => 1,
@@ -965,13 +1044,13 @@ fn theme_row(app: &mut SolveApp, ui: &mut egui::Ui) {
ui,
label,
Some(note),
- app.preferences.theme == *id,
+ !following && app.preferences.theme == *id,
true,
ui_kit::PreferenceFigure::Theme { palette: palette.into(), system: id == "system" },
);
crate::scenario::publish_target(&format!("prefs:theme_tile:{id}"), response.rect);
crate::scenario::publish_target(&format!("prefs:theme:{id}"), response.rect);
- if app.preferences.theme == *id {
+ if !following && app.preferences.theme == *id {
crate::scenario::publish_target("prefs:theme", response.rect);
}
if response.clicked() {
@@ -1006,6 +1085,8 @@ fn theme_row(app: &mut SolveApp, ui: &mut egui::Ui) {
action_theme = Some(id);
}
if let Some(id) = chosen {
+ // Choosing a theme stops following a file (#7573).
+ stop_following(app);
select_theme(app, &id);
}
match action {
@@ -1047,6 +1128,46 @@ fn theme_row(app: &mut SolveApp, ui: &mut egui::Ui) {
}
}
+/// Settings › Interface › Theme: a theme file to follow (#7573), chosen with the file picker,
+/// and why its last read was not applied. The desktop app only.
+fn follow_row(app: &mut SolveApp, ui: &mut egui::Ui) {
+ let path = app.prefs_window.follow.path(&app.preferences.theme_follow).to_string();
+ let launch = app.prefs_window.follow.launch.is_some();
+ let error = app.prefs_window.follow.error().map(str::to_string);
+ let (mut choose, mut stop) = (false, false);
+ // The setting's name is longer than the label column: it leads the row's own line.
+ ui_kit::row(ui, "", |ui| {
+ ui.horizontal(|ui| {
+ ui_kit::text(ui, app.tr("prefs.theme_follow"), ui_kit::Text::Inline);
+ let choose_button = ui_kit::button(ui, app.tr_label("Choose…"), ui_kit::Button::Small);
+ crate::scenario::publish_target("prefs:theme_follow", choose_button.rect);
+ choose = choose_button.clicked();
+ let stop_button = ui_kit::button(ui, app.tr("prefs.theme_follow_stop"), ui_kit::Button::Enabled(!path.is_empty()));
+ stop = stop_button.clicked();
+ let name = std::path::Path::new(&path).file_name().map(|n| n.to_string_lossy().to_string());
+ let shown = name.unwrap_or_else(|| app.tr("prefs.theme_follow_off").to_string());
+ ui_kit::text(ui, &shown, ui_kit::Text::Inline).on_hover_text(&path);
+ });
+ });
+ if !path.is_empty() {
+ ui_kit::text(ui, app.tr(if launch { "prefs.theme_follow_launch" } else { "prefs.theme_follow_note" }), ui_kit::Text::Hint("theme_follow"));
+ }
+ if let Some(error) = error.filter(|_| !path.is_empty()) {
+ ui_kit::text(ui, &crate::i18n::format("prefs.theme_follow_error", &[("error", &error)]), ui_kit::Text::Error("theme_follow"));
+ }
+ if stop {
+ stop_following(app);
+ }
+ if choose {
+ app.pick_open_for(&["json"], |app, path| {
+ let Some(path) = path else { return };
+ if let Err(e) = set_theme_follow(app, &serde_json::Value::String(path), FOLLOW_AVAILABLE) {
+ app.set_status(format!("Follow a theme file: {e}"), true);
+ }
+ });
+ }
+}
+
/// The interface font (#1290): the built-in font first, then the installed families, with a
/// search box. The choice applies at once, like the other preferences.
fn ui_font_row(app: &mut SolveApp, ui: &mut egui::Ui) {
@@ -1094,6 +1215,7 @@ fn defaults(app: &mut SolveApp, page: usize) {
set_autosave(app);
}
PAGE_INTERFACE => {
+ app.prefs_window.follow.launch = None;
app.ui.dark = true;
app.ui.layout = app.preferences.layout;
app.ui.show_navigation_bar = true;
@@ -1135,8 +1257,10 @@ pub fn apply(app: &mut SolveApp, ctx: &egui::Context) {
{
app.ui.dark = t == egui::Theme::Dark;
}
- // A theme file's palette, in place of its base's (dark or light); the visuals follow.
- let file = crate::theme_files::find(&app.preferences.theme, &app.preferences.custom_themes);
+ // A theme file's palette, in place of its base's (dark or light); the visuals follow. A
+ // followed file (#7573) wins while it is followed and has read completely once.
+ follow_theme_file(app, ctx);
+ let file = app.prefs_window.follow.theme().or_else(|| crate::theme_files::find(&app.preferences.theme, &app.preferences.custom_themes));
if let Some(f) = file {
app.ui.dark = f.base.is_dark();
}
@@ -2076,8 +2200,10 @@ fn button_job_picker(
/// presses OK, Cancel, Apply or Restore Defaults, `stand_up: true` answers the stand-up offer
/// (`false` leaves the file as it is, like "Leave it"), `theme_import` (a theme file's JSON or
/// text) adds a theme and turns it on, `theme_remove` (an id) removes an imported one and
-/// `theme_export: true` returns the theme on now as `theme_file`; any other keys set
-/// preferences. Returns them all, the open page, the offer and the theme ids.
+/// `theme_export: true` returns the theme on now as `theme_file`, `theme_follow` (a path, or
+/// `""` to stop) follows a theme file on the desktop (#7573); any other keys set preferences.
+/// Returns them all, the open page, the offer, the theme ids and the followed file
+/// (`theme_followed`, `theme_follow_error`).
pub fn control(app: &mut SolveApp, p: &serde_json::Value) -> Result<serde_json::Value, String> {
let mut rest = p.as_object().cloned().unwrap_or_default();
if let Some(page) = rest.remove("open") {
@@ -2100,6 +2226,12 @@ pub fn control(app: &mut SolveApp, p: &serde_json::Value) -> Result<serde_json::
if let Some(id) = rest.remove("theme_remove") {
remove_theme(app, id.as_str().unwrap_or_default())?;
}
+ match rest.remove("theme_follow") {
+ Some(v) => set_theme_follow(app, &v, FOLLOW_AVAILABLE)?,
+ // Choosing a theme stops following a file, as clicking a theme tile does.
+ None if rest.contains_key("theme") => stop_following(app),
+ None => {}
+ }
let export = rest.remove("theme_export").and_then(|v| v.as_bool()).unwrap_or(false);
let button = rest.remove("button");
let mut out = set(app, &serde_json::Value::Object(rest))?;
@@ -2120,6 +2252,10 @@ pub fn control(app: &mut SolveApp, p: &serde_json::Value) -> Result<serde_json::
o.insert("dark".into(), json!(app.ui.dark));
o.insert("viewport_dark".into(), json!(app.viewport_dark()));
o.insert("theme_ids".into(), json!(theme_choices(app).into_iter().map(|(id, _)| id).collect::<Vec<_>>()));
+ let follow = &app.prefs_window.follow;
+ let followed = follow.path(&app.preferences.theme_follow);
+ o.insert("theme_followed".into(), json!((!followed.is_empty()).then_some(followed)));
+ o.insert("theme_follow_error".into(), json!(follow.error().filter(|_| !followed.is_empty())));
if let Some(id) = imported {
o.insert("theme_imported".into(), json!(id));
}
@@ -2352,6 +2488,12 @@ pub fn set(app: &mut SolveApp, p: &serde_json::Value) -> Result<serde_json::Valu
crate::theme_files::parse_icon_palette(&theme.icon_palette)?;
crate::theme_files::parse_borders(&theme.borders)?;
}
+ if new.theme_follow != app.preferences.theme_follow {
+ if !FOLLOW_AVAILABLE && !new.theme_follow.trim().is_empty() {
+ return Err(FOLLOW_UNAVAILABLE.into());
+ }
+ crate::theme_files::follow_path(&new.theme_follow)?;
+ }
if !crate::i18n::is_supported(&new.language) {
return Err(format!("`language` must be one of: {}", crate::i18n::LOCALES.iter().map(|locale| locale.id).collect::<Vec<_>>().join(", ")));
}
@@ -3650,6 +3792,79 @@ mod tests {
}
}
+ #[test]
+ fn a_followed_theme_file_applies_reloads_keeps_the_last_good_theme_and_the_flag_is_not_saved() {
+ use crate::theme::Tokens;
+ use egui::Color32;
+ use serde_json::json;
+ let mut h = crate::scenario::Harness::new();
+ assert_eq!(h.app.preferences.theme_follow, "", "off by default");
+ let out = h.call("ui.prefs", json!({}));
+ assert!(out["result"]["theme_followed"].is_null() && out["result"]["theme_follow_error"].is_null(), "{out}");
+
+ let dir = std::env::temp_dir().join(format!("solidcraft-prefs-follow-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let file = dir.join("live.json");
+ let path = file.to_string_lossy().to_string();
+ let write = |panel: &str, extra: &str| {
+ let text = format!(r##"{{"format":"solidcraft-theme/1","name":"Live","base":"light","colors":{{"panel":"{panel}"{extra}}}}}"##);
+ std::fs::write(&file, text).unwrap();
+ };
+ write("#102030", "");
+ let out = h.call("ui.prefs", json!({"theme_follow": path}));
+ assert_eq!(
+ (out["result"]["theme_follow"].as_str(), out["result"]["theme_followed"].as_str()),
+ (Some(path.as_str()), Some(path.as_str())),
+ "{out}"
+ );
+ assert!(out["result"]["theme_follow_error"].is_null(), "{out}");
+ h.frames(2);
+ assert_eq!(Tokens::get().panel, Color32::from_rgb(0x10, 0x20, 0x30));
+ assert!(!h.app.ui.dark, "the file's base");
+
+ // Another tool rewrites it: reloaded within the poll interval, without a restart.
+ write("#405060", r##","accent":"#aa3300""##);
+ h.frames(70);
+ assert_eq!(Tokens::get().panel, Color32::from_rgb(0x40, 0x50, 0x60));
+
+ // Broken or missing: the last good theme stays on and the reply says why.
+ std::fs::write(&file, "{\"format\": \"solidcraft-theme/1\", \"na").unwrap();
+ h.frames(70);
+ assert_eq!(Tokens::get().panel, Color32::from_rgb(0x40, 0x50, 0x60));
+ let out = h.call("ui.prefs", json!({}));
+ assert!(out["result"]["theme_follow_error"].as_str().is_some_and(|e| e.contains("not a theme file")), "{out}");
+ std::fs::remove_file(&file).unwrap();
+ let out = h.call("ui.prefs", json!({"theme_follow": path}));
+ assert!(out["result"]["theme_follow_error"].as_str().is_some_and(|e| e.contains("can't read")), "{out}");
+
+ // Choosing a theme, or "", stops following.
+ let out = h.call("ui.prefs", json!({"theme": "dark"}));
+ assert!(out["result"]["theme_followed"].is_null() && out["result"]["theme_follow"] == "", "{out}");
+ h.frames(2);
+ assert_eq!(Tokens::get().panel, Tokens::dark().panel);
+
+ // The launch flag follows a file for this run only: the saved preferences never name it.
+ write("#708090", "");
+ follow_theme_file_for_run(&mut h.app, &path).unwrap();
+ h.frames(2);
+ assert_eq!(Tokens::get().panel, Color32::from_rgb(0x70, 0x80, 0x90));
+ assert_eq!(h.call("ui.prefs", json!({}))["result"]["theme_followed"].as_str(), Some(path.as_str()));
+ assert_eq!(h.app.preferences.theme_follow, "");
+ assert!(!h.app.prefs().contains("live.json"));
+ h.call("ui.prefs", json!({"theme_follow": ""}));
+ h.frames(2);
+ assert_eq!(Tokens::get().panel, Tokens::dark().panel);
+
+ // Hostile values are refused; the browser has no files to follow.
+ assert!(h.call("ui.prefs", json!({"theme_follow": 5}))["error"].is_string());
+ assert!(h.call("ui.prefs", json!({"theme_follow": "a\nb"}))["error"].is_string());
+ assert!(h.call("ui.prefs", json!({"theme_follow": "x".repeat(5000)}))["error"].is_string());
+ let web = set_theme_follow(&mut h.app, &json!(path), false).unwrap_err();
+ assert!(web.contains("not available in the browser"), "{web}");
+ assert_eq!(h.app.preferences.theme_follow, "");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
#[test]
fn theme_files_import_apply_export_save_and_remove() {
use crate::theme::{ColorVision, Tokens};
diff --git a/crates/ui-egui/src/prefs/interface.rs b/crates/ui-egui/src/prefs/interface.rs
index ee2a6368ce..bb0ed4f331 100644
--- a/crates/ui-egui/src/prefs/interface.rs
+++ b/crates/ui-egui/src/prefs/interface.rs
@@ -18,6 +18,10 @@ pub(super) fn interface(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) {
app.preferences.viewport_theme = *view;
}
});
+ // A theme file another tool writes, reloaded when it changes (#7573).
+ if FOLLOW_AVAILABLE {
+ follow_row(app, ui);
+ }
});
});
ui_kit::settings_section(ui, "layout", app.tr("prefs.layout"), |ui| {
diff --git a/crates/ui-egui/src/theme_files.rs b/crates/ui-egui/src/theme_files.rs
index d877e69187..3cca0a7c38 100644
--- a/crates/ui-egui/src/theme_files.rs
+++ b/crates/ui-egui/src/theme_files.rs
@@ -694,6 +694,129 @@ pub fn add(custom: &mut Vec<ThemeFile>, mut theme: ThemeFile) -> Result<String,
Ok(id)
}
+/// Seconds between two looks at a followed file's modified time and size.
+pub const FOLLOW_INTERVAL: f64 = 1.0;
+/// Longest followed path accepted, in bytes (hostile input from the control channel).
+pub const MAX_FOLLOW_PATH: usize = 4096;
+
+/// A theme file the desktop app follows (#7573): another tool writes it, and the app reloads it
+/// when its modified time or size changes. Only a read that parses completely is applied; while
+/// the file is being written, broken, missing or too big, the last good theme stays on and
+/// [`Follow::error`] says why.
+#[derive(Clone, Debug, Default)]
+pub struct Follow {
+ /// The `--theme-file` launch flag's path: followed for this run in place of the preference,
+ /// never saved.
+ pub launch: Option<String>,
+ /// The path the state below belongs to.
+ path: String,
+ /// The file's modified time and size at the last read.
+ stamp: Option<(Option<std::time::SystemTime>, u64)>,
+ /// When (`egui` input time, seconds) the file was last looked at.
+ checked: Option<f64>,
+ /// The last theme that read completely.
+ theme: Option<ThemeFile>,
+ /// Why the last read was not applied.
+ error: Option<String>,
+ /// Whether the window had the focus last frame (gaining it re-reads the file).
+ pub focused: bool,
+}
+
+/// What a [`Follow::poll`] changed.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum FollowChange {
+ /// Nothing new.
+ None,
+ /// The file read completely; its theme is on now.
+ Loaded(String),
+ /// A read failed for a new reason (reported once; the last good theme stays on).
+ Failed(String),
+}
+
+/// A followed path as given: trimmed, at most [`MAX_FOLLOW_PATH`] bytes, no control characters.
+pub fn follow_path(path: &str) -> Result<String, String> {
+ let path = path.trim();
+ if path.len() > MAX_FOLLOW_PATH || path.chars().any(char::is_control) {
+ return Err(format!("a followed theme file's path is at most {MAX_FOLLOW_PATH} bytes without control characters"));
+ }
+ Ok(path.to_string())
+}
+
+impl Follow {
+ /// The path followed now: the launch flag's, else the preference's (empty: none).
+ pub fn path<'a>(&'a self, preference: &'a str) -> &'a str {
+ match self.launch.as_deref().map(str::trim) {
+ Some(path) if !path.is_empty() => path,
+ _ => preference.trim(),
+ }
+ }
+
+ /// The theme the followed file gave last, if any read completely.
+ pub fn theme(&self) -> Option<&ThemeFile> {
+ self.theme.as_ref()
+ }
+
+ /// Why the followed file's last read was not applied.
+ pub fn error(&self) -> Option<&str> {
+ self.error.as_deref()
+ }
+
+ /// Look at `path` (`now` in seconds): at most every [`FOLLOW_INTERVAL`] unless `force`, and
+ /// read it only when its modified time or size changed. An empty path stops following.
+ pub fn poll(&mut self, path: &str, now: f64, force: bool) -> FollowChange {
+ if path != self.path {
+ *self = Follow { launch: self.launch.take(), focused: self.focused, path: path.to_string(), ..Default::default() };
+ }
+ if path.is_empty() {
+ return FollowChange::None;
+ }
+ let due = self.checked.is_none_or(|t| now - t >= FOLLOW_INTERVAL || now < t);
+ if !force && !due {
+ return FollowChange::None;
+ }
+ self.checked = Some(now);
+ match self.read(force) {
+ Ok(None) => FollowChange::None,
+ Ok(Some(theme)) => {
+ let name = theme.name.clone();
+ self.theme = Some(theme);
+ self.error = None;
+ FollowChange::Loaded(name)
+ }
+ Err(e) if self.error.as_deref() == Some(e.as_str()) => FollowChange::None,
+ Err(e) => {
+ self.error = Some(e.clone());
+ FollowChange::Failed(e)
+ }
+ }
+ }
+
+ /// The file's theme when it changed since the last read (`Ok(None)`: unchanged).
+ fn read(&mut self, force: bool) -> Result<Option<ThemeFile>, String> {
+ use std::io::Read;
+ let path = std::path::Path::new(&self.path);
+ let meta = std::fs::metadata(path).map_err(|e| format!("can't read {}: {e}", self.path))?;
+ if !meta.is_file() {
+ return Err(format!("{} is not a file", self.path));
+ }
+ if meta.len() > MAX_BYTES as u64 {
+ return Err(format!("a theme file is at most {} KiB", MAX_BYTES / 1024));
+ }
+ let stamp = (meta.modified().ok(), meta.len());
+ if !force && self.stamp == Some(stamp) {
+ return Ok(None);
+ }
+ self.stamp = Some(stamp);
+ // Never more than the cap, whatever the size said a moment ago.
+ let mut text = String::new();
+ std::fs::File::open(path)
+ .and_then(|f| f.take(MAX_BYTES as u64 + 1).read_to_string(&mut text))
+ .map_err(|e| format!("can't read {}: {e}", self.path))?;
+ let theme = parse(&text)?;
+ Ok(Some(ThemeFile { id: format!("file-{}", theme.id), ..theme }))
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -1183,4 +1306,63 @@ mod tests {
assert_eq!(radius_values(resolve(file)), defaults, "{}", file.id);
}
}
+
+ #[test]
+ fn a_followed_file_reloads_when_rewritten_and_keeps_the_last_good_theme() {
+ let dir = std::env::temp_dir().join(format!("solidcraft-theme-follow-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let file = dir.join("live.json");
+ let path = file.to_string_lossy().to_string();
+ let write = |panel: &str, extra: &str| {
+ std::fs::write(&file, format!(r##"{{"format":"{FORMAT}","name":"Live","base":"dark","colors":{{"panel":"{panel}"{extra}}}}}"##)).unwrap();
+ };
+ let panel = |f: &Follow| f.theme().map(|t| resolve(t).panel);
+
+ // Off by default: nothing is followed or read.
+ let mut follow = Follow::default();
+ assert_eq!(follow.path(""), "");
+ assert_eq!(follow.poll("", 0.0, true), FollowChange::None);
+ assert!(follow.theme().is_none() && follow.error().is_none());
+
+ // A valid file applies; an unchanged one is not read again.
+ write("#102030", "");
+ assert_eq!(follow.poll(&path, 0.0, false), FollowChange::Loaded("Live".into()));
+ assert_eq!(panel(&follow), Some(Color32::from_rgb(0x10, 0x20, 0x30)));
+ assert_eq!(follow.poll(&path, 0.5, false), FollowChange::None, "polled at most every second");
+ assert_eq!(follow.poll(&path, 1.5, false), FollowChange::None, "unchanged");
+
+ // Rewritten (another size, so even a coarse modified time sees it): reloaded.
+ write("#405060", r##","accent":"#aa3300""##);
+ assert_eq!(follow.poll(&path, 1.6, false), FollowChange::None, "not due yet");
+ assert_eq!(follow.poll(&path, 2.6, false), FollowChange::Loaded("Live".into()));
+ assert_eq!(panel(&follow), Some(Color32::from_rgb(0x40, 0x50, 0x60)));
+
+ // Half written, broken, missing or too big: the last good theme stays, the reason once.
+ std::fs::write(&file, r#"{"format":"solidcraft-theme/1","name":"Li"#).unwrap();
+ assert!(matches!(follow.poll(&path, 4.0, false), FollowChange::Failed(e) if e.contains("not a theme file")));
+ assert_eq!(follow.poll(&path, 5.0, true), FollowChange::None, "the same reason is reported once");
+ assert_eq!(panel(&follow), Some(Color32::from_rgb(0x40, 0x50, 0x60)));
+ std::fs::write(&file, vec![b' '; MAX_BYTES + 1]).unwrap();
+ assert!(matches!(follow.poll(&path, 6.0, false), FollowChange::Failed(e) if e.contains("KiB")));
+ std::fs::remove_file(&file).unwrap();
+ assert!(matches!(follow.poll(&path, 7.0, false), FollowChange::Failed(e) if e.contains("can't read")));
+ assert_eq!(panel(&follow), Some(Color32::from_rgb(0x40, 0x50, 0x60)));
+ assert!(follow.error().is_some());
+ assert!(matches!(follow.poll(&dir.to_string_lossy(), 8.0, false), FollowChange::Failed(e) if e.contains("not a file")));
+
+ // Written again completely: back on, the error gone.
+ write("#708090", "");
+ assert_eq!(follow.poll(&path, 9.0, false), FollowChange::Loaded("Live".into()));
+ assert_eq!((panel(&follow), follow.error()), (Some(Color32::from_rgb(0x70, 0x80, 0x90)), None));
+
+ // The launch flag's path wins over the preference's; an empty path stops following.
+ follow.launch = Some(path.clone());
+ assert_eq!(follow.path("/elsewhere.json"), path);
+ follow.launch = None;
+ assert_eq!(follow.poll("", 10.0, false), FollowChange::None);
+ assert!(follow.theme().is_none());
+ assert!(follow_path(&"x".repeat(MAX_FOLLOW_PATH + 1)).is_err() && follow_path("a\nb").is_err());
+ assert!(follow_path("a\u{7}b").is_err());
+ let _ = std::fs::remove_dir_all(&dir);
+ }
}
diff --git a/docs/book/src/guide/ui-tour.md b/docs/book/src/guide/ui-tour.md
index c216e356fa..9f4f60a7c5 100644
--- a/docs/book/src/guide/ui-tour.md
+++ b/docs/book/src/guide/ui-tour.md
@@ -220,6 +220,20 @@ Command icons use the shared SVG palette.
Imported themes are kept with your preferences, so they work in the browser app too. Colour
vision modes still apply on top of any theme.
+#### Follow a theme file
+
+In the desktop app, **Follow a theme file** (under the themes) takes a theme file that another
+tool writes and keeps it as the theme: whenever the file changes, SolidCraft reloads it within
+about a second, and again when its window comes back to the front, without a restart. This suits
+tools that generate a colour scheme from your wallpaper or keep one scheme across your desktop
+and applications (pywal and matugen are two examples); have them write a `solidcraft-theme/1`
+file from a template. **Choose…** picks the file, **Stop following** (or choosing any theme)
+turns it off; it is off until you choose a file. Only a file that reads completely is applied:
+while it is being written, or if it is broken, missing or larger than 256 KiB, the last good
+theme stays on and the setting says why. `solidcraft --theme-file my-theme.json` follows a file
+for one run without changing your preferences. The browser app has no file to follow; import the
+theme there instead.
+
Graphics › **Frame rate** shows frames per second in the view's bottom-right corner. Click it,
or turn on **Frame rate details**, for the performance overlay:
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 8a99c08ba4..82e7e2a134 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -303,7 +303,7 @@ labels; `prefs:measure_axis_distances` identifies the checkbox.
| `ui.home` | `open?`: bool; `sample?`: index | the start page: show or hide it, open a built-in sample (once built); returns `open` and the recent designs |
| `ui.shortcut` | `command`, `key?`, `replace?` | a command's key, or rebinds it (`""` clears; a key another command uses is refused unless `replace`) |
| `ui.help` | `item?`: `about`, `shortcuts` (read only), `report` (opens a report draft for review), `crashes` (the Crash Reports window) | the version, commit, build date and diagnostic text |
-| `ui.prefs` | any of `default_units`, `nav` (`fusion`, `solidworks`, `inventor`, `alias`, `blender`, `tinkercad`, `openscad`, `touchpad`), `zoom_reverse`, `pan_reverse_x` (default false: horizontal scrolling pans the other way), `zoom_to_cursor`, `smooth_wheel_zoom` (default true), `trackpad_pan` (default true: two-finger scroll pans, except Touchpad always zooms; pinch zooms), `orbit_around` (`view_centre` (default: what Pan moves and Fit frames), `origin` (the world origin stays still on screen), `cursor` (the model point under the pointer when the drag began); the older `orbit_cursor` boolean still sets `cursor` when true), `sketch_exit_view` (`keep` (default: the view stays where it is when a sketch ends), `previous` (back to the view from before the sketch), `unless_rotated` (back unless the sketch view was turned)), `look_at_anim`, `look_at_speed`, `middle_double_click` (`home` (default), `fit`, `off`), `msaa`, `show_frame_rate` (default false: frames per second in the view's bottom-right corner, counting the frames the view draws anyway; it reads 0 FPS once the view is idle), `window_system` (Linux: `auto` (default: XWayland whenever there is an X display, native Wayland on niri), `wayland`, `x11`; saved in `graphics.json`, applies at the next start; `SOLIDCRAFT_WAYLAND` overrides it), `graphics_adapter` (exact card name, or empty for Automatic; applies after restart; `WGPU_ADAPTER_NAME` takes precedence), `frame_rate_details` (default false: with the frame rate, a frame-time graph of the frames drawn with the triangles over it, a frame-time histogram and what the GPU drew; clicking the readout switches it), `length_decimals`, `angle_decimals`, `step_values` (default false: Up/Down and the wheel step a plain number in a focused value field), `theme` (`dark`, `light`, `system` or a theme file's id: a built-in one such as `gruvbox-dark`, or an imported one; the reply's `theme_ids` lists them), `viewport_theme` (`theme` (default: the theme's own), `light`, `dark`: the 3D view in the Light or Dark theme's colours whatever the window uses, #4146), `theme_import` (a `solidcraft-theme/1` file's JSON or text: adds the theme and turns it on; the reply's `theme_imported` is its id), `theme_remove` (an imported theme's id), `theme_export: true` (the reply's `theme_file` is the theme on now as a complete file; see [colour themes](book/src/guide/ui-tour.md#colour-themes)), `language` (`en`, `ar`, `ja`, `de`, `fr`, `he`, `ko`, `ms`, `ru`, `uk`, `zh`; see [localization](localization.md)), `ui_scale`, `ui_font` (an installed font family or a font file for the interface; empty for the built-in font), `up_axis` (`z`, `y`), `offer_stand_up`, `extrude_auto_to_object` (default false: in the Extrude dialog, with a profile picked, a face, vertex or parallel plane picked off its plane switches the extent to To Object; it applies to Extrude dialogs opened afterwards), `hole_snaps` (default false: a Single hole snaps to its face's middle and round edges' centres), `hole_moves` (default false: a placed Single hole has a drag handle (`hole:<n>`), and a pick on a face that has a hole moves it there), `placement_handles` (default false: handles on the preview of a Rest, Boss or Snap Fit that move it across the model and turn it), `color_vision` (`off` (default), `protan`, `deutan`, `tritan`: colour vision modes, #778), `view_confirm_corner` (default false: while a dialog or a sketch is open, a check and a cross at the view's top right, handles `view:confirm:ok` and `view:confirm:cancel`, do what the dialog's OK and Cancel do, or Finish Sketch and Cancel Sketch; the axis view or cube moves down below them, #6709), `history_sketches` (`in_order` (default), `under_feature`: the History at the left lists a sketch under the first feature built from it, #6489; the timeline at the bottom keeps the creation order), `dialog_buttons` (`bottom` (default), `top`: a feature dialog's OK, Cancel and Apply sit in its title row instead of under its inputs, #6708; the buttons keep their handles, and `dialog:close` is then Cancel's), `timeline_origin_bodies` (default false: the History on the left or under the browser starts with the active component's Bodies folder and the Origin, the browser's rows with their eyes, folds and menus; the bottom History is unchanged), `dialog_place` (`edge` (default) or `left_column`: command dialogs open in the left column in place of the browser and the History, #6707), `check_updates` (default true; [updates](book/src/guide/updates.md)), `nav_bridge_enabled` (default false) and `nav_bridge_port` (default 8765: a device's own app on this computer moves the view, [the navigation bridge](3d-mouse.md#device-apps-the-navigation-bridge)); `open` (a page: General, Interface, Design, Navigation, Keyboard Shortcuts, Sketch, Graphics, AI, Plugins; Shortcuts, Assistant and Sketch & selection are aliases, and the former Selection page opens Sketch) opens the Preferences dialog there; `button`: `ok`, `cancel`, `apply`, `defaults`; `stand_up: true` stands up a just-opened Y-up file, `stand_up: false` leaves it as it is ("Leave it": the offer closes and `offer_stand_up` stays on); the offer's buttons are the handles `stand_up:stand`, `stand_up:leave` and `stand_up:never` | sets preferences (kept between runs), returns them all plus `dialog` (the open page or null), `dark`, `viewport_dark` (whether the 3D view is dark) and `stand_up_offer` |
+| `ui.prefs` | any of `default_units`, `nav` (`fusion`, `solidworks`, `inventor`, `alias`, `blender`, `tinkercad`, `openscad`, `touchpad`), `zoom_reverse`, `pan_reverse_x` (default false: horizontal scrolling pans the other way), `zoom_to_cursor`, `smooth_wheel_zoom` (default true), `trackpad_pan` (default true: two-finger scroll pans, except Touchpad always zooms; pinch zooms), `orbit_around` (`view_centre` (default: what Pan moves and Fit frames), `origin` (the world origin stays still on screen), `cursor` (the model point under the pointer when the drag began); the older `orbit_cursor` boolean still sets `cursor` when true), `sketch_exit_view` (`keep` (default: the view stays where it is when a sketch ends), `previous` (back to the view from before the sketch), `unless_rotated` (back unless the sketch view was turned)), `look_at_anim`, `look_at_speed`, `middle_double_click` (`home` (default), `fit`, `off`), `msaa`, `show_frame_rate` (default false: frames per second in the view's bottom-right corner, counting the frames the view draws anyway; it reads 0 FPS once the view is idle), `window_system` (Linux: `auto` (default: XWayland whenever there is an X display, native Wayland on niri), `wayland`, `x11`; saved in `graphics.json`, applies at the next start; `SOLIDCRAFT_WAYLAND` overrides it), `graphics_adapter` (exact card name, or empty for Automatic; applies after restart; `WGPU_ADAPTER_NAME` takes precedence), `frame_rate_details` (default false: with the frame rate, a frame-time graph of the frames drawn with the triangles over it, a frame-time histogram and what the GPU drew; clicking the readout switches it), `length_decimals`, `angle_decimals`, `step_values` (default false: Up/Down and the wheel step a plain number in a focused value field), `theme` (`dark`, `light`, `system` or a theme file's id: a built-in one such as `gruvbox-dark`, or an imported one; the reply's `theme_ids` lists them), `viewport_theme` (`theme` (default: the theme's own), `light`, `dark`: the 3D view in the Light or Dark theme's colours whatever the window uses, #4146), `theme_import` (a `solidcraft-theme/1` file's JSON or text: adds the theme and turns it on; the reply's `theme_imported` is its id), `theme_remove` (an imported theme's id), `theme_export: true` (the reply's `theme_file` is the theme on now as a complete file; see [colour themes](book/src/guide/ui-tour.md#colour-themes)), `theme_follow` (desktop only, default `""`: a `solidcraft-theme/1` file's path to follow as the theme, reloaded within about a second whenever it changes and when the window gains the focus; the file is read at once, and a file that doesn't read keeps the last good theme; `""` stops following, as does setting `theme`; in the browser it is an error; the launch flag `--theme-file PATH` follows a file for one run without saving it; the reply's `theme_followed` is the path followed now or null, and `theme_follow_error` why its last read was not applied, or null), `language` (`en`, `ar`, `ja`, `de`, `fr`, `he`, `ko`, `ms`, `ru`, `uk`, `zh`; see [localization](localization.md)), `ui_scale`, `ui_font` (an installed font family or a font file for the interface; empty for the built-in font), `up_axis` (`z`, `y`), `offer_stand_up`, `extrude_auto_to_object` (default false: in the Extrude dialog, with a profile picked, a face, vertex or parallel plane picked off its plane switches the extent to To Object; it applies to Extrude dialogs opened afterwards), `hole_snaps` (default false: a Single hole snaps to its face's middle and round edges' centres), `hole_moves` (default false: a placed Single hole has a drag handle (`hole:<n>`), and a pick on a face that has a hole moves it there), `placement_handles` (default false: handles on the preview of a Rest, Boss or Snap Fit that move it across the model and turn it), `color_vision` (`off` (default), `protan`, `deutan`, `tritan`: colour vision modes, #778), `view_confirm_corner` (default false: while a dialog or a sketch is open, a check and a cross at the view's top right, handles `view:confirm:ok` and `view:confirm:cancel`, do what the dialog's OK and Cancel do, or Finish Sketch and Cancel Sketch; the axis view or cube moves down below them, #6709), `history_sketches` (`in_order` (default), `under_feature`: the History at the left lists a sketch under the first feature built from it, #6489; the timeline at the bottom keeps the creation order), `dialog_buttons` (`bottom` (default), `top`: a feature dialog's OK, Cancel and Apply sit in its title row instead of under its inputs, #6708; the buttons keep their handles, and `dialog:close` is then Cancel's), `timeline_origin_bodies` (default false: the History on the left or under the browser starts with the active component's Bodies folder and the Origin, the browser's rows with their eyes, folds and menus; the bottom History is unchanged), `dialog_place` (`edge` (default) or `left_column`: command dialogs open in the left column in place of the browser and the History, #6707), `check_updates` (default true; [updates](book/src/guide/updates.md)), `nav_bridge_enabled` (default false) and `nav_bridge_port` (default 8765: a device's own app on this computer moves the view, [the navigation bridge](3d-mouse.md#device-apps-the-navigation-bridge)); `open` (a page: General, Interface, Design, Navigation, Keyboard Shortcuts, Sketch, Graphics, AI, Plugins; Shortcuts, Assistant and Sketch & selection are aliases, and the former Selection page opens Sketch) opens the Preferences dialog there; `button`: `ok`, `cancel`, `apply`, `defaults`; `stand_up: true` stands up a just-opened Y-up file, `stand_up: false` leaves it as it is ("Leave it": the offer closes and `offer_stand_up` stays on); the offer's buttons are the handles `stand_up:stand`, `stand_up:leave` and `stand_up:never` | sets preferences (kept between runs), returns them all plus `dialog` (the open page or null), `dark`, `viewport_dark` (whether the 3D view is dark), `stand_up_offer`, `theme_followed` and `theme_follow_error` |
| `ui.capture` | `action?`: `capture`, `revert`, `cancel` | answers the Capture Position question (asked when a command starts or the design is saved while components were moved without capturing); without `action`, what waits |
| `ui.window` | `action`: minimize, maximize, restore, toggle, close | what the title bar's caption buttons do (on Windows and Linux the application bar is the title bar); close asks about unsaved designs first |
| `ui.agent_cursor` | `show` (bool), `speed`: a number from 1 to 5 (times the normal speed) or `"instant"` (no animation: the command runs at once and the pointer jumps to where it acted), `follow_camera` (bool); all optional | the settings. While the cursor is shown, `engine.execute` first glides to the command's toolbar button and to each pick, then runs and replies; later requests wait their turn. The pointer shows the command's localized name, including commands inside a closed toolbar group; an animated batch names each command it visits. It also follows the pointer input sent with `ui.move`, `ui.click`, `ui.drag` and `ui.scroll`, as each event reaches the app, and a press leaves a ripple. `"animate": false` on a call skips it |