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

* claim: #7573

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

* Translate the follow-a-theme-file strings
This commit is contained in:
raykholo
2026-10-27 20:08:12 +00:00
committed by GitHub
parent e0e2c566e7
commit d2f0627421
7 changed files with 659 additions and 8 deletions
+11 -1
View File
@@ -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(),
+226
View File
@@ -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"
}
}
+221 -6
View File
@@ -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};
+4
View File
@@ -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| {
+182
View File
@@ -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);
}
}
+14
View File
@@ -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:
File diff suppressed because one or more lines are too long