SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Appearance: browse themes in a carousel or grid, filter them, and set Day and Night themes (#12120)
Nathan Daneedb788281523
diff --git a/assets/locales/pending/theme-picker.json b/assets/locales/pending/theme-picker.jsonnew file mode 100644index 0000000000..95cd1b1506--- /dev/null+++ b/assets/locales/pending/theme-picker.json@@ -0,0 +1,110 @@+{+ "ar": {+ "prefs.picker.carousel": "عرض دوّار",+ "prefs.picker.change": "تغيير",+ "prefs.picker.clear": "مسح عوامل التصفية",+ "prefs.picker.day": "سمة النهار",+ "prefs.picker.empty": "لا توجد سمة تطابق عوامل التصفية هذه.",+ "prefs.picker.follow": "اتباع النظام",+ "prefs.picker.grid": "شبكة",+ "prefs.picker.high": "تباين عالٍ",+ "prefs.picker.high_note": "{source} · تباين عالٍ",+ "prefs.picker.hint": "تتغير تلقائيًا مع نظام التشغيل.",+ "prefs.picker.import": "استيراد ملف سمة…",+ "prefs.picker.imported": "مستوردة",+ "prefs.picker.night": "سمة الليل",+ "prefs.picker.one": "سمة واحدة",+ "prefs.picker.pick": "اختيار من الأسفل",+ "prefs.picker.standard": "قياسي"+ },+ "en": {+ "prefs.picker.carousel": "Carousel",+ "prefs.picker.change": "Change",+ "prefs.picker.clear": "Clear filters",+ "prefs.picker.day": "Day theme",+ "prefs.picker.empty": "No theme matches these filters.",+ "prefs.picker.follow": "Follow system",+ "prefs.picker.grid": "Grid",+ "prefs.picker.high": "High contrast",+ "prefs.picker.high_note": "{source} · High contrast",+ "prefs.picker.hint": "Switches with your operating system.",+ "prefs.picker.import": "Import theme file…",+ "prefs.picker.imported": "Imported",+ "prefs.picker.night": "Night theme",+ "prefs.picker.one": "One theme",+ "prefs.picker.pick": "Pick from below",+ "prefs.picker.standard": "Standard"+ },+ "he": {+ "prefs.picker.carousel": "קרוסלה",+ "prefs.picker.change": "שינוי",+ "prefs.picker.clear": "ניקוי מסננים",+ "prefs.picker.day": "ערכת נושא ליום",+ "prefs.picker.empty": "אין ערכת נושא שתואמת למסננים האלה.",+ "prefs.picker.follow": "לפי המערכת",+ "prefs.picker.grid": "רשת",+ "prefs.picker.high": "ניגודיות גבוהה",+ "prefs.picker.high_note": "{source} · ניגודיות גבוהה",+ "prefs.picker.hint": "מתחלפת בהתאם למערכת ההפעלה.",+ "prefs.picker.import": "ייבוא קובץ ערכת נושא…",+ "prefs.picker.imported": "מיובאות",+ "prefs.picker.night": "ערכת נושא ללילה",+ "prefs.picker.one": "ערכת נושא אחת",+ "prefs.picker.pick": "בחירה מהרשימה למטה",+ "prefs.picker.standard": "רגילה"+ },+ "ja": {+ "prefs.picker.carousel": "カルーセル",+ "prefs.picker.change": "変更",+ "prefs.picker.clear": "フィルターをクリア",+ "prefs.picker.day": "日中のテーマ",+ "prefs.picker.empty": "このフィルターに一致するテーマはありません。",+ "prefs.picker.follow": "システムに合わせる",+ "prefs.picker.grid": "グリッド",+ "prefs.picker.high": "ハイコントラスト",+ "prefs.picker.high_note": "{source} · ハイコントラスト",+ "prefs.picker.hint": "OSの設定に合わせて切り替わります。",+ "prefs.picker.import": "テーマファイルをインポート…",+ "prefs.picker.imported": "インポート済み",+ "prefs.picker.night": "夜間のテーマ",+ "prefs.picker.one": "単一のテーマ",+ "prefs.picker.pick": "下から選択",+ "prefs.picker.standard": "標準"+ },+ "vi": {+ "prefs.picker.carousel": "Băng chuyền",+ "prefs.picker.change": "Thay đổi",+ "prefs.picker.clear": "Xóa bộ lọc",+ "prefs.picker.day": "Giao diện ban ngày",+ "prefs.picker.empty": "Không có giao diện nào khớp với các bộ lọc này.",+ "prefs.picker.follow": "Theo hệ thống",+ "prefs.picker.grid": "Lưới",+ "prefs.picker.high": "Tương phản cao",+ "prefs.picker.high_note": "{source} · Tương phản cao",+ "prefs.picker.hint": "Tự động chuyển theo hệ điều hành.",+ "prefs.picker.import": "Nhập tệp giao diện…",+ "prefs.picker.imported": "Đã nhập",+ "prefs.picker.night": "Giao diện ban đêm",+ "prefs.picker.one": "Một giao diện",+ "prefs.picker.pick": "Chọn bên dưới",+ "prefs.picker.standard": "Tiêu chuẩn"+ },+ "zh": {+ "prefs.picker.carousel": "轮播",+ "prefs.picker.change": "更改",+ "prefs.picker.clear": "清除筛选条件",+ "prefs.picker.day": "日间主题",+ "prefs.picker.empty": "没有符合这些筛选条件的主题。",+ "prefs.picker.follow": "跟随系统",+ "prefs.picker.grid": "网格",+ "prefs.picker.high": "高对比度",+ "prefs.picker.high_note": "{source} · 高对比度",+ "prefs.picker.hint": "随操作系统设置自动切换。",+ "prefs.picker.import": "导入主题文件…",+ "prefs.picker.imported": "已导入",+ "prefs.picker.night": "夜间主题",+ "prefs.picker.one": "单一主题",+ "prefs.picker.pick": "从下方选择",+ "prefs.picker.standard": "标准"+ }+}diff --git a/crates/ui-egui/src/navigation.rs b/crates/ui-egui/src/navigation.rsindex 9aaf7323a5..e03b418492 100644--- a/crates/ui-egui/src/navigation.rs+++ b/crates/ui-egui/src/navigation.rs@@ -21,6 +21,22 @@ use crate::prefs::{OrbitAround, pivot_under};use crate::space_mouse::{BridgeMotion, Motion};use crate::viewport::{Hit, NavMode, axis_rect, nearest_quarter_turn, pick, pick_cached, projection};+/// Take a predominantly horizontal wheel gesture for a hovered scroll viewport.+/// Leave vertical input for its enclosing page, and leave horizontal input+/// unconsumed when this viewport is already at the requested end.+pub(crate) fn take_horizontal_wheel(ui: &egui::Ui, offset: f32, max_offset: f32) -> f32 {+ ui.input_mut(|input| {+ let delta = input.smooth_scroll_delta;+ if delta.x == 0.0 || delta.x.abs() <= delta.y.abs() {+ return 0.0;+ }+ if (offset - delta.x).clamp(0.0, max_offset) != offset {+ input.smooth_scroll_delta.x = 0.0;+ }+ delta.x+ })+}+/// What a page's camera may do.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub(crate) struct NavCaps {diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rsindex f6f3b3db3f..6a76269e7f 100644--- a/crates/ui-egui/src/prefs.rs+++ b/crates/ui-egui/src/prefs.rs@@ -31,6 +31,7 @@ mod mouse3d;mod navbar;mod navigation;mod sketch;+mod theme_picker;mod tools;use crate::SolveApp;@@ -1262,6 +1263,10 @@ preference_settings! {theme: String = "dark".into(), PAGE_APPEARANCE;/// A picture behind the model in place of the view's background; empty for none.background_image: String = String::new(), PAGE_APPEARANCE;+ /// Theme used when the operating system is light; unknown ids resolve to Light.+ theme_day: String = "light".into(), PAGE_APPEARANCE;+ /// Theme used when the operating system is dark; unknown ids resolve to Dark.+ theme_night: String = "dark".into(), PAGE_APPEARANCE;/// The 3D view's colours: the theme's own, or the Light or Dark theme's whatever the window/// uses (#4146).viewport_theme: crate::theme::ViewportTheme = crate::theme::ViewportTheme::Theme, PAGE_APPEARANCE;@@ -1732,6 +1737,10 @@ pub struct PrefsWindow {applied_profile: Option<bool>,/// The appearance last asked of the native window ([`sync_window_theme`]).window_theme: Option<egui::SystemTheme>,+ /// Last observed OS tone, independent of the selected theme's tone.+ system_theme_dark: Option<bool>,+ /// Import callbacks fill the same slot as a card click; never persisted in preferences.+ theme_picker_night: bool,/// The perspective angle the view was last drawn with ([`follow_view_fov`]); 0 before the first.drawn_fov: f64,/// The search text of the interface font list.@@ -2021,151 +2030,10 @@ pub(crate) fn held_overlay(app: &SolveApp) -> Option<serde_json::Map<String, ser/// ones, with Import…, Export… (the theme on now as a complete file, to start a new one from)/// and Remove (an imported theme). Like the other preferences, a choice applies at once.fn theme_row(app: &mut SolveApp, ui: &mut egui::Ui) {- let mut choices = theme_choices(app);- // While a file is followed (#7573) it is the theme, so no tile shows as chosen.- let following = !app.prefs_window.follow.path(&app.preferences.theme_follow).is_empty();- choices.sort_by_key(|(id, _)| match id.as_str() {- "light" => 0,- "dark" => 1,- "system" => 2,- _ => 3,- });- let mut tile_action: Option<(&str, String)> = None;- let mut action_theme: Option<String> = None;- let mut chosen: Option<String> = None;- let mut action: Option<&str> = None;- let mut import_tile = None;- let t = Tokens::get();- let width = t.space_24 * 3.0 + t.space_16;- let height = t.space_24 * 4.0;- let dark_sample = ui_kit::ThemeSample::from_tokens(&Tokens::dark());- let carousel_id = "appearance_themes";- // Reveal the active theme after a programmatic selection or import too.- let selection_key = ui.make_persistent_id((carousel_id, "selection"));- let carousel_key = ui.make_persistent_id(carousel_id);- ui.data_mut(|data| {- if data.get_temp::<String>(selection_key).as_deref() != Some(app.preferences.theme.as_str()) {- let index = choices.iter().position(|(id, _)| id == &app.preferences.theme).unwrap_or(0);- data.insert_temp(carousel_key, index.saturating_sub(1));- data.insert_temp(selection_key, app.preferences.theme.clone());- }- });- let mut item = |ui: &mut egui::Ui, index: usize| {- if let Some((id, label)) = choices.get(index) {- let palette = match id.as_str() {- "light" | "system" => Tokens::light(),- "dark" => 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" {- "prefs.follows_os"- } else if custom {- "prefs.imported_file"- } else {- "prefs.built_in"- });- let options = crate::theme_files::find(id, &app.preferences.custom_themes)- .is_some_and(|file| !crate::theme_options::offered(file, crate::theme_options::PROVIDERS).is_empty());- if crate::prefs_search::querying(ui) && !crate::prefs_search::visible(ui, &[label, note]) {- return;- }- let sample = ui_kit::ThemeSample::from_tokens(&palette);- let response = ui_kit::picture_card(- ui,- &ui_kit::Card {- label,- sub: Some(note),- selected: !following && app.preferences.theme == *id,- enabled: true,- options: options.then(|| app.tr("prefs.theme_options_badge")),- check: false,- aspect: 124.0 / 76.0,- figure: &|p, rect| {- if id == "system" {- ui_kit::paint_theme_system(p, rect, &sample, &dark_sample);- } else {- ui_kit::paint_theme_thumbnail(p, rect, &sample);- }- },- },- width.min(ui.available_width()),- );- if options {- 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 {- crate::scenario::publish_target("prefs:theme", response.rect);- }- if response.clicked() {- chosen = Some(id.clone());- }- ui_kit::Menu::context(&response, |ui| {- ui_kit::Menu::show(ui, Tokens::get().form_card_width, |ui| {- if ui_kit::MenuItem::new("theme_export", app.tr_label("Export…"), "export").show(ui).clicked() {- tile_action = Some(("export", id.clone()));- ui.close();- }- if custom {- let mut remove = ui_kit::MenuItem::new("theme_remove", app.tr_label("Remove"), "delete");- remove.danger = true;- if remove.show(ui).clicked() {- tile_action = Some(("remove", id.clone()));- ui.close();- }- }- });- });- } else {- let tile = ui_kit::theme_import_tile(ui, app.tr_label("Import…"), app.tr("prefs.theme_file"))- .backing_on_hover_text(app.tr("prefs.theme_import_hint"));- import_tile = Some(tile.rect);- if tile.clicked() {- action = Some("import");- }- // The keyboard's paste needs no menu; this is for touch screens and the browser's mouse users.- #[cfg(not(target_arch = "wasm32"))]- ui_kit::Menu::context(&tile, |ui| {- ui_kit::Menu::show(ui, Tokens::get().form_card_width, |ui| {- if ui_kit::MenuItem::new("theme_paste", app.tr("prefs.theme_paste"), "paste").show(ui).clicked() {- action = Some("paste");- ui.close();- }- });- });- }- };- if crate::prefs_search::suppress_chrome(ui) {- for index in 0..=choices.len() {- item(ui, index);- }- } else {- ui_kit::carousel(ui, carousel_id, choices.len() + 1, width, height, &mut item);- for (label, handle, help) in [- ("prefs.carousel_previous", "prefs:theme_previous", "prefs.appearance.previous_themes"),- ("prefs.carousel_next", "prefs:theme_next", "prefs.appearance.next_themes"),- ] {- if let Some(rect) = crate::scenario::rect_of(&format!("prefs:carousel:{}", crate::i18n::tr(label))) {- crate::scenario::publish_target(handle, rect);- ui.interact(rect, ui.make_persistent_id((handle, "help")), egui::Sense::hover()).backing_on_hover_text(app.tr(help));- }- }- }- app.prefs_window.import_tile = import_tile;- if let Some((kind, id)) = tile_action {- action = Some(kind);- action_theme = Some(id);- }- if let Some(id) = chosen {- // Choosing a theme stops following a file (#7573).- stop_following(app);- select_theme(app, &id);- ui.data_mut(|data| data.insert_temp(selection_key, id));- }+ theme_picker::row(app, ui);+}++fn theme_action(app: &mut SolveApp, ui: &mut egui::Ui, action: Option<&str>, action_theme: Option<String>) {match action {Some("import") => app.pick_open_for(&["json"], |app, path| {let Some(path) = path else { return };@@ -2183,7 +2051,7 @@ fn theme_row(app: &mut SolveApp, ui: &mut egui::Ui) {}}Some("export") => {- let system_dark = system_dark(app, ui.ctx()).unwrap_or(app.ui.dark);+ let system_dark = system_dark(app, ui.ctx()).unwrap_or_else(|| app.prefs_window.system_theme_dark.unwrap_or(app.ui.dark));let file = theme_file(app, action_theme.as_deref().unwrap_or(&app.preferences.theme), system_dark);let name = file.get("name").and_then(serde_json::Value::as_str).unwrap_or("Theme").to_string();let text = serde_json::to_string_pretty(&file).unwrap_or_default();@@ -2415,10 +2283,11 @@ pub fn apply(app: &mut SolveApp, ctx: &egui::Context) {up_axis_changed(app);}follow_view_fov(app);- if app.preferences.theme == "system"- && let Some(dark) = system_dark(app, ctx)- {- app.ui.dark = dark;+ let os_dark = system_dark(app, ctx).unwrap_or_else(|| app.prefs_window.system_theme_dark.unwrap_or(app.ui.dark));+ app.prefs_window.system_theme_dark = Some(os_dark);+ if app.preferences.theme == "system" {+ let id = theme_picker::active_id(&app.preferences, os_dark);+ app.ui.dark = crate::theme_files::find(id, &app.preferences.custom_themes).map_or(id == "dark", |f| f.base.is_dark());}// 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.@@ -2430,7 +2299,9 @@ pub fn apply(app: &mut SolveApp, ctx: &egui::Context) {if let Some(custom) = &custom {app.ui.dark = custom.dark;}- let follows_system = app.preferences.theme == "system" && custom.is_none();+ // Custom Day/Night palettes still need native OS appearance notifications. Fixing+ // the native window to the slot's tone can stop those notifications on macOS.+ let follows_system = app.preferences.theme == "system" && followed_theme(&app.preferences, &app.prefs_window.follow).is_none();if crate::theme::set_custom(custom) {app.styled = false;}@@ -3434,9 +3305,15 @@ fn button_jobs_that_read<'de, D: serde::Deserializer<'de>>(/// Every theme the Theme list offers, as (id, name): the modes, the built-in theme files, then/// the imported ones.fn theme_choices(app: &SolveApp) -> Vec<(String, String)> {- let modes = THEMES.iter().map(|(id, label)| ((*id).to_string(), crate::i18n::tr_label(label).to_string()));+ let modes = THEMES.iter().filter(|(id, _)| *id != "system").map(|(id, label)| ((*id).to_string(), crate::i18n::tr_label(label).to_string()));let files = crate::theme_files::builtin().iter().chain(&app.preferences.custom_themes).map(|t| (t.id.clone(), t.name.clone()));- modes.chain(files).collect()+ let mut choices: Vec<_> = modes.chain(files).collect();+ choices.sort_by_key(|(id, _)| match id.as_str() {+ "light" => 0,+ "dark" => 1,+ _ => 2,+ });+ choices}/// Turn a theme on (a mode or a theme file's id); dark follows it.@@ -3534,7 +3411,11 @@ pub fn import_theme(app: &mut SolveApp, v: &serde_json::Value) -> Result<String,other => crate::theme_files::from_value(other)?,};let id = crate::theme_files::add(&mut app.preferences.custom_themes, theme)?;- select_theme(app, &id);+ if app.prefs_window.open && app.prefs_window.section == PAGE_APPEARANCE {+ theme_picker::choose(app, app.prefs_window.theme_picker_night, &id);+ } else {+ select_theme(app, &id);+ }Ok(id)}@@ -3555,13 +3436,17 @@ fn remove_theme(app: &mut SolveApp, id: &str) -> Result<(), String> {fn current_theme_file(app: &SolveApp) -> serde_json::Value {match active_theme_file(app) {Some(f) => export_theme_file(f),- None => theme_file(app, &app.preferences.theme, app.ui.dark),+ None => theme_file(app, &app.preferences.theme, app.prefs_window.system_theme_dark.unwrap_or(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))+ followed_theme(&app.preferences, &app.prefs_window.follow).or_else(|| {+ crate::theme_files::find(+ theme_picker::active_id(&app.preferences, app.prefs_window.system_theme_dark.unwrap_or(app.ui.dark)),+ &app.preferences.custom_themes,+ )+ })}/// The single runtime decision used by controls, ui.prefs and renderer activation. It never@@ -3900,9 +3785,10 @@ fn theme_options_reply(app: &SolveApp) -> solidcraft_engine::schema::ui_prefs::T/// 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};+ let id = if id == "system" { theme_picker::slot_id(&app.preferences, system_dark) } else { id };match find(id, &app.preferences.custom_themes) {Some(f) => export_theme_file(f),- None if id == "dark" || (id == "system" && system_dark) => export("Dark", Base::Dark, &crate::theme::Tokens::dark()),+ None if id == "dark" => export("Dark", Base::Dark, &crate::theme::Tokens::dark()),None => export("Light", Base::Light, &crate::theme::Tokens::light()),}}@@ -4241,8 +4127,11 @@ pub(crate) fn reveal_preference(h: &mut crate::scenario::Harness, handle: &str)// Keep small scroll steps so a target cannot be skipped on a long Preferences page.for _ in 0..32 {let page = crate::scenario::rect_of("dialog:page_body").expect("preference body");+ // Scroll offsets are pixel-rounded: the final item can extend a fraction+ // of a point beyond the viewport even at the maximum scroll offset.+ // Match the tolerance used by the colour-vision sample geometry checks.let visible = crate::scenario::rect_of(handle)- .map(|r| page.contains_rect(r))+ .map(|r| page.expand(1.0).contains_rect(r)).unwrap_or_else(|| crate::scenario::handle_at(handle).is_some_and(|p| page.shrink(crate::theme::Tokens::get().space_16).contains(p)));if visible {return;@@ -4266,6 +4155,217 @@ pub(crate) fn reveal_preference(h: &mut crate::scenario::Harness, handle: &str)#[cfg(test)]mod tests {+ #[test]+ fn theme_traits_use_resolved_background_and_maximal_contrast() {+ use theme_picker::{Classification, theme_traits};+ let light = Tokens::light();+ let dark = Tokens::dark();+ assert_eq!(theme_traits(&light), Classification { dark: false, high: false });+ assert_eq!(theme_traits(&dark), Classification { dark: true, high: false });+ for (ground, ink, night) in [(egui::Color32::WHITE, egui::Color32::BLACK, false), (egui::Color32::BLACK, egui::Color32::WHITE, true)] {+ let mut palette = light;+ palette.dialog_footer = ground;+ palette.form_ink = ink;+ assert_eq!(theme_traits(&palette), Classification { dark: night, high: true });+ }+ let mut palette = light;+ for (gray, night) in [(187, true), (188, false)] {+ palette.dialog_footer = egui::Color32::from_gray(gray);+ assert_eq!(theme_traits(&palette).dark, night, "linear luminance straddles 0.5");+ }+ let maximal: Vec<_> = crate::theme_files::builtin()+ .iter()+ .filter(|f| theme_traits(&resolved_theme(&Prefs::default(), f)).high)+ .map(|f| f.id.as_str())+ .collect();+ assert_eq!(maximal.len(), 4, "ordinary palettes must stay Standard: {maximal:?}");+ assert!(maximal.contains(&"1-bit") && maximal.contains(&"1-bit-dark"));+ }++ #[test]+ fn theme_slots_default_persist_allow_command_access_and_restore_with_appearance() {+ let mut h = crate::scenario::Harness::new();+ assert_eq!((&h.app.preferences.theme_day[..], &h.app.preferences.theme_night[..]), ("light", "dark"));+ let out = super::set(&mut h.app, &json!({"theme_day":"akari", "theme_night":"onyx"})).unwrap();+ assert_eq!((out["theme_day"].as_str(), out["theme_night"].as_str()), (Some("akari"), Some("onyx")));+ let out = h.call("ui.prefs", json!({}));+ assert_eq!(out["result"]["theme_day"], "akari");+ assert_eq!(out["result"]["theme_night"], "onyx");+ let mut restored = SolveApp::new(solidcraft_engine::Session::default(), Default::default());+ restored.load_prefs(&h.app.prefs());+ assert_eq!((restored.preferences.theme_day.as_str(), restored.preferences.theme_night.as_str()), ("akari", "onyx"));+ h.call("ui.prefs", json!({"theme_day":"clay", "theme_night":"clay-dark", "open":"Appearance"}));+ assert_eq!(h.app.preferences.theme_day, "clay");+ defaults(&mut h.app, PAGE_GENERAL);+ assert_eq!(h.app.preferences.theme_day, "clay", "another page's reset does not clear slots");+ defaults(&mut h.app, PAGE_APPEARANCE);+ assert_eq!((h.app.preferences.theme_day.as_str(), h.app.preferences.theme_night.as_str()), ("light", "dark"));+ }++ #[test]+ fn theme_slots_resolve_unknown_and_recursive_ids_without_changing_saved_intent() {+ let mut prefs = Prefs { theme: "system".into(), theme_day: "missing".into(), theme_night: "system".into(), ..Default::default() };+ assert_eq!(theme_picker::active_id(&prefs, false), "light");+ assert_eq!(theme_picker::active_id(&prefs, true), "dark");+ assert_eq!((&prefs.theme_day[..], &prefs.theme_night[..]), ("missing", "system"));+ prefs.theme = "onyx".into();+ assert_eq!(theme_picker::active_id(&prefs, false), "onyx");+ assert_eq!(theme_picker::active_id(&prefs, true), "onyx");+ let mut h = crate::scenario::Harness::new();+ h.app.services.desktop_dark = Some(Box::new(|| Some(false)));+ let out = h.call("ui.prefs", json!({"theme":"system", "theme_day":"missing", "theme_night":"system"}));+ assert!(out["error"].is_null(), "{out}");+ h.frames(2);+ assert!(!h.app.ui.dark);+ assert_eq!(h.app.preferences.theme_day, "missing");+ h.app.services.desktop_dark = Some(Box::new(|| Some(true)));+ h.frames(2);+ assert!(h.app.ui.dark);+ assert_eq!(h.app.preferences.theme_night, "system");+ }++ #[test]+ fn theme_onyx_is_reachable_selectable_and_shows_its_options_in_both_views() {+ for grid in [false, true] {+ let mut h = crate::scenario::Harness::new();+ h.app.home.open = false;+ h.call("ui.resize", json!({"width":1467,"height":1146}));+ h.call("ui.prefs", json!({"language":"en","theme":"light","open":"Appearance"}));+ h.frames(5);+ if grid {+ h.step(&json!({"click":{"handle":"prefs:theme_view:1"}})).unwrap();+ h.frames(3);+ super::reveal_preference(&mut h, "prefs:theme_tile:onyx");+ } else {+ for _ in 0..theme_choices(&h.app).len() {+ if crate::scenario::rect_of("prefs:theme_tile:onyx").is_some() {+ break;+ }+ h.step(&json!({"click":{"handle":"prefs:theme_next"}})).unwrap();+ h.frames(3);+ }+ }+ h.step(&json!({"click":{"handle":"prefs:theme_tile:onyx"}})).unwrap();+ h.frames(4);+ assert_eq!(h.app.preferences.theme, "onyx");+ assert!(crate::scenario::rect_of("prefs:theme_options_badge:onyx").is_some());+ assert!(crate::scenario::rect_of("prefs:theme_options_header").is_some());+ let out = h.call("ui.prefs", json!({}));+ assert_eq!(out["result"]["theme_option_values"]["opacity"], 80.0);+ }+ }++ #[test]+ fn theme_system_resolves_custom_day_and_night_by_os_including_cross_tone_slots() {+ use std::sync::{+ Arc,+ atomic::{AtomicBool, Ordering},+ };+ let desktop = Arc::new(AtomicBool::new(false));+ let reading = desktop.clone();+ let mut h = crate::scenario::Harness::new();+ h.app.services.desktop_dark = Some(Box::new(move || Some(reading.load(Ordering::Relaxed))));+ h.call("ui.prefs", json!({"theme":"system", "theme_day":"onyx", "theme_night":"akari"}));+ h.frames(3);+ assert!(h.app.ui.dark, "the OS is light, but the Day slot may hold a dark theme");+ assert_eq!(h.app.prefs_window.window_theme, Some(egui::SystemTheme::SystemDefault));+ assert_eq!(active_theme_file(&h.app).unwrap().id, "onyx");+ assert_eq!(current_theme_file(&h.app)["name"], "Onyx");+ desktop.store(true, Ordering::Relaxed);+ h.frames(3);+ assert!(!h.app.ui.dark);+ assert_eq!(active_theme_file(&h.app).unwrap().id, "akari");+ h.call("ui.prefs", json!({"theme_day":"dark", "theme_night":"light"}));+ h.frames(2);+ assert_eq!(current_theme_file(&h.app)["base"], "light");+ desktop.store(false, Ordering::Relaxed);+ h.frames(2);+ assert_eq!(current_theme_file(&h.app)["base"], "dark");+ // If OS observation temporarily disappears, the mode button must use the same+ // remembered OS tone as rendering, rather than the cross-tone slot's palette.+ h.app.services.desktop_dark = Some(Box::new(|| None));+ h.app.home.open = false;+ h.call("ui.prefs", json!({"open":"Appearance"}));+ h.frames(3);+ h.step(&json!({"click":{"handle":"prefs:theme_mode:0"}})).unwrap();+ assert_eq!(h.app.preferences.theme, "dark", "leaving System preserves the theme actually in effect");+ }++ #[test]+ fn theme_mode_switches_preserve_the_effective_theme_and_fill_only_the_aimed_slot() {+ let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default());+ select_theme(&mut app, "onyx");+ theme_picker::switch_mode(&mut app, true, true);+ assert_eq!((&app.preferences.theme[..], &app.preferences.theme_day[..], &app.preferences.theme_night[..]), ("system", "light", "onyx"));+ theme_picker::choose(&mut app, false, "akari");+ assert_eq!((&app.preferences.theme[..], &app.preferences.theme_day[..], &app.preferences.theme_night[..]), ("system", "akari", "onyx"));+ theme_picker::switch_mode(&mut app, false, false);+ assert_eq!(app.preferences.theme, "akari", "leaving system picks the effective Day theme, not its tone's default");+ theme_picker::switch_mode(&mut app, true, false);+ theme_picker::choose(&mut app, true, "clay-dark");+ theme_picker::switch_mode(&mut app, false, true);+ assert_eq!(app.preferences.theme, "clay-dark");+ let mut state = theme_picker::State::default();+ assert!(!state.night && !state.grid && state.tone.is_none());+ state.aim(true);+ assert!(state.night && state.tone == Some(true));+ state.aim(false);+ assert!(!state.night && state.tone == Some(false));+ }++ #[test]+ fn theme_filter_counts_ignore_only_their_own_group() {+ let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default());+ let file = crate::theme_files::from_value(&json!({"format":"solidcraft-theme/1", "name":"Imported maximal", "base":"dark", "colors":{"dialog_footer":"#000000", "form_ink":"#ffffff"}})).unwrap();+ crate::theme_files::add(&mut app.preferences.custom_themes, file).unwrap();+ let entries = theme_picker::entries(&app);+ let state = theme_picker::State { tone: Some(true), high: Some(false), imported: false, ..Default::default() };+ assert_eq!((state.count(&entries, "tone", false), state.count(&entries, "tone", true)), (8, 14));+ assert_eq!((state.count(&entries, "contrast", false), state.count(&entries, "contrast", true)), (14, 4));+ assert_eq!(state.count(&entries, "imported", true), 0);+ let state = theme_picker::State { high: Some(true), imported: true, ..state };+ assert_eq!(state.count(&entries, "tone", true), 1);+ assert_eq!(state.count(&entries, "contrast", true), 1);+ assert_eq!(state.count(&entries, "contrast", false), 0);+ assert_eq!(state.count(&entries, "imported", true), 1);+ }++ #[test]+ fn theme_carousel_wheel_passes_vertical_to_page_and_handles_horizontal_and_shift() {+ let mut h = crate::scenario::Harness::new();+ h.app.home.open = false;+ h.call("ui.resize", json!({"width":1467,"height":1146}));+ h.call("ui.prefs", json!({"language":"en","theme":"light","open":"Appearance"}));+ h.frames(6);+ for (delta, modifiers, horizontal) in [+ (egui::vec2(1.0, -96.0), egui::Modifiers::NONE, false),+ (egui::vec2(-180.0, 0.0), egui::Modifiers::NONE, true),+ (egui::vec2(0.0, -180.0), egui::Modifiers::SHIFT, true),+ ] {+ let before = crate::scenario::rect_of("prefs:card:Light").unwrap();+ let at = crate::scenario::rect_of("prefs:theme_viewport").unwrap().center();+ h.frame_with(vec![+ egui::Event::PointerMoved(at),+ egui::Event::MouseWheel {+ source: egui::MouseWheelSource::Unknown,+ unit: egui::MouseWheelUnit::Point,+ delta,+ modifiers,+ phase: egui::TouchPhase::Move,+ },+ ]);+ h.frames(60);+ let after = crate::scenario::rect_of("prefs:card:Light").unwrap();+ if horizontal {+ assert!(after.left() < before.left() - 100.0, "horizontal wheel must move a card: {before:?} -> {after:?}");+ assert!((after.top() - before.top()).abs() < 1.0, "horizontal wheel must leave the page in place");+ } else {+ assert!((after.left() - before.left()).abs() < 1.0, "vertical wheel must not move carousel");+ assert!(after.top() < before.top() - 50.0, "vertical wheel must scroll the page");+ }+ }+ }+/// Profile operations switches the profiler when it changes, and only then: an agent's/// diagnostics.profile in between is not undone next frame.#[test]@@ -6669,12 +6769,16 @@ mod tests {/// back complete, imported themes are saved with the preferences, Remove falls back to the/// base and Cancel takes an import back.#[test]- fn system_theme_tile_export_uses_os_brightness_without_selecting_it() {+ fn system_theme_export_uses_os_slot_without_selecting_it() {let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default());app.preferences.theme = "light".into();app.ui.dark = false;assert_eq!(theme_file(&app, "system", true)["base"], "dark");assert_eq!(theme_file(&app, "system", false)["base"], "light");+ app.preferences.theme_day = "akari".into();+ app.preferences.theme_night = "onyx".into();+ assert_eq!(theme_file(&app, "system", false)["name"], "Akari");+ assert_eq!(theme_file(&app, "system", true)["name"], "Onyx");assert_eq!(app.preferences.theme, "light");assert!(!app.ui.dark);}@@ -6863,15 +6967,7 @@ mod tests {h.app.home.open = false;h.call("ui.prefs", json!({"theme": "dark", "open": "Interface"}));h.frames(2);- // The Import card is the last one in the theme carousel: page it into view.- for _ in 0..40 {- if h.app.prefs_window.import_tile.is_some() {- break;- }- h.step(&json!({"click":{"handle":"prefs:theme_next"}})).unwrap();- h.frames(2);- }- assert!(h.app.prefs_window.import_tile.is_some(), "the Import card is reachable in the theme carousel");+ assert!(h.app.prefs_window.import_tile.is_some(), "Import is always visible");let (root, out) = (h.dir.join("root"), h.dir.join("out"));std::fs::create_dir_all(&root).unwrap();std::fs::create_dir_all(&out).unwrap();@@ -6882,7 +6978,7 @@ mod tests {h.app.services.pick_open = Some(Box::new(move |_| Box::pin(std::future::ready(Some(answer.clone())))));h.app.status = None;vfs::scoped(Some(vfs::PathScope::new([root.clone()])), || {- h.step(&json!({"click":{"handle":"dialog:Import…"}})).unwrap();+ h.step(&json!({"click":{"handle":"prefs:theme_import"}})).unwrap();h.frames(4);});let status = h.app.status.clone().map(|(text, ..)| text);@@ -6999,28 +7095,26 @@ mod tests {});}assert!(painted_count, "count comes from actual themes");- for _ in 0..choices.len() + 1 {+ while crate::scenario::rect_of("prefs:theme_previous").is_some() {h.step(&json!({"click":{"handle":"prefs:theme_previous"}})).unwrap();- h.frames(2);+ h.frames(3);}let mut found = std::collections::BTreeSet::new();for _ in 0..choices.len() + 1 {for (id, _) in &choices {if let Some(rect) = crate::scenario::rect_of(&format!("prefs:theme:{id}")) {assert!(page.expand(1.0).contains_rect(rect), "{base} width={screen}: {id} {rect:?}");- assert!((rect.width() - 88.0).abs() <= 1.0);found.insert(id.clone());}}- if let Some(import) = h.app.prefs_window.import_tile {- assert!(page.expand(1.0).contains_rect(import));+ if crate::scenario::rect_of("prefs:theme_next").is_none() {break;}h.step(&json!({"click":{"handle":"prefs:theme_next"}})).unwrap();- h.frames(2);+ h.frames(3);}assert_eq!(found, choices.into_iter().map(|(id, _)| id).collect());- assert!(h.app.prefs_window.import_tile.is_some(), "Import is the last carousel card");+ assert!(h.app.prefs_window.import_tile.is_some(), "Import stays visible while scrolling");assert_eq!(h.app.preferences.theme, base, "scrolling does not select a theme");assert_eq!(h.app.preferences.ui_scale, 1.0);assert_eq!(h.app.preferences.viewport_background, None);@@ -8192,7 +8286,7 @@ mod tests {let out = h.call("ui.prefs", json!({"theme": "gruvbox-dark-hard"}));assert_eq!(out["result"]["theme"], "gruvbox-dark", "{out}");assert_eq!(out["result"]["theme_option_values"]["contrast"], "hard");- assert!(out["result"]["theme_ids"].as_array().is_some_and(|ids| ids.len() == 3 + crate::theme_files::builtin().len()), "{out}");+ assert!(out["result"]["theme_ids"].as_array().is_some_and(|ids| ids.len() == 2 + crate::theme_files::builtin().len()), "{out}");h.frames(2);let hard = resolved_theme(&h.app.preferences, active_theme_file(&h.app).unwrap());assert!(h.app.ui.dark);diff --git a/crates/ui-egui/src/prefs/theme_picker.rs b/crates/ui-egui/src/prefs/theme_picker.rsnew file mode 100644index 0000000000..f97dc2b61e--- /dev/null+++ b/crates/ui-egui/src/prefs/theme_picker.rs@@ -0,0 +1,388 @@+//! Appearance's theme browser. Only the Day/Night assignments are saved preferences.+use super::*;+use ui_kit::{ThemeGlyph as Glyph, ThemeSegment};++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(super) struct Classification {+ pub dark: bool,+ pub high: bool,+}++/// Interim traits until themes declare tone and contrast in a later file-contract change.+/// Use the resolved thumbnail ground and primary ink. 20:1 reserves High contrast for+/// near-maximal text/background contrast: four shipped palettes measure 21:1, while+/// every other shipped palette is at most 16.006:1. No theme ids are special-cased.+pub(super) fn theme_traits(t: &Tokens) -> Classification {+ let linear = solidcraft_engine::geom::srgb::decode8;+ let luminance = 0.2126 * linear(t.dialog_footer.r()) + 0.7152 * linear(t.dialog_footer.g()) + 0.0722 * linear(t.dialog_footer.b());+ Classification { dark: luminance < 0.5, high: crate::theme::contrast_ratio(t.form_ink, t.dialog_footer) >= 20.0 }+}++pub(super) fn palette(p: &Prefs, id: &str) -> Tokens {+ match id {+ "light" => Tokens::light(),+ "dark" => Tokens::dark(),+ _ => crate::theme_files::find(id, &p.custom_themes).map(|f| resolved_theme(p, f)).unwrap_or_else(Tokens::dark),+ }+}++/// No recursion through `system`, even for hand-edited or removed theme ids.+pub(super) fn slot_id(p: &Prefs, night: bool) -> &str {+ let (id, fallback) = if night { (&p.theme_night, "dark") } else { (&p.theme_day, "light") };+ if matches!(id.as_str(), "light" | "dark") || crate::theme_files::find(id, &p.custom_themes).is_some() { id } else { fallback }+}++pub(super) fn active_id(p: &Prefs, system_dark: bool) -> &str {+ if p.theme == "system" { slot_id(p, system_dark) } else { &p.theme }+}++#[derive(Clone, Default, PartialEq)]+pub(super) struct State {+ pub tone: Option<bool>,+ pub high: Option<bool>,+ pub imported: bool,+ pub grid: bool,+ pub night: bool,+}++#[derive(Clone)]+pub(super) struct Entry {+ id: String,+ name: String,+ palette: Tokens,+ class: Classification,+ imported: bool,+ options: bool,+}++impl State {+ fn matches(&self, entry: &Entry, skip: &str) -> bool {+ (skip == "tone" || self.tone.is_none_or(|dark| dark == entry.class.dark))+ && (skip == "contrast" || self.high.is_none_or(|high| high == entry.class.high))+ && (skip == "imported" || !self.imported || entry.imported)+ }++ pub(super) fn count(&self, entries: &[Entry], group: &str, value: bool) -> usize {+ entries+ .iter()+ .filter(|e| {+ self.matches(e, group)+ && match group {+ "tone" => e.class.dark == value,+ "contrast" => e.class.high == value,+ _ => e.imported,+ }+ })+ .count()+ }++ pub(super) fn aim(&mut self, night: bool) {+ self.night = night;+ self.tone = Some(night);+ }+}++pub(super) fn entries(app: &SolveApp) -> Vec<Entry> {+ theme_choices(app)+ .into_iter()+ .map(|(id, name)| {+ let palette = palette(&app.preferences, &id);+ let class = theme_traits(&palette);+ let imported = app.preferences.custom_themes.iter().any(|f| f.id == id);+ let options = crate::theme_files::find(&id, &app.preferences.custom_themes)+ .is_some_and(|f| !crate::theme_options::offered(f, crate::theme_options::PROVIDERS).is_empty());+ Entry { id, name, palette, class, imported, options }+ })+ .collect()+}++pub(super) fn switch_mode(app: &mut SolveApp, follow: bool, dark: bool) {+ if follow == (app.preferences.theme == "system") {+ return;+ }+ stop_following(app);+ if follow {+ let id = app.preferences.theme.clone();+ let night = theme_traits(&palette(&app.preferences, &id)).dark;+ fill_slot(&mut app.preferences, night, &id);+ app.preferences.theme = "system".into();+ } else {+ let id = active_id(&app.preferences, dark).to_owned();+ select_theme(app, &id);+ }+}++pub(super) fn fill_slot(p: &mut Prefs, night: bool, id: &str) {+ if night {+ p.theme_night = id.to_owned();+ } else {+ p.theme_day = id.to_owned();+ }+}++pub(super) fn choose(app: &mut SolveApp, night: bool, id: &str) {+ if app.preferences.theme == "system" {+ fill_slot(&mut app.preferences, night, id);+ } else {+ stop_following(app);+ select_theme(app, id);+ }+}++pub(super) fn row(app: &mut SolveApp, ui: &mut egui::Ui) {+ if crate::prefs_search::suppress_chrome(ui) {+ row_contents(app, ui);+ return;+ }+ // The page scroller's host can be wider than its clipped content well. Give the+ // picker its real visible width, and never propagate a child's horizontal growth.+ let start = ui.next_widget_position();+ let width = ui.available_width().min((ui.clip_rect().right() - start.x).max(0.0));+ let mut child = ui.new_child(+ egui::UiBuilder::new()+ .id_salt("theme_picker_content")+ .max_rect(egui::Rect::from_min_size(start, egui::vec2(width, ui.available_height())))+ .layout(egui::Layout::top_down(egui::Align::Min)),+ );+ child.set_width(width);+ row_contents(app, &mut child);+ ui.allocate_exact_size(egui::vec2(width, child.min_size().y), egui::Sense::hover());+}++fn row_contents(app: &mut SolveApp, ui: &mut egui::Ui) {+ let key = ui.make_persistent_id("theme_picker_state");+ let mut state = ui.data(|d| d.get_temp::<State>(key)).unwrap_or_default();+ let search = crate::prefs_search::suppress_chrome(ui);+ let mut action = None;+ let mut action_theme = None;+ let t = Tokens::get();+ let dark = system_dark(app, ui.ctx()).unwrap_or_else(|| app.prefs_window.system_theme_dark.unwrap_or(app.ui.dark));+ let label = app.tr("prefs.picker.import");+ let import_width = ui_kit::ContentWidth::name(ui, label) + t.space_14 + t.space_6 + t.space_10 * 2.0;+ let (mode, import_rect) = ui_kit::theme_toolbar(+ ui,+ "mode",+ import_width,+ t.space_24 * 19.0 + t.space_4,+ |ui| {+ let mode = ui_kit::theme_segments(+ ui,+ "mode",+ &[+ ThemeSegment::new(app.tr("prefs.picker.one"), Glyph::Monitor, None),+ ThemeSegment::new(app.tr("prefs.picker.follow"), Glyph::Contrast, None),+ ],+ Some(usize::from(app.preferences.theme == "system")),+ false,+ );+ if app.preferences.theme == "system" {+ ui_kit::settings_inline_note(ui, app.tr("prefs.picker.hint"));+ }+ mode+ },+ |ui| {+ let button = ui_kit::theme_import_button(ui, label).backing_on_hover_text(app.tr("prefs.theme_import_hint"));+ crate::scenario::publish_target("prefs:theme_import", button.rect);+ if button.clicked() {+ action = Some("import");+ }+ #[cfg(not(target_arch = "wasm32"))]+ ui_kit::Menu::context(&button, |ui| {+ ui_kit::Menu::show(ui, t.form_card_width, |ui| {+ if ui_kit::MenuItem::new("theme_paste", app.tr("prefs.theme_paste"), "paste").show(ui).clicked() {+ action = Some("paste");+ ui.close();+ }+ });+ });+ button.rect+ },+ );+ app.prefs_window.import_tile = Some(import_rect);+ if let Some(index) = mode {+ switch_mode(app, index == 1, dark);+ state.tone = if index == 1 { Some(state.night) } else { None };+ }+ let system = app.preferences.theme == "system";+ if system {+ let width = (ui.available_width() - t.space_10) / 2.0;+ ui.horizontal(|ui| {+ ui.spacing_mut().item_spacing.x = t.space_10;+ for night in [false, true] {+ let id = slot_id(&app.preferences, night);+ let name = theme_choices(app).into_iter().find(|(i, _)| i == id).map(|(_, n)| n).unwrap_or_default();+ let title = app.tr(if night { "prefs.picker.night" } else { "prefs.picker.day" });+ let aimed = state.night == night;+ let response = ui_kit::theme_slot(+ ui,+ &ui_kit::ThemeSlot {+ title,+ name: &name,+ aimed,+ night,+ width,+ hint: app.tr(if aimed { "prefs.picker.pick" } else { "prefs.picker.change" }),+ sample: ui_kit::ThemeSample::from_tokens(&palette(&app.preferences, id)),+ },+ );+ crate::scenario::publish_target(if night { "prefs:theme_slot:night" } else { "prefs:theme_slot:day" }, response.rect);+ if response.clicked() {+ state.aim(night);+ }+ }+ });+ }+ let entries = entries(app);+ let (filters, view) = ui_kit::theme_toolbar(+ ui,+ "filters",+ (t.space_24 + t.space_10) * 2.0,+ 0.0,+ |ui| {+ let mut tone = state.tone;+ let mut high = state.high;+ let mut imported = state.imported;+ if let Some(index) = ui_kit::theme_segments(+ ui,+ "tone",+ &[+ ThemeSegment::new(app.tr("ui.light"), Glyph::Sun, Some(state.count(&entries, "tone", false))),+ ThemeSegment::new(app.tr("ui.dark"), Glyph::Moon, Some(state.count(&entries, "tone", true))),+ ],+ state.tone.map(usize::from),+ false,+ ) {+ let value = Some(index == 1);+ tone = if state.tone == value { None } else { value };+ }+ if let Some(index) = ui_kit::theme_segments(+ ui,+ "contrast",+ &[+ ThemeSegment::new(app.tr("prefs.picker.standard"), Glyph::None, Some(state.count(&entries, "contrast", false))),+ ThemeSegment::new(app.tr("prefs.picker.high"), Glyph::Contrast, Some(state.count(&entries, "contrast", true))),+ ],+ state.high.map(usize::from),+ false,+ ) {+ let value = Some(index == 1);+ high = if state.high == value { None } else { value };+ }+ if ui_kit::theme_segments(+ ui,+ "imported",+ &[ThemeSegment::new(app.tr("prefs.picker.imported"), Glyph::None, Some(state.count(&entries, "imported", true)))],+ state.imported.then_some(0),+ false,+ )+ .is_some()+ {+ imported = !state.imported;+ }+ (tone, high, imported)+ },+ |ui| {+ ui_kit::theme_segments(+ ui,+ "view",+ &[+ ThemeSegment::new(app.tr("prefs.picker.carousel"), Glyph::Carousel, None),+ ThemeSegment::new(app.tr("prefs.picker.grid"), Glyph::Grid, None),+ ],+ Some(usize::from(state.grid)),+ true,+ )+ },+ );+ (state.tone, state.high, state.imported) = filters;+ if let Some(index) = view {+ state.grid = index == 1;+ }+ let visible: Vec<_> = entries.iter().filter(|e| search || state.matches(e, "")).collect();+ let following = !app.prefs_window.follow.path(&app.preferences.theme_follow).is_empty();+ let reveal = if system { slot_id(&app.preferences, state.night) } else { &app.preferences.theme };+ let selected_index = visible.iter().position(|e| e.id == reveal);+ let identity = format!("{reveal}:{:?}:{:?}:{}:{}", state.tone, state.high, state.imported, state.grid);+ let reveal_key = ui.make_persistent_id("theme_picker_reveal");+ let changed = ui.data(|d| d.get_temp::<String>(reveal_key)).as_ref() != Some(&identity);+ let mut chosen = None;+ let mut card = |ui: &mut egui::Ui, index: usize, width: f32| {+ let Some(e) = visible.get(index) else { return };+ let source = app.tr(if e.imported { "prefs.imported_file" } else { "prefs.built_in" });+ let note = if e.class.high { crate::i18n::format("prefs.picker.high_note", &[("source", source)]) } else { source.to_owned() };+ let day = system && slot_id(&app.preferences, false) == e.id;+ let night = system && slot_id(&app.preferences, true) == e.id;+ let selected = !following && if system { day || night } else { app.preferences.theme == e.id };+ let response = ui_kit::theme_card(+ ui,+ &ui_kit::ThemeCard {+ name: &e.name,+ note: ¬e,+ selected,+ day,+ night,+ dark: e.class.dark,+ high: e.class.high,+ options: e.options.then(|| app.tr("prefs.theme_options_badge")),+ sample: ui_kit::ThemeSample::from_tokens(&e.palette),+ },+ width,+ );+ let clipped = response.rect.intersect(ui.clip_rect());+ if clipped.is_positive() {+ crate::scenario::publish_target(&format!("prefs:theme_tile:{}", e.id), clipped);+ crate::scenario::publish_target(&format!("prefs:theme:{}", e.id), clipped);+ if e.options {+ crate::scenario::publish_rect(&format!("prefs:theme_options_badge:{}", e.id), clipped);+ }+ if selected && !system {+ crate::scenario::publish_target("prefs:theme", clipped);+ }+ }+ if response.clicked() {+ chosen = Some(e.id.clone());+ }+ ui_kit::Menu::context(&response, |ui| {+ ui_kit::Menu::show(ui, t.form_card_width, |ui| {+ if ui_kit::MenuItem::new("theme_export", app.tr_label("Export…"), "export").show(ui).clicked() {+ action = Some("export");+ action_theme = Some(e.id.clone());+ ui.close();+ }+ if e.imported {+ let mut remove = ui_kit::MenuItem::new("theme_remove", app.tr_label("Remove"), "delete");+ remove.danger = true;+ if remove.show(ui).clicked() {+ action = Some("remove");+ action_theme = Some(e.id.clone());+ ui.close();+ }+ }+ });+ });+ };+ if search {+ for index in 0..visible.len() {+ card(ui, index, t.space_24 * 5.0);+ }+ } else if visible.is_empty() {+ ui_kit::theme_empty(ui, app.tr("prefs.picker.empty"), app.tr("prefs.picker.clear"), || {+ state.tone = None;+ state.high = None;+ state.imported = false;+ });+ } else {+ ui_kit::theme_browser(ui, "appearance_theme_picker", visible.len(), state.grid, changed.then_some(selected_index).flatten(), &mut card);+ }+ ui.data_mut(|d| {+ d.insert_temp(key, state.clone());+ d.insert_temp(reveal_key, identity);+ });+ if !search {+ app.prefs_window.theme_picker_night = state.night;+ }+ if let Some(id) = chosen {+ choose(app, state.night, &id);+ }+ super::theme_action(app, ui, action, action_theme);+}diff --git a/crates/ui-egui/src/prefs_search.rs b/crates/ui-egui/src/prefs_search.rsindex 359cf5f773..1932a16c02 100644--- a/crates/ui-egui/src/prefs_search.rs+++ b/crates/ui-egui/src/prefs_search.rs@@ -838,6 +838,39 @@ pub(crate) fn follow(ui: &Ui, label: &str, rect: Rect) {mod tests {use super::*;+ #[test]+ fn theme_picker_names_and_controls_are_searchable_and_theme_results_reveal_real_cards() {+ let mut h = crate::scenario::Harness::new();+ h.app.home.open = false;+ h.call("ui.resize", serde_json::json!({"width":1467,"height":1146}));+ h.call("ui.prefs", serde_json::json!({"language":"en","theme":"system","open":"Appearance"}));+ for label in+ ["Onyx", "Follow system", "One theme", "Carousel", "Grid", "Day theme", "Night theme", "High contrast", "Import theme file…", "Imported"]+ {+ h.app.prefs_window.filter = label.to_owned();+ h.frames(5);+ let (_, _, hits) = nav(&h.ctx);+ let matches: Vec<_> =+ hits.iter().enumerate().filter(|(_, hit)| hit.page == crate::prefs::PAGE_APPEARANCE && hit.label == label).collect();+ assert_eq!(+ matches.len(),+ 1,+ "{label} has one searchable Appearance control: {:?}",+ hits.iter().map(|hit| (&hit.label, hit.page)).collect::<Vec<_>>()+ );+ if label == "Onyx" {+ set_cursor(&h.ctx, matches[0].0);+ h.frames(2);+ h.step(&serde_json::json!({"key":"Enter"})).unwrap();+ h.frames(25);+ let page = crate::scenario::rect_of("prefs:page_body").unwrap();+ let target = crate::scenario::rect_of("prefs:theme:onyx").unwrap();+ assert!(page.contains_rect(target));+ assert_eq!(h.app.preferences.theme, "system", "revealing a theme never selects it");+ }+ }+ }+#[test]fn graphics_cards_tiles_and_short_status_labels_keep_search_paths_and_reveal() {for theme in ["light", "dark"] {diff --git a/crates/ui-egui/src/settings_profiles.rs b/crates/ui-egui/src/settings_profiles.rsindex 2d38cde5be..b3326b1bef 100644--- a/crates/ui-egui/src/settings_profiles.rs+++ b/crates/ui-egui/src/settings_profiles.rs@@ -118,7 +118,9 @@ const PROFILE_KEYS: &[&str] = &["status_bar","suppress_sketch_snap","theme",+ "theme_day","theme_follow",+ "theme_night","theme_options","timeline_collapsed","timeline_left",diff --git a/crates/ui-egui/src/settings_profiles_tests.rs b/crates/ui-egui/src/settings_profiles_tests.rsindex 067994ab62..e9da4684cf 100644--- a/crates/ui-egui/src/settings_profiles_tests.rs+++ b/crates/ui-egui/src/settings_profiles_tests.rs@@ -17,13 +17,15 @@ fn error(h: &mut Harness, id: &str, params: Value) -> String {#[test]fn a_profile_holds_input_and_interface_settings_but_not_the_machine() {let keys: Vec<&str> = keys().collect();- assert_eq!(keys.len(), 100, "page presentation must not alter profile membership");+ assert_eq!(keys.len(), 102, "Appearance includes its two system-theme slots");for key in ["nav","mouse_gestures","radial_context_menu","zoom_reverse","theme",+ "theme_day",+ "theme_night","ui_scale","ui_font","navigator_style",@@ -817,7 +819,9 @@ fn profile_keys_preserve_the_baseline_and_explicit_additions() {"status_bar","suppress_sketch_snap","theme",+ "theme_day","theme_follow",+ "theme_night","theme_options","timeline_collapsed","timeline_left",@@ -844,7 +848,7 @@ fn profile_keys_preserve_the_baseline_and_explicit_additions() {];let mut actual: Vec<_> = keys().collect();actual.sort_unstable();- assert_eq!(expected.len(), 100);+ assert_eq!(expected.len(), 102);assert_eq!(actual, expected);}@@ -926,6 +930,24 @@ fn moved_profile_settings_survive_saved_roundtrip_and_apply() {}}+#[test]+fn theme_day_and_night_are_captured_restored_and_saved_in_appearance_profiles() {+ let mut h = Harness::new();+ h.call("ui.prefs", json!({"theme":"system", "theme_day":"akari", "theme_night":"onyx"}));+ run(&mut h, "settings.profile.save", json!({"name":"System pair"}));+ let saved = h.app.settings_profiles.list[0].clone();+ assert_eq!(saved["preferences"]["theme_day"], "akari");+ assert_eq!(saved["preferences"]["theme_night"], "onyx");+ assert_eq!(sanitize(&saved).unwrap(), saved);+ h.call("ui.prefs", json!({"theme_day":"light", "theme_night":"dark"}));+ run(&mut h, "settings.profile.apply", json!({"name":"System pair"}));+ assert_eq!((&h.app.preferences.theme_day[..], &h.app.preferences.theme_night[..]), ("akari", "onyx"));+ for key in ["theme_day", "theme_night"] {+ let pages: Vec<_> = crate::prefs::FIELD_PAGES.iter().filter(|(field, _)| *field == key).map(|(_, page)| *page).collect();+ assert_eq!(pages, [Some(crate::prefs::PAGE_APPEARANCE)]);+ }+}+#[test]fn profile_sidebar_switches_saves_and_marks_edits_with_existing_commands() {let mut h = Harness::new();diff --git a/crates/ui-egui/src/ui_kit/gallery.rs b/crates/ui-egui/src/ui_kit/gallery.rsindex 03025a09e3..5ec93f8c84 100644--- a/crates/ui-egui/src/ui_kit/gallery.rs+++ b/crates/ui-egui/src/ui_kit/gallery.rs@@ -1,5 +1,5 @@//! Table-driven layout/paint references in both themes. No window or GPU required.-use super::preferences_figures::{ThemeSample, paint_theme_system, paint_theme_thumbnail};+use super::preferences_figures::{ThemeSample, paint_theme_thumbnail};use super::*;use crate::ui_kit::{Container, Surface};use crate::{scenario, theme::Tokens};@@ -57,6 +57,128 @@ fn navigation_sample(ui: &mut Ui, size: crate::navigation_bar::Size) {// One entry per element/variant: names, rendering and geometry expectations stay together.const ELEMENTS: &[Element] = &[+ element!("theme_mode_segments", |ui, _| {+ theme_segments(+ ui,+ "gallery_mode",+ &[ThemeSegment::new("One theme", ThemeGlyph::Monitor, None), ThemeSegment::new("Follow system", ThemeGlyph::Contrast, None)],+ Some(1),+ false,+ );+ }),+ element!("theme_imported_filter", |ui, _| {+ theme_segments(ui, "gallery_imported", &[ThemeSegment::new("Imported", ThemeGlyph::None, Some(2))], Some(0), false);+ }),+ element!("theme_toolbar", |ui, _| {+ theme_toolbar(+ ui,+ "gallery_toolbar",+ 68.0,+ 0.0,+ |ui| {+ theme_segments(+ ui,+ "gallery_tone",+ &[ThemeSegment::new("Light", ThemeGlyph::Sun, Some(9)), ThemeSegment::new("Dark", ThemeGlyph::Moon, Some(17))],+ Some(0),+ false,+ );+ },+ |ui| {+ theme_segments(+ ui,+ "gallery_view",+ &[ThemeSegment::new("Carousel", ThemeGlyph::Carousel, None), ThemeSegment::new("Grid", ThemeGlyph::Grid, None)],+ Some(0),+ true,+ );+ },+ );+ }),+ element!("theme_browser_grid", |ui, _| {+ theme_browser(ui, "gallery_grid", 14, true, None, |ui, _, width| {+ theme_card(+ ui,+ &ThemeCard {+ name: "Light",+ note: "Built in",+ options: None,+ sample: ThemeSample::from_tokens(&Tokens::light()),+ selected: false,+ dark: false,+ high: false,+ day: false,+ night: false,+ },+ width,+ );+ });+ }),+ element!("theme_segments", |ui, _| {+ theme_segments(+ ui,+ "gallery",+ &[ThemeSegment::new("Light", ThemeGlyph::Sun, Some(10)), ThemeSegment::new("Dark", ThemeGlyph::Moon, Some(17))],+ Some(0),+ false,+ );+ }),+ element!("theme_import_button", |ui, _| {+ theme_import_button(ui, "Import theme file…");+ }),+ element!("theme_slot", |ui, _| {+ theme_slot(+ ui,+ &ThemeSlot {+ title: "Day theme",+ name: "Light",+ hint: "Pick from below",+ aimed: true,+ night: false,+ width: ui.available_width(),+ sample: ThemeSample::from_tokens(&Tokens::light()),+ },+ );+ }),+ element!("theme_card", |ui, _| {+ theme_card(+ ui,+ &ThemeCard {+ name: "Dark",+ note: "Built in · High contrast",+ options: Some("Has options"),+ sample: ThemeSample::from_tokens(&Tokens::dark()),+ selected: true,+ dark: true,+ high: true,+ day: true,+ night: true,+ },+ 118.0,+ );+ }),+ element!("theme_empty", |ui, _| {+ theme_empty(ui, "No theme matches these filters.", "Clear filters", || {});+ }),+ element!("theme_browser", |ui, _| {+ theme_browser(ui, "gallery_browser", 9, false, None, |ui, i, width| {+ theme_card(+ ui,+ &ThemeCard {+ name: if i % 2 == 0 { "Light" } else { "Dark" },+ note: "Built in",+ options: None,+ sample: ThemeSample::from_tokens(&Tokens::get()),+ selected: i == 0,+ dark: i % 2 != 0,+ high: false,+ day: false,+ night: false,+ },+ width,+ );+ });+ }),element!("viewport_status_item", "viewport_status:sample:item", Some("viewport_status:sample:close"), |ui, _| {let item = StatusItem {id: "sample".into(),@@ -586,35 +708,6 @@ const ELEMENTS: &[Element] = &[);settings_pointer_preview(ui, true, "Normal", true);}),- element!("preference_theme_carousel", |ui, _| {- let light = ThemeSample::from_tokens(&Tokens::light());- let dark = ThemeSample::from_tokens(&Tokens::dark());- carousel(ui, "gallery_theme_carousel", 4, 88.0, 96.0, |ui, index| {- if index == 3 {- theme_import_tile(ui, "Import…", "theme file");- } else {- let label = ["Light", "Dark", "System"][index];- picture_card(- ui,- &Card {- label,- sub: Some(if index == 2 { "Follows the OS" } else { "Built in" }),- selected: index == 0,- enabled: true,- options: None,- check: false,- aspect: 124.0 / 76.0,- figure: &|p, rect| match index {- 0 => paint_theme_thumbnail(p, rect, &light),- 1 => paint_theme_thumbnail(p, rect, &dark),- _ => paint_theme_system(p, rect, &light, &dark),- },- },- 88.0,- );- }- });- }),element!("picture_card", |ui, _| {use super::preferences_figure_data as figures;let gap = ui.spacing().item_spacing.x;@@ -742,36 +835,15 @@ const ELEMENTS: &[Element] = &[help_icon(ui, "Applies when SolidCraft restarts.");});}),- element!("carousel", |ui, _| {- let sample = ThemeSample::from_tokens(&Tokens::get());- let width = Tokens::get().space_24 * 2.0 + Tokens::get().space_24;- carousel(ui, "gallery_carousel", 6, width, width * 0.8, |ui, index| {- let label = ["Light", "Dark", "System", "Gruvbox", "Studio", "Mono"][index % 6];- picture_card(- ui,- &Card {- label,- sub: Some("Built in"),- selected: index == 1,- enabled: true,- options: None,- check: false,- aspect: 124.0 / 76.0,- figure: &|p, r| paint_theme_thumbnail(p, r, &sample),- },- width,- );- });- }),element!("preference_theme_thumbnails", |ui, _| {let (light, dark) = (ThemeSample::from_tokens(&Tokens::light()), ThemeSample::from_tokens(&Tokens::dark()));ui.horizontal(|ui| {- for kind in 0..3 {+ for kind in 0..2 {let (rect, _) = ui.allocate_exact_size(vec2(88.0, 88.0 * 76.0 / 124.0), egui::Sense::hover());match kind {0 => paint_theme_thumbnail(ui.painter(), rect, &light),1 => paint_theme_thumbnail(ui.painter(), rect, &dark),- _ => paint_theme_system(ui.painter(), rect, &light, &dark),+ _ => {}}}});@@ -2361,6 +2433,7 @@ fn gallery_covers_every_inline_element() {"sphere.rs","status.rs","table.rs",+ "theme_picker.rs","tree.rs",] {let source = std::fs::read_to_string(root.join(file)).unwrap();@@ -2986,19 +3059,14 @@ fn card_looks_follow_selected_hover_disabled_and_focus() {#[test]fn cards_size_to_their_container_and_survive_hostile_sizes() {- use super::preferences_cards::{card_width, carousel_window};+ use super::preferences_cards::card_width;assert_eq!(card_width(320.0, 4, 10.0), 72.5);assert_eq!(card_width(320.0, 0, 10.0), 320.0);for bad in [0.0, -5.0, f32::NAN, f32::INFINITY, f32::MAX] {let w = card_width(bad, 3, 10.0);assert!(w.is_finite() && w >= 0.0, "{bad}: {w}");- let (first, visible) = carousel_window(5, 9, bad, 88.0, 8.0, 26.0);- assert!(first + visible <= 5 && visible >= 1, "{bad}: {first} {visible}");}- assert_eq!(carousel_window(0, 3, 400.0, 88.0, 8.0, 26.0), (0, 0));// 400 wide: two arrows and their gaps leave 332, which fits three 88-wide items with gaps.- assert_eq!(carousel_window(6, 0, 400.0, 88.0, 8.0, 26.0), (0, 3));- assert_eq!(carousel_window(6, 5, 400.0, 88.0, 8.0, 26.0), (3, 3), "the offset stops at the last full window");}fn sample_card<'a>(label: &'a str, selected: bool, enabled: bool) -> super::preferences_cards::Card<'a> {@@ -3053,8 +3121,8 @@ fn picture_cards_and_tiles_click_only_when_enabled_and_never_panic() {}#[test]-fn preset_card_help_icon_and_carousel_behave() {- use super::preferences_cards::{carousel, help_icon, preset_card};+fn preset_card_and_help_icon_behave() {+ use super::preferences_cards::{help_icon, preset_card};let ctx = crate::fonts::test_context();let icon = |p: &egui::Painter, r: egui::Rect, ink: egui::Color32| crate::icons::paint_ink(p, r, "settings", ink);super::test_support::frame(&ctx, vec![], |ui| {@@ -3065,29 +3133,6 @@ fn preset_card_help_icon_and_carousel_behave() {let help = help_icon(ui, "Help text");assert!(help.rect.width() > 8.0 && help.rect.width() < 20.0);});- // The next arrow moves the window by a page and stays inert at the end.- let mut first = vec![];- let mut at = None;- for pass in 0..6 {- let events = match (pass, at) {- (2, Some(p)) => super::test_support::pointer(p, true),- (3, Some(p)) => super::test_support::pointer(p, false),- _ => vec![],- };- super::test_support::frame(&ctx, events, |ui| {- let (f, visible) = carousel(ui, "carousel_test", 5, 60.0, 40.0, |ui, _| {- ui.allocate_exact_size(egui::vec2(60.0, 40.0), egui::Sense::hover());- });- first.push((f, visible));- if let Some(rect) = scenario::rect_of("prefs:carousel:Next") {- at = Some(rect.center());- }- });- }- let (f0, visible) = first[0];- assert_eq!(f0, 0);- assert!((1..5).contains(&visible), "{visible}");- assert!(first.last().unwrap().0 >= 1, "the next arrow advanced the window: {first:?}");}/// Light and dark boards of the shared Preferences widgets and of every figure, rendered on the CPU.@@ -3100,7 +3145,7 @@ fn preference_widgets_and_figures_board_in_both_themes() {for dark in [false, true] {crate::theme::set_dark(dark);for (board, names) in [- ("widgets", &["picture_card", "toggle_tile", "preset_card", "help_icon", "carousel", "preference_theme_thumbnails"][..]),+ ("widgets", &["picture_card", "toggle_tile", "preset_card", "help_icon", "theme_browser", "preference_theme_thumbnails"][..]),("figures", &["preference_figures"][..]),] {for scale in [1.0_f32, 2.0] {diff --git a/crates/ui-egui/src/ui_kit/layout_tests.rs b/crates/ui-egui/src/ui_kit/layout_tests.rsindex 86d17fd1c9..5c4f2f1389 100644--- a/crates/ui-egui/src/ui_kit/layout_tests.rs+++ b/crates/ui-egui/src/ui_kit/layout_tests.rs@@ -4,6 +4,66 @@ use crate::ui_kit::*;use crate::{scenario, theme::Tokens};use egui::Ui;+#[test]+fn theme_browser_has_equal_end_padding_and_screenful_arrows_without_selecting() {+ let ctx = crate::fonts::test_context();+ let clicked = std::cell::Cell::new(false);+ let draw = |ui: &mut Ui| {+ theme_browser(ui, "padding_browser", 10, false, None, |ui, i, width| {+ let card = theme_card(+ ui,+ &ThemeCard {+ name: "Example",+ note: "Built in",+ options: None,+ sample: ThemeSample::from_tokens(&Tokens::light()),+ selected: i == 0,+ dark: false,+ high: false,+ day: false,+ night: false,+ },+ width,+ );+ clicked.set(clicked.get() || card.clicked());+ scenario::publish_rect(&format!("test:theme_card:{i}"), card.rect);+ });+ };+ for _ in 0..3 {+ frame(&ctx, vec![], draw);+ }+ let viewport = scenario::rect_of("prefs:theme_viewport").unwrap();+ let first = scenario::rect_of("test:theme_card:0").unwrap();+ for gap in [first.left() - viewport.left(), first.top() - viewport.top(), viewport.bottom() - first.bottom()] {+ assert!((gap - Tokens::get().space_10).abs() < 0.1, "same padding on every resting side: {gap}");+ }+ assert!(scenario::handle_at("prefs:theme_previous").is_none());+ let advance = || {+ let at = scenario::handle_at("prefs:theme_next").unwrap();+ frame(&ctx, pointer(at, true), draw);+ frame(&ctx, pointer(at, false), draw);+ frame(&ctx, vec![], draw);+ };+ let stride = scenario::rect_of("test:theme_card:1").unwrap().left() - first.left();+ let page = ((viewport.width() / stride).floor() as usize).max(1);+ advance();+ let moved = scenario::rect_of(&format!("test:theme_card:{page}")).unwrap();+ assert!((moved.left() - first.left()).abs() < 0.1, "arrow moves a screenful of {page} cards");+ assert!(scenario::handle_at("prefs:theme_previous").is_some());+ assert!(scenario::handle_at("prefs:theme_next").is_some());+ for _ in 0..10 {+ if scenario::handle_at("prefs:theme_next").is_none() {+ break;+ }+ advance();+ }+ let viewport = scenario::rect_of("prefs:theme_viewport").unwrap();+ let last = scenario::rect_of("test:theme_card:9").unwrap();+ assert!((viewport.right() - last.right() - Tokens::get().space_10).abs() < 0.1);+ assert!(scenario::handle_at("prefs:theme_next").is_none());+ assert!(!clicked.get(), "floating arrows never select the card under them");+}+#[test]fn navigation_cards_keep_their_proportions_and_native_targets_at_narrow_widths() {let previous = crate::theme::is_dark();@@ -272,16 +332,6 @@ fn status_lines_wrap_at_form_width_and_leave_room_for_the_next_row() {crate::theme::set_dark(previous_dark);}-#[test]-fn carousel_window_clamps_offsets_and_keeps_a_card_on_narrow_pages() {- use crate::ui_kit::preferences_cards::carousel_window;- assert_eq!(carousel_window(0, 9, 280.0, 88.0, 8.0, 26.0), (0, 0));- assert_eq!(carousel_window(6, 0, 280.0, 88.0, 8.0, 26.0), (0, 2));- assert_eq!(carousel_window(6, 2, 280.0, 88.0, 8.0, 26.0), (2, 2));- assert_eq!(carousel_window(6, 99, 280.0, 88.0, 8.0, 26.0), (4, 2));- assert_eq!(carousel_window(6, 99, 100.0, 88.0, 8.0, 26.0), (5, 1));-}-#[test]fn shared_picture_choices_wrap_inside_the_row_and_reserve_their_height() {let choices = [@@ -364,166 +414,6 @@ fn shared_picture_choices_return_clicks_and_respect_both_disabled_states() {}/// #11434: an arrow moves by the cards that fit, not by one, and the last page ends on the last card.-#[test]-fn carousel_arrows_move_a_page_of_the_cards_that_fit_at_each_width() {- let count = 11;- for width in [280.0_f32, 480.0, 700.0] {- let ctx = crate::fonts::test_context();- let shown = || -> Vec<usize> { (0..count).filter(|i| scenario::rect_of(&format!("page:item:{i}")).is_some()).collect() };- let draw = |events: Vec<egui::Event>| {- scenario::clear_handles();- crate::test_support::frame(- &ctx,- egui::RawInput {- screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width + 40.0, 400.0))),- events,- ..Default::default()- },- |ui| {- ui.set_width(width);- scope(ui, |ui| {- carousel(ui, ("page_carousel", width as u32), count, 88.0, 96.0, |ui, i| {- let (r, _) = ui.allocate_exact_size(egui::vec2(88.0, 90.0), egui::Sense::hover());- scenario::publish_rect(&format!("page:item:{i}"), r);- });- });- },- );- };- let click = |label: &str| {- let at = scenario::handle_at(&format!("prefs:carousel:{}", crate::i18n::tr(label))).unwrap();- draw(pointer(at, true));- draw(pointer(at, false));- draw(vec![]);- };- draw(vec![]);- draw(vec![]);- let page = shown().len();- assert!(page > 1 && page < count, "width {width}: {page} cards fit");- assert_eq!(shown(), (0..page).collect::<Vec<_>>());- click("prefs.carousel_previous");- assert_eq!(shown(), (0..page).collect::<Vec<_>>(), "width {width}: previous is inert at the start");- click("prefs.carousel_next");- let second = page.min(count - page);- assert_eq!(shown(), (second..second + page).collect::<Vec<_>>(), "width {width}: next shows the cards that were hidden");- for _ in 0..count {- click("prefs.carousel_next");- }- let last: Vec<usize> = (count - page..count).collect();- assert_eq!(shown(), last, "width {width}: the last page ends on the last card");- click("prefs.carousel_previous");- let back = (count - page).saturating_sub(page);- assert_eq!(shown(), (back..back + page).collect::<Vec<_>>(), "width {width}: previous shows the cards before");- for _ in 0..count {- click("prefs.carousel_previous");- }- assert_eq!(shown(), (0..page).collect::<Vec<_>>(), "width {width}: previous stops at the first card");- }-}--#[test]-fn theme_carousel_moves_and_disables_its_ends_without_selecting() {- let ctx = crate::fonts::test_context();- let sample = ThemeSample::from_tokens(&Tokens::light());- let draw = |ui: &mut Ui| {- let bounds = ui.max_rect();- carousel(ui, "test_themes", 3, 88.0, 96.0, |ui, index| {- let label = ["Light", "Dark", "System"][index];- let response = picture_card(- ui,- &Card {- label,- sub: Some("Built in"),- selected: index == 0,- enabled: true,- options: (index == 2).then_some("Has options"),- check: false,- aspect: 124.0 / 76.0,- figure: &|p, r| paint_theme_thumbnail(p, r, &sample),- },- 88.0,- );- assert!(!response.clicked(), "scrolling must not select a card");- assert!(bounds.contains_rect(response.rect));- scenario::publish_target(&format!("test:theme:{index}"), response.rect);- });- };- for _ in 0..3 {- frame(&ctx, vec![], draw);- }- let previous = format!("prefs:carousel:{}", crate::i18n::tr("prefs.carousel_previous"));- let next = format!("prefs:carousel:{}", crate::i18n::tr("prefs.carousel_next"));- let click = |handle: &str| {- let at = scenario::handle_at(handle).unwrap();- frame(&ctx, pointer(at, true), draw);- frame(&ctx, pointer(at, false), draw);- frame(&ctx, vec![], draw);- };- let start = scenario::rect_of("test:theme:0").unwrap().left();- click(&previous);- assert_eq!(scenario::rect_of("test:theme:0").unwrap().left(), start, "previous is inert at the start");- click(&next);- assert!(scenario::rect_of("test:theme:0").is_none());- assert!((scenario::rect_of("test:theme:1").unwrap().left() - start).abs() < 1.0, "the last page ends on the last card");- assert!(scenario::rect_of("test:theme:2").is_some());- click(&next);- assert!((scenario::rect_of("test:theme:1").unwrap().left() - start).abs() < 1.0, "next is inert at the end");- click(&previous);- assert!(scenario::rect_of("test:theme:0").is_some());- assert!(scenario::rect_of("test:theme:2").is_none());-}--#[test]-fn carousel_arrows_expose_disabled_state_hover_and_keyboard_focus() {- let ctx = crate::fonts::test_context();- ctx.enable_accesskit();- let draw = |events| {- scenario::clear_handles();- crate::test_support::frame(- &ctx,- egui::RawInput {- screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(320.0, 400.0))),- events,- focused: true,- ..Default::default()- },- |ui| {- ui.set_width(280.0);- scope(ui, |ui| {- carousel(ui, "keyboard_carousel", 3, 88.0, 96.0, |ui, i| {- let (r, _) = ui.allocate_exact_size(egui::vec2(88.0, 90.0), egui::Sense::hover());- scenario::publish_rect(&format!("keyboard:item:{i}"), r);- });- });- },- )- };- let previous = crate::i18n::tr("prefs.carousel_previous");- let next = crate::i18n::tr("prefs.carousel_next");- draw(vec![]);- let idle = draw(vec![]);- let tree = idle.platform_output.accesskit_update.as_ref().unwrap();- for (label, disabled) in [(previous, true), (next, false)] {- let nodes: Vec<_> =- tree.nodes.iter().filter(|(_, node)| node.role() == egui::accesskit::Role::Button && node.label() == Some(label)).collect();- assert_eq!(nodes.len(), 1);- assert_eq!(nodes[0].1.is_disabled(), disabled);- }- let at = scenario::handle_at(&format!("prefs:carousel:{next}")).unwrap();- let hover = draw(vec![egui::Event::PointerMoved(at)]);- assert_eq!(hover.platform_output.cursor_icon, egui::CursorIcon::PointingHand);- draw(vec![egui::Event::PointerMoved(egui::pos2(310.0, 390.0))]);- let focus = draw(key(egui::Key::Tab));- assert!(- focus.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Rect(r) if r.stroke.color == Tokens::get().form_primary)),- "keyboard focus uses the standard ring"- );- draw(key(egui::Key::Enter));- draw(vec![]);- assert!(scenario::rect_of("keyboard:item:0").is_none(), "keyboard activates Next");- assert!(scenario::rect_of("keyboard:item:2").is_some());-}-#[test]fn layout_picture_choices_wrap_inside_the_indexed_row_and_keep_real_targets() {let previous = crate::theme::is_dark();diff --git a/crates/ui-egui/src/ui_kit/mod.rs b/crates/ui-egui/src/ui_kit/mod.rsindex b5b8ad5197..1bff7a7676 100644--- a/crates/ui-egui/src/ui_kit/mod.rs+++ b/crates/ui-egui/src/ui_kit/mod.rs@@ -50,6 +50,7 @@ mod status;mod table;mod text;mod text_menu;+mod theme_picker;mod tree;mod value_focus;mod viewport_status;@@ -99,7 +100,7 @@ pub(crate) use preferences_figure_data::{paint_aa_2x, paint_aa_4x, paint_aa_8x, paint_aa_off, paint_ao_on, paint_frame_rate, paint_quick_measure, paint_tess_coarse, paint_tess_fine,paint_tess_normal, paint_tess_ultra, paint_vertex_markers, paint_view_angles, paint_view_grid, paint_view_perspective, paint_view_shadow,};-pub(crate) use preferences_figures::{ThemeSample, paint_theme_system, paint_theme_thumbnail};+pub(crate) use preferences_figures::{ThemeSample, paint_theme_thumbnail_rounded};pub(crate) use preferences_navigation::*;pub(crate) use preferences_small::*;pub(crate) use radial::{RADIAL_RADIUS, radial_menu};@@ -117,6 +118,7 @@ pub(crate) use table::*;#[cfg(test)]pub(crate) use text::ellipsize_middle;pub(crate) use text_menu::menu_open as text_menu_open;+pub(crate) use theme_picker::*;pub(crate) use tree::*;pub(crate) use value_focus::*;pub(crate) use viewport_status::*;diff --git a/crates/ui-egui/src/ui_kit/preferences.rs b/crates/ui-egui/src/ui_kit/preferences.rsindex 4f13cd0539..85663f15bd 100644--- a/crates/ui-egui/src/ui_kit/preferences.rs+++ b/crates/ui-egui/src/ui_kit/preferences.rs@@ -566,15 +566,18 @@ fn settings_section_count_spaced<R>(pub(crate) fn settings_card<R>(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> egui::InnerResponse<R> {let t = Tokens::get();let container = super::Container::new(ui.ctx(), super::Surface::Navigation);- let frame = container- .frame(ui.ctx(), t.dialog_footer, crate::frame::Side::Left)- .inner_margin(egui::Margin::symmetric(t.space_12 as i8, t.space_10 as i8));+ let frame = settings_card_frame(ui).inner_margin(egui::Margin::symmetric(t.space_12 as i8, t.space_10 as i8));container.show_frame(ui, frame, ui.max_rect(), |ui| {ui.set_min_width(dimension(ui.available_width()));add(ui)})}+/// The theme browser and its options panel share exactly the same themed backing.+pub(super) fn settings_card_frame(ui: &Ui) -> egui::Frame {+ super::Container::new(ui.ctx(), super::Surface::Navigation).frame(ui.ctx(), Tokens::get().dialog_footer, crate::frame::Side::Left)+}+/// Controls and one explanatory specimen side by side, stacked on narrow viewports.pub(crate) fn settings_pair<R>(ui: &mut Ui, controls: impl FnOnce(&mut Ui) -> R, preview: impl FnOnce(&mut Ui, R)) {if crate::prefs_search::suppress_chrome(ui) {@@ -602,44 +605,6 @@ pub(crate) fn settings_pair<R>(ui: &mut Ui, controls: impl FnOnce(&mut Ui) -> R,}}-/// Dashed import tile, bounded by its carousel cell.-pub(crate) fn theme_import_tile(ui: &mut Ui, label: &str, note: &str) -> Response {- if crate::prefs_search::suppress_chrome(ui) && !crate::prefs_search::texts_hit(ui, &[label, note]) {- return crate::prefs_search::hidden_response(ui);- }- let t = Tokens::get();- let width = t.space_24 * 3.0 + t.space_16;- let height = t.space_24 * 4.0;- let (r, response) = ui.allocate_exact_size(vec2(width.min(dimension(ui.available_width())), height), Sense::click());- if response.hovered() {- ui.painter().rect_filled(r, t.radius_lg, t.hover);- }- let mut outline = rounded_perimeter(r.shrink(t.space_2 / 2.0), f32::from(t.radius_lg));- if let Some(first) = outline.first().copied() {- outline.push(first);- }- ui.painter().extend(egui::Shape::dashed_line(&outline, Stroke::new(t.space_3 / 2.0, t.control_border), t.space_3, t.space_3));- let icon = Rect::from_center_size(pos2(r.center().x, r.top() + t.space_16), vec2(t.space_16, t.space_16));- crate::icons::paint_ink(ui.painter(), icon, "import_tray", t.form_dim);- centred_text(- ui.painter(),- Rect::from_min_size(pos2(r.left(), r.top() + t.space_24 + t.space_4), vec2(r.width(), t.space_16)),- label,- FontId::proportional(t.font_label),- t.form_dim,- );- centred_text(- ui.painter(),- Rect::from_min_size(pos2(r.left(), r.top() + t.space_24 + t.space_4 + t.space_16), vec2(r.width(), t.space_16)),- note,- FontId::proportional(t.font_small),- t.form_dim,- );- response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), label));- scenario::publish_target(&format!("dialog:{label}"), r);- response.on_hover_cursor(egui::CursorIcon::PointingHand)-}-/// Compact informational state badge for settings; never an interactive control.pub(crate) fn settings_badge(ui: &mut Ui, text: &str, warning: bool) {if crate::prefs_search::suppress_chrome(ui) && !crate::prefs_search::texts_hit(ui, &[text]) {diff --git a/crates/ui-egui/src/ui_kit/preferences_cards.rs b/crates/ui-egui/src/ui_kit/preferences_cards.rsindex 54fbf9d025..149370951c 100644--- a/crates/ui-egui/src/ui_kit/preferences_cards.rs+++ b/crates/ui-egui/src/ui_kit/preferences_cards.rs@@ -392,79 +392,6 @@ pub(crate) fn help_icon(ui: &mut Ui, text: &str) -> Response {response.backing_on_hover_text(text)}-/// Which items of a carousel are shown: the first one and how many fit between the two arrows.-pub(super) fn carousel_window(count: usize, offset: usize, available: f32, item_width: f32, gap: f32, arrow: f32) -> (usize, usize) {- if count == 0 {- return (0, 0);- }- let room = dimension(available) - 2.0 * (arrow + gap);- let unit = dimension(item_width).max(1.0) + gap.max(0.0);- let visible = (((room + gap) / unit).floor() as usize).clamp(1, count);- (offset.min(count - visible), visible)-}--/// A row of items with a previous and a next arrow; an arrow is dimmed and inert at its end.-/// An arrow moves by the items that fit (#11434); the last page ends on the last item.-/// `item` paints the item at an index into a column `item_width` wide and `item_height` high.-pub(crate) fn carousel(- ui: &mut Ui,- id: impl std::hash::Hash + std::fmt::Debug,- count: usize,- item_width: f32,- item_height: f32,- mut item: impl FnMut(&mut Ui, usize),-) -> (usize, usize) {- let t = Tokens::get();- let key = ui.make_persistent_id(id);- let gap = t.space_8;- let arrow = t.space_24 + 2.0;- let offset = ui.data(|d| d.get_temp::<usize>(key)).unwrap_or(0);- let (first, visible) = carousel_window(count, offset, ui.available_width(), item_width, gap, arrow);- let height = dimension(item_height);- let mut next_offset = first;- ui.horizontal_top(|ui| {- ui.spacing_mut().item_spacing.x = gap;- let can_back = first > 0;- if carousel_arrow(ui, vec2(arrow, height), -1.0, can_back, crate::i18n::tr("prefs.carousel_previous")).clicked() {- next_offset = first.saturating_sub(visible);- }- for index in first..first + visible {- ui.allocate_ui_with_layout(vec2(dimension(item_width), height), egui::Layout::top_down(egui::Align::Min), |ui| {- ui.set_width(dimension(item_width));- item(ui, index);- });- }- let can_forward = first + visible < count;- if carousel_arrow(ui, vec2(arrow, height), 1.0, can_forward, crate::i18n::tr("prefs.carousel_next")).clicked() {- next_offset = (first + visible).min(count.saturating_sub(visible));- }- });- ui.data_mut(|d| d.insert_temp(key, next_offset));- (first, visible)-}--fn carousel_arrow(ui: &mut Ui, size: egui::Vec2, direction: f32, enabled: bool, label: &str) -> Response {- let t = Tokens::get();- let (rect, response) = ui.allocate_exact_size(size, if enabled { Sense::click() } else { Sense::hover() });- let alpha = if enabled { 1.0 } else { 0.35 };- let p = ui.painter();- let fill = if enabled && response.hovered() { t.hover } else { t.control_fill };- p.rect(rect, f32::from(t.radius_lg), fill.gamma_multiply(alpha), Stroke::new(1.0, t.dialog_border.gamma_multiply(alpha)), StrokeKind::Inside);- let icon = Rect::from_center_size(rect.center(), vec2(t.space_16, t.space_16));- let ink = t.form_ink.gamma_multiply(alpha);- if direction < 0.0 {- crate::icons::paint_ink_mirrored(p, icon, "chevron_right", ink);- } else {- crate::icons::paint_ink(p, icon, "chevron_right", ink);- }- if enabled && response.has_focus() {- p.rect_stroke(rect.expand(t.space_2), f32::from(t.radius_lg) + t.space_2, Stroke::new(t.space_2, t.form_primary), StrokeKind::Outside);- }- response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, label));- scenario::publish_target(&format!("prefs:carousel:{label}"), rect);- if enabled { response.on_hover_cursor(egui::CursorIcon::PointingHand) } else { response }-}-/// Installed add-on row: 12 pt padding, 36 pt mark and centred, unframed folder action.pub(crate) fn settings_plugin_card(ui: &mut Ui,diff --git a/crates/ui-egui/src/ui_kit/preferences_figure_ops.rs b/crates/ui-egui/src/ui_kit/preferences_figure_ops.rsindex 8f5a8728c8..aa809b6229 100644--- a/crates/ui-egui/src/ui_kit/preferences_figure_ops.rs+++ b/crates/ui-egui/src/ui_kit/preferences_figure_ops.rs@@ -298,6 +298,23 @@ pub(super) fn paint(p: &Painter, rect: Rect, figure: &Figure, sample: Option<&Thpaint_with_tokens(p, rect, figure, sample, clip, &Tokens::get(), Palette::Figure);}+/// Clip every miniature-window operation, including its top bar, to its rounded outline.+/// Rectangular scissoring alone leaves the bar's square corners outside the rounded ground.+pub(super) fn paint_rounded(p: &Painter, rect: Rect, figure: &Figure, sample: &ThemeSample, radius: f32) {+ let size = rect.size();+ if !rect.is_finite() || !size.is_finite() || size.min_elem() < 1.0 || size.max_elem() > MAX_SIDE || !radius.is_finite() {+ return;+ }+ let [fw, fh] = figure.size;+ if !(fw > 0.0 && fh > 0.0) {+ return;+ }+ let scale = (size.x / fw).min(size.y / fh);+ let outline: Vec<_> =+ rounded(Rect::from_min_size(Pos2::ZERO, vec2(fw, fh)), radius.max(0.0) / scale).into_iter().map(|point| [point.x, point.y]).collect();+ paint(p, rect, figure, Some(sample), Some(&outline));+}+/// Reuse the six canonical figures with the semantic palette being previewed, without global state.pub(super) fn paint_colour_vision(p: &Painter, rect: Rect, index: usize, t: &Tokens) {use super::preferences_figure_data as figures;diff --git a/crates/ui-egui/src/ui_kit/preferences_figures.rs b/crates/ui-egui/src/ui_kit/preferences_figures.rsindex 94267f0d1a..c63ce27be4 100644--- a/crates/ui-egui/src/ui_kit/preferences_figures.rs+++ b/crates/ui-egui/src/ui_kit/preferences_figures.rs@@ -295,14 +295,10 @@ pub(crate) fn paint_theme_thumbnail(p: &Painter, rect: Rect, sample: &ThemeSamplpaint(p, rect, &super::preferences_figure_data::THEME_THUMBNAIL, Some(sample), None);}-#[allow(dead_code, reason = "painted by the Preferences pages of #9875 to #9883")]-/// The "System" theme card: `light` with `dark` over a slanted band of it (the board clips the dark-/// half to the polygon 56 %,0 / 100 %,0 / 100 %,100 % / 40 %,100 %).-pub(crate) fn paint_theme_system(p: &Painter, rect: Rect, light: &ThemeSample, dark: &ThemeSample) {- const BAND: [[f32; 2]; 4] = [[69.44, 0.0], [124.0, 0.0], [124.0, 76.0], [49.6, 76.0]];- let figure = &super::preferences_figure_data::THEME_THUMBNAIL;- paint(p, rect, figure, Some(light), None);- paint(p, rect, figure, Some(dark), Some(&BAND));+/// The theme picker's thumbnails have an inner radius matching their card's border.+/// Keep other thumbnail callers' existing sizing and painting unchanged.+pub(crate) fn paint_theme_thumbnail_rounded(p: &Painter, rect: Rect, sample: &ThemeSample, radius: f32) {+ super::preferences_figure_ops::paint_rounded(p, rect, &super::preferences_figure_data::THEME_THUMBNAIL, sample, radius);}#[cfg(test)]@@ -364,7 +360,7 @@ mod tests {}}- use super::{ThemeSample, paint_theme_system, paint_theme_thumbnail};+ use super::{ThemeSample, paint_theme_thumbnail, paint_theme_thumbnail_rounded};use crate::theme::Tokens;use crate::ui_kit::preferences_figure_data::FIGURES;use egui::{Pos2, Rect, vec2};@@ -397,6 +393,34 @@ mod tests {]}+ #[test]+ fn theme_thumbnail_operations_stay_inside_the_rounded_inner_border() {+ let rect = Rect::from_min_size(Pos2::new(20.0, 20.0), vec2(124.0, 76.0));+ for dark in [false, true] {+ let sample = ThemeSample::from_tokens(&if dark { Tokens::dark() } else { Tokens::light() });+ for border in [1.0, 2.0] {+ let radius = f32::from(Tokens::get().radius_lg) - border;+ let centre_rect = rect.shrink(radius);+ let mut vertices = 0;+ for clipped in shapes(rect, |p, r| paint_theme_thumbnail_rounded(p, r, &sample, radius)) {+ crate::test_support::each_shape(&clipped.shape, &mut |shape| {+ if let egui::Shape::Mesh(mesh) = shape {+ for vertex in &mesh.vertices {+ let nearest = Pos2::new(+ vertex.pos.x.clamp(centre_rect.left(), centre_rect.right()),+ vertex.pos.y.clamp(centre_rect.top(), centre_rect.bottom()),+ );+ assert!(vertex.pos.distance(nearest) <= radius + 0.05, "thumbnail fill leaks outside rounded clip: {:?}", vertex.pos);+ vertices += 1;+ }+ }+ });+ }+ assert!(vertices > 20, "check the actual background and top-bar geometry");+ }+ }+ }+/// Every figure, in both themes, paints at size zero, tiny, normal, huge and non-finite without/// panicking, and at a normal size stays inside its rectangle with a bounded number of shapes.#[test]@@ -444,18 +468,16 @@ mod tests {}#[test]- fn theme_thumbnails_paint_with_the_sample_colours_and_a_slanted_system_band() {+ fn theme_thumbnails_paint_with_the_sample_colours() {let (light, dark) = (ThemeSample::from_tokens(&Tokens::light()), ThemeSample::from_tokens(&Tokens::dark()));assert_ne!(light, dark);let rect = Rect::from_min_size(Pos2::new(4.0, 4.0), vec2(124.0, 76.0));for rect in rects().into_iter().chain([rect]) {let _ = shapes(rect, |p, r| paint_theme_thumbnail(p, r, &light));- let _ = shapes(rect, |p, r| paint_theme_system(p, r, &light, &dark));}- let single = shapes(rect, |p, r| paint_theme_thumbnail(p, r, &light)).len();- let system = shapes(rect, |p, r| paint_theme_system(p, r, &light, &dark)).len();- assert!(system > single, "the dark band adds shapes over the light card");- for shape in shapes(rect, |p, r| paint_theme_system(p, r, &light, &dark)) {+ let single = shapes(rect, |p, r| paint_theme_thumbnail(p, r, &light));+ assert!(!single.is_empty());+ for shape in single {let bounds = shape.shape.visual_bounding_rect().intersect(shape.clip_rect);assert!(!bounds.is_positive() || rect.expand(1.0).contains_rect(bounds), "{bounds:?}");}diff --git a/crates/ui-egui/src/ui_kit/theme_picker.rs b/crates/ui-egui/src/ui_kit/theme_picker.rsnew file mode 100644index 0000000000..9f3ad9ddde--- /dev/null+++ b/crates/ui-egui/src/ui_kit/theme_picker.rs@@ -0,0 +1,549 @@+//! Shared theme browser vocabulary: toggle segments, slots, marked cards and scroll viewport.+use super::*;+use crate::{scenario, theme::Tokens};+use egui::{Align2, Color32, FontId, Painter, Rect, Response, Sense, Stroke, StrokeKind, Ui, pos2, vec2};++#[derive(Clone, Copy, PartialEq)]+pub(crate) enum ThemeGlyph {+ None,+ Sun,+ Moon,+ Contrast,+ Monitor,+ Carousel,+ Grid,+ Check,+ Import,+ Previous,+ Next,+}++fn glyph(p: &Painter, r: Rect, kind: ThemeGlyph, ink: Color32) {+ if !r.is_finite() || !r.is_positive() {+ return;+ }+ let scale = r.width().min(r.height()) / 24.0;+ let origin = r.center() - egui::Vec2::splat(Tokens::get().space_12) * scale;+ let at = |x, y| origin + vec2(x, y) * scale;+ let line = |points: &[[f32; 2]], width| {+ p.add(egui::Shape::line(points.iter().map(|[x, y]| at(*x, *y)).collect(), Stroke::new(width * scale, ink)));+ };+ let stroke = Stroke::new(2.0 * scale, ink);+ match kind {+ ThemeGlyph::None => {}+ ThemeGlyph::Sun => {+ p.circle_stroke(at(12.0, 12.0), 4.0 * scale, stroke);+ for points in [+ [[12.0, 2.0], [12.0, 5.0]],+ [[12.0, 19.0], [12.0, 22.0]],+ [[2.0, 12.0], [5.0, 12.0]],+ [[19.0, 12.0], [22.0, 12.0]],+ [[5.0, 5.0], [7.0, 7.0]],+ [[17.0, 17.0], [19.0, 19.0]],+ [[19.0, 5.0], [17.0, 7.0]],+ [[7.0, 17.0], [5.0, 19.0]],+ ] {+ line(&points, 2.0);+ }+ }+ ThemeGlyph::Moon => {+ // SVG A8 8 0 1 1 10 4: the large clockwise arc from (20,14).+ let centre = vec2(15.0 - 7.0_f32.sqrt(), 9.0 + 7.0_f32.sqrt());+ let start = (14.0 - centre.y).atan2(20.0 - centre.x);+ let end = (4.0 - centre.y).atan2(10.0 - centre.x) + std::f32::consts::TAU;+ let points: Vec<_> = (0..=32)+ .map(|i| {+ let a = start + (end - start) * i as f32 / 32.0;+ let point = centre + vec2(a.cos(), a.sin()) * 8.0;+ at(point.x, point.y)+ })+ .chain((0..=32).map(|i| {+ // SVG scales the second radius (6.5) to half the chord, sqrt(50).+ let a = -3.0 * std::f32::consts::FRAC_PI_4 - std::f32::consts::PI * i as f32 / 32.0;+ at(15.0 + a.cos() * 50.0_f32.sqrt(), 9.0 + a.sin() * 50.0_f32.sqrt())+ }))+ .collect();+ p.add(egui::Shape::closed_line(points, stroke));+ }+ ThemeGlyph::Contrast => {+ p.circle_stroke(at(12.0, 12.0), 9.0 * scale, stroke);+ line(&[[12.0, 3.0], [12.0, 21.0]], 2.0);+ let points = (0..=32)+ .map(|i| {+ let a = -std::f32::consts::FRAC_PI_2 + i as f32 / 32.0 * std::f32::consts::PI;+ at(12.0 + a.cos() * 9.0, 12.0 + a.sin() * 9.0)+ })+ .collect();+ p.add(egui::Shape::convex_polygon(points, ink, Stroke::NONE));+ }+ ThemeGlyph::Monitor => {+ p.rect_stroke(Rect::from_min_max(at(3.0, 4.0), at(21.0, 16.0)), 2.0 * scale, stroke, StrokeKind::Middle);+ line(&[[8.0, 20.0], [16.0, 20.0]], 2.0);+ line(&[[12.0, 16.0], [12.0, 20.0]], 2.0);+ }+ ThemeGlyph::Carousel => {+ for (x, y, w, h, radius, opacity) in+ [(2.0, 6.0, 5.0, 12.0, 1.2, 0.55), (9.0, 4.0, 6.0, 16.0, 1.5, 1.0), (17.0, 6.0, 5.0, 12.0, 1.2, 0.55)]+ {+ p.rect_filled(Rect::from_min_size(at(x, y), vec2(w, h) * scale), radius * scale, ink.gamma_multiply(opacity));+ }+ }+ ThemeGlyph::Grid => {+ for x in [3.0, 13.0] {+ for y in [3.0, 13.0] {+ p.rect_filled(Rect::from_min_size(at(x, y), egui::Vec2::splat(Tokens::get().space_8) * scale), 1.5 * scale, ink);+ }+ }+ }+ ThemeGlyph::Check => {+ line(&[[5.0, 12.0], [10.0, 17.0], [19.0, 7.0]], 3.2);+ }+ ThemeGlyph::Import => {+ line(&[[12.0, 4.0], [12.0, 15.0]], 2.0);+ line(&[[7.0, 10.0], [12.0, 15.0], [17.0, 10.0]], 2.0);+ line(&[[5.0, 20.0], [19.0, 20.0]], 2.0);+ }+ ThemeGlyph::Previous => line(&[[15.0, 5.0], [8.0, 12.0], [15.0, 19.0]], 2.4),+ ThemeGlyph::Next => line(&[[9.0, 5.0], [16.0, 12.0], [9.0, 19.0]], 2.4),+ }+}++pub(crate) struct ThemeSegment<'a> {+ label: &'a str,+ icon: ThemeGlyph,+ count: Option<usize>,+}+impl<'a> ThemeSegment<'a> {+ pub(crate) fn new(label: &'a str, icon: ThemeGlyph, count: Option<usize>) -> Self {+ Self { label, icon, count }+ }+}++pub(crate) fn theme_segments(ui: &mut Ui, key: &str, options: &[ThemeSegment<'_>], selected: Option<usize>, icon_only: bool) -> Option<usize> {+ let labels: Vec<_> = options.iter().map(|o| o.label).collect();+ crate::prefs_search::note_unlabelled(ui, &labels);+ if crate::prefs_search::querying(ui) && !crate::prefs_search::visible(ui, &labels) {+ return None;+ }+ let t = Tokens::get();+ let mut clicked = None;+ let icon_size = if key == "tone" || key == "contrast" { t.space_12 } else { t.space_14 };+ let widths: Vec<_> = options+ .iter()+ .map(|option| {+ let text = option.count.map(|n| format!("{} {n}", option.label)).unwrap_or_else(|| option.label.to_owned());+ let icon_width = if option.icon == ThemeGlyph::None { 0.0 } else { icon_size + t.space_6 };+ if icon_only { t.space_24 + t.space_10 } else { ContentWidth::name(ui, &text) + t.space_16 + icon_width }+ })+ .collect();+ // Reserve just the group's natural width. A nested horizontal Ui would reserve the+ // remaining row too, pushing the right-hand toolbar controls beyond the page.+ let (group, _) = ui.allocate_exact_size(vec2(widths.iter().sum(), t.control_height), Sense::hover());+ let mut x = group.left();+ for (index, option) in options.iter().enumerate() {+ let text = option.count.map(|n| format!("{} {n}", option.label)).unwrap_or_else(|| option.label.to_owned());+ let icon_size = if key == "tone" || key == "contrast" { t.space_12 } else { t.space_14 };+ let icon_width = if option.icon == ThemeGlyph::None { 0.0 } else { icon_size + t.space_6 };+ let width = widths.get(index).copied().unwrap_or_default();+ let r = Rect::from_min_size(pos2(x, group.top()), vec2(width, t.control_height));+ x += width;+ let response = ui.interact(r, ui.make_persistent_id((key, index)), Sense::click());+ let on = selected == Some(index);+ let rounding = egui::CornerRadius {+ nw: if index == 0 { t.radius_md } else { 0 },+ sw: if index == 0 { t.radius_md } else { 0 },+ ne: if index + 1 == options.len() { t.radius_md } else { 0 },+ se: if index + 1 == options.len() { t.radius_md } else { 0 },+ };+ let rounding = if options.len() == 1 { egui::CornerRadius::same((t.control_height / 2.0) as u8) } else { rounding };+ ui.painter().rect(+ r,+ rounding,+ if on {+ t.selected_bg+ } else if response.hovered() {+ t.hover+ } else {+ t.control_fill+ },+ Stroke::new(1.0, if on { t.form_primary } else { t.control_border }),+ StrokeKind::Inside,+ );+ let ink = if on { t.selected_ink } else { t.form_ink };+ let icon = Rect::from_center_size(+ if icon_only { r.center() } else { pos2(r.left() + t.space_8 + icon_size / 2.0, r.center().y) },+ vec2(icon_size, icon_size),+ );+ glyph(ui.painter(), icon, option.icon, ink);+ if !icon_only {+ ui.painter().text(+ pos2(r.left() + t.space_8 + icon_width, r.center().y),+ Align2::LEFT_CENTER,+ &text,+ FontId::proportional(t.font_label),+ ink,+ );+ }+ if response.has_focus() {+ ui.painter().rect_stroke(r.expand(t.space_2), rounding, Stroke::new(t.space_2, t.form_primary), StrokeKind::Outside);+ }+ response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), on, option.label));+ crate::prefs_search::remember(ui, option.label, r);+ crate::prefs_search::follow(ui, option.label, r);+ let visible = r.intersect(ui.clip_rect());+ if visible.is_positive() {+ scenario::publish_target(&format!("prefs:theme_{key}:{index}"), visible);+ }+ if response.clicked() {+ clicked = Some(index);+ }+ response.backing_on_hover_text(option.label).on_hover_cursor(egui::CursorIcon::PointingHand);+ }+ clicked+}++/// Reserve the trailing control first; the leading groups wrap within the space left.+/// Only the mode/import row supplies a nonzero stacking threshold (about 460 pt).+pub(crate) fn theme_toolbar<L, R>(+ ui: &mut Ui,+ key: &str,+ trailing_width: f32,+ stack_below: f32,+ leading: impl FnOnce(&mut Ui) -> L,+ trailing: impl FnOnce(&mut Ui) -> R,+) -> (L, R) {+ let t = Tokens::get();+ let width = bounded_width(ui);+ let gap = t.space_10;+ let stacked = width < stack_below;+ let right_width = trailing_width.min(width);+ let left_width = if stacked { width } else { (width - right_width - gap).max(0.0) };+ let start = ui.next_widget_position();+ let mut left = ui.new_child(+ egui::UiBuilder::new()+ .id_salt((key, "leading"))+ .max_rect(Rect::from_min_size(start, vec2(left_width, t.control_height)))+ .layout(egui::Layout::left_to_right(egui::Align::Center).with_main_wrap(true)),+ );+ left.set_clip_rect(left.clip_rect().intersect(Rect::from_x_y_ranges(start.x..=start.x + left_width, f32::NEG_INFINITY..=f32::INFINITY)));+ left.spacing_mut().item_spacing.x = t.space_8;+ let a = leading(&mut left);+ let left_height = left.min_size().y.max(t.control_height);+ let right_start = pos2(start.x + width - right_width, start.y + if stacked { left_height + gap } else { 0.0 });+ let mut right = ui.new_child(+ egui::UiBuilder::new()+ .id_salt((key, "trailing"))+ .max_rect(Rect::from_min_size(right_start, vec2(right_width, t.control_height)))+ .layout(egui::Layout::left_to_right(egui::Align::Center)),+ );+ let b = trailing(&mut right);+ let height = if stacked { left_height + gap + right.min_size().y } else { left_height.max(right.min_size().y) };+ let (rect, _) = ui.allocate_exact_size(vec2(width, height), Sense::hover());+ scenario::publish_rect(&format!("prefs:theme_toolbar:{key}"), rect);+ (a, b)+}++fn bounded_width(ui: &Ui) -> f32 {+ let available = super::metrics::dimension(ui.available_width());+ if ui.is_visible() { available.min((ui.clip_rect().right() - ui.next_widget_position().x).max(0.0)) } else { available }+}++pub(crate) fn theme_import_button(ui: &mut Ui, label: &str) -> Response {+ crate::prefs_search::note_unlabelled(ui, &[label]);+ if crate::prefs_search::querying(ui) && !crate::prefs_search::visible(ui, &[label]) {+ return crate::prefs_search::hidden_response(ui);+ }+ let t = Tokens::get();+ let width = ContentWidth::name(ui, label) + t.space_14 + t.space_6 + t.space_10 * 2.0;+ let (r, response) = ui.allocate_exact_size(vec2(width, t.control_height), Sense::click());+ ui.painter().rect(+ r,+ t.radius_md,+ if response.hovered() { t.hover } else { t.control_fill },+ Stroke::new(1.0, t.control_border),+ StrokeKind::Inside,+ );+ let icon = Rect::from_center_size(pos2(r.left() + t.space_10 + t.space_14 / 2.0, r.center().y), vec2(t.space_14, t.space_14));+ glyph(ui.painter(), icon, ThemeGlyph::Import, t.form_ink);+ ui.painter().text(pos2(icon.right() + t.space_6, r.center().y), Align2::LEFT_CENTER, label, FontId::proportional(t.font_label), t.form_ink);+ if response.has_focus() {+ ui.painter().rect_stroke(r.expand(t.space_2), t.radius_md, Stroke::new(t.space_2, t.form_primary), StrokeKind::Outside);+ }+ response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), label));+ crate::prefs_search::remember(ui, label, r);+ crate::prefs_search::follow(ui, label, r);+ response.on_hover_cursor(egui::CursorIcon::PointingHand)+}++pub(crate) struct ThemeSlot<'a> {+ pub title: &'a str,+ pub name: &'a str,+ pub hint: &'a str,+ pub aimed: bool,+ pub night: bool,+ pub width: f32,+ pub sample: ThemeSample,+}+pub(crate) fn theme_slot(ui: &mut Ui, slot: &ThemeSlot<'_>) -> Response {+ let t = Tokens::get();+ crate::prefs_search::note_unlabelled(ui, &[slot.title, slot.name, slot.hint]);+ if crate::prefs_search::querying(ui) && !crate::prefs_search::visible(ui, &[slot.title, slot.name, slot.hint]) {+ return crate::prefs_search::hidden_response(ui);+ }+ let (r, response) = ui.allocate_exact_size(vec2(slot.width.max(0.0), t.space_24 * 2.0 + t.space_16), Sense::click());+ ui.painter().rect(+ r,+ t.radius_lg,+ if slot.aimed { t.selected_bg } else { t.control_fill },+ Stroke::new(if slot.aimed { 2.0 } else { 1.0 }, if slot.aimed { t.form_primary } else { t.dialog_border }),+ StrokeKind::Inside,+ );+ let thumbnail = Rect::from_min_size(r.min + vec2(t.space_10, t.space_10), vec2(t.space_24 * 2.0 + t.space_16, t.space_24 * 2.0 - t.space_8));+ paint_theme_thumbnail_rounded(ui.painter(), thumbnail, &slot.sample, (f32::from(t.radius_lg) - if slot.aimed { 2.0 } else { 1.0 }).max(0.0));+ let x = thumbnail.right() + t.space_10;+ let icon = Rect::from_min_size(pos2(x, r.top() + t.space_10), vec2(t.space_12, t.space_12));+ glyph(ui.painter(), icon, if slot.night { ThemeGlyph::Moon } else { ThemeGlyph::Sun }, t.form_dim);+ let p = ui.painter().with_clip_rect(r.shrink(t.space_8).intersect(ui.clip_rect()));+ p.text(pos2(icon.right() + t.space_4, icon.center().y), Align2::LEFT_CENTER, slot.title, FontId::proportional(t.font_small), t.form_dim);+ p.text(pos2(x, r.bottom() - t.space_16 - t.space_4), Align2::LEFT_CENTER, slot.name, crate::fonts::semibold(t.font_label), t.form_ink);+ p.text(pos2(r.right() - t.space_10, r.center().y), Align2::RIGHT_CENTER, slot.hint, FontId::proportional(t.font_small), t.form_dim);+ response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), slot.aimed, slot.title));+ crate::prefs_search::remember(ui, slot.title, r);+ crate::prefs_search::follow(ui, slot.title, r);+ response.on_hover_cursor(egui::CursorIcon::PointingHand)+}++pub(crate) struct ThemeCard<'a> {+ pub name: &'a str,+ pub note: &'a str,+ pub options: Option<&'a str>,+ pub sample: ThemeSample,+ pub selected: bool,+ pub dark: bool,+ pub high: bool,+ pub day: bool,+ pub night: bool,+}+pub(crate) fn theme_card(ui: &mut Ui, card: &ThemeCard<'_>, width: f32) -> Response {+ let t = Tokens::get();+ let inner_radius = (f32::from(t.radius_lg) - if card.selected { 2.0 } else { 1.0 }).max(0.0);+ let response = picture_card(+ ui,+ &Card {+ label: card.name,+ sub: Some(card.note),+ selected: card.selected,+ enabled: true,+ options: None,+ check: false,+ aspect: 124.0 / 76.0,+ figure: &|p, r| paint_theme_thumbnail_rounded(p, r, &card.sample, inner_radius),+ },+ width,+ );+ if !response.rect.is_positive() {+ return response;+ }+ let r = response.rect;+ let size = t.space_16 + t.space_2;+ let badge_width = if card.high { t.space_10 * 2.0 + t.space_2 + t.space_4 * 2.0 } else { size };+ let badge = Rect::from_min_size(r.min + vec2(t.space_8, t.space_8), vec2(badge_width, size));+ let dark = Tokens::dark();+ ui.painter().rect_filled(badge, size / 2.0, dark.panel.gamma_multiply(0.85));+ let tone = Rect::from_center_size(pos2(badge.left() + t.space_4 + t.space_10 / 2.0, badge.center().y), vec2(t.space_10, t.space_10));+ glyph(ui.painter(), tone, if card.dark { ThemeGlyph::Moon } else { ThemeGlyph::Sun }, dark.text);+ if card.high {+ glyph(ui.painter(), tone.translate(vec2(t.space_12, 0.0)), ThemeGlyph::Contrast, dark.text);+ }+ let mut x = r.right() - t.space_8 - size / 2.0;+ for kind in [+ card.night.then_some(ThemeGlyph::Moon),+ card.day.then_some(ThemeGlyph::Sun),+ (card.selected && !card.day && !card.night).then_some(ThemeGlyph::Check),+ ]+ .into_iter()+ .flatten()+ {+ let centre = pos2(x, badge.center().y);+ ui.painter().circle_filled(centre, size / 2.0, t.form_primary);+ glyph(ui.painter(), Rect::from_center_size(centre, vec2(t.space_10 + 1.0, t.space_10 + 1.0)), kind, t.on_accent);+ x -= size + t.space_2;+ }+ if let Some(help) = card.options {+ let centre = pos2(r.right() - t.space_8 - size / 2.0, r.top() + t.space_4 + (width - t.space_8) * 76.0 / 124.0 - size / 2.0);+ ui.painter().circle_filled(centre, size / 2.0, t.form_primary);+ crate::icons::paint_ink(ui.painter(), Rect::from_center_size(centre, vec2(t.space_12, t.space_12)), "settings", t.on_accent);+ return response.backing_on_hover_text(help);+ }+ response+}++fn browser_frame<R>(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> egui::InnerResponse<R> {+ let container = Container::new(ui.ctx(), Surface::Navigation);+ let frame = super::preferences::settings_card_frame(ui).inner_margin(0);+ let border = frame.stroke.width;+ let width = bounded_width(ui);+ container.show_frame(ui, frame, ui.max_rect(), |ui| {+ ui.set_width((width - border * 2.0).max(0.0));+ add(ui)+ })+}++pub(crate) fn theme_empty(ui: &mut Ui, message: &str, clear: &str, reset: impl FnOnce()) {+ browser_frame(ui, |ui| {+ ui.set_min_width(ui.available_width());+ ui.set_min_height(Tokens::get().space_24 * 5.0);+ ui.vertical_centered(|ui| {+ ui.add_space(Tokens::get().space_24);+ ui.label(message);+ if ui.link(clear).clicked() {+ reset();+ }+ });+ scenario::publish_rect("prefs:theme_empty", ui.min_rect());+ });+}++/// A clipped row with overlaid fades, or five equal columns with vertical scrolling.+pub(crate) fn theme_browser(ui: &mut Ui, id: &str, count: usize, grid: bool, reveal: Option<usize>, mut item: impl FnMut(&mut Ui, usize, f32)) {+ let t = Tokens::get();+ let fill = super::preferences::settings_card_frame(ui).fill;+ browser_frame(ui, |ui| {+ let width = bounded_width(ui);+ let gap = t.space_8;+ let card_width = if grid { ((width - t.space_10 * 2.0 - gap * 4.0) / 5.0).max(1.0) } else { t.space_24 * 5.0 - t.space_2 };+ let card_height = (card_width - t.space_8) * 76.0 / 124.0 + t.space_16 + t.space_14 + t.space_8 + t.space_6;+ if grid {+ egui::ScrollArea::vertical()+ .id_salt((id, "grid"))+ .auto_shrink([false, false])+ .max_width(width)+ .max_height((card_height + gap) * 2.5)+ .show(ui, |ui| {+ let card_width = ((ui.available_width() - t.space_10 * 2.0 - gap * 4.0) / 5.0).max(1.0);+ ui.add_space(t.space_10);+ for row in (0..count).step_by(5) {+ ui.horizontal_top(|ui| {+ ui.spacing_mut().item_spacing.x = gap;+ ui.spacing_mut().item_spacing.y = gap;+ ui.allocate_exact_size(vec2((t.space_10 - gap).max(0.0), 0.0), Sense::hover());+ for index in row..(row + 5).min(count) {+ ui.allocate_ui_with_layout(vec2(card_width, card_height), egui::Layout::top_down(egui::Align::Min), |ui| {+ item(ui, index, card_width);+ if reveal == Some(index) {+ ui.scroll_to_rect(ui.min_rect(), None);+ }+ });+ }+ });+ }+ ui.add_space(t.space_10);+ });+ return;+ }+ let stride = card_width + gap;+ let padding = t.space_10;+ let content_width = count as f32 * stride - gap + padding * 2.0;+ let key = ui.make_persistent_id((id, "offset"));+ let mut offset = ui.data(|d| d.get_temp::<f32>(key)).unwrap_or_default();+ let max = (content_width - width).max(0.0);+ if let Some(index) = reveal {+ let start = padding + index as f32 * stride;+ if start < offset + padding {+ offset = start - padding;+ } else if start + card_width + padding > offset + width {+ offset = start + card_width + padding - width;+ }+ }+ offset = offset.clamp(0.0, max);+ let out = egui::ScrollArea::horizontal()+ .id_salt((id, "carousel"))+ .auto_shrink([false, true])+ .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysHidden)+ // egui normally maps vertical wheels to a horizontal-only scroll area.+ // Handle the horizontal axis below, leaving vertical input for the page.+ .scroll_source(egui::scroll_area::ScrollSource { mouse_wheel: false, ..Default::default() })+ .horizontal_scroll_offset(offset)+ .max_width(width)+ .max_height(card_height + padding * 2.0)+ .show(ui, |ui| {+ // A single reservation avoids implicit layout spacing below the row.+ // The end spacers scroll with the cards, so mid-scroll clipping still+ // reaches the box edges while both resting ends have equal padding.+ let (content, _) = ui.allocate_exact_size(vec2(content_width, card_height + padding * 2.0), Sense::hover());+ for index in 0..count {+ let at = content.min + vec2(padding + index as f32 * stride, padding);+ let mut card_ui = ui.new_child(+ egui::UiBuilder::new()+ .id_salt((id, index))+ .max_rect(Rect::from_min_size(at, vec2(card_width, card_height)))+ .layout(egui::Layout::top_down(egui::Align::Min)),+ );+ item(&mut card_ui, index, card_width);+ }+ });+ offset = out.state.clamped_offset().x;+ let r = out.inner_rect;+ let hovered = ui.rect_contains_pointer(r);+ let wheel = if hovered { crate::navigation::take_horizontal_wheel(ui, offset, max) } else { 0.0 };+ let horizontal_wheel = wheel != 0.0;+ if horizontal_wheel {+ offset = (offset - wheel).clamp(0.0, max);+ }+ let time_key = key.with("last_scroll");+ let now = ui.input(|i| i.time);+ if horizontal_wheel || ui.input(|i| i.pointer.any_down()) {+ ui.data_mut(|d| d.insert_temp(time_key, now));+ } else if let Some(last) = ui.data(|d| d.get_temp::<f64>(time_key)) {+ if now - last > 0.15 {+ offset = ((offset / stride).round() * stride).clamp(0.0, max);+ ui.data_mut(|d| d.remove::<f64>(time_key));+ } else {+ ui.ctx().request_repaint();+ }+ }+ for (left, present) in [(true, offset > 0.5), (false, offset < max - 0.5)] {+ if !present {+ continue;+ }+ let fade_width = (t.space_24 * 3.0 + t.space_12).min(r.width() / 2.0);+ let edge = if left { r.left() } else { r.right() };+ let end = edge + if left { fade_width } else { -fade_width };+ let mut mesh = egui::Mesh::default();+ let clear = fill.gamma_multiply(0.0);+ for (x, color) in [(edge, fill), (end, clear)] {+ mesh.colored_vertex(pos2(x, r.top()), color);+ mesh.colored_vertex(pos2(x, r.bottom()), color);+ }+ mesh.add_triangle(0, 1, 2);+ mesh.add_triangle(1, 3, 2);+ ui.painter().with_clip_rect(r).add(egui::Shape::mesh(mesh));+ let size = t.space_24 + t.space_4;+ let centre = pos2(edge + if left { t.space_8 + size / 2.0 } else { -t.space_8 - size / 2.0 }, r.center().y);+ let arrow = Rect::from_center_size(centre, vec2(size, size));+ let response = ui.interact(arrow, key.with(left), Sense::click());+ let shadow = t.shell_shadow();+ ui.painter().add(shadow.as_shape(arrow, egui::CornerRadius::same((size / 2.0) as u8)));+ ui.painter().circle(centre, size / 2.0, if response.hovered() { t.hover } else { t.control_fill }, Stroke::new(1.0, t.dialog_border));+ let icon = Rect::from_center_size(centre, vec2(t.space_14, t.space_14));+ glyph(ui.painter(), icon, if left { ThemeGlyph::Previous } else { ThemeGlyph::Next }, t.form_ink);+ if response.has_focus() {+ ui.painter().circle_stroke(centre, size / 2.0 + t.space_2, Stroke::new(t.space_2, t.form_primary));+ }+ let label = crate::i18n::tr(if left { "prefs.appearance.previous_themes" } else { "prefs.appearance.next_themes" });+ response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), label));+ scenario::publish_target(if left { "prefs:theme_previous" } else { "prefs:theme_next" }, arrow);+ if response.clicked() {+ // A screenful: the cards that fit in view, at least one (#11434).+ let page = (r.width() / stride).floor().max(1.0) * stride;+ offset = (offset + if left { -page } else { page }).clamp(0.0, max);+ }+ response.backing_on_hover_text(label).on_hover_cursor(egui::CursorIcon::PointingHand);+ }+ if (offset - out.state.clamped_offset().x).abs() > 0.1 {+ ui.ctx().request_repaint();+ }+ ui.data_mut(|d| d.insert_temp(key, offset));+ scenario::publish_rect("prefs:theme_viewport", r);+ });+}diff --git a/docs/design/preferences/pages/appearance.md b/docs/design/preferences/pages/appearance.mdindex a6f95545cc..f2ce7cee33 100644--- a/docs/design/preferences/pages/appearance.md+++ b/docs/design/preferences/pages/appearance.md@@ -5,16 +5,21 @@ Tag: In profile (hover "Saved in settings profiles"). Reference boards: `Theme_O`Settings_Interface` for Scale and text and Colour vision. Source today: Interface page(`prefs/interface.rs`).-## Theme (6 themes)+## Theme| Label | Control | Edits | Default | Hover | Figure | Notes ||---|---|---|---|---|---|---|-| Theme cards: Light (Built in), Dark (Built in), System (Follows the OS), Gruvbox (Built in), Studio glass (Imported file) | Carousel of picture cards (88 wide) with previous and next arrows ("Previous themes", "Next themes") | `Prefs.theme` (id string); "System" follows the OS (`app.window_theme`) | `"dark"` | "Has options" on the disc of cards that have theme options | `theme-light`, `theme-dark`, `theme-system-light-half` + `theme-system-dark-half`, `theme-gruvbox`, `theme-imported` | The count "6 themes" is the number of cards. Gruvbox and Studio glass carry the "has options" disc. Build the cards from the theme list in `theme_files` (built-ins in `assets/styles/ui/themes`, imported in `Prefs.custom_themes`); only the first five are drawn on the board, the carousel scrolls to the rest. |-| Import... / theme file | Dashed card at the end of the carousel | theme import (`Prefs.custom_themes`) | n/a | none | none | "Import..." with the sub-label "theme file". |+| One theme / Follow system | Segmented mode control, monitor / half-filled circle icons | `Prefs.theme` | One theme, `"dark"` | none | Painter glyphs | Follow system is `"system"`; System is no longer a theme card. Entering One theme selects the theme currently in effect. Entering Follow system assigns the previous theme to the slot matching its tone. |+| Import theme file… | Small import button, always at the right of the mode row | `Prefs.custom_themes` | n/a | Existing import help | Painter glyph | Keeps the file picker, drop target and desktop clipboard context menu. |+| Day theme / Night theme | Two slot cards with thumbnails, sun/moon icons, names and Pick from below / Change | `Prefs.theme_day`, `Prefs.theme_night` | `"light"`, `"dark"` | none | Existing thumbnail painter | Only shown in Follow system. Exactly one is aimed, initially Day. Clicking a slot presets Light/Dark; choosing a card fills only that slot. Unknown ids resolve to the slot's default. Both settings are persistent, command accessible, in Appearance profiles and restored by the page's defaults. |+| Light / Dark; Standard / High contrast; Imported | Independent toggle segments and an Imported chip, with counts | UI state | All clear | Count with the other filters applied | Painter glyphs | Clicking a selected filter clears it. A count ignores its own group. Interim classification in `theme_traits`: tone uses resolved thumbnail background luminance below 0.5; high contrast uses primary text/background contrast at least 20:1. The four maximal-contrast shipped themes measure 21:1; the others are at most 16.006:1. A later change will let themes declare these traits; this picker adds no theme-file fields. |+| Carousel / Grid | Icon-only view switch at the right of the filter row | UI state | Carousel | Accessible names | Painter glyphs | The browser reuses the theme-options panel's fill and stroke. Carousel content has equal 10 pt padding on all four sides at its resting ends; mid-scroll cards clip at the box edges, with 84 pt fades and round 28 pt arrows where there are more cards. Arrows move three cards. Horizontal wheel/trackpad input and dragging scroll and snap; predominantly vertical input passes through to the Preferences page. Grid has five equal columns, a vertical scroller and a height of about 2.5 rows. |+| Theme cards | Existing thumbnails, names, Built in / Imported file and optional · High contrast | `Prefs.theme` or the aimed slot | As above | Has options; context menu Export… and Remove for imported themes | Existing thumbnail painter | The section shows the real theme count excluding System. Tone/contrast badges sit at top left; check or Day/Night marks at top right. Selected and slot-holding cards use accent borders and selected backgrounds. Options keep their badge and panel. No search field or footer within the picker. |+| No theme matches these filters. / Clear filters | Empty well with reset link | All three filters | n/a | none | none | Clear filters leaves mode, aimed slot and view unchanged. |### Theme options panel ("Studio glass", "6 options", Reset)-Follows `Theme_Options.dc.html`. Shown under the carousel for a theme that has options. "Reset"+Follows `Theme_Options.dc.html`. Shown under the picker for the active theme when it has options. "Reset"restores the theme's own option values (`Prefs.theme_options[<theme>]`). Two columns.| Label | Control | Edits | Default | Hover | Notes |@@ -64,4 +69,7 @@ Source: `Settings_Interface.dc.html` (section "Scale and text").* The dark board's accent `#8CBEF5` has no token (see `tokens.md`).* Only `opacity` has a provider on main (`theme_options.rs`); blur, tab colours and the fade are standard idswithout one yet, so the board shows them ahead of the code.-* Only 5 of the 6 theme cards are drawn on the board.+The updated theme states are in `plan/theme-picker/Prefs2_Appearance_Theme.dc.html`; the interactive+behaviour and icon coordinates are in that folder's `SPEC.md` and `ICONS.md`. Filters, view and aimed+slot are window UI state, never saved preferences. Changes a default: no (default Day/Night retain the+previous operating-system Light/Dark resolution). Ctrl F still indexes theme names and picker labels.diff --git a/docs/ui-kit.md b/docs/ui-kit.mdindex 3ca4ef19de..4fa6e12890 100644--- a/docs/ui-kit.md+++ b/docs/ui-kit.md@@ -893,7 +893,7 @@ these shared pieces; the pages themselves arrive in later steps. Sizes follow| `preset_card(ui, name, word, selected, enabled, &icon, width)` | A 70 pt card with a 38 pt icon box (`icon` paints into it in the ink it is given), a name, one word and an accent check. Used for Performance, Quality and Custom. | as above, `pref_well` || `help_icon(ui, text)` | The (i) after a label. Shows `text` as a tooltip and exposes it as the widget's label. | `form_dim`, `form_ink` || `shortcut_binding(ui, chord, editable)` | Complete mono keycaps using the command-search painter; one focusable recorder target per binding, or a read-only label. Empty chords show dim Not assigned. `shortcut_binding_width` measures the same font and padding, including literal plus keys. Gallery: `shortcut_binding`. | `font_small/label`, `control_height`, `form_dim`, `form_primary`, `space_4/8/10`, `radius_sm` |-| `carousel(ui, id, count, item_width, item_height, item)` | A row of items between a previous and a next arrow (both labelled from the `prefs.carousel_*` messages). `carousel_window(count, offset, available, item_width, gap, arrow)` says which items show; an arrow moves by the number of items that fit, the last page ends on the last item, and the arrow at an end is dimmed (0.35) and inert. The first shown index is kept in the Ui's temporary memory under `id`. | `dialog_border`, `control_fill`, `hover`, `form_ink`, `radius_lg` |+| `theme_browser(ui, id, count, grid, reveal, item)` | The Appearance theme list: a carousel (one clipped row, an edge fade in the container fill, round arrows on a side with more cards, an arrow moves by the cards that fit, drag and horizontal wheel scroll while vertical wheel input goes to the page) or a 5-across grid with its own vertical scroll. `reveal` scrolls an index into view. The box and fades use the `settings_card_frame` fill and stroke. | `dialog_border`, `dialog_border`, `control_fill`, `hover`, `form_ink`, `radius_lg` |`card_look(selected, enabled, hovered, focused)` holds the state rules (border width, fill, ink, weight,dimming, focus ring) apart from the painting so they can be tested.@@ -929,7 +929,7 @@ Theme thumbnails (`paint_theme_thumbnail`, `paint_theme_system`) take a `ThemeSaThe Orientation figures and the visual-style icon are not repeated here: the app already has them.New pieces and figures each have an entry in `gallery::ELEMENTS` (`picture_card`, `toggle_tile`,-`preset_card`, `help_icon`, `carousel`, `preference_theme_thumbnails`, `preference_figures`), checked+`preset_card`, `help_icon`, `theme_browser`, `preference_theme_thumbnails`, `preference_figures`), checkedin both themes. `SOLIDCRAFT_PREFERENCE_WIDGET_EVIDENCE=<dir>` keeps the CPU-rendered boards(`preferences-widgets-*.png`, `preferences-figures-*.png`) from`preference_widgets_and_figures_board_in_both_themes`.