From d7cba9e96d4c1a72845fefbb786336b2e1007ebc Mon Sep 17 00:00:00 2001 From: Nathan Dane Date: Sat, 31 Oct 2026 04:01:29 +0000 Subject: [PATCH] Preferences: theme options list and the opacity option (#8876) (#9807) * claim: #8876 * claim: #8876 * Theme options: persist per-theme values and expose preferences contracts * Restore selected theme mode after stopping a followed theme * claim: #8876 * Preferences: render theme options and apply readable panel opacity * Use floating-point scale expectation in theme preferences scenario * Keep panel opacity colour construction inside theme tokens * Complete theme options translations in Arabic Hebrew and Vietnamese * Let standalone theme sliders fill their option cells --- assets/locales/pending/theme-options.json | 69 ++ crates/engine/src/schema/mod.rs | 1 + crates/engine/src/schema/tests.rs | 87 ++ crates/engine/src/schema/ui_prefs.rs | 89 ++ crates/ui-egui/src/i18n.rs | 40 +- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/prefs.rs | 1027 ++++++++++++++++- crates/ui-egui/src/prefs/interface.rs | 1 + crates/ui-egui/src/scenario.rs | 10 + crates/ui-egui/src/settings_profiles.rs | 15 +- crates/ui-egui/src/settings_profiles_tests.rs | 30 + crates/ui-egui/src/theme.rs | 41 + crates/ui-egui/src/theme_files.rs | 97 +- crates/ui-egui/src/theme_options.rs | 87 ++ crates/ui-egui/src/ui_kit/mod.rs | 1 + crates/ui-egui/src/ui_kit/preferences.rs | 304 +++++ .../ui-egui/src/ui_kit/preferences_layout.rs | 103 ++ .../ui-egui/tests/fixtures/theme-options.json | 658 +++++++++++ .../tests/scenarios/prefs_theme_files.json | 16 +- docs/book/src/guide/ui-tour.md | 41 +- docs/control-protocol.md | 24 +- docs/ui-kit.md | 28 + 22 files changed, 2719 insertions(+), 51 deletions(-) create mode 100644 assets/locales/pending/theme-options.json create mode 100644 crates/engine/src/schema/ui_prefs.rs create mode 100644 crates/ui-egui/src/theme_options.rs create mode 100644 crates/ui-egui/src/ui_kit/preferences_layout.rs create mode 100644 crates/ui-egui/tests/fixtures/theme-options.json diff --git a/assets/locales/pending/theme-options.json b/assets/locales/pending/theme-options.json new file mode 100644 index 000000000..f5478413d --- /dev/null +++ b/assets/locales/pending/theme-options.json @@ -0,0 +1,69 @@ +{ + "ar": { + "prefs.theme_option_opacity": "العتامة", + "prefs.theme_option_opacity_help": "اضبط عتامة اللوحات العائمة. يُطبّق حد أدنى للعتامة للحفاظ على وضوح النص فوق ألوان منفذ العرض.", + "prefs.theme_options_badge": "الخيارات", + "prefs.theme_options_more": "المزيد · {count}", + "prefs.theme_options_reset": "إعادة تعيين", + "prefs.theme_options_unavailable": "غير متاح على هذا الجهاز" + }, + "de": { + "prefs.theme_option_opacity": "Deckkraft", + "prefs.theme_option_opacity_help": "Deckkraft schwebender Bedienfelder anpassen. Eine Mindestdeckkraft schützt die Lesbarkeit über den Ansichtsfarben.", + "prefs.theme_options_badge": "Optionen", + "prefs.theme_options_more": "Mehr · {count}", + "prefs.theme_options_reset": "Zurücksetzen", + "prefs.theme_options_unavailable": "Auf diesem Gerät nicht verfügbar" + }, + "en": { + "prefs.theme_option_opacity": "Opacity", + "prefs.theme_option_opacity_help": "Adjust floating panel opacity. A readability floor protects text over viewport colors.", + "prefs.theme_options_badge": "Options", + "prefs.theme_options_more": "More · {count}", + "prefs.theme_options_reset": "Reset", + "prefs.theme_options_unavailable": "Unavailable on this device" + }, + "en-GB": { + "prefs.theme_option_opacity_help": "Adjust floating panel opacity. A readability floor protects text over viewport colours." + }, + "he": { + "prefs.theme_option_opacity": "אטימות", + "prefs.theme_option_opacity_help": "כוונון אטימות הלוחות הצפים. רמת אטימות מינימלית שומרת על קריאות הטקסט על רקע צבעי חלון התצוגה.", + "prefs.theme_options_badge": "אפשרויות", + "prefs.theme_options_more": "עוד · {count}", + "prefs.theme_options_reset": "איפוס", + "prefs.theme_options_unavailable": "לא זמין במכשיר זה" + }, + "ja": { + "prefs.theme_option_opacity": "不透明度", + "prefs.theme_option_opacity_help": "フローティングパネルの不透明度を調整します。ビューポートの色に重なっても文字が読めるように下限が適用されます。", + "prefs.theme_options_badge": "オプション", + "prefs.theme_options_more": "その他 · {count}", + "prefs.theme_options_reset": "リセット", + "prefs.theme_options_unavailable": "このデバイスでは利用できません" + }, + "ko": { + "prefs.theme_option_opacity": "불투명도", + "prefs.theme_option_opacity_help": "플로팅 패널의 불투명도를 조정합니다. 뷰포트 색상 위에서도 텍스트를 읽을 수 있도록 최솟값이 적용됩니다.", + "prefs.theme_options_badge": "옵션", + "prefs.theme_options_more": "더 보기 · {count}", + "prefs.theme_options_reset": "초기화", + "prefs.theme_options_unavailable": "이 기기에서는 사용할 수 없음" + }, + "vi": { + "prefs.theme_option_opacity": "Độ đục", + "prefs.theme_option_opacity_help": "Điều chỉnh độ đục của các bảng nổi. Giới hạn độ đục tối thiểu giúp văn bản luôn dễ đọc trên nền màu của khung nhìn.", + "prefs.theme_options_badge": "Tùy chọn", + "prefs.theme_options_more": "Thêm · {count}", + "prefs.theme_options_reset": "Đặt lại", + "prefs.theme_options_unavailable": "Không khả dụng trên thiết bị này" + }, + "zh": { + "prefs.theme_option_opacity": "不透明度", + "prefs.theme_option_opacity_help": "调整浮动面板的不透明度。最低不透明度限制可确保文字在视口颜色上清晰可读。", + "prefs.theme_options_badge": "选项", + "prefs.theme_options_more": "更多 · {count}", + "prefs.theme_options_reset": "重置", + "prefs.theme_options_unavailable": "此设备不支持" + } +} diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index 7103af6f0..803f90b34 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -70,6 +70,7 @@ pub mod sketch_constraints; pub mod sketch_create; pub mod sketch_equation; pub mod surface_analysis; +pub mod ui_prefs; pub mod view_navigation; pub use check::{Contract, Issue, ParamCheck, TypedContract, input_schema_for, issues, output_schema_for, run_checked, run_checked_as}; diff --git a/crates/engine/src/schema/tests.rs b/crates/engine/src/schema/tests.rs index 20492bf72..fa2a0d3b5 100644 --- a/crates/engine/src/schema/tests.rs +++ b/crates/engine/src/schema/tests.rs @@ -378,6 +378,93 @@ fn a_level_is_read_back_from_its_name() { } } +#[test] +fn ui_prefs_theme_options_input_schema_covers_updates_and_resets() { + use super::ui_prefs::PrefsParams; + let schema = input_schema_for::(); + let schema = schema.as_value(); + assert!(schema["properties"]["theme_options"].is_object()); + for value in [ + json!({}), + json!({"theme_options":{}}), + json!({"theme_options":{"a":{}}}), + json!({"theme_options":{"a":{"enabled":true,"amount":3.5,"style":"cool","reset":null}},"theme":"a"}), + ] { + assert!(serde_json::from_value::(value.clone()).is_ok(), "{value}"); + assert!(conforms(schema, schema, &value), "{value}"); + } + for value in [ + json!({"theme_options":null}), + json!({"theme_options":[]}), + json!({"theme_options":{"a":true}}), + json!({"theme_options":{"a":{"enabled":{}}}}), + json!({"theme_options":{"a":{"amount":[]}}}), + ] { + assert!(serde_json::from_value::(value.clone()).is_err(), "{value}"); + } +} + +#[test] +fn ui_prefs_theme_options_output_schema_matches_serialized_reply() { + use super::ui_prefs::*; + let options = ThemeOptionsReply { + theme_option_defs: vec![ + ThemeOptionDef { + id: "enabled".into(), + kind: ThemeOptionKind::Bool { default: false }, + label: "Enabled".into(), + help: String::new(), + parent: None, + advanced: false, + section: None, + standard: false, + available: true, + reason: None, + }, + ThemeOptionDef { + id: "blur".into(), + kind: ThemeOptionKind::Range { default: 0.0, min: 0.0, max: 100.0, step: 1.0, unit: Some("px".into()) }, + label: "blur".into(), + help: String::new(), + parent: None, + advanced: false, + section: None, + standard: true, + available: false, + reason: Some("not implemented".into()), + }, + ThemeOptionDef { + id: "style".into(), + kind: ThemeOptionKind::Choice { default: "warm".into(), values: vec![ThemeChoice { id: "warm".into(), label: "Warm".into() }] }, + label: "Style".into(), + help: String::new(), + parent: Some("enabled".into()), + advanced: true, + section: Some("Details".into()), + standard: false, + available: true, + reason: None, + }, + ], + theme_option_values: [ + ("enabled".into(), ThemeOptionValue::Bool(true)), + ("blur".into(), ThemeOptionValue::Num(0.0)), + ("style".into(), ThemeOptionValue::Choice("warm".into())), + ] + .into(), + theme_option_notices: vec![ThemeOptionNotice { id: "removed".into(), kind: ThemeOptionNoticeKind::UnknownOption }], + }; + let reply = PrefsReply { options, settings: [("theme".into(), json!("a")), ("theme_options".into(), json!({"a":{"enabled":true}}))].into() }; + let value = serde_json::to_value(&reply).unwrap(); + let schema = output_schema_for::(); + let schema = schema.as_value(); + for field in ["theme_option_defs", "theme_option_values", "theme_option_notices"] { + assert!(schema["properties"][field].is_object(), "{schema}"); + } + assert!(conforms(schema, schema, &value), "{schema}\n{value}"); + assert_eq!(serde_json::to_value(serde_json::from_value::(value.clone()).unwrap()).unwrap(), value); +} + /// Whether `v` conforms to `node` of the schema `root`, for the keywords these schemas use /// apart from `pattern`: `type`, `properties`, `required`, `additionalProperties: false`, /// `items`, `minItems`, `maxItems`, `uniqueItems`, `enum`, `minLength`, `maxLength`, `minimum`, diff --git a/crates/engine/src/schema/ui_prefs.rs b/crates/engine/src/schema/ui_prefs.rs new file mode 100644 index 000000000..c992dd855 --- /dev/null +++ b/crates/engine/src/schema/ui_prefs.rs @@ -0,0 +1,89 @@ +//! Theme-option contracts for the UI-owned `ui.prefs` control method. +//! Other preferences remain owned and validated by the UI preference table. + +use std::collections::BTreeMap; + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, JsonSchema)] +#[serde(untagged)] +pub enum ThemeOptionValue { + Bool(bool), + Choice(String), + Num(f32), +} + +/// Null resets one option; an empty inner map resets that theme. +pub type ThemeOptionsUpdate = BTreeMap>>; + +#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)] +pub struct PrefsParams { + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub theme_options: ThemeOptionsUpdate, + #[serde(flatten)] + pub settings: BTreeMap, +} + +#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)] +pub struct ThemeChoice { + pub id: String, + pub label: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)] +#[serde(tag = "type", rename_all = "lowercase")] +pub enum ThemeOptionKind { + Bool { default: bool }, + Choice { default: String, values: Vec }, + Range { default: f32, min: f32, max: f32, step: f32, unit: Option }, +} + +#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)] +pub struct ThemeOptionDef { + pub id: String, + #[serde(flatten)] + pub kind: ThemeOptionKind, + pub label: String, + pub help: String, + pub parent: Option, + pub advanced: bool, + pub section: Option, + pub standard: bool, + pub available: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub reason: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ThemeOptionNoticeKind { + UnknownOption, + WrongType, + UnknownChoice, + NonFinite, + OutOfRange, +} + +#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)] +pub struct ThemeOptionNotice { + pub id: String, + pub kind: ThemeOptionNoticeKind, +} + +#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)] +pub struct ThemeOptionsReply { + pub theme_option_defs: Vec, + pub theme_option_values: BTreeMap, + pub theme_option_notices: Vec, +} + +/// Complete control reply: other preferences and dialog state share the outer object. +#[derive(Debug, Deserialize, Serialize, JsonSchema)] +pub struct PrefsReply { + #[serde(flatten)] + pub options: ThemeOptionsReply, + #[serde(flatten)] + pub settings: BTreeMap, +} diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index e4351e809..17ddee583 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -277,6 +277,26 @@ thread_local! { // Helpers without an app reference share a render scope. Nested renders restore // their caller's locale; no owned language strings or persistent global setting. static CURRENT: Cell = const { Cell::new(Locale(&ENGLISH)) }; + /// Theme-authored language maps are already resolved and are not catalog source labels. + static RESOLVED_LABELS: Cell = const { Cell::new(false) }; +} + +#[must_use] +pub(crate) struct ResolvedLabels { + previous: bool, + _thread: std::marker::PhantomData>, +} + +/// Shared controls can render supplied translations verbatim while retaining catalog messages. +pub(crate) fn resolved_labels() -> ResolvedLabels { + let previous = RESOLVED_LABELS.with(|labels| labels.replace(true)); + ResolvedLabels { previous, _thread: std::marker::PhantomData } +} + +impl Drop for ResolvedLabels { + fn drop(&mut self) { + RESOLVED_LABELS.with(|labels| labels.set(self.previous)); + } } #[must_use] @@ -306,7 +326,7 @@ pub fn tr(id: &str) -> &str { CURRENT.with(|current| current.get().text(id)) } pub fn tr_label(label: &str) -> &str { - CURRENT.with(|current| current.get().label(label)) + if RESOLVED_LABELS.with(Cell::get) { label } else { CURRENT.with(|current| current.get().label(label)) } } /// Every English catalog entry `(id, text)`, for Preferences search to match a translation @@ -331,6 +351,24 @@ pub fn tr_diagnostic(text: &str) -> String { #[cfg(test)] mod tests { + #[test] + fn theme_options_resolved_labels_are_verbatim_and_restore_catalog_adapters() { + let _language = super::scope("de"); + assert_eq!(super::tr_label("Profile"), "Profil"); + { + let _labels = super::resolved_labels(); + assert_eq!(super::tr_label("Profile"), "Profile"); + assert_eq!(super::tr_label("ui.cancel"), "ui.cancel"); + assert_ne!(super::tr("ui.cancel"), "ui.cancel", "stable catalog messages remain translated"); + { + let _nested = super::resolved_labels(); + assert_eq!(super::tr_label("Profile"), "Profile"); + } + assert_eq!(super::tr_label("Profile"), "Profile"); + } + assert_eq!(super::tr_label("Profile"), "Profil"); + } + use super::*; /// Strings a pull request adds under `assets/locales/pending/` work before they are folded diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 771ee59a0..51615b603 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -285,6 +285,7 @@ mod sweep_dialog_tests; pub(crate) mod test_boat; pub mod theme; pub mod theme_files; +mod theme_options; #[cfg(test)] mod thin_extrude_tests; pub mod timeline; diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index f4a3142a3..ea7adfc40 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -1,6 +1,8 @@ //! Grouped preferences composed with the shared UI kit. Changes apply immediately; Cancel //! restores the opening snapshot, Apply keeps editing, and Defaults affects the current page. +use std::collections::BTreeMap; + use egui::{Modifiers, Pos2}; use serde::{Deserialize, Serialize}; use serde_json::json; @@ -1064,10 +1066,13 @@ preference_settings! { /// The application bar's logo in the theme's accent instead of the theme's logo colours. logo_accent: bool = false, PAGE_INTERFACE; /// Imported theme files (`theme_files`), kept here so they also work in the browser. + #[serde(deserialize_with = "themes_that_read")] custom_themes: Vec = 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; + /// Per-theme overrides. Raw JSON retains entries from newer or hand-edited settings. + theme_options: BTreeMap> = BTreeMap::new(), PAGE_INTERFACE; /// Interface language (a registered locale ID). language: String = "en".into(), 0; /// Shared workspace composition; system windows and popups retain their purpose. @@ -1732,7 +1737,9 @@ fn theme_row(app: &mut SolveApp, ui: &mut egui::Ui) { let palette = match id.as_str() { "light" | "system" => Tokens::light(), "dark" => Tokens::dark(), - _ => crate::theme_files::find(id, &app.preferences.custom_themes).map(crate::theme_files::resolve).unwrap_or_else(Tokens::dark), + _ => crate::theme_files::find(id, &app.preferences.custom_themes) + .map(|f| resolved_theme(&app.preferences, f)) + .unwrap_or_else(Tokens::dark), }; let custom = app.preferences.custom_themes.iter().any(|t| t.id == *id); let note = app.tr(if id == "system" { @@ -1750,6 +1757,12 @@ fn theme_row(app: &mut SolveApp, ui: &mut egui::Ui) { true, ui_kit::PreferenceFigure::Theme { palette: palette.into(), system: id == "system" }, ); + if crate::theme_files::find(id, &app.preferences.custom_themes) + .is_some_and(|file| !crate::theme_options::offered(file, crate::theme_options::PROVIDERS).is_empty()) + { + ui_kit::theme_options_badge(ui, response.rect, app.tr("prefs.theme_options_badge")); + crate::scenario::publish_rect(&format!("prefs:theme_options_badge:{id}"), response.rect); + } crate::scenario::publish_target(&format!("prefs:theme_tile:{id}"), response.rect); crate::scenario::publish_target(&format!("prefs:theme:{id}"), response.rect); if !following && app.preferences.theme == *id { @@ -2040,12 +2053,11 @@ pub fn apply(app: &mut SolveApp, ctx: &egui::Context) { // 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(); + let custom = active_theme_file(app).map(|f| crate::theme::Custom { dark: f.base.is_dark(), tokens: resolved_theme(&app.preferences, f) }); + if let Some(custom) = &custom { + app.ui.dark = custom.dark; } - let follows_system = app.preferences.theme == "system" && file.is_none(); - let custom = file.map(|f| crate::theme::Custom { dark: f.base.is_dark(), tokens: crate::theme_files::resolve(f) }); + let follows_system = app.preferences.theme == "system" && custom.is_none(); if crate::theme::set_custom(custom) { app.styled = false; } @@ -3094,37 +3106,88 @@ fn button_job_picker( /// Returns them all, the open page, the offer (and whether it is the note), the theme ids and the /// followed file (`theme_followed`, `theme_follow_error`). pub fn control(app: &mut SolveApp, p: &serde_json::Value) -> Result { - let mut rest = p.as_object().cloned().unwrap_or_default(); - if let Some(page) = rest.remove("open") { - let name = page.as_str().unwrap_or("General"); - let i = page_index(name).ok_or_else(|| format!("no page `{name}` ({})", PAGES.join(", ")))?; + // Stage every fallible preference operation before dialogs, document actions or writes. + let mut rest = p.as_object().cloned().ok_or("preferences must be an object")?; + let page = rest + .remove("open") + .map(|page| { + let name = page.as_str().unwrap_or("General"); + page_index(name) + .map(|i| (i, name.eq_ignore_ascii_case("Interface/Navigation bar"))) + .ok_or_else(|| format!("no page `{name}` ({})", PAGES.join(", "))) + }) + .transpose()?; + let button = rest.remove("button"); + if let Some(b) = button.as_ref().and_then(|v| v.as_str()) + && !["ok", "cancel", "apply", "defaults"].contains(&b) + { + return Err(format!("unknown button `{b}` (ok, cancel, apply, defaults)")); + } + let stand_up = rest.remove("stand_up").and_then(|v| v.as_bool()); + let mut staged = app.preferences.clone(); + let mut follow = app.prefs_window.follow.clone(); + let imported = rest + .remove("theme_import") + .map(|value| { + let theme = match value { + serde_json::Value::String(text) => crate::theme_files::parse(&text)?, + other => crate::theme_files::from_value(&other)?, + }; + let id = crate::theme_files::add(&mut staged.custom_themes, theme)?; + staged.theme = id.clone(); + Ok::<_, String>(id) + }) + .transpose()?; + if let Some(id) = rest.remove("theme_remove") { + let id = id.as_str().unwrap_or_default(); + let i = staged.custom_themes.iter().position(|t| t.id == id).ok_or_else(|| format!("no imported theme `{id}`"))?; + let gone = staged.custom_themes.remove(i); + staged.theme_options.remove(id); + if staged.theme == id { + staged.theme = if gone.base.is_dark() { "dark" } else { "light" }.into(); + } + } + match rest.remove("theme_follow") { + Some(value) => { + if !FOLLOW_AVAILABLE { + return Err(FOLLOW_UNAVAILABLE.into()); + } + let path = value.as_str().ok_or("`theme_follow` must be a theme file's path, or an empty string to stop following")?; + staged.theme_follow = crate::theme_files::follow_path(path)?; + follow.launch = None; + let _ = follow.poll(&staged.theme_follow, f64::NEG_INFINITY, true); + } + None if rest.contains_key("theme") => { + staged.theme_follow.clear(); + follow.launch = None; + let _ = follow.poll("", f64::NEG_INFINITY, true); + } + None => {} + } + let export = rest.remove("theme_export").and_then(|v| v.as_bool()).unwrap_or(false); + let new = prepare_preferences(app, &staged, followed_theme(&staged, &follow), &serde_json::Value::Object(rest.clone()))?; + let stopped_following = !app.prefs_window.follow.path(&app.preferences.theme_follow).is_empty() && follow.path(&new.theme_follow).is_empty(); + if stand_up == Some(true) && app.stand_up.is_none() { + return Err("no file is waiting to be stood up".into()); + } + if let Some((i, navbar)) = page { open_at(app, i); - app.prefs_window.navbar_scroll = name.eq_ignore_ascii_case("Interface/Navigation bar"); + app.prefs_window.navbar_scroll = navbar; if app.prefs_window.snapshot.is_none() { app.prefs_window.snapshot = Some(Snapshot::take(app)); } } - match rest.remove("stand_up").and_then(|v| v.as_bool()) { + match stand_up { Some(true) => crate::stand_up::stand_up(app)?, Some(false) => crate::stand_up::leave(app), None => {} } - let imported = match rest.remove("theme_import") { - Some(v) => Some(import_theme(app, &v)?), - None => None, - }; - if let Some(id) = rest.remove("theme_remove") { - remove_theme(app, id.as_str().unwrap_or_default())?; + if stopped_following { + // Restore the selected theme's dark/light mode even when its saved id did not change. + stop_following(app); } - 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))?; + app.prefs_window.follow = follow; + let mut out = apply_preferences(app, new, &serde_json::Value::Object(rest))?; match button.as_ref().and_then(|b| b.as_str()) { Some("ok") => close(app, false), Some("cancel") => close(app, true), @@ -3139,6 +3202,9 @@ pub fn control(app: &mut SolveApp, p: &serde_json::Value) -> Result Result Result { + let mut base = value.clone(); + if let Some(object) = base.as_object_mut() { + object.remove("options"); + object.remove("overlays"); + } + let mut theme: crate::theme_files::ThemeFile = serde_json::from_value(base).map_err(|e| e.to_string())?; + if let Err(error) = theme.set_option_tables(value) { + if strict { + return Err(error); + } + log::warn!("preferences: theme `{}` has invalid option tables ({error}); keeping its base palette", theme.id); + } + Ok(theme) +} + +fn themes_that_read<'de, D: serde::Deserializer<'de>>(saved: D) -> Result, D::Error> { + Vec::::deserialize(saved)?.iter().map(|value| theme_from_preferences(value, false).map_err(serde::de::Error::custom)).collect() +} + /// The saved 3D mouse calibrations that still read. One this version can't read (a hand edit, a /// format from another release) is dropped on its own, with a log line, not with all the others. fn calibrations_that_read<'de, D: serde::Deserializer<'de>>( @@ -3328,6 +3416,7 @@ fn remove_theme(app: &mut SolveApp, id: &str) -> Result<(), String> { return Err(format!("no imported theme `{id}`")); }; let gone = app.preferences.custom_themes.remove(i); + app.preferences.theme_options.remove(id); if app.preferences.theme == id { select_theme(app, if gone.base.is_dark() { "dark" } else { "light" }); } @@ -3336,14 +3425,246 @@ fn remove_theme(app: &mut SolveApp, id: &str) -> Result<(), String> { /// The theme on now as a complete theme file, a starting point for a new one. fn current_theme_file(app: &SolveApp) -> serde_json::Value { - theme_file(app, &app.preferences.theme, app.ui.dark) + match active_theme_file(app) { + Some(f) => export_theme_file(f), + None => theme_file(app, &app.preferences.theme, app.ui.dark), + } +} + +fn active_theme_file(app: &SolveApp) -> Option<&crate::theme_files::ThemeFile> { + followed_theme(&app.preferences, &app.prefs_window.follow) + .or_else(|| crate::theme_files::find(&app.preferences.theme, &app.preferences.custom_themes)) +} + +fn followed_theme<'a>(prefs: &Prefs, follow: &'a crate::theme_files::Follow) -> Option<&'a crate::theme_files::ThemeFile> { + (!follow.path(&prefs.theme_follow).is_empty()).then(|| follow.theme()).flatten() +} + +/// Preserve authored definitions; themes predating options retain their complete snapshot export. +fn export_theme_file(file: &crate::theme_files::ThemeFile) -> serde_json::Value { + if !file.options.is_empty() || !file.overlays.is_empty() || file.needs_newer() { + crate::theme_files::export_file(file) + } else { + crate::theme_files::export(&file.name, file.base, &crate::theme_files::resolve(file)) + } +} + +fn effective_theme_options( + prefs: &Prefs, + file: &crate::theme_files::ThemeFile, +) -> (BTreeMap, Vec) { + use crate::theme_files::{OptionKind, OptionNoticeKind, OptionValue}; + use solidcraft_engine::schema::ui_prefs::{ThemeOptionNotice, ThemeOptionNoticeKind as Kind}; + let mut saved = BTreeMap::new(); + let mut notices = Vec::new(); + let definitions = crate::theme_files::ordered_options(file); + for (id, value) in prefs.theme_options.get(&file.id).into_iter().flatten() { + let definition = definitions.iter().find(|o| &o.id == id); + if let Some(definition) = definition + && let OptionKind::Range { min, max, .. } = &definition.kind + && value.as_f64().is_some_and(|n| n < f64::from(*min) || n > f64::from(*max)) + { + notices.push(ThemeOptionNotice { id: id.clone(), kind: Kind::OutOfRange }); + continue; + } + match serde_json::from_value::(value.clone()) { + Ok(value) => { + saved.insert(id.clone(), value); + } + Err(_) => { + notices.push(ThemeOptionNotice { id: id.clone(), kind: if definition.is_some() { Kind::WrongType } else { Kind::UnknownOption } }) + } + } + } + let (values, problems) = crate::theme_files::effective_values(file, &saved); + notices.extend(problems.into_iter().map(|notice| ThemeOptionNotice { + id: notice.id, + kind: match notice.kind { + OptionNoticeKind::UnknownOption => Kind::UnknownOption, + OptionNoticeKind::WrongType => Kind::WrongType, + OptionNoticeKind::UnknownChoice => Kind::UnknownChoice, + OptionNoticeKind::NonFinite => Kind::NonFinite, + OptionNoticeKind::Clamped => Kind::OutOfRange, + }, + })); + notices.sort_by(|a, b| a.id.cmp(&b.id)); + (values, notices) +} + +fn resolved_theme(prefs: &Prefs, file: &crate::theme_files::ThemeFile) -> Tokens { + crate::theme_files::resolve_with(file, &effective_theme_options(prefs, file).0) +} + +fn theme_option_text(text: &crate::theme_files::OptionText, language: &str, fallback: &str) -> String { + text.get(language).or_else(|| text.get("en")).map(String::as_str).unwrap_or(fallback).to_owned() +} + +fn theme_option_rows<'a>( + file: &'a crate::theme_files::ThemeFile, + language: &str, + providers: &[crate::theme_options::Provider], +) -> Vec> { + use crate::theme_options::{Availability, offered, provider}; + let locale = crate::i18n::Locale::for_language(language); + offered(file, providers) + .into_iter() + .map(|definition| { + let provider = provider(&definition.id, providers); + ui_kit::ThemeOptionRow { + definition, + label: provider + .map(|p| locale.text(p.label).to_owned()) + .unwrap_or_else(|| theme_option_text(&definition.label, language, &definition.id)), + help: provider.map(|p| locale.text(p.help).to_owned()).unwrap_or_else(|| theme_option_text(&definition.help, language, "")), + choices: match &definition.kind { + crate::theme_files::OptionKind::Choice { values, .. } => { + values.iter().map(|v| theme_option_text(&v.label, language, &v.id)).collect() + } + _ => Vec::new(), + }, + reason: provider.and_then(|p| match (p.availability)() { + Availability::Available => None, + Availability::Unavailable(reason) => Some(locale.text(reason).to_owned()), + }), + } + }) + .collect() +} + +fn theme_options_row(app: &mut SolveApp, ui: &mut egui::Ui) { + let Some(file) = active_theme_file(app) else { return }; + let rows = theme_option_rows(file, &app.preferences.language, crate::theme_options::PROVIDERS); + if rows.is_empty() { + return; + } + let (mut values, _) = effective_theme_options(&app.preferences, file); + let before = values.clone(); + let reset = ui_kit::theme_options_list(ui, &file.id, &file.name, &rows, &mut values); + let changes: BTreeMap<_, _> = values.into_iter().filter(|(id, value)| before.get(id) != Some(value)).collect(); + if reset || !changes.is_empty() { + let update = if reset { json!({}) } else { json!(changes) }; + let params = json!({"theme_options": {(file.id.clone()): update}}); + // Same atomic validation/merge and followed-file semantics as the control channel. + // No button, page selection or dialog is added by this live preference update. + if let Err(error) = control(app, ¶ms) { + app.set_status(error, true); + } + } +} + +/// Only explicitly supplied entries are checked. Stale saved entries survive unrelated changes. +fn merge_theme_options(prefs: &mut Prefs, followed: Option<&crate::theme_files::ThemeFile>, update: &serde_json::Value) -> Result<(), String> { + use crate::theme_files::{OptionKind, OptionValue}; + let themes = update.as_object().ok_or("`theme_options` must be a map of theme ids to option maps")?; + for (theme_id, update) in themes { + let key = format!("theme_options.{theme_id}"); + let file = followed.filter(|f| &f.id == theme_id).or_else(|| crate::theme_files::find(theme_id, &prefs.custom_themes)); + let mode = THEMES.iter().any(|(id, _)| *id == theme_id.as_str()); + if file.is_none() && !mode { + return Err(format!("`{key}`: unknown theme")); + } + let options = update.as_object().ok_or_else(|| format!("`{key}` must be an option map"))?; + if options.is_empty() { + prefs.theme_options.remove(theme_id); + continue; + } + for (id, value) in options { + let key = format!("{key}.{id}"); + let definition = file + .and_then(|file| crate::theme_files::ordered_options(file).into_iter().find(|o| &o.id == id)) + .ok_or_else(|| format!("`{key}`: unknown option"))?; + if value.is_null() { + if let Some(saved) = prefs.theme_options.get_mut(theme_id) { + saved.remove(id); + } + continue; + } + let parsed: OptionValue = serde_json::from_value(value.clone()).map_err(|_| format!("`{key}`: wrong type"))?; + let valid = match (&definition.kind, &parsed) { + (OptionKind::Bool { .. }, OptionValue::Bool(_)) => true, + (OptionKind::Choice { values, .. }, OptionValue::Choice(id)) => values.iter().any(|v| &v.id == id), + (OptionKind::Range { min, max, .. }, OptionValue::Num(n)) => { + // Check the original JSON number too, before f32 conversion rounds at a bound. + n.is_finite() && value.as_f64().is_some_and(|n| n.is_finite() && n >= f64::from(*min) && n <= f64::from(*max)) + } + _ => false, + }; + if !valid { + return Err(format!("`{key}`: wrong type, unknown choice or out of range")); + } + prefs.theme_options.entry(theme_id.clone()).or_default().insert(id.clone(), value.clone()); + } + if prefs.theme_options.get(theme_id).is_some_and(BTreeMap::is_empty) { + prefs.theme_options.remove(theme_id); + } + } + Ok(()) +} + +fn theme_options_reply(app: &SolveApp) -> solidcraft_engine::schema::ui_prefs::ThemeOptionsReply { + use crate::theme_files::{OptionKind, OptionValue}; + use solidcraft_engine::schema::ui_prefs::{ThemeChoice, ThemeOptionDef, ThemeOptionKind, ThemeOptionValue, ThemeOptionsReply}; + let Some(file) = active_theme_file(app) else { return ThemeOptionsReply::default() }; + let text = |texts: &crate::theme_files::OptionText, fallback: &str| { + texts.get(&app.preferences.language).or_else(|| texts.get("en")).map(String::as_str).unwrap_or(fallback).to_string() + }; + let (values, notices) = effective_theme_options(&app.preferences, file); + ThemeOptionsReply { + theme_option_defs: crate::theme_files::ordered_options(file) + .into_iter() + .map(|o| { + let standard = crate::theme_options::standard(&o.id); + let provider = crate::theme_options::provider(&o.id, crate::theme_options::PROVIDERS); + let availability = provider.map(|p| (p.availability)()); + ThemeOptionDef { + id: o.id.clone(), + kind: match &o.kind { + OptionKind::Bool { default } => ThemeOptionKind::Bool { default: *default }, + OptionKind::Choice { default, values } => ThemeOptionKind::Choice { + default: default.clone(), + values: values.iter().map(|v| ThemeChoice { id: v.id.clone(), label: text(&v.label, &v.id) }).collect(), + }, + OptionKind::Range { default, min, max, step, unit } => { + ThemeOptionKind::Range { default: *default, min: *min, max: *max, step: *step, unit: unit.clone() } + } + }, + label: provider.map(|p| app.tr(p.label).to_owned()).unwrap_or_else(|| text(&o.label, &o.id)), + help: provider.map(|p| app.tr(p.help).to_owned()).unwrap_or_else(|| text(&o.help, "")), + parent: o.parent.clone(), + advanced: o.advanced, + section: o.section.clone(), + standard, + available: !standard || availability == Some(crate::theme_options::Availability::Available), + reason: match availability { + Some(crate::theme_options::Availability::Unavailable(reason)) => Some(app.tr(reason).to_owned()), + None if standard => Some("not implemented".into()), + _ => None, + }, + } + }) + .collect(), + theme_option_values: values + .into_iter() + .map(|(id, value)| { + ( + id, + match value { + OptionValue::Bool(v) => ThemeOptionValue::Bool(v), + OptionValue::Choice(v) => ThemeOptionValue::Choice(v), + OptionValue::Num(v) => ThemeOptionValue::Num(v), + }, + ) + }) + .collect(), + theme_option_notices: notices, + } } /// Export the tile the user chose, without applying it or changing the dialog snapshot. fn theme_file(app: &SolveApp, id: &str, system_dark: bool) -> serde_json::Value { - use crate::theme_files::{Base, export, find, resolve}; + use crate::theme_files::{Base, export, find}; match find(id, &app.preferences.custom_themes) { - Some(f) => export(&f.name, f.base, &resolve(f)), + Some(f) => export_theme_file(f), None if id == "dark" || (id == "system" && system_dark) => export("Dark", Base::Dark, &crate::theme::Tokens::dark()), None => export("Light", Base::Light, &crate::theme::Tokens::light()), } @@ -3443,8 +3764,13 @@ pub fn lenient(saved: &serde_json::Value) -> Prefs { serde_json::from_value(cur).map(migrate).map(limit_disabled_plugins).map(limit_toolbar_tabs).unwrap_or_default() } -/// Set preferences from JSON (control channel); returns them all. -pub fn set(app: &mut SolveApp, p: &serde_json::Value) -> Result { +/// Validate a proposed preference state without applying it or performing writes. +fn prepare_preferences( + app: &SolveApp, + base: &Prefs, + followed: Option<&crate::theme_files::ThemeFile>, + p: &serde_json::Value, +) -> Result { for key in ["joint_rotation_coarse", "joint_rotation_fine"] { if let Some(value) = p.get(key) && value.as_f64().is_none_or(|v| !v.is_finite() || !(0.001..=180.0).contains(&v)) @@ -3452,13 +3778,26 @@ pub fn set(app: &mut SolveApp, p: &serde_json::Value) -> Result = values + .iter() + .enumerate() + .map(|(i, value)| theme_from_preferences(value, true).map_err(|error| format!("`custom_themes[{i}]`: {error}"))) + .collect::>()?; + o.insert(k.clone(), serde_json::to_value(themes).map_err(|e| e.to_string())?); + } else if k != "theme_options" { + o.insert(k.clone(), v.clone()); + } } } // Saved preferences read an unknown mode as the default; asked for here, it is an error. @@ -3480,7 +3819,10 @@ pub fn set(app: &mut SolveApp, p: &serde_json::Value) -> Result Result Result { + let new = prepare_preferences(app, &app.preferences, followed_theme(&app.preferences, &app.prefs_window.follow), p)?; + apply_preferences(app, new, p) +} + +/// All fallible preference checks finish before any application or file write. +fn apply_preferences(app: &mut SolveApp, new: Prefs, p: &serde_json::Value) -> Result { + let file = crate::theme_files::find(&new.theme, &new.custom_themes); + if (new.theme != app.preferences.theme || new.custom_themes != app.preferences.custom_themes) && new.theme != "system" { app.ui.dark = file.map_or(new.theme == "dark", |f| f.base.is_dark()); } let units_changed = new.default_units != app.preferences.default_units; @@ -5707,6 +6061,607 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + fn theme_options_fixture(base: &str, count: usize) -> serde_json::Value { + let fixtures: serde_json::Value = serde_json::from_str(include_str!("../tests/fixtures/theme-options.json")).unwrap(); + fixtures[format!("{base}-{count}")].clone() + } + + #[test] + fn theme_options_ui_counts_badges_more_and_reset_in_light_and_dark() { + for base in ["light", "dark"] { + for count in [0, 1, 3, 6, 12] { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.call("ui.resize", json!({"width":1600,"height":1100})); + let out = h.call("ui.prefs", json!({"theme_import":theme_options_fixture(base, count),"open":"Interface"})); + assert!(out["error"].is_null(), "{out}"); + h.frames(3); + assert_eq!(crate::scenario::rect_of("prefs:theme_options_header").is_some(), count > 0, "{base} {count}"); + let id = format!("options-{base}-{count}"); + assert_eq!(crate::scenario::rect_of(&format!("prefs:theme_options_badge:{id}")).is_some(), count > 0); + assert_eq!(crate::scenario::handle_at("prefs:theme_options_more").is_some(), count == 12); + let cells: std::collections::BTreeSet<_> = crate::scenario::rects("prefs:theme_option_cell:").into_iter().map(|(id, _)| id).collect(); + assert_eq!(cells.len(), count.min(10), "only ten top-level cells before More"); + assert_eq!( + crate::scenario::rect_of("dialog:hint:theme_option_section").is_some(), + count > 6, + "dim section labels only above six entries" + ); + assert!(crate::scenario::handle_at("prefs:theme_options_reset").is_none()); + if count == 0 { + let strip = crate::scenario::rect_of("dialog:hint:tab_accent").unwrap(); + let mut unknown = theme_options_fixture(base, count); + unknown["options"] = json!([{"id":"blur","type":"range","default":0}]); + h.call("ui.prefs", json!({"theme_import":unknown})); + h.frames(2); + assert!(crate::scenario::rect_of("prefs:theme_options_header").is_none()); + assert!(crate::scenario::rect_of(&format!("prefs:theme_options_badge:{id}")).is_none()); + assert_eq!(crate::scenario::rect_of("dialog:hint:tab_accent").unwrap(), strip, "unknown providers add no gap or notice"); + } + if count == 12 { + assert!(crate::scenario::rect_of("prefs:theme_option:outline").is_none()); + assert!(crate::scenario::rect_of("prefs:theme_option:extra").is_none(), "advanced is always under More"); + super::reveal_preference(&mut h, "prefs:theme_options_more"); + h.step(&json!({"click":{"handle":"prefs:theme_options_more"}})).unwrap(); + h.frames(2); + assert!(crate::scenario::rect_of("prefs:theme_option:outline").is_some()); + assert!(crate::scenario::rect_of("prefs:theme_option:extra").is_some()); + } + if count >= 3 { + super::reveal_preference(&mut h, "prefs:theme_option_switch:Warm accent"); + h.step(&json!({"click":{"handle":"prefs:theme_option_switch:Warm accent"}})).unwrap(); + h.frames(2); + assert_eq!(h.app.preferences.theme_options[&id]["warm"], true, "UI edits go through preference merging"); + assert!(crate::scenario::handle_at("prefs:theme_options_reset").is_some()); + super::reveal_preference(&mut h, "prefs:theme_options_reset"); + h.step(&json!({"click":{"handle":"prefs:theme_options_reset"}})).unwrap(); + h.frames(2); + assert!(!h.app.preferences.theme_options.contains_key(&id)); + assert!(crate::scenario::handle_at("prefs:theme_options_reset").is_none()); + } + } + } + } + + #[test] + fn theme_options_ui_short_composite_shares_row_with_narrow_control() { + for base in ["light", "dark"] { + for language in ["en", "de"] { + for width in [1600, 520] { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.call("ui.resize", json!({"width":width,"height":1100})); + let file = json!({"format":"solidcraft-theme/1","name":"Compact options","base":base,"options":[ + {"id":"shadow","type":"bool","default":true,"label":{"en":"Shadow","de":"Schatten"}}, + {"id":"softness","type":"range","default":5.5,"min":0,"max":10,"step":0.5,"unit":"px","parent":"shadow", + "label":{"en":"Softness","de":"Weichheit"}}, + {"id":"edges","type":"range","default":5.5,"min":0,"max":10,"step":0.5,"unit":"px", + "label":{"en":"Edges","de":"Kanten"}} + ]}); + let out = h.call("ui.prefs", json!({"theme_import":file,"open":"Interface","language":language})); + assert!(out["error"].is_null(), "{out}"); + h.frames(3); + let rect = |name: &str| crate::scenario::rect_of(name).unwrap(); + let parent = rect("prefs:theme_option:shadow"); + let child = rect("prefs:theme_option:softness"); + let composite = rect("prefs:theme_option_cell:shadow"); + let neighbour = rect("prefs:theme_option_cell:edges"); + let body = rect("prefs:page_body").expand(1.0); + assert!(body.contains_rect(composite) && body.contains_rect(neighbour), "{base} {language} width={width}"); + assert!(composite.contains_rect(parent) && composite.contains_rect(child)); + assert!(!composite.intersects(neighbour)); + if width == 1600 { + assert!( + (composite.top() - neighbour.top()).abs() < 1.0, + "short composite must share a normal Preferences row: {composite:?} {neighbour:?}" + ); + assert!(composite.right() < neighbour.left(), "declared left-to-right order"); + assert!((parent.top() - child.top()).abs() < 1.0); + assert!(parent.right() < child.left(), "parent and child share one compact cell"); + } else { + assert!(neighbour.top() > composite.bottom(), "a genuinely narrow page falls back to a full composite row"); + } + let labels = if language == "de" { ["Schatten", "Weichheit", "Kanten"] } else { ["Shadow", "Softness", "Edges"] }; + let parts = [ + rect(&format!("dialog:label:{}", labels[0])), + rect(&format!("prefs:theme_option_switch:{}", labels[0])), + rect(&format!("dialog:label:{}", labels[1])), + rect(&format!("dialog:slider:{}", labels[1])), + rect("prefs:theme_option_readout:softness"), + rect(&format!("dialog:label:{}", labels[2])), + rect(&format!("dialog:slider:{}", labels[2])), + rect("prefs:theme_option_readout:edges"), + ]; + for (i, part) in parts.iter().enumerate() { + assert!(body.contains_rect(*part), "{base} {language} width={width}: {part:?} outside {body:?}"); + for other in parts.iter().skip(i + 1) { + assert!(!part.intersects(*other), "{base} {language} width={width}: {part:?} overlaps {other:?}"); + } + } + assert!(rect(&format!("dialog:slider:{}", labels[1])).width() >= Tokens::get().space_24 * 2.0, "retain a usable slider track"); + let control = rect(&format!("dialog:control:{}", labels[2])); + let track = rect(&format!("dialog:slider_track:{}", labels[2])); + let readout = rect("prefs:theme_option_readout:edges"); + let t = Tokens::get(); + let natural_width = |text: &str| { + h.ctx.fonts_mut(|fonts| { + fonts.layout_no_wrap(text.to_owned(), egui::FontId::proportional(t.font_label), t.form_ink).size().x.ceil() + }) + }; + assert!((rect(&format!("dialog:label:{}", labels[2])).width() - natural_width(labels[2]) - t.space_4).abs() <= 1.0); + assert!((readout.width() - natural_width("5.5px")).abs() <= 1.0, "readout must retain its natural width"); + let reserved_readout = ["0px", "10px", "5.5px", "0.5px", "9.5px"].into_iter().map(natural_width).fold(0.0, f32::max); + assert!(neighbour.expand(1.0).contains_rect(control)); + assert!(control.contains_rect(track) && control.contains_rect(readout)); + assert!( + (track.width() - (control.width() - reserved_readout - t.space_8 - t.space_4)).abs() <= 1.0, + "standalone slider must fill the width left by its natural label and readout: {base} {language} width={width}: {control:?} {track:?} {readout:?}" + ); + } + } + } + } + + #[test] + fn theme_options_ui_wide_composite_dropdown_and_advanced_keep_order() { + for base in ["light", "dark"] { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.call("ui.resize", json!({"width":1600,"height":1100})); + h.call("ui.prefs", json!({"theme_import":theme_options_fixture(base, 12),"open":"Interface"})); + h.frames(3); + let rect = |id: &str| crate::scenario::rect_of(&format!("prefs:theme_option:{id}")).unwrap(); + assert!(rect("opacity").center().x < rect("warm").center().x); + assert!((rect("opacity").top() - rect("warm").top()).abs() < 1.0); + assert!(rect("palette").top() > rect("warm").top()); + assert!(rect("radius").top() > rect("palette").top(), "four choices occupy a full row"); + let composite = crate::scenario::rect_of("prefs:theme_option_cell:shadow").unwrap(); + assert!(composite.contains_rect(rect("shadow")) && composite.contains_rect(rect("softness"))); + assert!(crate::scenario::rect_of("prefs:theme_option_cell:softness").is_none(), "child is not an eleventh cell"); + super::reveal_preference(&mut h, "dialog:Palette:Warm"); + h.step(&json!({"click":{"handle":"dialog:Palette:Warm"}})).unwrap(); + h.frames(2); + let id = format!("options-{base}-12"); + assert_eq!(h.app.preferences.theme_options[&id]["palette"], "v2"); + super::reveal_preference(&mut h, "prefs:theme_option_switch:Shadow"); + h.step(&json!({"click":{"handle":"prefs:theme_option_switch:Shadow"}})).unwrap(); + h.frames(2); + assert_eq!(h.app.preferences.theme_options[&id]["shadow"], false); + let saved = h.app.preferences.theme_options[&id].clone(); + let track = crate::scenario::rect_of("dialog:slider_track:Softness").unwrap(); + h.step(&json!({"click":[track.center().x,track.center().y]})).unwrap(); + h.frames(2); + assert_eq!(h.app.preferences.theme_options[&id], saved, "inactive child is inert and retains its value"); + super::reveal_preference(&mut h, "prefs:theme_option:pattern"); + h.step(&json!({"click":{"handle":"dialog:Pattern"}})).unwrap(); + h.frames(2); + assert!(crate::scenario::handle_at("dialog:Pattern:Plain").is_some(), "six choices use a dropdown"); + h.step(&json!({"click":{"handle":"dialog:Pattern:Plain"}})).unwrap(); + h.frames(2); + assert_eq!(h.app.preferences.theme_options[&id]["pattern"], "v6"); + assert!(crate::scenario::rect_of("prefs:theme_option:extra").is_none()); + super::reveal_preference(&mut h, "prefs:theme_options_more"); + h.step(&json!({"click":{"handle":"prefs:theme_options_more"}})).unwrap(); + h.frames(2); + assert!(rect("extra").top() > rect("compact").top()); + assert!((rect("extra").top() - rect("outline").top()).abs() < 1.0); + } + } + + #[test] + fn theme_options_ui_opacity_live_reset_and_cancel_use_the_existing_path() { + for base in ["light", "dark"] { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + control(&mut h.app, &json!({"theme_import":theme_options_fixture(base, 1)})).unwrap(); + h.call("ui.prefs", json!({"open":"Interface"})); + h.frames(3); + let full = Tokens::get(); + let file = active_theme_file(&h.app).unwrap(); + let mut invalid_saved = h.app.preferences.clone(); + invalid_saved.theme_options.entry(file.id.clone()).or_default().insert("opacity".into(), json!(20)); + assert_eq!(resolved_theme(&invalid_saved, file), full, "saved preference fallback stays at the theme default"); + assert_eq!(invalid_saved.theme_options[&file.id]["opacity"], 20, "fallback must retain the raw saved value"); + super::reveal_preference(&mut h, "dialog:slider:Opacity"); + let slider = crate::scenario::rect_of("dialog:slider_track:Opacity").unwrap(); + h.step(&json!({"click":[slider.center().x,slider.center().y]})).unwrap(); + h.frames(2); + let id = format!("options-{base}-1"); + let value = h.app.preferences.theme_options[&id]["opacity"].as_f64().unwrap(); + assert!((40.0..100.0).contains(&value)); + assert!(Tokens::get().panel.a() < full.panel.a()); + assert_eq!(Tokens::get().text, full.text); + assert!(h.app.prefs_window.open, "editing must keep the same Preferences window"); + h.step(&json!({"click":{"handle":"prefs:theme_options_reset"}})).unwrap(); + h.frames(2); + assert_eq!(Tokens::get(), full); + h.call("ui.prefs", json!({"theme_options":{(id.clone()):{"opacity":60}}})); + h.frames(2); + assert!(Tokens::get().panel.a() < full.panel.a()); + h.call("ui.prefs", json!({"button":"cancel"})); + h.frames(2); + assert_eq!(Tokens::get(), full); + assert!(!h.app.preferences.theme_options.contains_key(&id)); + } + } + + #[test] + fn theme_options_provider_registry_filters_unknown_and_retains_unavailable() { + use crate::theme_options::{Availability, Provider}; + let file = crate::theme_files::from_value(&json!({"format":"solidcraft-theme/1","name":"Providers","base":"dark","options":[ + {"id":"blur","type":"range","default":0}, + {"id":"tab_colours","type":"bool","default":true}, + {"id":"tab_fade_ms","type":"range","default":100}, + {"id":"dependent","type":"bool","default":true,"parent":"tab_colours"}, + {"id":"custom","type":"bool","default":false,"label":{"en":"Custom","de":"Eigene"}}, + {"id":"opacity","type":"range","default":100} + ]})) + .unwrap_err(); + assert!(file.contains("more than one child")); + let file = crate::theme_files::from_value(&json!({"format":"solidcraft-theme/1","name":"Providers","base":"dark","options":[ + {"id":"blur","type":"range","default":0}, {"id":"tab_colours","type":"bool","default":true}, + {"id":"tab_fade_ms","type":"range","default":100}, + {"id":"custom","type":"bool","default":false,"label":{"en":"Custom","de":"Eigene"}}, + {"id":"opacity","type":"range","default":100} + ]})) + .unwrap(); + let rows = theme_option_rows(&file, "de", crate::theme_options::PROVIDERS); + assert_eq!(rows.iter().map(|r| r.definition.id.as_str()).collect::>(), ["opacity", "custom"]); + assert_eq!(rows[0].label, "Deckkraft"); + assert_eq!(rows[1].label, "Eigene"); + assert_eq!(theme_option_rows(&file, "ja", crate::theme_options::PROVIDERS)[1].label, "Custom", "English fallback"); + let providers = [Provider { + id: "blur", + label: "prefs.theme_option_opacity", + help: "prefs.theme_option_opacity_help", + availability: || Availability::Unavailable("prefs.theme_options_unavailable"), + apply: |_, _| {}, + }]; + let rows = theme_option_rows(&file, "en", &providers); + assert_eq!(rows.iter().map(|r| r.definition.id.as_str()).collect::>(), ["blur", "custom"]); + assert_eq!(rows[0].reason.as_deref(), Some("Unavailable on this device")); + // The internal fixture goes through the real kit. No fake provider is shipped. + for dark in [false, true] { + crate::theme::set_custom(None); + crate::theme::set_dark(dark); + let mut values = crate::theme_files::effective_values(&file, &BTreeMap::new()).0; + let before = values.clone(); + let ctx = crate::fonts::test_context(); + let mut draw = |events| { + crate::scenario::clear_handles(); + crate::test_support::frame( + &ctx, + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), + events, + focused: true, + ..Default::default() + }, + |ui| { + ui_kit::scope(ui, |ui| { + ui_kit::theme_options_list(ui, &file.id, &file.name, &rows, &mut values); + }); + }, + ); + }; + draw(vec![]); + assert!(crate::scenario::rect_of("prefs:theme_option_reason:blur").is_some()); + let at = crate::scenario::handle_at("dialog:slider:Opacity").unwrap(); + draw(crate::test_support::pointer(at, true)); + draw(crate::test_support::pointer(at, false)); + assert_eq!(values, before, "unavailable controls stay visible and inert"); + } + } + + fn option_theme_file(name: &str) -> serde_json::Value { + json!({ + "format": "solidcraft-theme/1", "name": name, "base": "dark", "colors": {"panel": "#112233"}, + "options": [ + {"id":"enabled", "type":"bool", "default":false, "label":{"en":"Enabled", "de":"Aktiv"}, "help":{"en":"Use the overlay", "de":"Farben verwenden"}}, + {"id":"amount", "type":"range", "default":5, "min":0, "max":10, "step":1, "unit":"px", "advanced":true, "section":"Details"}, + {"id":"style", "type":"choice", "default":"warm", "parent":"enabled", "values":[{"id":"warm", "label":{"en":"Warm", "de":"Warmton"}}, {"id":"cool", "label":{"en":"Cool"}}]}, + {"id":"blur", "type":"range", "default":0} + ], + "overlays": [{"when":{"opt":"enabled", "eq":true}, "colors":{"panel":"#abcdef"}}] + }) + } + + #[test] + fn theme_options_raw_values_default_while_theme_api_clamps() { + use crate::theme_files::{OptionNotice, OptionNoticeKind, OptionValue}; + use solidcraft_engine::schema::ui_prefs::ThemeOptionNoticeKind; + let file = crate::theme_files::from_value(&option_theme_file("Options A")).unwrap(); + for (raw, clamped) in [(-1.0, 0.0), (20.0, 10.0)] { + let (values, notices) = crate::theme_files::effective_values(&file, &BTreeMap::from([("amount".into(), OptionValue::Num(raw))])); + assert_eq!(values["amount"], OptionValue::Num(clamped)); + assert_eq!(notices, [OptionNotice { id: "amount".into(), kind: OptionNoticeKind::Clamped }]); + + let mut prefs = Prefs::default(); + prefs.theme_options.insert(file.id.clone(), BTreeMap::from([("amount".into(), json!(raw))])); + let saved = prefs.theme_options.clone(); + let (values, notices) = effective_theme_options(&prefs, &file); + assert_eq!(values["amount"], OptionValue::Num(5.0)); + assert_eq!(notices.len(), 1); + assert_eq!((notices[0].id.as_str(), notices[0].kind), ("amount", ThemeOptionNoticeKind::OutOfRange)); + assert_eq!(prefs.theme_options, saved); + } + } + + #[test] + fn theme_options_direct_definitions_validate_and_restore_safely() { + let mut source = option_theme_file("Options A"); + source["id"] = json!("options-a"); + let mut other = source.clone(); + other["id"] = json!("options-b"); + other["name"] = json!("Options B"); + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + let invalid_tables = [ + ("options", json!((0..17).map(|i| json!({"id":format!("option_{i}"),"type":"bool","default":true})).collect::>())), + ("options", json!([{ "id":"amount","type":"range","default":5,"min":10,"max":0,"step":1 }])), + ("options", json!([{ "id":"amount","type":"range","default":11,"min":0,"max":10,"step":1 }])), + ("options", json!([{ "id":"amount","type":"range","default":5,"min":0,"max":10,"step":0 }])), + ("options", json!([{ "id":"amount","type":"range","default":"bad","min":0,"max":10,"step":1 }])), + ("options", json!([{ "id":"enabled","type":"unknown","default":true }])), + ("options", json!([{ "id":"enabled","type":"bool","default":true,"parent":"missing" }])), + ("options", json!([{ "id":"a","type":"bool","default":true,"parent":"b" },{ "id":"b","type":"bool","default":true,"parent":"a" }])), + ("options", json!([{ "id":"style","type":"choice","default":"missing","values":[{"id":"a","label":{}}] }])), + ("overlays", json!((0..33).map(|_| json!({"when":{"opt":"enabled","eq":true},"colors":{"panel":"#abcdef"}})).collect::>())), + ("overlays", json!([{ "when":{"opt":"enabled","eq":1},"colors":{"panel":"#abcdef"} }])), + ("overlays", json!([{ "when":{"opt":"unknown","eq":true},"colors":{"panel":"#abcdef"} }])), + ("overlays", json!([{ "when":{"opt":"enabled","eq":true},"radii":{"radius_sm":-1} }])), + ]; + for (table, invalid) in invalid_tables { + let mut malformed = source.clone(); + malformed[table] = invalid; + assert!(crate::theme_files::from_value(&malformed).is_err(), "{malformed}"); + let before = app.preferences.clone(); + let error = control(&mut app, &json!({"custom_themes":[malformed],"ui_scale":1.5,"open":"Interface"})).unwrap_err(); + assert!(error.contains("custom_themes[0]"), "{error}"); + assert_eq!(app.preferences, before); + assert!(!app.prefs_window.open); + + let mut restored = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + restored.load_prefs( + &json!({"preferences":{ + "custom_themes":[malformed,other],"theme":"options-a","zoom_reverse":true, + "theme_options":{"options-a":{"amount":99}} + }}) + .to_string(), + ); + assert_eq!(restored.preferences.custom_themes.len(), 2); + assert!(restored.preferences.custom_themes[0].options.is_empty()); + assert!(restored.preferences.custom_themes[0].overlays.is_empty()); + assert_eq!(restored.preferences.custom_themes[0].colors, restored.preferences.custom_themes[1].colors); + assert!(!restored.preferences.custom_themes[1].options.is_empty()); + assert!(restored.preferences.zoom_reverse); + apply(&mut restored, &egui::Context::default()); + assert_eq!( + resolved_theme(&restored.preferences, &restored.preferences.custom_themes[0]).panel, + egui::Color32::from_rgb(0x11, 0x22, 0x33) + ); + let out = control(&mut restored, &json!({"ui_scale":1.25})).unwrap(); + assert_eq!(out["theme_option_defs"], json!([])); + assert_eq!(out["theme_option_values"], json!({})); + assert_eq!(out["theme_options"]["options-a"]["amount"], 99); + assert!(restored.preferences.zoom_reverse); + } + + // Reserved fields ignored by import must also be ignored before serde sees an update. + source["options"][3] = json!({"id":"blur","type":"range","default":999,"step":null,"unit":false,"label":null,"advanced":"ignored"}); + let expected = crate::theme_files::from_value(&source).unwrap(); + control(&mut app, &json!({"custom_themes":[source],"theme":"options-a"})).unwrap(); + assert_eq!(app.preferences.custom_themes, [expected]); + app.preferences.custom_themes[0].options[1].kind = + crate::theme_files::OptionKind::Range { default: 5.0, min: 10.0, max: 0.0, step: 1.0, unit: None }; + let out = control(&mut app, &json!({"ui_scale":1.25})).unwrap(); + assert_eq!(out["theme_option_defs"], json!([])); + assert_eq!(app.preferences.custom_themes[0].colors["panel"], "#112233"); + } + + #[test] + fn theme_options_persist_isolate_reset_remove_and_export_definitions() { + let mut h = crate::scenario::Harness::new(); + let out = + control(&mut h.app, &json!({"theme_import":option_theme_file("Options A"), "theme_options":{"options-a":{"enabled":true,"amount":7.5}}})) + .unwrap(); + assert_eq!(out["theme_option_values"]["enabled"], true); + h.frames(2); + assert_eq!(Tokens::get().panel, egui::Color32::from_rgb(0xab, 0xcd, 0xef)); + control(&mut h.app, &json!({"theme_import":option_theme_file("Options B"), "theme_options":{"options-b":{"amount":3}}})).unwrap(); + assert_eq!(control(&mut h.app, &json!({})).unwrap()["theme_option_values"]["enabled"], false); + let out = control(&mut h.app, &json!({"theme":"options-a", "theme_export":true})).unwrap(); + assert_eq!(out["theme_option_values"]["amount"], 7.5); + assert_eq!(out["theme_file"]["options"][0]["default"], false); + assert_eq!(out["theme_file"]["colors"]["panel"], "#112233"); + assert_eq!(out["theme_file"]["overlays"][0]["colors"]["panel"], "#abcdef"); + let mut other = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + other.load_prefs(&h.app.prefs()); + assert_eq!(other.preferences.theme_options, h.app.preferences.theme_options); + control(&mut other, &json!({"theme_options":{"options-a":{"amount":null}}})).unwrap(); + assert_eq!(control(&mut other, &json!({})).unwrap()["theme_option_values"]["amount"], 5.0); + assert!(other.preferences.theme_options["options-a"].contains_key("enabled")); + control(&mut other, &json!({"theme_options":{"options-a":{}}})).unwrap(); + assert!(!other.preferences.theme_options.contains_key("options-a")); + assert!(other.preferences.theme_options.contains_key("options-b")); + control(&mut h.app, &json!({"theme_remove":"options-a"})).unwrap(); + assert!(!h.app.preferences.theme_options.contains_key("options-a")); + assert!(h.app.preferences.theme_options.contains_key("options-b")); + control(&mut other, &json!({"open":"Interface", "button":"defaults"})).unwrap(); + assert!(other.preferences.theme_options.is_empty()); + h.frames(2); + assert_eq!(Tokens::get().panel, Tokens::dark().panel); + control( + &mut h.app, + &json!({"theme_import":option_theme_file("Options A"),"theme_options":{"options-a":{"enabled":true}},"open":"Interface"}), + ) + .unwrap(); + control(&mut h.app, &json!({"button":"apply"})).unwrap(); + control(&mut h.app, &json!({"button":"defaults"})).unwrap(); + h.frames(2); + assert!(h.app.preferences.theme_options.is_empty()); + assert_eq!(Tokens::get().panel, Tokens::dark().panel); + control(&mut h.app, &json!({"button":"cancel"})).unwrap(); + h.frames(2); + assert_eq!(Tokens::get().panel, egui::Color32::from_rgb(0xab, 0xcd, 0xef)); + } + + #[test] + fn theme_options_saved_invalid_values_survive_with_defaults_and_notices() { + let mut h = crate::scenario::Harness::new(); + control(&mut h.app, &json!({"theme_import":option_theme_file("Options A")})).unwrap(); + let mut saved = serde_json::to_value(&h.app.preferences).unwrap(); + saved["theme_options"] = + json!({"options-a":{"enabled":[], "amount":99, "style":"dropped", "removed":{"future":true}}, "unknown-theme":{"anything":null}}); + saved["zoom_reverse"] = json!(true); + saved["ui_scale"] = json!("bad saved field"); + h.app.preferences = lenient(&saved); + assert!(h.app.preferences.zoom_reverse); + let out = control(&mut h.app, &json!({"look_at_anim":false})).unwrap(); + assert_eq!(out["theme_options"], saved["theme_options"]); + assert_eq!(out["theme_option_values"], json!({"enabled":false,"amount":5.0,"style":"warm","blur":0.0})); + assert_eq!( + out["theme_option_notices"], + json!([ + {"id":"amount","kind":"out_of_range"}, {"id":"enabled","kind":"wrong_type"}, + {"id":"removed","kind":"unknown_option"}, {"id":"style","kind":"unknown_choice"} + ]) + ); + let mut other = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + other.load_prefs(&h.app.prefs()); + assert_eq!(other.preferences.theme_options, h.app.preferences.theme_options); + assert!(other.preferences.zoom_reverse); + } + + #[test] + fn theme_options_control_refuses_entire_mixed_call_before_side_effects() { + let mut h = crate::scenario::Harness::new(); + control(&mut h.app, &json!({"theme_import":option_theme_file("Options A")})).unwrap(); + h.app.stand_up = Some(vec!["Offered".into()]); + h.app.stand_up_note = true; + let before = h.app.prefs(); + for (options, key) in [ + (json!({"unknown":{"enabled":true}}), "theme_options.unknown"), + (json!({"options-a":{"unknown":true}}), "theme_options.options-a.unknown"), + (json!({"options-a":{"enabled":1}}), "theme_options.options-a.enabled"), + (json!({"options-a":{"amount":10.0000001}}), "theme_options.options-a.amount"), + (json!({"options-a":{"amount":-1}}), "theme_options.options-a.amount"), + (json!({"options-a":{"style":"missing"}}), "theme_options.options-a.style"), + (json!({"options-a":{"amount":8,"enabled":{}},"options-b":{"enabled":true}}), "theme_options.options-a.enabled"), + ] { + let err = control( + &mut h.app, + &json!({ + "theme_import":option_theme_file("Options B"), "theme_options":options, + "theme":"options-b", "theme_follow":"", "open":"Interface", "button":"defaults", "stand_up":false, + "msaa":4, "default_units":"inch", "up_axis":"y", "ui_scale":1.5 + }), + ) + .unwrap_err(); + assert!(err.contains(key), "{err}"); + assert_eq!(h.app.prefs(), before, "{key}"); + assert!(!h.app.prefs_window.open && h.app.prefs_window.snapshot.is_none()); + assert_eq!(h.app.stand_up.as_deref(), Some(["Offered".to_string()].as_slice())); + assert!(h.app.stand_up_note); + } + let err = control(&mut h.app, &json!({"theme_remove":"options-a", "theme_options":{"options-a":{}}})).unwrap_err(); + assert!(err.contains("theme_options.options-a")); + assert_eq!(h.app.prefs(), before); + assert!(control(&mut h.app, &json!({"theme_options":{"options-a":{"enabled":true}},"ui_scale":9})).is_err()); + assert_eq!(h.app.prefs(), before); + assert!(control(&mut h.app, &json!({"theme_import":option_theme_file("Options B"),"button":"invalid"})).is_err()); + assert_eq!(h.app.prefs(), before); + assert!(control(&mut h.app, &json!({"theme_options":null})).is_err()); + } + + #[test] + fn theme_options_active_reply_is_localized_ordered_and_matches_schema_types() { + use solidcraft_engine::schema::ui_prefs::{PrefsReply, ThemeOptionKind}; + let mut h = crate::scenario::Harness::new(); + let out = control(&mut h.app, &json!({"theme_import":option_theme_file("Options A"), "language":"de"})).unwrap(); + let reply: PrefsReply = serde_json::from_value(out.clone()).unwrap(); + assert_eq!(reply.options.theme_option_defs.iter().map(|o| o.id.as_str()).collect::>(), ["blur", "enabled", "amount", "style"]); + let defs = &reply.options.theme_option_defs; + assert!(defs[0].standard && !defs[0].available); + assert_eq!(defs[0].reason.as_deref(), Some("not implemented")); + assert_eq!((&defs[1].label, &defs[1].help), (&"Aktiv".to_string(), &"Farben verwenden".to_string())); + assert!(defs[1].available && defs[1].reason.is_none()); + assert!(defs[2].advanced && defs[2].section.as_deref() == Some("Details")); + let ThemeOptionKind::Choice { values, .. } = &defs[3].kind else { panic!("choice definition") }; + assert_eq!(values.iter().map(|v| v.label.as_str()).collect::>(), ["Warmton", "Cool"]); + assert_eq!(serde_json::to_value(reply).unwrap(), out); + let out = control(&mut h.app, &json!({"theme":"dark"})).unwrap(); + assert_eq!(out["theme_option_defs"], json!([])); + assert_eq!(out["theme_option_values"], json!({})); + assert_eq!(out["theme_option_notices"], json!([])); + } + + #[test] + fn theme_options_followed_file_uses_its_id_and_reload_keeps_saved_entries() { + let mut h = crate::scenario::Harness::new(); + let path = h.dir.join("follow-options.json"); + let mut file = option_theme_file("Follow Options"); + file["base"] = json!("light"); + std::fs::write(&path, file.to_string()).unwrap(); + let out = control(&mut h.app, &json!({"theme_follow":path, "theme_options":{"file-follow-options":{"enabled":true,"amount":8}}})).unwrap(); + assert_eq!(out["theme"], "dark"); + assert_eq!(out["theme_option_values"]["enabled"], true); + h.frames(2); + assert_eq!(Tokens::get().panel, egui::Color32::from_rgb(0xab, 0xcd, 0xef)); + assert!(!h.app.ui.dark); + let saved = h.app.prefs(); + let err = control(&mut h.app, &json!({"theme":"light", "theme_options":{"missing":{}}, "stand_up":false})).unwrap_err(); + assert!(err.contains("theme_options.missing")); + assert_eq!(h.app.prefs(), saved); + assert_eq!(active_theme_file(&h.app).unwrap().id, "file-follow-options"); + let other_path = h.dir.join("other-options.json"); + std::fs::write(&other_path, option_theme_file("Other Options").to_string()).unwrap(); + let err = control(&mut h.app, &json!({"theme_follow":other_path,"theme_options":{"file-other-options":{"enabled":42}}})).unwrap_err(); + assert!(err.contains("theme_options.file-other-options.enabled"), "{err}"); + assert_eq!(h.app.prefs(), saved); + assert_eq!(active_theme_file(&h.app).unwrap().id, "file-follow-options"); + file["options"][1]["max"] = json!(6); + file["options"][1]["default"] = json!(2); + std::fs::write(&path, file.to_string()).unwrap(); + let out = control(&mut h.app, &json!({"theme_follow":path, "theme_export":true})).unwrap(); + assert_eq!(out["theme_option_values"]["amount"], 2.0); + assert_eq!(out["theme_options"]["file-follow-options"]["amount"], 8); + assert_eq!(out["theme_option_notices"], json!([{"id":"amount","kind":"out_of_range"}])); + assert_eq!(out["theme_file"]["name"], "Follow Options"); + assert_eq!(out["theme_file"]["options"][1]["default"], 2.0); + std::fs::write(&path, "incomplete").unwrap(); + let out = control(&mut h.app, &json!({"theme_follow":path})).unwrap(); + assert!(out["theme_follow_error"].is_string()); + assert_eq!(out["theme_option_values"]["enabled"], true); + let out = control(&mut h.app, &json!({"theme_follow":""})).unwrap(); + assert_eq!(out["dark"], true); + assert!(active_theme_file(&h.app).is_none()); + h.frames(2); + assert_eq!(Tokens::get().panel, Tokens::dark().panel); + let out = control(&mut h.app, &json!({"theme_follow":path})).unwrap(); + assert_eq!(out["theme_option_values"], json!({}), "stopping clears the last good file"); + control(&mut h.app, &json!({"theme_follow":""})).unwrap(); + std::fs::write(&path, file.to_string()).unwrap(); + follow_theme_file_for_run(&mut h.app, path.to_str().unwrap()).unwrap(); + h.frames(2); + let out = control(&mut h.app, &json!({})).unwrap(); + assert_eq!(out["theme_follow"], ""); + assert_eq!(out["theme_option_values"]["enabled"], true); + assert_eq!(Tokens::get().panel, egui::Color32::from_rgb(0xab, 0xcd, 0xef)); + assert!(!h.app.ui.dark); + let saved = h.app.prefs(); + let launch = h.app.prefs_window.follow.launch.clone(); + assert!(control(&mut h.app, &json!({"theme":"dark","theme_options":{"missing":{}}})).is_err()); + assert_eq!(h.app.prefs(), saved); + assert_eq!(h.app.prefs_window.follow.launch, launch); + assert_eq!(active_theme_file(&h.app).unwrap().id, "file-follow-options"); + let out = control(&mut h.app, &json!({"theme":"dark"})).unwrap(); + assert_eq!(out["dark"], true); + assert!(out["theme_followed"].is_null()); + assert!(h.app.prefs_window.follow.theme().is_none()); + h.frames(2); + assert_eq!(Tokens::get().panel, Tokens::dark().panel); + } + #[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 fb39a3438..e35f1ba47 100644 --- a/crates/ui-egui/src/prefs/interface.rs +++ b/crates/ui-egui/src/prefs/interface.rs @@ -31,6 +31,7 @@ pub(super) fn interface(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) { ui_kit::settings_heading(ui, app.tr("prefs.interface"), app.tr("prefs.interface_note")); ui_kit::settings_section(ui, "theme", app.tr("ui.theme"), |ui| { theme_row(app, ui); + theme_options_row(app, ui); ui_kit::tab_accent_strip(ui); // The 3D view in the theme's colours, or the Light or Dark theme's (#4146). ui_kit::settings_form(ui, t.form_label_width + t.space_16 + t.space_6, |ui| { diff --git a/crates/ui-egui/src/scenario.rs b/crates/ui-egui/src/scenario.rs index ada0605f4..121323e9c 100644 --- a/crates/ui-egui/src/scenario.rs +++ b/crates/ui-egui/src/scenario.rs @@ -1098,6 +1098,16 @@ pub fn check(h: &mut Harness, e: &Value) -> Result<(), String> { } } } + "theme_colors" => { + // Read the applied tokens after the scenario frame, not the source theme file. + let tokens = crate::theme::Tokens::get(); + let resolved = crate::theme_files::export("Scenario", crate::theme_files::Base::Dark, &tokens); + for (key, want) in v.as_object().into_iter().flatten() { + if resolved["colors"][key] != *want { + return Err(format!("theme colour {key}: got {}, want {want}", resolved["colors"][key])); + } + } + } "file_busy" | "quit_requested" | "quitting" => { if ui[k] != *v { return Err(format!("{k}: got {}, want {v}", ui[k])); diff --git a/crates/ui-egui/src/settings_profiles.rs b/crates/ui-egui/src/settings_profiles.rs index 25df84320..122510ac8 100644 --- a/crates/ui-egui/src/settings_profiles.rs +++ b/crates/ui-egui/src/settings_profiles.rs @@ -9,6 +9,7 @@ //! preference this version can't read is left out. Applying one sets each preference through //! [`prefs::set`], so it is checked again and has the same effects as a change in Preferences; //! one that is refused there (an interface font this computer lacks) keeps its current value. +//! Saved theme option maps are restored intact, retaining stale entries for fallback notices. //! //! The `settings.profile.*` commands reach the profiles; the engine only checks their //! parameters, and [`command`] does the rest after `SolveApp::run`. @@ -243,7 +244,7 @@ fn shortcut_keys(v: &Value) -> Option { keys.iter().all(|k| k.chars().count() <= MAX_ID).then(|| crate::keymap::keys_value(&keys)) } -/// Apply a checked profile: its themes, each preference (through [`prefs::set`]), the +/// Apply a checked profile: its themes, each preference (through [`prefs::set`], except saved option maps), the /// shortcuts, the favourites and the toolbar. Returns the preferences that were refused. fn apply(app: &mut SolveApp, doc: &Value) -> Vec { let mut theme_ids = std::collections::BTreeMap::new(); @@ -257,6 +258,18 @@ fn apply(app: &mut SolveApp, doc: &Value) -> Vec { } let mut skipped = Vec::new(); for (key, value) in doc.get("preferences").and_then(Value::as_object).into_iter().flatten() { + if key == "theme_options" { + // Restoring saved state keeps stale entries just like loading preferences. The + // control channel's strict merge is for new edits, not profile restoration. + match serde_json::from_value::>>(value.clone()) { + Ok(options) => { + app.preferences.theme_options = + options.into_iter().map(|(id, values)| (theme_ids.get(&id).cloned().unwrap_or(id), values)).collect(); + } + Err(_) => skipped.push(key.clone()), + } + continue; + } let value = match value.as_str().and_then(|id| theme_ids.get(id)) { Some(id) if key == "theme" => json!(id), _ => value.clone(), diff --git a/crates/ui-egui/src/settings_profiles_tests.rs b/crates/ui-egui/src/settings_profiles_tests.rs index d6efe1981..87d07adde 100644 --- a/crates/ui-egui/src/settings_profiles_tests.rs +++ b/crates/ui-egui/src/settings_profiles_tests.rs @@ -109,6 +109,36 @@ fn profiles_and_the_active_one_are_kept_between_runs() { assert_eq!(other.settings_profiles.list, h.app.settings_profiles.list); } +#[test] +fn theme_options_profiles_restore_replace_and_preserve_stale_values() { + let mut h = Harness::new(); + let file = json!({ + "format":"solidcraft-theme/1", "name":"Profile Options", "base":"dark", + "options":[{"id":"enabled","type":"bool","default":false}], + "overlays":[{"when":{"opt":"enabled","eq":true},"colors":{"panel":"#abcdef"}}] + }); + let out = h.call("ui.prefs", json!({"theme_import":file,"theme_options":{"profile-options":{"enabled":true}}})); + assert!(out["error"].is_null(), "{out}"); + h.app.preferences.theme_options.entry("profile-options".into()).or_default().insert("future".into(), json!({"unrecognized":true})); + h.app.preferences.theme_options.insert("unknown-theme".into(), [("saved".into(), json!([1, 2]))].into()); + run(&mut h, "settings.profile.save", json!({"name":"Options"})); + let exported = run(&mut h, "settings.profile.export", json!({"name":"Options"}))["profile"].clone(); + let options = exported["preferences"]["theme_options"].clone(); + assert_eq!(exported["themes"][0]["options"][0]["default"], false); + h.call("ui.prefs", json!({"open":"Interface","button":"defaults"})); + run(&mut h, "settings.profile.save", json!({"name":"Empty"})); + run(&mut h, "settings.profile.import", json!({"profile":exported,"name":"Imported"})); + let out = run(&mut h, "settings.profile.apply", json!({"name":"Imported"})); + assert_eq!(out["skipped"], json!([])); + assert_eq!(serde_json::to_value(&h.app.preferences.theme_options).unwrap(), options); + h.frames(2); + assert_eq!(crate::theme::Tokens::get().panel, egui::Color32::from_rgb(0xab, 0xcd, 0xef)); + run(&mut h, "settings.profile.apply", json!({"name":"Empty"})); + assert!(h.app.preferences.theme_options.is_empty()); + run(&mut h, "settings.profile.apply", json!({"name":"Options"})); + assert_eq!(serde_json::to_value(&h.app.preferences.theme_options).unwrap(), options); +} + #[test] fn export_and_import_go_through_one_file_and_import_never_switches() { let dir = std::env::temp_dir().join(format!("solidcraft-profile-test-{}", std::process::id())); diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index dfa7bb3ae..1677d2995 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -286,6 +286,32 @@ pub(crate) fn contrast_ratio(a: Color32, b: Color32) -> f64 { (a.max(b) + 0.05) / (a.min(b) + 0.05) } +/// Composite a translucent foreground over an opaque background in sRGB for contrast checks. +pub(crate) fn composite(fill: Color32, background: Color32) -> Color32 { + let rgb = fill.to_srgba_unmultiplied(); + let a = f64::from(rgb[3]) / 255.0; + let channel = |index: usize| (f64::from(rgb[index]) * a + f64::from(background[index]) * (1.0 - a)).round() as u8; + Color32::from_rgb(channel(0), channel(1), channel(2)) +} + +fn readable_fill(fill: Color32, inks: &[Color32], scale: f32) -> Color32 { + let [r, g, b, alpha] = fill.to_srgba_unmultiplied(); + let requested = (f32::from(alpha) * scale).round() as u8; + // At most 256 cheap colour comparisons per changed role; no allocations, GPU or I/O. + for a in requested..=255 { + let candidate = Color32::from_rgba_unmultiplied(r, g, b, a); + if [Color32::BLACK, Color32::WHITE].iter().all(|background| { + let ground = composite(candidate, *background); + inks.iter().all(|ink| contrast_ratio(composite(*ink, ground), ground) >= 4.5) + }) { + return candidate; + } + } + // An authored foreground may already fail at full opacity. Never alter that foreground; + // full alpha gives it the strongest protection this option can supply. + Color32::from_rgb(r, g, b) +} + impl TabAccent { pub fn for_tab(t: &Tokens, tab: &str) -> Self { let (color, ink, soft) = match tab { @@ -898,6 +924,21 @@ impl Tokens { Tokens::themed(viewport_dark(), vision()).with_background(viewport_background()) } + /// Scale only floating surface fill alpha, preserving full-opacity tokens exactly. + /// Raise each fill's floor to protect text over both black and white viewport extremes. + pub(crate) fn apply_panel_opacity(&mut self, percent: f32) { + if !percent.is_finite() || percent >= 100.0 { + return; + } + let scale = percent.clamp(40.0, 100.0) / 100.0; + let body_inks = [self.text, self.form_ink, self.dialog_label]; + for fill in [&mut self.panel, &mut self.panel_header, &mut self.dialog_bg, &mut self.dialog_body, &mut self.dialog_footer, &mut self.overlay] + { + *fill = readable_fill(*fill, &body_inks, scale); + } + self.nav_tip = readable_fill(self.nav_tip, &[self.nav_tip_ink], scale); + } + /// These tokens with the 3D view's background one flat colour (#7688), or as they are for `None`. pub fn with_background(mut self, colour: Option<[u8; 3]>) -> Tokens { if let Some([r, g, b]) = colour { diff --git a/crates/ui-egui/src/theme_files.rs b/crates/ui-egui/src/theme_files.rs index b05f4c428..3bc227a19 100644 --- a/crates/ui-egui/src/theme_files.rs +++ b/crates/ui-egui/src/theme_files.rs @@ -264,6 +264,16 @@ impl ThemeFile { self.requires > REQUIREMENTS_LEVEL } + /// Read option tables from a stored or directly supplied theme with the import parser. + /// Base tables are deliberately left alone; only completely valid declarations replace these. + pub(crate) fn set_option_tables(&mut self, source: &Value) -> Result<(), String> { + let options = if self.needs_newer() { Vec::new() } else { parse_options(source.get("options"))? }; + let overlays = if self.needs_newer() { Vec::new() } else { parse_overlays(source.get("overlays"), &options)? }; + self.options = options; + self.overlays = overlays; + Ok(()) + } + /// Validate direct control-channel preference updates as strictly as file imports. pub(crate) fn validate_radii(&self) -> Result<(), String> { for (key, value) in &self.radii { @@ -704,7 +714,7 @@ fn parse_option(v: &Value) -> Result { if step <= 0.0 { return Err("`step` must be greater than zero".into()); } - let default = option_number(v, "default")?; + let default = if id == "opacity" && v.get("default").is_none() { 100.0 } else { option_number(v, "default")? }; let default = if reserved { default.clamp(min, max) } else { @@ -987,7 +997,7 @@ pub fn resolve(theme: &ThemeFile) -> Tokens { /// Resolve base tables, then matching overlays in file order. Later tables replace earlier /// entries by key. Saved values are normalized here too, so callers cannot bypass finite checks. pub fn resolve_with(theme: &ThemeFile, saved: &BTreeMap) -> Tokens { - if theme.needs_newer() || theme.overlays.is_empty() || theme.overlays.len() > MAX_OVERLAYS { + if theme.needs_newer() || (theme.options.is_empty() && theme.overlays.is_empty()) || theme.overlays.len() > MAX_OVERLAYS { return resolve_base(theme); } let options = usable_options(theme); @@ -1012,7 +1022,9 @@ pub fn resolve_with(theme: &ThemeFile, saved: &BTreeMap) -> merged.borders.extend(overlay.values.borders); merged.icon_palette.extend(overlay.values.icon_palette); } - resolve_base(&merged) + let mut tokens = resolve_base(&merged); + crate::theme_options::apply(theme, &values, &mut tokens); + tokens } /// A colour the saved preferences hold that this version cannot read is skipped safely. @@ -1737,6 +1749,85 @@ mod tests { } } + #[test] + fn theme_options_opacity_only_changes_floating_fill_roles_and_full_is_exact() { + for base in ["light", "dark"] { + let mut source = json!({"format":FORMAT,"name":"Opacity","base":base,"options":[{"id":"opacity","type":"range"}]}); + let file = from_value(&source).unwrap(); + let original = resolve_base(&file); + assert_eq!(resolve(&file), original, "omitted default is 100"); + assert_eq!(resolve_with(&file, &BTreeMap::from([("opacity".into(), OptionValue::Num(100.0))])), original); + let faded = resolve_with(&file, &BTreeMap::from([("opacity".into(), OptionValue::Num(60.0))])); + let mut only_fills = original; + only_fills.panel = faded.panel; + only_fills.panel_header = faded.panel_header; + only_fills.dialog_bg = faded.dialog_bg; + only_fills.dialog_body = faded.dialog_body; + only_fills.dialog_footer = faded.dialog_footer; + only_fills.overlay = faded.overlay; + only_fills.nav_tip = faded.nav_tip; + assert_eq!(faded, only_fills, "every other token (including text/icons/borders) stays exact"); + assert!(faded.panel.a() < original.panel.a(), "the effect must actually change a panel"); + source["options"] = json!([]); + let without = from_value(&source).unwrap(); + assert_eq!(resolve_with(&without, &BTreeMap::from([("opacity".into(), OptionValue::Num(40.0))])), resolve_base(&without)); + } + } + + #[test] + fn theme_options_opacity_contrast_protects_text_at_40_over_viewport_extremes() { + use crate::theme::{composite, contrast_ratio}; + for base in ["light", "dark"] { + let file = from_value(&json!({"format":FORMAT,"name":"Contrast","base":base, + "options":[{"id":"opacity","type":"range","default":40}]})) + .unwrap(); + let full = resolve_base(&file); + let faded = resolve(&file); + for (role, fill) in [ + ("panel", faded.panel), + ("panel_header", faded.panel_header), + ("dialog_bg", faded.dialog_bg), + ("dialog_body", faded.dialog_body), + ("dialog_footer", faded.dialog_footer), + ("overlay", faded.overlay), + ] { + for background in [Color32::BLACK, Color32::WHITE, full.viewport_top, full.viewport_bottom] { + let ground = composite(fill, background); + for ink in [faded.text, faded.form_ink, faded.dialog_label] { + assert!(contrast_ratio(composite(ink, ground), ground) >= 4.5, "{base} {role} {ink:?} on {background:?}: {fill:?}"); + } + } + } + for background in [Color32::BLACK, Color32::WHITE] { + let ground = composite(faded.nav_tip, background); + assert!(contrast_ratio(composite(faded.nav_tip_ink, ground), ground) >= 4.5); + } + assert!(faded.panel.a() > (f32::from(full.panel.a()) * 0.4).round() as u8, "raise the floor when requested alpha is unreadable"); + assert!(faded.panel.a() < 255, "do not make all options effectively opaque"); + assert_eq!(resolve_with(&file, &BTreeMap::from([("opacity".into(), OptionValue::Num(-10.0))])), faded, "theme API still clamps"); + assert_eq!( + resolve_with(&file, &BTreeMap::from([("opacity".into(), OptionValue::Num(f32::NAN))])), + faded, + "non-finite values use defaults" + ); + } + } + + #[test] + fn theme_options_opacity_is_applied_after_overlays_and_uses_the_theme_default() { + let file = from_value(&json!({"format":FORMAT,"name":"Overlay opacity","base":"dark", + "options":[{"id":"opacity","type":"range","default":60},{"id":"warm","type":"bool","default":true}], + "overlays":[{"when":{"opt":"warm","eq":true},"colors":{"panel":"#111111"}}]})) + .unwrap(); + let faded = resolve(&file); + let full = resolve_with(&file, &BTreeMap::from([("opacity".into(), OptionValue::Num(100.0))])); + assert_eq!(full.panel, Color32::from_rgb(17, 17, 17)); + assert!(faded.panel.a() < full.panel.a()); + assert_eq!(faded.text, full.text); + // Premultiplied Color32 storage can quantize unmultiplied channels by one byte. + assert!(faded.panel.to_srgba_unmultiplied()[..3].iter().all(|c| c.abs_diff(17) <= 1)); + } + #[test] fn all_shipped_themes_keep_the_original_resolver_output_and_serialization() { assert_eq!(builtin().len(), BUILTIN.len()); diff --git a/crates/ui-egui/src/theme_options.rs b/crates/ui-egui/src/theme_options.rs new file mode 100644 index 000000000..ec8767b5b --- /dev/null +++ b/crates/ui-egui/src/theme_options.rs @@ -0,0 +1,87 @@ +//! Standard behaviours are registered here; file declarations alone do not offer a control. +use crate::{ + theme::Tokens, + theme_files::{OptionDef, OptionValue, ThemeFile}, +}; +use std::collections::BTreeMap; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Availability { + Available, + /// Message-catalog id, translated at the presentation boundary. + #[allow(dead_code)] // Hardware-dependent registrations arrive with blur and tab providers. + Unavailable(&'static str), +} + +pub(crate) struct Provider { + pub id: &'static str, + pub label: &'static str, + pub help: &'static str, + pub availability: fn() -> Availability, + pub apply: fn(&mut Tokens, &OptionValue), +} + +// Future blur/tab_colours/tab_fade_ms implementations register their behaviour here. +pub(crate) const PROVIDERS: &[Provider] = &[Provider { + id: "opacity", + label: "prefs.theme_option_opacity", + help: "prefs.theme_option_opacity_help", + availability: || Availability::Available, + apply: apply_opacity, +}]; + +pub(crate) fn standard(id: &str) -> bool { + matches!(id, "opacity" | "blur" | "tab_colours" | "tab_fade_ms") +} + +pub(crate) fn provider<'a>(id: &str, providers: &'a [Provider]) -> Option<&'a Provider> { + providers.iter().find(|p| p.id == id) +} + +/// A child of an absent provider is absent too, even if it has a custom id. +pub(crate) fn offered<'a>(file: &'a ThemeFile, providers: &[Provider]) -> Vec<&'a OptionDef> { + let ordered = crate::theme_files::ordered_options(file); + ordered + .iter() + .copied() + .filter(|option| { + let mut current = Some(*option); + for _ in 0..=crate::theme_files::MAX_OPTIONS { + let Some(def) = current else { return true }; + if standard(&def.id) && provider(&def.id, providers).is_none() { + return false; + } + current = def.parent.as_ref().and_then(|id| ordered.iter().find(|o| &o.id == id).copied()); + } + false + }) + .collect() +} + +pub(crate) fn apply(file: &ThemeFile, values: &BTreeMap, tokens: &mut Tokens) { + let offered = offered(file, PROVIDERS); + for def in &offered { + let mut parent = def.parent.as_deref(); + let mut active = true; + for _ in 0..crate::theme_files::MAX_OPTIONS { + let Some(id) = parent else { break }; + active &= values.get(id) == Some(&OptionValue::Bool(true)); + active &= provider(id, PROVIDERS).is_none_or(|p| (p.availability)() == Availability::Available); + parent = offered.iter().find(|o| o.id == id).and_then(|o| o.parent.as_deref()); + } + if let Some(provider) = provider(&def.id, PROVIDERS) + && active + && (provider.availability)() == Availability::Available + && let Some(value) = values.get(&def.id) + { + (provider.apply)(tokens, value); + } + } +} + +/// Adapt the option value; all colour math belongs to the theme boundary. +fn apply_opacity(t: &mut Tokens, value: &OptionValue) { + if let OptionValue::Num(percent) = value { + t.apply_panel_opacity(*percent); + } +} diff --git a/crates/ui-egui/src/ui_kit/mod.rs b/crates/ui-egui/src/ui_kit/mod.rs index 9e828329e..4e5d5eede 100644 --- a/crates/ui-egui/src/ui_kit/mod.rs +++ b/crates/ui-egui/src/ui_kit/mod.rs @@ -28,6 +28,7 @@ pub(crate) mod panel; mod preferences; mod preferences_assistant; mod preferences_figures; +mod preferences_layout; mod preferences_navigation; mod preferences_small; mod radial; diff --git a/crates/ui-egui/src/ui_kit/preferences.rs b/crates/ui-egui/src/ui_kit/preferences.rs index 42595ed47..64c0ec6ec 100644 --- a/crates/ui-egui/src/ui_kit/preferences.rs +++ b/crates/ui-egui/src/ui_kit/preferences.rs @@ -9,6 +9,310 @@ use egui::{Color32, FontId, Pos2, Rect, Response, Sense, Stroke, Ui, pos2, vec2} pub(super) const PAGE_SCROLL_GUTTER: &str = "sc_page_scroll_gutter"; +/// Presentation data is resolved by the caller; controls never distinguish standard/custom ids. +pub(crate) struct ThemeOptionRow<'a> { + pub definition: &'a crate::theme_files::OptionDef, + pub label: String, + pub help: String, + pub choices: Vec, + pub reason: Option, +} + +#[derive(Clone, Copy)] +struct ThemeOptionMetrics { + label: f32, + readout: f32, + reason: f32, + minimum: f32, +} + +fn theme_option_slider_minimum(t: &Tokens) -> f32 { + t.space_24 * 2.0 + t.space_8 +} + +/// Measure the same fonts, gutters and control sizes used by `theme_option_control`. +fn theme_option_metrics(ui: &Ui, option: &ThemeOptionRow<'_>, value: Option<&crate::theme_files::OptionValue>) -> ThemeOptionMetrics { + use crate::theme_files::{OptionKind, OptionValue}; + let t = Tokens::get(); + let label = super::ContentWidth::label(ui, &option.label) + t.space_4; + let mut readout = 0.0; + let control = match &option.definition.kind { + OptionKind::Bool { .. } => t.space_24 + t.space_8, + OptionKind::Range { default, min, max, step, unit } => { + let current = match value { + Some(OptionValue::Num(n)) => *n, + _ => *default, + }; + // Endpoints and adjacent steps reserve fractional readouts before the first edit. + readout = [*min, *max, *default, current, (*min + *step).min(*max), (*max - *step).max(*min)] + .into_iter() + .map(|n| super::ContentWidth::label(ui, &format!("{n}{}", unit.as_deref().unwrap_or("")))) + .fold(0.0, f32::max); + theme_option_slider_minimum(&t) + t.space_8 + readout + } + OptionKind::Choice { values, .. } => { + if values.len() > 5 { + let labels: Vec<_> = option.choices.iter().map(String::as_str).collect(); + super::ContentWidth::dropdown(ui, &labels).min(t.form_label_width + t.space_24) + } else { + // Compact segments use equal widths based on the widest semibold label. + let widest = option.choices.iter().map(|s| super::ContentWidth::name(ui, s)).fold(0.0, f32::max); + (widest + t.space_16) * values.len() as f32 + } + } + }; + let reason = option + .reason + .as_ref() + .map_or(0.0, |reason| ui.painter().layout_no_wrap(reason.clone(), FontId::proportional(t.font_body), t.form_dim).size().x.ceil() + t.space_8); + // settings_form/row use the measured label plus a fixed space_14 gutter. + ThemeOptionMetrics { label, readout, reason, minimum: label + t.space_14 + control + reason } +} + +/// A quiet badge drawn within the existing theme card, without changing its hit target or size. +pub(crate) fn theme_options_badge(ui: &Ui, card: Rect, label: &str) { + let t = Tokens::get(); + let text = ui.painter().layout_no_wrap(label.to_owned(), FontId::proportional(t.font_micro), t.form_ink); + let size = vec2(text.size().x + t.space_8, t.space_16); + let rect = Rect::from_min_size(card.left_top() + vec2(t.space_6, t.space_6), size); + ui.painter().rect_filled(rect, t.radius_sm, t.dialog_body); + ui.painter().galley(rect.center() - text.size() / 2.0, text, t.form_ink); + scenario::publish_rect("prefs:theme_options_badge", rect); +} + +/// Ordered two-column list, with composite children sharing their parent's cell and hit row. +/// Returns Reset; edited values are returned through `values` for the caller's preference merge. +pub(crate) fn theme_options_list( + ui: &mut Ui, + theme_id: &str, + name: &str, + options: &[ThemeOptionRow<'_>], + values: &mut std::collections::BTreeMap, +) -> bool { + use super::preferences_layout::{Entry, Width, choice_width, layout}; + use crate::theme_files::OptionKind; + // Label/help/choice text is already resolved, including the theme's English fallback. + let _labels = crate::i18n::resolved_labels(); + if options.is_empty() { + return false; + } + let t = Tokens::get(); + let mut cells: Vec> = Vec::new(); + for (i, option) in options.iter().enumerate() { + if option.definition.parent.as_ref().is_some_and(|id| options.iter().any(|o| &o.definition.id == id)) { + continue; + } + let mut cell = vec![i]; + let mut parent = option.definition.id.as_str(); + for _ in 0..crate::theme_files::MAX_OPTIONS { + let Some((j, child)) = options.iter().enumerate().find(|(_, o)| o.definition.parent.as_deref() == Some(parent)) else { break }; + if cell.contains(&j) { + break; + } + cell.push(j); + parent = &child.definition.id; + } + cells.push(cell); + } + let metrics: Vec<_> = options.iter().map(|option| theme_option_metrics(ui, option, values.get(&option.definition.id))).collect(); + let entries: Vec<_> = cells + .iter() + .map(|cell| { + let mut width = if cell.len() > 1 { Width::Composite } else { Width::Narrow }; + let mut minimum = t.space_8 * cell.len().saturating_sub(1) as f32; + let mut advanced = false; + for &index in cell { + let Some(option) = options.get(index) else { continue }; + advanced |= option.definition.advanced; + if let OptionKind::Choice { values, .. } = &option.definition.kind + && choice_width(values.len()) == Width::Wide + { + width = Width::Wide; + } + minimum += metrics.get(index).map_or(0.0, |m| m.minimum); + } + Entry { width, advanced, minimum } + }) + .collect(); + let plan = layout(&entries, dimension(ui.available_width()) - t.space_16); + let mut reset = false; + let header = ui.horizontal(|ui| { + super::text(ui, name, super::Text::Inline); + if options.iter().any(|option| values.get(&option.definition.id).is_some_and(|v| *v != option.definition.default_value())) { + let response = super::text_button(ui, crate::i18n::tr("prefs.theme_options_reset"), true); + scenario::publish_target("prefs:theme_options_reset", response.rect); + reset = response.clicked(); + } + }); + scenario::publish_rect("prefs:theme_options_header", header.response.rect); + let mut draw_rows = |ui: &mut Ui, rows: &[Vec]| { + let mut section = None; + for row in rows { + // Labels are theme-authored metadata, shown only above the six-cell threshold. + let label = + row.iter().filter_map(|i| cells.get(*i)).flatten().filter_map(|i| options.get(*i)).find_map(|o| o.definition.section.as_deref()); + if plan.section_labels && label != section { + if let Some(label) = label { + super::text(ui, label, super::Text::Hint("theme_option_section")); + } + section = label; + } + let width = dimension(ui.available_width()); + let cell_width = (width - t.space_16) / 2.0; + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = t.space_16; + for &index in row { + let Some(cell) = cells.get(index) else { continue }; + let full = entries.get(index).is_some_and(|e| e.width == Width::Wide || e.minimum > cell_width); + let width = if full { width } else { cell_width }; + ui.allocate_ui_with_layout(vec2(width.max(0.0), t.control_height), egui::Layout::top_down(egui::Align::Min), |ui| { + ui.set_width(width.max(0.0)); + let stack = entries.get(index).is_some_and(|e| e.minimum > width); + let direction = + if stack { egui::Layout::top_down(egui::Align::Min) } else { egui::Layout::left_to_right(egui::Align::Center) }; + let response = ui.with_layout(direction, |ui| { + ui.spacing_mut().item_spacing.x = t.space_8; + let total: f32 = cell.iter().filter_map(|i| metrics.get(*i)).map(|m| m.minimum).sum(); + let usable = (width - t.space_8 * cell.len().saturating_sub(1) as f32).max(0.0); + for &i in cell { + if let (Some(option), Some(metrics)) = (options.get(i), metrics.get(i)) { + let option_width = if stack { width } else { usable * metrics.minimum / total.max(1.0) }; + ui.allocate_ui_with_layout( + vec2(option_width.max(0.0), t.control_height), + egui::Layout::left_to_right(egui::Align::Center), + |ui| { + theme_option_control(ui, option, options, values, metrics, cell.len() == 1); + }, + ); + } + } + }); + if let Some(option) = cell.first().and_then(|i| options.get(*i)) { + scenario::publish_rect(&format!("prefs:theme_option_cell:{}", option.definition.id), response.response.rect); + } + }); + } + }); + } + }; + ui.push_id(("theme_options", theme_id), |ui| { + draw_rows(ui, &plan.rows); + if plan.more_count > 0 { + let title = crate::i18n::format("prefs.theme_options_more", &[("count", &plan.more_count.to_string())]); + super::section(ui, "more", &title, false, |ui| draw_rows(ui, &plan.more)); + if let Some(rect) = scenario::rect_of(&format!("dialog:section:{title}")) { + scenario::publish_target("prefs:theme_options_more", rect); + } + } + }); + reset +} + +fn theme_option_control( + ui: &mut Ui, + option: &ThemeOptionRow<'_>, + options: &[ThemeOptionRow<'_>], + values: &mut std::collections::BTreeMap, + metrics: &ThemeOptionMetrics, + fill_range: bool, +) { + use crate::theme_files::{OptionKind, OptionValue}; + let t = Tokens::get(); + let def = option.definition; + let mut active = option.reason.is_none(); + let mut parent = def.parent.as_deref(); + for _ in 0..crate::theme_files::MAX_OPTIONS { + let Some(id) = parent else { break }; + active &= values.get(id) == Some(&OptionValue::Bool(true)); + let ancestor = options.iter().find(|o| o.definition.id == id); + active &= ancestor.is_some_and(|o| o.reason.is_none()); + parent = ancestor.and_then(|o| o.definition.parent.as_deref()); + } + let mut value = values.get(&def.id).cloned().unwrap_or_else(|| def.default_value()); + let before = value.clone(); + let control_width = (ui.available_width() - metrics.reason).max(0.0); + let response = ui.allocate_ui_with_layout(vec2(control_width, t.control_height), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.push_id(&def.id, |ui| { + ui.add_enabled_ui(active, |ui| { + // `row` owns the accessible control label and the shared control geometry. + super::settings_form(ui, metrics.label, |ui| { + super::row(ui, &option.label, |ui| { + match (&def.kind, &mut value) { + (OptionKind::Bool { .. }, OptionValue::Bool(on)) => { + theme_option_switch(ui, &option.label, on); + } + (OptionKind::Range { min, max, step, unit, .. }, OptionValue::Num(n)) => { + let available = dimension(ui.available_width() - metrics.readout - t.space_8); + // Standalone ranges fill their cell; composites retain their compact control alignment. + let width = + if fill_range { available } else { available.min(t.form_label_width.max(theme_option_slider_minimum(&t))) }; + ui.allocate_ui_with_layout(vec2(width, t.control_height), egui::Layout::left_to_right(egui::Align::Center), |ui| { + super::slider( + ui, + n, + *min..=*max, + super::Slider { step: Some(f64::from(*step)), show_value: false, ..Default::default() }, + ); + }); + // Keep fractional theme values visible, including sliders with fractional steps. + let readout = ui.allocate_ui_with_layout( + vec2(metrics.readout, t.control_height), + egui::Layout::left_to_right(egui::Align::Center), + |ui| { + super::text(ui, &format!("{}{}", *n, unit.as_deref().unwrap_or("")), super::Text::Inline); + }, + ); + scenario::publish_rect(&format!("prefs:theme_option_readout:{}", def.id), readout.response.rect); + } + (OptionKind::Choice { values, .. }, OptionValue::Choice(selected)) => { + let labels: Vec<_> = option.choices.iter().map(String::as_str).collect(); + let mut index = values.iter().position(|v| &v.id == selected).unwrap_or(0); + let changed = if values.len() > 5 { + super::dropdown_picked(ui, &def.id, &mut index, &labels) + } else { + super::segmented(ui, &mut index, &labels, super::Segments { compact: true, ..Default::default() }) + }; + if changed && let Some(choice) = values.get(index) { + *selected = choice.id.clone(); + } + } + _ => {} + } + }) + }); + }) + }) + .inner + .response + }); + let response = response.inner.on_hover_text(&option.help); + scenario::publish_target(&format!("prefs:theme_option:{}", def.id), response.rect); + if let Some(reason) = &option.reason { + let note = ui.horizontal(|ui| super::settings_inline_note(ui, reason)); + scenario::publish_rect(&format!("prefs:theme_option_reason:{}", def.id), note.response.rect); + } + if active && value != before { + values.insert(def.id.clone(), value); + } +} + +fn theme_option_switch(ui: &mut Ui, label: &str, on: &mut bool) { + let t = Tokens::get(); + let (rect, response) = ui.allocate_exact_size(vec2(t.space_24 + t.space_8, t.control_height), Sense::click()); + if response.clicked() { + *on = !*on; + } + let track = Rect::from_center_size(rect.center(), vec2(rect.width(), t.space_16 + t.space_2)); + ui.painter().rect_filled(track, t.radius_xl, if *on { t.form_primary_fill } else { t.control_border }); + let x = if *on { track.right() - t.space_8 - t.space_2 } else { track.left() + t.space_8 + t.space_2 }; + ui.painter().circle_filled(pos2(x, track.center().y), t.space_6, if *on { t.on_accent } else { t.form_ink }); + if response.has_focus() { + ui.painter().rect_stroke(rect, t.control_radius, Stroke::new(t.space_2, t.form_primary), egui::StrokeKind::Inside); + } + response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Checkbox, ui.is_enabled(), *on, label)); + scenario::publish_target(&format!("prefs:theme_option_switch:{label}"), response.rect); +} + /// Page scroller keeps content aligned while centring its bar in the window's right inset. /// Nested pages (including Shortcuts) inherit the same gutter and height contract. pub(crate) fn settings_scroll(ui: &mut Ui, id: impl egui::AsIdSalt, add: impl FnOnce(&mut Ui) -> R) -> egui::scroll_area::ScrollAreaOutput { diff --git a/crates/ui-egui/src/ui_kit/preferences_layout.rs b/crates/ui-egui/src/ui_kit/preferences_layout.rs new file mode 100644 index 000000000..f92b3c5cc --- /dev/null +++ b/crates/ui-egui/src/ui_kit/preferences_layout.rs @@ -0,0 +1,103 @@ +//! Pure ordered option packing. Composite descendants belong to their parent's single cell. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum Width { + Narrow, + Composite, + Wide, +} + +pub(crate) struct Entry { + pub width: Width, + pub advanced: bool, + /// Measured minimum row width, including translated labels and controls. + pub minimum: f32, +} + +#[derive(Debug, PartialEq)] +pub(crate) struct Plan { + pub rows: Vec>, + pub more: Vec>, + pub more_count: usize, + pub section_labels: bool, +} + +pub(crate) fn choice_width(values: usize) -> Width { + if (4..=5).contains(&values) { Width::Wide } else { Width::Narrow } +} + +/// `width` is the usable width after the caller subtracts the inter-column gutter. +pub(crate) fn layout(entries: &[Entry], width: f32) -> Plan { + let mut main = Vec::new(); + let mut more = Vec::new(); + for (i, entry) in entries.iter().enumerate() { + if entry.advanced || main.len() >= 10 { + more.push(i); + } else { + main.push(i); + } + } + let pack = |indices: &[usize]| { + let mut rows: Vec> = Vec::new(); + let mut pending = Vec::new(); + for &i in indices { + let Some(entry) = entries.get(i) else { continue }; + let wide = entry.width == Width::Wide || !width.is_finite() || entry.minimum > width.max(0.0) / 2.0; + if wide { + if !pending.is_empty() { + rows.push(std::mem::take(&mut pending)); + } + rows.push(vec![i]); + } else { + pending.push(i); + if pending.len() == 2 { + rows.push(std::mem::take(&mut pending)); + } + } + } + if !pending.is_empty() { + rows.push(pending); + } + rows + }; + Plan { rows: pack(&main), more: pack(&more), more_count: more.len(), section_labels: entries.len() > 6 } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn theme_options_layout_counts_and_order() { + for count in [0_usize, 1, 2, 3, 6, 10, 12] { + let entries: Vec<_> = (0..count).map(|_| Entry { width: Width::Narrow, advanced: false, minimum: 100.0 }).collect(); + let plan = layout(&entries, 600.0); + assert_eq!(plan.rows.iter().flatten().copied().collect::>(), (0..count.min(10)).collect::>()); + assert_eq!(plan.more.iter().flatten().copied().collect::>(), (10..count).collect::>()); + assert_eq!(plan.rows.len(), count.min(10).div_ceil(2)); + assert_eq!(plan.more_count, count.saturating_sub(10)); + assert_eq!(plan.section_labels, count > 6); + } + } + + #[test] + fn theme_options_layout_wide_composite_dropdown_advanced_and_width() { + let mut entries: Vec<_> = (0..13).map(|_| Entry { width: Width::Narrow, advanced: false, minimum: 100.0 }).collect(); + entries[1].width = Width::Wide; + entries[2].width = Width::Composite; + entries[3].advanced = true; + let plan = layout(&entries, 600.0); + assert_eq!(&plan.rows[..3], &[vec![0], vec![1], vec![2, 4]]); + assert_eq!(plan.rows.iter().flatten().count(), 10, "advanced does not consume the ten offered cells"); + assert_eq!(plan.more.iter().flatten().copied().collect::>(), [3, 11, 12]); + assert_eq!(choice_width(3), Width::Narrow); + assert_eq!(choice_width(4), Width::Wide); + assert_eq!(choice_width(5), Width::Wide); + assert_eq!(choice_width(6), Width::Narrow); + let advanced_only = [Entry { width: Width::Composite, advanced: true, minimum: 100.0 }]; + assert!(layout(&advanced_only, 600.0).rows.is_empty()); + assert_eq!(layout(&advanced_only, 600.0).more, [vec![0]], "advanced stays in More even below ten entries"); + entries[0].minimum = 350.0; + assert_eq!(layout(&entries, 600.0).rows[0], [0]); + assert!(layout(&entries, 150.0).rows.iter().all(|row| row.len() == 1)); + } +} diff --git a/crates/ui-egui/tests/fixtures/theme-options.json b/crates/ui-egui/tests/fixtures/theme-options.json new file mode 100644 index 000000000..a97d38bc8 --- /dev/null +++ b/crates/ui-egui/tests/fixtures/theme-options.json @@ -0,0 +1,658 @@ +{ + "light-0": { + "format": "solidcraft-theme/1", + "name": "Options light 0", + "base": "light", + "options": [] + }, + "light-1": { + "format": "solidcraft-theme/1", + "name": "Options light 1", + "base": "light", + "options": [ + { + "id": "opacity", + "type": "range", + "default": 100 + } + ] + }, + "light-3": { + "format": "solidcraft-theme/1", + "name": "Options light 3", + "base": "light", + "options": [ + { + "id": "opacity", + "type": "range", + "default": 100 + }, + { + "id": "warm", + "type": "bool", + "default": false, + "label": { + "en": "Warm accent" + }, + "section": "Theme controls" + }, + { + "id": "palette", + "type": "choice", + "default": "v1", + "label": { + "en": "Palette" + }, + "values": [ + { + "id": "v1", + "label": { + "en": "Soft" + } + }, + { + "id": "v2", + "label": { + "en": "Warm" + } + }, + { + "id": "v3", + "label": { + "en": "Cool" + } + } + ] + } + ] + }, + "light-6": { + "format": "solidcraft-theme/1", + "name": "Options light 6", + "base": "light", + "options": [ + { + "id": "opacity", + "type": "range", + "default": 100 + }, + { + "id": "warm", + "type": "bool", + "default": false, + "label": { + "en": "Warm accent" + }, + "section": "Theme controls" + }, + { + "id": "palette", + "type": "choice", + "default": "v1", + "label": { + "en": "Palette" + }, + "values": [ + { + "id": "v1", + "label": { + "en": "Soft" + } + }, + { + "id": "v2", + "label": { + "en": "Warm" + } + }, + { + "id": "v3", + "label": { + "en": "Cool" + } + } + ] + }, + { + "id": "radius", + "type": "range", + "default": 5, + "min": 0, + "max": 10, + "step": 0.5, + "unit": "px", + "label": { + "en": "Rounding" + } + }, + { + "id": "shadow", + "type": "bool", + "default": false, + "label": { + "en": "Shadow" + } + }, + { + "id": "details", + "type": "bool", + "default": false, + "label": { + "en": "Details" + } + } + ] + }, + "light-12": { + "format": "solidcraft-theme/1", + "name": "Options light 12", + "base": "light", + "options": [ + { + "id": "opacity", + "type": "range", + "default": 100 + }, + { + "id": "warm", + "type": "bool", + "default": false, + "label": { + "en": "Warm accent" + }, + "section": "Theme controls" + }, + { + "id": "palette", + "type": "choice", + "default": "v1", + "label": { + "en": "Palette" + }, + "values": [ + { + "id": "v1", + "label": { + "en": "Soft" + } + }, + { + "id": "v2", + "label": { + "en": "Warm" + } + }, + { + "id": "v3", + "label": { + "en": "Cool" + } + }, + { + "id": "v4", + "label": { + "en": "Bold" + } + } + ] + }, + { + "id": "radius", + "type": "range", + "default": 5, + "min": 0, + "max": 10, + "step": 0.5, + "unit": "px", + "label": { + "en": "Rounding" + } + }, + { + "id": "shadow", + "type": "bool", + "default": true, + "label": { + "en": "Shadow" + } + }, + { + "id": "softness", + "type": "range", + "default": 5, + "min": 0, + "max": 10, + "step": 0.5, + "unit": "px", + "label": { + "en": "Softness" + }, + "parent": "shadow" + }, + { + "id": "details", + "type": "bool", + "default": false, + "label": { + "en": "Details" + } + }, + { + "id": "pattern", + "type": "choice", + "default": "v1", + "label": { + "en": "Pattern" + }, + "values": [ + { + "id": "v1", + "label": { + "en": "Soft" + } + }, + { + "id": "v2", + "label": { + "en": "Warm" + } + }, + { + "id": "v3", + "label": { + "en": "Cool" + } + }, + { + "id": "v4", + "label": { + "en": "Bold" + } + }, + { + "id": "v5", + "label": { + "en": "Muted" + } + }, + { + "id": "v6", + "label": { + "en": "Plain" + } + } + ] + }, + { + "id": "grid_tint", + "type": "bool", + "default": false, + "label": { + "en": "Tint grid" + } + }, + { + "id": "strong_edges", + "type": "bool", + "default": false, + "label": { + "en": "Strong edges" + } + }, + { + "id": "compact", + "type": "bool", + "default": false, + "label": { + "en": "Compact" + } + }, + { + "id": "extra", + "type": "bool", + "default": false, + "label": { + "en": "Extra" + }, + "advanced": true, + "section": "Fine tuning" + }, + { + "id": "outline", + "type": "bool", + "default": false, + "label": { + "en": "Outline" + } + } + ] + }, + "dark-0": { + "format": "solidcraft-theme/1", + "name": "Options dark 0", + "base": "dark", + "options": [] + }, + "dark-1": { + "format": "solidcraft-theme/1", + "name": "Options dark 1", + "base": "dark", + "options": [ + { + "id": "opacity", + "type": "range", + "default": 100 + } + ] + }, + "dark-3": { + "format": "solidcraft-theme/1", + "name": "Options dark 3", + "base": "dark", + "options": [ + { + "id": "opacity", + "type": "range", + "default": 100 + }, + { + "id": "warm", + "type": "bool", + "default": false, + "label": { + "en": "Warm accent" + }, + "section": "Theme controls" + }, + { + "id": "palette", + "type": "choice", + "default": "v1", + "label": { + "en": "Palette" + }, + "values": [ + { + "id": "v1", + "label": { + "en": "Soft" + } + }, + { + "id": "v2", + "label": { + "en": "Warm" + } + }, + { + "id": "v3", + "label": { + "en": "Cool" + } + } + ] + } + ] + }, + "dark-6": { + "format": "solidcraft-theme/1", + "name": "Options dark 6", + "base": "dark", + "options": [ + { + "id": "opacity", + "type": "range", + "default": 100 + }, + { + "id": "warm", + "type": "bool", + "default": false, + "label": { + "en": "Warm accent" + }, + "section": "Theme controls" + }, + { + "id": "palette", + "type": "choice", + "default": "v1", + "label": { + "en": "Palette" + }, + "values": [ + { + "id": "v1", + "label": { + "en": "Soft" + } + }, + { + "id": "v2", + "label": { + "en": "Warm" + } + }, + { + "id": "v3", + "label": { + "en": "Cool" + } + } + ] + }, + { + "id": "radius", + "type": "range", + "default": 5, + "min": 0, + "max": 10, + "step": 0.5, + "unit": "px", + "label": { + "en": "Rounding" + } + }, + { + "id": "shadow", + "type": "bool", + "default": false, + "label": { + "en": "Shadow" + } + }, + { + "id": "details", + "type": "bool", + "default": false, + "label": { + "en": "Details" + } + } + ] + }, + "dark-12": { + "format": "solidcraft-theme/1", + "name": "Options dark 12", + "base": "dark", + "options": [ + { + "id": "opacity", + "type": "range", + "default": 100 + }, + { + "id": "warm", + "type": "bool", + "default": false, + "label": { + "en": "Warm accent" + }, + "section": "Theme controls" + }, + { + "id": "palette", + "type": "choice", + "default": "v1", + "label": { + "en": "Palette" + }, + "values": [ + { + "id": "v1", + "label": { + "en": "Soft" + } + }, + { + "id": "v2", + "label": { + "en": "Warm" + } + }, + { + "id": "v3", + "label": { + "en": "Cool" + } + }, + { + "id": "v4", + "label": { + "en": "Bold" + } + } + ] + }, + { + "id": "radius", + "type": "range", + "default": 5, + "min": 0, + "max": 10, + "step": 0.5, + "unit": "px", + "label": { + "en": "Rounding" + } + }, + { + "id": "shadow", + "type": "bool", + "default": true, + "label": { + "en": "Shadow" + } + }, + { + "id": "softness", + "type": "range", + "default": 5, + "min": 0, + "max": 10, + "step": 0.5, + "unit": "px", + "label": { + "en": "Softness" + }, + "parent": "shadow" + }, + { + "id": "details", + "type": "bool", + "default": false, + "label": { + "en": "Details" + } + }, + { + "id": "pattern", + "type": "choice", + "default": "v1", + "label": { + "en": "Pattern" + }, + "values": [ + { + "id": "v1", + "label": { + "en": "Soft" + } + }, + { + "id": "v2", + "label": { + "en": "Warm" + } + }, + { + "id": "v3", + "label": { + "en": "Cool" + } + }, + { + "id": "v4", + "label": { + "en": "Bold" + } + }, + { + "id": "v5", + "label": { + "en": "Muted" + } + }, + { + "id": "v6", + "label": { + "en": "Plain" + } + } + ] + }, + { + "id": "grid_tint", + "type": "bool", + "default": false, + "label": { + "en": "Tint grid" + } + }, + { + "id": "strong_edges", + "type": "bool", + "default": false, + "label": { + "en": "Strong edges" + } + }, + { + "id": "compact", + "type": "bool", + "default": false, + "label": { + "en": "Compact" + } + }, + { + "id": "extra", + "type": "bool", + "default": false, + "label": { + "en": "Extra" + }, + "advanced": true, + "section": "Fine tuning" + }, + { + "id": "outline", + "type": "bool", + "default": false, + "label": { + "en": "Outline" + } + } + ] + } +} diff --git a/crates/ui-egui/tests/scenarios/prefs_theme_files.json b/crates/ui-egui/tests/scenarios/prefs_theme_files.json index d93995b09..7485932d9 100644 --- a/crates/ui-egui/tests/scenarios/prefs_theme_files.json +++ b/crates/ui-egui/tests/scenarios/prefs_theme_files.json @@ -15,5 +15,19 @@ {"call": "ui.prefs", "params": {"theme": "akari"}}, {"expect": {"prefs": {"theme": "akari", "dark": false}}}, {"call": "ui.prefs", "params": {"theme": "okibi"}}, - {"expect": {"prefs": {"theme": "okibi", "dark": true}}} + {"expect": {"prefs": {"theme": "okibi", "dark": true}}}, + {"note":"#9806: per-theme option overrides apply through ui.prefs and keep authored export defaults."}, + {"call":"ui.prefs","params":{"theme_import":{"format":"solidcraft-theme/1","name":"Scenario Options","base":"dark","colors":{"panel":"#112233"},"options":[{"id":"enabled","type":"bool","default":false}],"overlays":[{"when":{"opt":"enabled","eq":true},"colors":{"panel":"#abcdef"}}]},"theme_options":{"scenario-options":{"enabled":true}}}}, + {"expect":{"prefs":{"theme":"scenario-options","theme_option_values":{"enabled":true},"theme_option_notices":[]},"theme_colors":{"panel":"#abcdef"}}}, + {"call":"ui.prefs","params":{"theme":"dark"}}, + {"expect":{"prefs":{"theme_option_values":{},"theme_option_notices":[]}}}, + {"call":"ui.prefs","params":{"theme":"scenario-options"}}, + {"expect":{"prefs":{"theme_option_values":{"enabled":true}},"theme_colors":{"panel":"#abcdef"}}}, + {"call":"ui.prefs","params":{"theme_options":{"scenario-options":{"enabled":false,"unknown":true}},"ui_scale":1.5},"fail":true}, + {"expect":{"prefs":{"theme_option_values":{"enabled":true},"ui_scale":1.0},"theme_colors":{"panel":"#abcdef"}}}, + {"call":"ui.prefs","params":{"theme_options":{"scenario-options":{"enabled":null}}}}, + {"expect":{"prefs":{"theme_option_values":{"enabled":false}},"theme_colors":{"panel":"#112233"}}}, + {"call":"ui.prefs","params":{"theme_options":{"scenario-options":{"enabled":true}}}}, + {"call":"ui.prefs","params":{"theme_options":{"scenario-options":{}}}}, + {"expect":{"prefs":{"theme_options":{},"theme_option_values":{"enabled":false}},"theme_colors":{"panel":"#112233"}}} ] diff --git a/docs/book/src/guide/ui-tour.md b/docs/book/src/guide/ui-tour.md index 24ae3cc86..27e763331 100644 --- a/docs/book/src/guide/ui-tour.md +++ b/docs/book/src/guide/ui-tour.md @@ -294,10 +294,27 @@ vision modes still apply on top of any theme. #### Theme-file options and overlays -Theme authors can add `options` and `overlays` to `solidcraft-theme/1`. This is a file-format -and resolver API; this version has no controls for changing or saving option values. Import -uses the declared defaults. Existing files need no changes, and **Export…** still writes a -complete snapshot of the resolved colours, radii, borders and icon palette. +Theme authors can add `options` and `overlays` to `solidcraft-theme/1`. Offered options appear +below the theme cards in Interface, with the theme's name. Switches, sliders, segmented choices +and dropdowns apply immediately and are saved per theme, including a followed theme file. +**Reset** appears when an offered value differs from its default and restores that theme's +defaults through the same preference update path. Cancel retains its existing behaviour of +restoring the Preferences window's opening snapshot. Themes with no offered options add no +options block or badge. Existing theme files need no changes or appearance changes. + +Options flow left to right into two columns. A parent and its child occupy one cell; turning +the parent off disables its child without forgetting the child's value. Choices with four or +five values and long labels take a full row; choices with more than five values use a dropdown. +The first ten non-advanced top-level entries appear before **More · N**; advanced entries and +overflow always appear inside it. Section labels appear only above six top-level entries. +Help is available on hover. A registered behaviour unavailable on the current device stays +disabled in its place with a reason; unimplemented standard behaviours and their children +are absent. Theme cards show an Options badge only when the theme offers controls. + +**Export…** preserves the authored definitions and overlays for a theme that declares them. +Older themes still export a complete token snapshot. The resolver API clamps numeric values; +invalid saved preference values instead fall back to the theme's defaults, retaining the raw +saved values for compatibility. For example, add these two keys alongside a theme's `colors`: @@ -336,7 +353,8 @@ For example, add these two keys alongside a theme's `colors`: ``` A file can declare up to 16 options. Each `id` is unique and matches -`[a-z][a-z0-9_]{0,31}`. Every option has a `type` and `default`: +`[a-z][a-z0-9_]{0,31}`. Every option has a `type` and a `default` (opacity may omit its +default to use 100): - `bool`: the default is `true` or `false`. - `choice`: `values` contains 2 to 12 entries, each with a unique `id` in the same syntax @@ -369,10 +387,21 @@ A theme declares these with their required type and a default; it may also narro presentation text, `step` (fixed at 1 for standard ranges), unit and parent. A wrong type or bounds outside the standard range are import errors. Declaring `tab_fade_ms` also requires declaring its boolean parent, `tab_colours`. Custom options cannot redefine reserved ids. -These declarations alone do not change opacity, blur or tab behaviour in this version. +Only `opacity` currently has a registered standard behaviour. `blur`, `tab_colours` and +`tab_fade_ms` remain absent from the list until their behaviours are registered. The resolver exposes declared standard options in the order `opacity`, `blur`, `tab_colours`, each immediately followed by its child, then custom options in declared order. +Opacity scales only these floating surface fill tokens: `panel`, `panel_header`, `dialog_bg`, +`dialog_body`, `dialog_footer`, `overlay` and `nav_tip`. Scaling is applied after matching +overlays. All other tokens, including text, icons, borders, controls, viewport and document +colours, retain their resolved values. At 100%, with the implicit 100% default, or without +offered opacity, every token is exactly the original resolved value. The supported range is +40–100%; the theme may narrow it. To keep normal text at 4.5:1 against a panel over black and +white viewport extremes, each fill's actual alpha rises as necessary. This also protects +against background overrides and busy models. A theme whose authored foreground and opaque +fill already fail contrast receives full alpha; opacity never rewrites the theme's text colours. + Up to 32 overlays apply in file order, after the base palette and the theme's own value tables. Later matching entries win by key. Every overlay has one `when`: `{"opt":"id","eq":value}` for an exact, correctly typed comparison, or `gte`, `lte`, or both for inclusive range bounds. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 7d06213ed..0a7317052 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -397,7 +397,7 @@ no box selection. | `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?`, `slot?`, `replace?` | a command's keys (`key`: the first, shown in menus; `keys`: all), or rebinds it: `key` becomes its only key, or with `slot` replaces its key there (one past the last adds a key, `""` there removes that key); `""` without `slot` clears them; key names are case-insensitive and modifiers are normalized (`shift+ctrl+t` becomes `Ctrl+Shift+T`); unknown and reserved keys are refused; a key another command uses is refused unless `replace` | | `ui.help` | `item?`: `about`, `updates` (checks for updates and shows the result), `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 the [`ui.prefs` settings](#uiprefs-settings) below; also `open`, `button` and `stand_up` (listed there) | sets preferences (kept between runs), returns them all plus `dialog` (the open page or null), `apply_enabled` (whether the dialog's Apply has a change to keep), `dark`, `viewport_dark` (whether the 3D view is dark), `stand_up_offer` (the offered bodies, or null), `stand_up_note` (whether that offer is the note), `theme_followed` and `theme_follow_error` | +| `ui.prefs` | any of the [`ui.prefs` settings](#uiprefs-settings) below; also `open`, `button` and `stand_up` (listed there) | sets preferences (kept between runs), returns them all plus `dialog` (the open page or null), `apply_enabled` (whether the dialog's Apply has a change to keep), `dark`, `viewport_dark` (whether the 3D view is dark), `stand_up_offer` (the offered bodies, or null), `stand_up_note` (whether that offer is the note), `theme_followed`, `theme_follow_error`, `theme_option_defs`, `theme_option_values` and `theme_option_notices` | | `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 | @@ -487,10 +487,11 @@ One setting per line, sorted by name. A change that adds a setting adds its own - `status_bar` (default false: a thin bar along the window's bottom edge, below History, handle `status:bar`: what is being edited (`status:editing`), the open sketch's state in its colour (`status:sketch`) and the design's units (`status:units`, a click opens the Units menu, whose rows run `document.units`); the sketch's state then leaves the view's top-left corner, #7243) - `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) -- `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_export: true` (the reply's `theme_file` is the active theme, including a followed file; themes with options retain their authored definitions, defaults and overlays, while older themes keep the complete snapshot shape; saved option values are excluded; 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) - `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_options` (default `{}`): a map of theme id to option-id/value map, merged per theme; `{"theme_options":{"my-theme":{"enabled":true,"amount":5}}}` changes those options, `null` resets one option, and an empty map resets that theme. Unknown themes or option ids, wrong types, unknown choices and out-of-range numbers refuse the entire call and name the key, before imports, removals, dialogs or other preference effects occur. +- `theme_remove` (an imported theme's id; also removes its saved option values) - `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) - `toast_place` (`corner` (default: notices and offers stack in one column in the view's bottom-right corner, each 360 points wide, buttons right-aligned with the main action right-most, #7893), `centre` (at the bottom centre above the view toolbar, each as wide as its text, as before)) - `trackpad_pan` (default true: two-finger scroll pans, except Touchpad always zooms; pinch zooms) @@ -506,6 +507,23 @@ One setting per line, sorted by name. A change that adds a setting adds its own - `zoom_stop_at_model` (default false: the 3D mouse and navigation bridge stop zoom at the surface in the middle of the view; drag-zoom holds its press point; independent of `zoom_to_cursor`) - `zoom_to_cursor` +Theme option values persist per theme, including a followed file's own id, through the same +preference store in the browser and on desktop. Switching themes restores their saved values; +Interface's Restore Defaults clears them. Preference exports and settings profiles carry values; +`theme_export` carries the author's defaults. Saved entries that no longer fit a definition remain +stored and use the default with a notice; unknown ids have a notice and no effective value. + +For the active theme, `theme_option_defs` lists the declared options in `ordered_options` order: +`id`, `type`, `default`, type-specific `min`, `max`, `step`, `unit` or choice `values` (each with +`id` and `label`), `parent`, `advanced`, `section`, `label`, `help`, `standard` and `available`. +Labels, help and choice labels use the current language with English fallback. Unavailable +definitions include `reason`; standard options currently have `available: false` and +`reason: "not implemented"`. `theme_option_values` contains the effective values, including +defaults and values of inactive children. `theme_option_notices` contains `{id, kind}` entries, +where `kind` is `unknown_option`, `wrong_type`, `unknown_choice`, `non_finite` or `out_of_range`. +Without an active theme file these fields are `[]`, `{}` and `[]`. Portable input +and output schema types live in `solidcraft_engine::schema::ui_prefs` (`PrefsParams`, `PrefsReply`). + Other `ui.prefs` parameters: - `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 diff --git a/docs/ui-kit.md b/docs/ui-kit.md index c2601dcd7..a5b0b1847 100644 --- a/docs/ui-kit.md +++ b/docs/ui-kit.md @@ -156,6 +156,34 @@ four workspace choices without opening another viewport. Scale, palette, autosav and live-axis specimens share tokens and the gallery; live bars show actual calibrated input and introduce no repaint timer. +`theme_options_list` renders generic `ThemeOptionRow` definitions without standard-option +branches. Its pure `preferences_layout::layout` packs measured narrow/composite/wide entries +in order, with ten non-advanced top-level cells before More. A composite retains its child in +one cell; advanced descendants move the entire cell under More. Packing and allocation share +measured localized label/readout widths, the form gutter and a compact slider minimum; short +composites can share a row with narrow entries. A composite takes a full row when needed and +stacks its controls only if they exceed that entire row's width. `theme_options_badge` paints +inside an existing theme card and is called only for offered options. The small registry in +`theme_options.rs` supplies standard label/help catalog ids, availability and behaviour; +only opacity is registered today. Missing providers are absent; unavailable registered +providers keep their controls and show their translated reason. Callers submit list edits +and Reset through the existing atomic preference merge/control path. +The scoped `i18n::resolved_labels` adapter keeps theme language-map text and fallback labels +verbatim through shared controls, while stable catalog messages continue to translate. + +Review fixtures are in `crates/ui-egui/tests/fixtures/theme-options.json`, keyed by +`light-0/1/3/6/12` and `dark-0/1/3/6/12`. Each value is a complete importable theme file: +pass it as `ui.prefs` `theme_import` together with `open: "Interface"`. The 12-entry files +include a four-choice wide row, Shadow/Softness composite, six-choice dropdown, an advanced +entry and overflow. More contains two top-level entries. Set +`theme_options: {"options-dark-12": {"opacity": 60}}` (or the selected fixture's id) to +compare with 100 on a busy model. Reset uses `prefs:theme_options_reset`; More uses +`prefs:theme_options_more`; controls and cells publish `prefs:theme_option:` and +`prefs:theme_option_cell:`. Unavailable-provider specimens are internal to the existing +`prefs::tests::theme_options_provider_registry_filters_unknown_and_retains_unavailable` test; +they are never installed in the live registry or exposed as preferences. The manager captures +and reviews live-app screenshot evidence separately from the headless harness tests. + ## Elements `aspect_grid` composes three-column `AspectTile` choices with token-sized aspect glyphs,