From 160662ffecc40928b116fa114840ed40bf48700c Mon Sep 17 00:00:00 2001 From: Nathan Dane Date: Sat, 31 Oct 2026 04:39:12 +0000 Subject: [PATCH] Tab colours: per-tab surfaces and fade (#8876) (#9808) * claim: #8876 * Resolve theme tab surfaces with cached Oklab transitions * Apply tab surfaces to unauthored Render preview backgrounds * Allow quantized endpoint colours late in cubic Render fades * Keep tab surface publication from restyling ordinary widgets --- assets/locales/pending/theme-tab-colours.json | 55 ++ crates/ui-egui/src/gpu.rs | 14 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/prefs.rs | 79 ++- crates/ui-egui/src/render_workspace.rs | 26 +- crates/ui-egui/src/render_workspace_tests.rs | 145 +++++ crates/ui-egui/src/theme.rs | 615 +++++++++++++++++- crates/ui-egui/src/theme_files.rs | 148 ++++- crates/ui-egui/src/theme_options.rs | 50 +- crates/ui-egui/src/toolbar.rs | 3 + crates/ui-egui/src/viewport.rs | 17 +- crates/ui-egui/tests/fixtures/theme-tabs.json | 34 + .../tests/scenarios/prefs_theme_files.json | 19 +- docs/book/src/guide/ui-tour.md | 43 +- 14 files changed, 1208 insertions(+), 41 deletions(-) create mode 100644 assets/locales/pending/theme-tab-colours.json create mode 100644 crates/ui-egui/tests/fixtures/theme-tabs.json diff --git a/assets/locales/pending/theme-tab-colours.json b/assets/locales/pending/theme-tab-colours.json new file mode 100644 index 000000000..21cd35441 --- /dev/null +++ b/assets/locales/pending/theme-tab-colours.json @@ -0,0 +1,55 @@ +{ + "ar": { + "prefs.theme_option_tab_colours": "ألوان علامات التبويب", + "prefs.theme_option_tab_colours_help": "استخدم ألوان اللوحة ومساحة العرض في هذه السمة لكل علامة تبويب في الشريط.", + "prefs.theme_option_tab_fade_ms": "انتقال علامات التبويب", + "prefs.theme_option_tab_fade_ms_help": "غيّر ألوان اللوحة ومساحة العرض تدريجيًا عند تبديل علامات التبويب. تؤدي القيمة صفر إلى التبديل فورًا." + }, + "de": { + "prefs.theme_option_tab_colours": "Tabfarben", + "prefs.theme_option_tab_colours_help": "Panel- und Ansichtsfarben dieses Designs je Registerkarte verwenden.", + "prefs.theme_option_tab_fade_ms": "Tabübergang", + "prefs.theme_option_tab_fade_ms_help": "Panel- und Ansichtsfarben beim Tabwechsel überblenden. Null wechselt sofort." + }, + "en": { + "prefs.theme_option_tab_colours": "Tab colors", + "prefs.theme_option_tab_colours_help": "Use this theme’s panel and viewport colors for each ribbon tab.", + "prefs.theme_option_tab_fade_ms": "Tab transition", + "prefs.theme_option_tab_fade_ms_help": "Fade panel and viewport colors when switching tabs. Zero switches instantly." + }, + "en-GB": { + "prefs.theme_option_tab_colours": "Tab colours", + "prefs.theme_option_tab_colours_help": "Use this theme’s panel and viewport colours for each ribbon tab.", + "prefs.theme_option_tab_fade_ms_help": "Fade panel and viewport colours when switching tabs. Zero switches instantly." + }, + "he": { + "prefs.theme_option_tab_colours": "צבעי כרטיסיות", + "prefs.theme_option_tab_colours_help": "השתמש בצבעי הלוח ואזור התצוגה של ערכת נושא זו עבור כל כרטיסייה ברצועת הכלים.", + "prefs.theme_option_tab_fade_ms": "מעבר בין כרטיסיות", + "prefs.theme_option_tab_fade_ms_help": "שנה בהדרגה את צבעי הלוח ואזור התצוגה בעת מעבר בין כרטיסיות. ערך אפס מבצע את המעבר מיד." + }, + "ja": { + "prefs.theme_option_tab_colours": "タブの色", + "prefs.theme_option_tab_colours_help": "リボンタブごとにテーマのパネルとビューポートの色を使用します。", + "prefs.theme_option_tab_fade_ms": "タブの切り替え", + "prefs.theme_option_tab_fade_ms_help": "タブの切り替え時にパネルとビューポートの色を徐々に変えます。0で即座に切り替えます。" + }, + "ko": { + "prefs.theme_option_tab_colours": "탭 색상", + "prefs.theme_option_tab_colours_help": "각 리본 탭에 이 테마의 패널 및 뷰포트 색상을 사용합니다.", + "prefs.theme_option_tab_fade_ms": "탭 전환", + "prefs.theme_option_tab_fade_ms_help": "탭을 전환할 때 패널 및 뷰포트 색상을 서서히 변경합니다. 0이면 즉시 전환합니다." + }, + "vi": { + "prefs.theme_option_tab_colours": "Màu thẻ", + "prefs.theme_option_tab_colours_help": "Sử dụng màu bảng điều khiển và khung nhìn của chủ đề này cho từng thẻ trên dải băng.", + "prefs.theme_option_tab_fade_ms": "Chuyển đổi thẻ", + "prefs.theme_option_tab_fade_ms_help": "Chuyển dần màu của bảng điều khiển và khung nhìn khi đổi thẻ. Đặt thành 0 để chuyển ngay lập tức." + }, + "zh": { + "prefs.theme_option_tab_colours": "选项卡颜色", + "prefs.theme_option_tab_colours_help": "为每个功能区选项卡使用主题的面板和视口颜色。", + "prefs.theme_option_tab_fade_ms": "选项卡过渡", + "prefs.theme_option_tab_fade_ms_help": "切换选项卡时渐变面板和视口颜色。设为零可立即切换。" + } +} diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 2e6ddcfbc..8a1953938 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -16,6 +16,20 @@ pub use solidcraft_gpu::view::{ /// A frame of the viewport as an egui paint callback. pub struct ViewportCallback(pub Frame); +/// The viewport callback composites transparently onto this egui GPU mesh. Both its clear +/// surface and gradient therefore use the same published/animated tokens as the panels; no +/// background colour belongs to a cached model scene or GPU upload. +pub(crate) fn paint_background(painter: &egui::Painter, rect: egui::Rect, tokens: &crate::theme::Tokens) { + let mut mesh = egui::Mesh::default(); + mesh.colored_vertex(rect.left_top(), tokens.viewport_top); + mesh.colored_vertex(rect.right_top(), tokens.viewport_top); + mesh.colored_vertex(rect.right_bottom(), tokens.viewport_bottom); + mesh.colored_vertex(rect.left_bottom(), tokens.viewport_bottom); + mesh.add_triangle(0, 1, 2); + mesh.add_triangle(0, 2, 3); + painter.add(egui::Shape::mesh(mesh)); +} + /// The GPU plan evaluation compiling beside the window: there once it is ready ([`tick_tessellation`]). pub type TessReady = std::sync::Arc>; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 1358cd015..18bd2fca6 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2573,6 +2573,7 @@ impl SolveApp { theme::apply(ctx); self.styled = true; } + theme::TabAccent::publish(self, ctx); if !self.fitted { self.fit_view(); self.fitted = true; diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index ea7adfc40..b8fe106f9 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -2053,7 +2053,10 @@ pub fn apply(app: &mut SolveApp, ctx: &egui::Context) { // A theme file's palette, in place of its base's (dark or light); the visuals follow. A // followed file (#7573) wins while it is followed and has read completely once. follow_theme_file(app, ctx); - let custom = active_theme_file(app).map(|f| crate::theme::Custom { dark: f.base.is_dark(), tokens: resolved_theme(&app.preferences, f) }); + let file = active_theme_file(app); + let custom = crate::theme::prepare_tabs(ctx, file, file.and_then(|f| app.preferences.theme_options.get(&f.id)), || { + file.map(|f| effective_theme_options(&app.preferences, f).0).unwrap_or_default() + }); if let Some(custom) = &custom { app.ui.dark = custom.dark; } @@ -3233,8 +3236,15 @@ fn theme_from_preferences(value: &serde_json::Value, strict: bool) -> Result(prefs: &Prefs, follow: &'a crate::theme_files::Follow) -> /// Preserve authored definitions; themes predating options retain their complete snapshot export. fn export_theme_file(file: &crate::theme_files::ThemeFile) -> serde_json::Value { - if !file.options.is_empty() || !file.overlays.is_empty() || file.needs_newer() { + if !file.options.is_empty() || !file.overlays.is_empty() || !file.tabs.is_empty() || file.needs_newer() { crate::theme_files::export_file(file) } else { crate::theme_files::export(&file.name, file.base, &crate::theme_files::resolve(file)) @@ -6306,10 +6316,10 @@ mod tests { ]})) .unwrap(); let rows = theme_option_rows(&file, "de", crate::theme_options::PROVIDERS); - assert_eq!(rows.iter().map(|r| r.definition.id.as_str()).collect::>(), ["opacity", "custom"]); + assert_eq!(rows.iter().map(|r| r.definition.id.as_str()).collect::>(), ["opacity", "tab_colours", "tab_fade_ms", "custom"]); assert_eq!(rows[0].label, "Deckkraft"); - assert_eq!(rows[1].label, "Eigene"); - assert_eq!(theme_option_rows(&file, "ja", crate::theme_options::PROVIDERS)[1].label, "Custom", "English fallback"); + assert_eq!(rows[3].label, "Eigene"); + assert_eq!(theme_option_rows(&file, "ja", crate::theme_options::PROVIDERS)[3].label, "Custom", "English fallback"); let providers = [Provider { id: "blur", label: "prefs.theme_option_opacity", @@ -6387,6 +6397,65 @@ mod tests { } } + #[test] + fn tabs_preferences_validate_atomically_restore_safely_and_preserve_export_defaults() { + for base in ["dark", "light"] { + let file = crate::theme_files::tab_fixture(base); + let source = serde_json::to_value(&file).unwrap(); + let mut h = crate::scenario::Harness::new(); + for invalid in [json!(false), json!({"sketch":{}}), json!({"SKETCH":{"error":"#ffffff"}}), json!({"SKETCH":{"panel":"bad"}})] { + let mut damaged = source.clone(); + damaged["tabs"] = invalid; + let before = h.app.preferences.clone(); + let error = control(&mut h.app, &json!({"custom_themes":[damaged],"theme":file.id,"ui_scale":1.5,"open":"Interface"})).unwrap_err(); + assert!(error.contains("tabs"), "{error}"); + assert_eq!(h.app.preferences, before); + assert!(!h.app.prefs_window.open); + h.app.load_prefs(&json!({"preferences":{"custom_themes":[damaged,source],"theme":file.id,"zoom_reverse":true}}).to_string()); + assert_eq!(h.app.preferences.custom_themes.len(), 2); + assert!(h.app.preferences.custom_themes[0].tabs.is_empty()); + assert_eq!(h.app.preferences.custom_themes[1].tabs, file.tabs); + assert!(h.app.preferences.zoom_reverse); + } + let out = control(&mut h.app, &json!({"custom_themes":[source],"theme":file.id,"theme_options":{&file.id:{"tab_colours":false,"tab_fade_ms":123}},"theme_export":true})).unwrap(); + assert_eq!(out["theme_file"]["tabs"], serde_json::to_value(&file.tabs).unwrap()); + assert_eq!(out["theme_file"]["options"][0]["default"], true); + assert_eq!(out["theme_file"]["options"][1]["default"], 240.0); + assert_eq!(out["theme_option_values"]["tab_fade_ms"], 123.0, "step is a control increment, never rounding"); + assert_eq!(out["theme_option_defs"].as_array().unwrap().iter().find(|o| o["id"] == "tab_fade_ms").unwrap()["step"], 20.0); + let mut restored = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + restored.load_prefs(&h.app.prefs()); + assert_eq!(restored.preferences.custom_themes, h.app.preferences.custom_themes); + assert_eq!(restored.preferences.theme_options, h.app.preferences.theme_options); + } + } + + #[test] + fn tabs_followed_reload_updates_surfaces_without_losing_saved_options() { + let mut h = crate::scenario::Harness::new(); + let mut source = crate::theme_files::export_file(&crate::theme_files::tab_fixture("dark")); + let path = h.dir.join("tabs.json"); + std::fs::write(&path, source.to_string()).unwrap(); + control(&mut h.app, &json!({"theme_follow":path,"theme_options":{"file-tabs-dark":{"tab_fade_ms":0}}})).unwrap(); + assert!(h.call("engine.execute", json!({"command":"sketch.create","params":{"plane":"XY"}}))["ok"].as_bool().unwrap()); + h.frames(2); + assert_eq!(Tokens::get().viewport_top, egui::Color32::from_rgb(0x10, 0x31, 0x28)); + source["tabs"]["SKETCH"]["viewport_top"] = json!("#1a4232"); + std::fs::write(&path, source.to_string()).unwrap(); + control(&mut h.app, &json!({"theme_follow":path})).unwrap(); + h.frames(2); + assert_eq!(Tokens::get().viewport_top, egui::Color32::from_rgb(0x1a, 0x42, 0x32)); + assert_eq!(h.app.preferences.theme_options["file-tabs-dark"]["tab_fade_ms"], 0); + source["tabs"]["SKETCH"]["warning"] = json!("#ffffff"); + std::fs::write(&path, source.to_string()).unwrap(); + assert!(control(&mut h.app, &json!({"theme_follow":path})).unwrap()["theme_follow_error"].as_str().unwrap().contains("warning")); + h.frames(2); + assert_eq!(Tokens::get().viewport_top, egui::Color32::from_rgb(0x1a, 0x42, 0x32)); + control(&mut h.app, &json!({"theme_follow":""})).unwrap(); + h.frames(2); + assert_eq!(Tokens::get(), Tokens::dark()); + } + #[test] fn theme_options_direct_definitions_validate_and_restore_safely() { let mut source = option_theme_file("Options A"); diff --git a/crates/ui-egui/src/render_workspace.rs b/crates/ui-egui/src/render_workspace.rs index 98347e2c6..509a8cc2e 100644 --- a/crates/ui-egui/src/render_workspace.rs +++ b/crates/ui-egui/src/render_workspace.rs @@ -3,7 +3,7 @@ use std::hash::{Hash, Hasher}; use std::sync::{Arc, Mutex}; -use egui::{Color32, Sense}; +use egui::Sense; use serde_json::json; use solidcraft_engine::doc::render_settings::RenderSetup; #[cfg(test)] @@ -1944,6 +1944,27 @@ pub fn preview_size(executor: Option<&ExecutorDescriptor>, full: (u64, u64)) -> executor.and_then(|e| e.fit(full.0, full.1)).unwrap_or(full) } +/// Theme only the untouched, unsaved preview. Saved setups have no background provenance, +/// so even a saved default-colour backplate remains scene-owned. Never alter image requests. +fn preview_background(app: &SolveApp) -> Tokens { + let view = &app.render_workspace.view; + let tokens = Tokens::get(); + if crate::theme::tab_surfaces_enabled() + && !app.session.doc.render.setups.contains_key(&view.name) + && view.clean_setup.as_ref().is_some_and(|clean| clean.background == view.draft.background) + && !view.transparent + && !view.studio.backdrop_enabled + && view.studio.environment == studio::Environment::None + && view.cpu.environment == cpu::Environment::None + && view.raytrace.environment.is_none() + { + // Includes the current fade and explicit viewport palette/flat-colour preferences. + tokens + } else { + tokens.with_background(Some(view.draft.background)) + } +} + pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { if app.render_workspace.view.result { app.render_workspace.view.environment_ring = environment::RingView::default(); @@ -1998,8 +2019,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { } else { app.viewport.hover = None; } - let bg = app.render_workspace.view.draft.background; - ui.painter().rect_filled(viewport, 0.0, Color32::from_rgb(bg[0], bg[1], bg[2])); + crate::gpu::paint_background(ui.painter(), viewport, &preview_background(app)); let result = (|| -> Result<(), String> { if app.viewport.gpu.is_none() { return Err(crate::i18n::tr("render.error_gpu_preview").into()); diff --git a/crates/ui-egui/src/render_workspace_tests.rs b/crates/ui-egui/src/render_workspace_tests.rs index d61f924ca..ea6a4f01e 100644 --- a/crates/ui-egui/src/render_workspace_tests.rs +++ b/crates/ui-egui/src/render_workspace_tests.rs @@ -1,5 +1,6 @@ use super::*; use crate::scenario::Harness; +use egui::Color32; use solidcraft_engine::Session; fn environment_editor_frame(h: &mut Harness, events: Vec) { @@ -1349,6 +1350,150 @@ fn saved_camera_survives_frames_and_product_fit_ignores_selection() { assert_eq!(h.app.cam, design); } +/// Inspect the mesh submitted by the actual Render canvas, including its GPU-unavailable path. +/// This is a headless colour handoff assertion, not a rendered-pixel or screenshot comparison. +fn render_preview_background_frame(h: &mut Harness, time: f64) -> [Color32; 4] { + let app = &mut h.app; + let mut viewport = egui::Rect::NOTHING; + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), + time: Some(time), + ..Default::default() + }, + |ui| { + app.logic(ui.ctx()); + viewport = ui.max_rect(); + show(app, ui); + }, + ); + let corners = [viewport.left_top(), viewport.right_top(), viewport.right_bottom(), viewport.left_bottom()]; + let colors = output + .shapes + .iter() + .find_map(|shape| match &shape.shape { + egui::Shape::Mesh(mesh) if mesh.vertices.len() == 4 && mesh.vertices.iter().zip(corners).all(|(vertex, corner)| vertex.pos == corner) => { + Some(std::array::from_fn(|i| mesh.vertices[i].color)) + } + _ => None, + }) + .expect("Render must paint a background mesh over the full viewport"); + output.textures_delta.clear(); + colors +} + +#[test] +fn render_preview_tab_surfaces_use_published_gradient_through_fade() { + for base in ["dark", "light"] { + let mut h = Harness::new(); + let file = crate::theme_files::tab_fixture(base); + crate::prefs::control(&mut h.app, &json!({"theme_import":crate::theme_files::export_file(&file)})).unwrap(); + let app = &mut h.app; + h.ctx.run_ui(egui::RawInput { time: Some(1.0), ..Default::default() }, |ui| app.logic(ui.ctx())).textures_delta.clear(); + let model = Tokens::get(); + enter(&mut h.app, true).unwrap(); + assert!(h.app.session.doc.render.setups.is_empty()); + let document = h.app.session.doc.clone(); + let request = image_request(&h.app).unwrap(); + let history = (h.app.session.revision, h.app.session.undo.len()); + let end = crate::theme_files::resolve_for_tab(&file, &Default::default(), Some("RENDER")); + let expected_start = [model.viewport_top, model.viewport_top, model.viewport_bottom, model.viewport_bottom]; + let expected_end = [end.viewport_top, end.viewport_top, end.viewport_bottom, end.viewport_bottom]; + let mut previous = expected_start; + for progress in [0.0, 0.25, 0.5, 0.75, 1.0] { + let colors = render_preview_background_frame(&mut h, 2.0 + 0.24 * progress); + let shown = Tokens::get(); + assert_eq!(colors, [shown.viewport_top, shown.viewport_top, shown.viewport_bottom, shown.viewport_bottom]); + if progress == 0.0 { + assert_eq!(colors, expected_start); + } else if progress == 1.0 { + assert_eq!(colors, expected_end); + } else if progress <= 0.5 { + assert_ne!(colors, expected_start, "the Render canvas must leave the starting colours at {progress}"); + assert_ne!(colors, expected_end, "the Render canvas must receive intermediate fade colours at {progress}"); + assert_ne!(colors, previous, "the Render canvas fade must advance between early samples at {progress}"); + } + // At 75% elapsed time, ease-out cubic is already 98.4375% of the way to the + // destination. Byte quantization can legitimately produce the exact final colours. + previous = colors; + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len()), history); + assert_eq!(image_request(&h.app).unwrap(), request, "UI themes never modify rendered image settings"); + } + assert_eq!(render_preview_background_frame(&mut h, 3.0), expected_end); + } +} + +#[test] +fn render_preview_tab_surfaces_preserve_scene_backplates_and_viewport_overrides() { + for base in ["dark", "light"] { + let mut h = Harness::new(); + let file = crate::theme_files::tab_fixture(base); + crate::prefs::control( + &mut h.app, + &json!({ + "theme_import":crate::theme_files::export_file(&file), + "theme_options":{&file.id:{"tab_fade_ms":0}} + }), + ) + .unwrap(); + enter(&mut h.app, true).unwrap(); + let scene_rgb = h.app.render_workspace.view.draft.background; + let scene = [Color32::from_rgb(scene_rgb[0], scene_rgb[1], scene_rgb[2]); 4]; + let gradient = render_preview_background_frame(&mut h, 1.0); + assert_ne!(gradient, scene); + + crate::prefs::control(&mut h.app, &json!({"theme_options":{&file.id:{"tab_colours":false}}})).unwrap(); + assert_eq!(render_preview_background_frame(&mut h, 2.0), scene); + crate::prefs::control( + &mut h.app, + &json!({"theme_options":{&file.id:{"tab_colours":true}},"viewport_theme":if base == "dark" {"light"} else {"dark"}}), + ) + .unwrap(); + let opposite = if base == "dark" { Tokens::light() } else { Tokens::dark() }; + assert_eq!( + render_preview_background_frame(&mut h, 3.0), + [opposite.viewport_top, opposite.viewport_top, opposite.viewport_bottom, opposite.viewport_bottom] + ); + crate::prefs::control(&mut h.app, &json!({"viewport_theme":"theme","viewport_background":[3,7,11]})).unwrap(); + assert_eq!(render_preview_background_frame(&mut h, 4.0), [Color32::from_rgb(3, 7, 11); 4]); + + // Authored scene intent takes priority even over a viewport preference. Test temporary + // drafts as well as saved setups, without persisting any theme colour into the scene. + let original = h.app.render_workspace.view.clone(); + for case in 0..6 { + h.app.render_workspace.view = original.clone(); + match case { + 0 => h.app.render_workspace.view.draft.background = [21, 43, 65], + 1 => h.app.render_workspace.view.transparent = true, + 2 => h.app.render_workspace.view.studio.backdrop_enabled = true, + 3 => h.app.render_workspace.view.studio.environment = studio::Environment::Sky, + 4 => h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant, + _ => { + h.app.render_workspace.view.raytrace.environment = + Some(solidcraft_engine::render::job::RaytraceEnvironmentOptions { color: [0.2, 0.3, 0.4], intensity: 1.0 }) + } + } + let expected = if case == 0 { [Color32::from_rgb(21, 43, 65); 4] } else { scene }; + assert_eq!(render_preview_background_frame(&mut h, 5.0 + f64::from(case)), expected); + } + h.app.render_workspace.view = original; + h.app.run("render.settings.set", json!({"name":"Studio","set":{"camera":h.app.cam}})).unwrap(); + setups::load(&mut h.app); + let authored = h.app.session.doc.clone(); + assert_eq!(render_preview_background_frame(&mut h, 11.0), scene, "even a saved default-colour backplate is scene-owned"); + assert!(Arc::ptr_eq(&authored, &h.app.session.doc)); + + // A theme without tabs keeps the legacy Render background, as do built-in themes. + h.app.render_workspace.view.name = "Unsaved".into(); + setups::load(&mut h.app); + crate::prefs::control(&mut h.app, &json!({"theme_import":{"format":"solidcraft-theme/1","name":"No tabs","base":base}})).unwrap(); + assert_eq!(render_preview_background_frame(&mut h, 12.0), scene); + crate::prefs::control(&mut h.app, &json!({"theme":base})).unwrap(); + assert_eq!(render_preview_background_frame(&mut h, 13.0), scene); + } +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn progressive_image_controls_route_to_the_registered_host() { diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 1677d2995..e6616aaa0 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -3,6 +3,7 @@ //! set any of their colours (`theme_files`). Every colour the UI uses comes from [`Tokens`]. use std::cell::Cell; +use std::collections::BTreeMap; #[path = "../../../assets/styles/ui/palettes.rs"] mod palettes; @@ -25,6 +26,7 @@ thread_local! { /// The palette of a theme file (`theme_files`) in place of the built-in one of its base /// (dark or light), per thread like the rest. `None`: the built-in palettes. static CUSTOM: Cell> = const { Cell::new(None) }; + static CUSTOM_GENERATION: Cell = const { Cell::new(0) }; /// The application bar's logo in the theme's accent instead of its own logo colours /// (Preferences › Interface › Logo), per thread like the rest. static LOGO_ACCENT: Cell = const { Cell::new(false) }; @@ -34,6 +36,298 @@ thread_local! { /// The 3D view's background colour when Preferences give it one (#7688), per thread like the /// rest. `None`: the theme's gradient. static VIEWPORT_BACKGROUND: Cell> = const { Cell::new(None) }; + /// The last published frame, guarded by every palette input so another app/context cannot + /// reuse it after changing the thread's theme. Resolution/fade state lives in that context. + static PUBLISHED: Cell> = const { Cell::new(None) }; +} + +/// Exact registry names, including contextual/specialty tabs and legacy Render sub-tabs that +/// still share the Render accent. Unknown names must never silently become Model on import. +pub(crate) const TAB_NAMES: &[&str] = &[ + "MODEL", + "SKETCH", + "SURFACE", + "MESH", + "FORM", + "SHEET METAL", + "WELDMENTS", + "ASSEMBLE", + "INSERT", + "INSPECT", + "MANAGE", + "VIEW", + "RENDER", + "RENDER APPEARANCE", + "RENDER SCENE", + "RENDER CAMERA", +]; + +#[derive(Clone, Copy, Debug, PartialEq)] +struct Environment { + dark: bool, + vision: ColorVision, + custom_generation: u64, + logo: bool, + viewport: Option, + background: Option<[u8; 3]>, +} + +impl Environment { + fn current() -> Self { + Self { + dark: is_dark(), + vision: vision(), + custom_generation: CUSTOM_GENERATION.get(), + logo: LOGO_ACCENT.get(), + viewport: VIEWPORT_DARK.get(), + background: viewport_background(), + } + } + + fn window(self, tokens: Tokens) -> Tokens { + let tokens = if self.logo { tokens.with_accent_logo() } else { tokens }; + tokens.with_vision(self.dark, self.vision) + } +} + +#[derive(Clone, Copy)] +struct PublishedTab { + environment: Environment, + tokens: Tokens, + view: Tokens, + tab_surfaces: bool, +} + +#[derive(Clone)] +struct PreparedTheme { + file: crate::theme_files::ThemeFile, + raw: Option>, + values: BTreeMap, + base: Custom, + enabled: bool, + fade_ms: f32, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +struct Surfaces { + panel: Color32, + top: Color32, + bottom: Color32, +} + +impl Surfaces { + fn of(t: Tokens) -> Self { + Self { panel: t.panel, top: t.viewport_top, bottom: t.viewport_bottom } + } + + fn apply(self, t: &mut Tokens) { + t.panel = self.panel; + t.viewport_top = self.top; + t.viewport_bottom = self.bottom; + } + + fn blend(self, to: Self, progress: f32) -> Self { + // Return endpoints verbatim, including premultiplied alpha and byte rounding. + if progress <= 0.0 { + return self; + } + if progress >= 1.0 { + return to; + } + let eased = 1.0 - (1.0 - progress).powi(3); + Self { + panel: oklab_blend(self.panel, to.panel, eased), + top: oklab_blend(self.top, to.top, eased), + bottom: oklab_blend(self.bottom, to.bottom, eased), + } + } +} + +/// Interpolate unassociated sRGB in Oklab; alpha stays independent and is premultiplied once +/// by Color32 on output. This avoids dark fringes when an opacity provider is also enabled. +fn oklab_blend(from: Color32, to: Color32, fraction: f32) -> Color32 { + let lab = |color: Color32| { + let [r, g, b, a] = color.to_srgba_unmultiplied(); + let decode = solidcraft_engine::geom::srgb::decode8; + let (r, g, b) = (decode(r), decode(g), decode(b)); + let l = (0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b).cbrt(); + let m = (0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b).cbrt(); + let s = (0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b).cbrt(); + [ + 0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s, + 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s, + 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s, + f64::from(a), + ] + }; + let (a, b) = (lab(from), lab(to)); + let mix = |i: usize| a[i] + (b[i] - a[i]) * f64::from(fraction); + let (light, a, b) = (mix(0), mix(1), mix(2)); + let l = (light + 0.3963377774 * a + 0.2158037573 * b).powi(3); + let m = (light - 0.1055613458 * a - 0.0638541728 * b).powi(3); + let s = (light - 0.0894841775 * a - 1.2914855480 * b).powi(3); + let encode = |linear: f64| { + let linear = linear.clamp(0.0, 1.0); + let srgb = if linear <= 0.0031308 { 12.92 * linear } else { 1.055 * linear.powf(1.0 / 2.4) - 0.055 }; + (srgb * 255.0).round() as u8 + }; + Color32::from_rgba_unmultiplied( + encode(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s), + encode(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s), + encode(-0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s), + mix(3).round() as u8, + ) +} + +#[derive(Clone, Copy)] +struct Fade { + from: Surfaces, + to: Surfaces, + start: f64, + seconds: f64, +} + +impl Fade { + fn sample(self, now: f64) -> (Surfaces, bool) { + if !now.is_finite() || self.seconds <= 0.0 { + return (self.to, false); + } + let progress = ((now - self.start) / self.seconds).clamp(0.0, 1.0) as f32; + (self.from.blend(self.to, progress), progress < 1.0) + } +} + +#[derive(Clone, Default)] +struct TabThemeState { + prepared: Option, + environment: Option, + targets: BTreeMap, + tab: String, + shown: Option, + fade: Option, + /// Ownership of the two egui fills survives target/theme invalidation until restored. + styled_surfaces: bool, + #[cfg(test)] + resolutions: usize, +} + +#[derive(Clone, Copy)] +struct TabTarget { + tokens: Tokens, + view: Tokens, + accent: TabAccent, +} + +const TAB_STATE: &str = "sc_tab_theme_state"; + +/// Cache the authored theme and raw saved values before any effective-value normalization. +/// Followed-file reloads use full content equality, including edits that keep the same id/base. +/// The caller supplies its existing normalization contract only on a cache miss. +pub(crate) fn prepare_tabs( + ctx: &egui::Context, + file: Option<&crate::theme_files::ThemeFile>, + raw: Option<&BTreeMap>, + values: impl FnOnce() -> BTreeMap, +) -> Option { + ctx.data_mut(|data| { + let state = data.get_temp_mut_or_default::(egui::Id::new(TAB_STATE)); + let same = match (&state.prepared, file) { + (Some(old), Some(file)) => old.file == *file && old.raw.as_ref() == raw, + (None, None) => true, + _ => false, + }; + if !same { + state.prepared = file.map(|file| { + let values = values(); + let (enabled, fade_ms) = crate::theme_options::tab_settings(file, &values); + let base = Custom { dark: file.base.is_dark(), tokens: crate::theme_files::resolve_with(file, &values) }; + PreparedTheme { file: file.clone(), raw: raw.cloned(), values, base, enabled, fade_ms } + }); + state.environment = None; + state.targets.clear(); + // A theme/option change applies immediately; only tab changes animate. + state.shown = None; + state.fade = None; + PUBLISHED.set(None); + } + state.prepared.as_ref().map(|p| p.base) + }) +} + +impl TabThemeState { + fn publish(&mut self, tab: &str, now: f64) -> (PublishedTab, TabAccent, bool) { + let environment = Environment::current(); + if self.environment != Some(environment) { + self.environment = Some(environment); + self.targets.clear(); + self.shown = None; + self.fade = None; + } + // Bound the cache even if an internal caller supplies an unknown tab name. + let tab = if TAB_NAMES.contains(&tab) { tab } else { "MODEL" }; + // Borrow the key on resting frames; own a name only when caching a new target. + let target = if let Some(target) = self.targets.get(tab) { + *target + } else { + #[cfg(test)] + { + self.resolutions += 1; + } + let window = if let Some(prepared) = &self.prepared { + environment.window(crate::theme_files::resolve_for_tab(&prepared.file, &prepared.values, Some(tab))) + } else { + Tokens::themed(environment.dark, environment.vision) + }; + let accent = TabAccent::for_tab(&window, tab); + let window = if viewport_dark() == is_dark() { window } else { window.with_viewport(Tokens::themed(viewport_dark(), vision())) }; + let target = TabTarget { + tokens: window.with_background(environment.background), + view: Tokens::themed(viewport_dark(), vision()).with_background(environment.background), + accent, + }; + self.targets.insert(tab.to_owned(), target); + target + }; + let destination = Surfaces::of(target.tokens); + // Sample the old fade before retargeting, even when two tab changes happen in one frame. + if let Some(fade) = self.fade { + let (shown, running) = fade.sample(now); + let mut current = target.tokens; + shown.apply(&mut current); + if running { + current.protect_tab_panel(); + } + self.shown = Some(Surfaces::of(current)); + if !running { + self.fade = None; + } + } + if self.tab != tab || self.shown.is_none() { + let duration = self.prepared.as_ref().filter(|p| p.enabled).map_or(0.0, |p| p.fade_ms); + self.fade = self.shown.filter(|from| *from != destination && duration > 0.0 && now.is_finite()).map(|from| Fade { + from, + to: destination, + start: now, + seconds: f64::from(duration) / 1000.0, + }); + tab.clone_into(&mut self.tab); + if self.fade.is_none() { + self.shown = Some(destination); + } + } + let mut tokens = target.tokens; + self.shown.unwrap_or(destination).apply(&mut tokens); + // Protect interpolated alpha too; opacity's readability floor applies throughout a fade. + if self.fade.is_some() { + tokens.protect_tab_panel(); + } + self.shown = Some(Surfaces::of(tokens)); + let mut view = if viewport_dark() == is_dark() { tokens } else { target.view }; + view.viewport_top = tokens.viewport_top; + view.viewport_bottom = tokens.viewport_bottom; + let tab_surfaces = self.prepared.as_ref().is_some_and(|p| p.enabled && !p.file.tabs.is_empty()); + (PublishedTab { environment, tokens, view, tab_surfaces }, target.accent, self.fade.is_some()) + } } /// Three structural border levels plus independent content and control outlines. @@ -233,7 +527,11 @@ pub struct Custom { /// Use a theme file's palette for its base, or the built-in palettes (`None`). Returns whether /// that changed anything (the visuals follow on the next [`apply`]). pub fn set_custom(custom: Option) -> bool { - CUSTOM.with(|c| c.replace(custom) != custom) + let changed = CUSTOM.with(|c| c.replace(custom) != custom); + if changed { + CUSTOM_GENERATION.with(|generation| generation.set(generation.get().wrapping_add(1))); + } + changed } /// Draw the logo in the theme's accent (`true`) or its own logo colours. Returns whether that @@ -295,15 +593,22 @@ pub(crate) fn composite(fill: Color32, background: Color32) -> Color32 { } fn readable_fill(fill: Color32, inks: &[Color32], scale: f32) -> Color32 { + let readable = |candidate| { + [Color32::BLACK, Color32::WHITE].iter().all(|background| { + let ground = composite(candidate, *background); + inks.iter().all(|ink| contrast_ratio(composite(*ink, ground), ground) >= 4.5) + }) + }; + // A sampled/retargeted colour that already reads must stay bit-exact, including alpha. + if scale >= 1.0 && readable(fill) { + return fill; + } let [r, g, b, alpha] = fill.to_srgba_unmultiplied(); let requested = (f32::from(alpha) * scale).round() as u8; // At most 256 cheap colour comparisons per changed role; no allocations, GPU or I/O. for a in requested..=255 { let candidate = Color32::from_rgba_unmultiplied(r, g, b, a); - if [Color32::BLACK, Color32::WHITE].iter().all(|background| { - let ground = composite(candidate, *background); - inks.iter().all(|ink| contrast_ratio(composite(*ink, ground), ground) >= 4.5) - }) { + if readable(candidate) { return candidate; } } @@ -360,7 +665,30 @@ impl TabAccent { } pub fn publish(app: &crate::SolveApp, ctx: &egui::Context) { - let accent = Self::for_tab(&Tokens::get(), &app.ui.tab); + let now = ctx.input(|i| i.time); + let (published, accent, fading, style_surfaces) = ctx.data_mut(|data| { + let state = data.get_temp_mut_or_default::(egui::Id::new(TAB_STATE)); + let (published, accent, fading) = state.publish(&app.ui.tab, now); + let style_surfaces = published.tab_surfaces || state.styled_surfaces; + state.styled_surfaces = published.tab_surfaces; + (published, accent, fading, style_surfaces) + }); + PUBLISHED.set(Some(published)); + if style_surfaces { + let fills = { + let style = ctx.global_style(); + (style.visuals.panel_fill, style.visuals.window_fill) + }; + if fills != (published.tokens.panel, published.tokens.panel) { + ctx.global_style_mut(|style| { + style.visuals.panel_fill = published.tokens.panel; + style.visuals.window_fill = published.tokens.panel; + }); + } + } + if fading { + ctx.request_repaint(); + } ctx.data_mut(|d| { d.insert_temp(egui::Id::new("sc_tab_accent"), accent); d.insert_temp(egui::Id::new("sc_tab_icon_accent"), icon_accent_for_tab(&app.ui.tab)); @@ -396,6 +724,12 @@ pub fn viewport_background() -> Option<[u8; 3]> { VIEWPORT_BACKGROUND.get() } +/// Whether the published theme opts into per-tab surfaces. Render's unauthored preview uses +/// this cached policy; it must retain its existing scene backplate when the option is absent/off. +pub(crate) fn tab_surfaces_enabled() -> bool { + PUBLISHED.get().is_some_and(|p| p.environment == Environment::current() && p.tab_surfaces) +} + /// The common conversion boundary for compiled icon palette data. pub(crate) const fn icon_color(rgb: [u8; 3]) -> Color32 { Color32::from_rgb(rgb[0], rgb[1], rgb[2]) @@ -912,6 +1246,23 @@ impl Tokens { /// [`Tokens::get`] in another colour vision mode: the Colour vision preference previews the /// mode being chosen before it is applied (#7152). pub fn get_in(mode: ColorVision) -> Tokens { + if let Some(published) = PUBLISHED.get().filter(|p| p.environment == Environment::current()) { + if mode == published.environment.vision { + return published.tokens; + } + let mut tokens = Self::base_in(mode); + Surfaces::of(published.tokens).apply(&mut tokens); + return tokens; + } + Self::base_in(mode) + } + + /// Unanimated colours for geometry cache keys: fading backgrounds must not rebuild bodies. + pub(crate) fn base() -> Tokens { + Self::base_in(vision()) + } + + fn base_in(mode: ColorVision) -> Tokens { let window = Tokens::themed(is_dark(), mode); let tokens = if viewport_dark() == is_dark() { window } else { window.with_viewport(Tokens::themed(viewport_dark(), mode)) }; tokens.with_background(viewport_background()) @@ -921,9 +1272,16 @@ impl Tokens { /// with nothing behind it (a status line, a label or a warning beside the geometry), so it /// reads on the view's background. As [`Tokens::get`] unless the view has its own side. pub fn view() -> Tokens { + if let Some(published) = PUBLISHED.get().filter(|p| p.environment == Environment::current()) { + return published.view; + } Tokens::themed(viewport_dark(), vision()).with_background(viewport_background()) } + pub(crate) fn protect_tab_panel(&mut self) { + self.panel = readable_fill(self.panel, &[self.text, self.text_dim, self.form_ink, self.dialog_label], 1.0); + } + /// Scale only floating surface fill alpha, preserving full-opacity tokens exactly. /// Raise each fill's floor to protect text over both black and white viewport extremes. pub(crate) fn apply_panel_opacity(&mut self, percent: f32) { @@ -1136,6 +1494,188 @@ pub fn apply(ctx: &egui::Context) { #[cfg(test)] mod tests { + use super::*; + + fn tabs_state(base: &str, overrides: BTreeMap) -> TabThemeState { + let file = crate::theme_files::tab_fixture(base); + let values = crate::theme_files::effective_values(&file, &overrides).0; + let (enabled, fade_ms) = crate::theme_options::tab_settings(&file, &values); + let base = Custom { dark: file.base.is_dark(), tokens: crate::theme_files::resolve_with(&file, &values) }; + set_dark(base.dark); + set_custom(Some(base)); + set_vision(ColorVision::Off); + set_viewport_dark(None); + set_viewport_background(None); + TabThemeState { prepared: Some(PreparedTheme { file, values, raw: None, base, enabled, fade_ms }), ..Default::default() } + } + + #[test] + fn tabs_fade_has_exact_endpoints_oklab_cubic_midpoint_and_independent_alpha() { + let from = Surfaces { panel: Color32::BLACK, top: Color32::BLACK, bottom: Color32::BLACK }; + let to = Surfaces { panel: Color32::WHITE, top: Color32::WHITE, bottom: Color32::WHITE }; + assert_eq!(from.blend(to, 0.0), from); + assert_eq!(from.blend(to, 1.0), to); + // Neutral Oklab L at half-time is 1 - (1 - .5)^3 = .875. The independent + // sRGB encoding of .875^3 is .8375, or byte 214 (gamma blending would give 223). + assert_eq!(from.blend(to, 0.5), Surfaces { panel: Color32::from_gray(214), top: Color32::from_gray(214), bottom: Color32::from_gray(214) }); + let a = Color32::from_rgba_unmultiplied(40, 90, 130, 128); + let b = Color32::from_rgba_unmultiplied(90, 150, 190, 64); + assert_eq!(oklab_blend(a, b, 0.875).a(), 72); + let fade = Fade { from, to, start: 1.0, seconds: 0.24 }; + assert_eq!(fade.sample(1.0), (from, true)); + assert_eq!(fade.sample(1.24), (to, false)); + assert_eq!(Fade { seconds: 0.0, ..fade }.sample(1.0), (to, false)); + assert_eq!(fade.sample(f64::NAN), (to, false)); + } + + #[test] + fn tabs_fade_retargets_from_displayed_surfaces_and_stops_resolving_at_rest() { + for opacity in [40.0, 100.0] { + let mut state = tabs_state("dark", BTreeMap::from([("opacity".into(), crate::theme_files::OptionValue::Num(opacity))])); + let (model, _, repaint) = state.publish("MODEL", 0.0); + assert!(!repaint); + let (start, _, repaint) = state.publish("SKETCH", 1.0); + assert!(repaint); + assert_eq!(Surfaces::of(start.tokens), Surfaces::of(model.tokens)); + let (middle, _, _) = state.publish("SKETCH", 1.12); + let (retarget, _, repaint) = state.publish("RENDER", 1.12); + assert!(repaint); + assert_eq!(Surfaces::of(retarget.tokens), Surfaces::of(middle.tokens)); + assert_eq!(retarget.view.viewport_top, retarget.tokens.viewport_top); + assert_eq!(retarget.view, retarget.tokens); + let (end, _, repaint) = state.publish("RENDER", 1.36); + assert!(!repaint); + assert_eq!(state.resolutions, 3); + for frame in 0..20 { + let (resting, _, repaint) = state.publish("RENDER", 2.0 + f64::from(frame)); + assert!(!repaint); + assert_eq!(resting.tokens, end.tokens); + } + assert_eq!(state.resolutions, 3, "resting frames must hit the resolved-token cache"); + state.publish("MODEL", 30.0); + assert_eq!(state.resolutions, 3, "returning to a tab reuses its target"); + } + } + + #[test] + fn tabs_panel_text_contrast_holds_at_five_fade_steps_with_opacity() { + use crate::theme_files::OptionValue; + for base in ["dark", "light"] { + for percent in [40.0, 75.0, 100.0] { + for mode in ColorVision::ALL { + for destination in ["SKETCH", "RENDER", "MODEL"] { + let mut state = tabs_state(base, BTreeMap::from([("opacity".into(), OptionValue::Num(percent))])); + set_vision(mode); + state.publish(if destination == "MODEL" { "RENDER" } else { "MODEL" }, 0.0); + state.publish(destination, 1.0); + for step in [0.0, 0.25, 0.5, 0.75, 1.0] { + let (frame, _, _) = state.publish(destination, 1.0 + step * 0.24); + let t = frame.tokens; + for behind in [Color32::BLACK, Color32::WHITE] { + let ground = composite(t.panel, behind); + for ink in [t.text, t.text_dim, t.form_ink, t.dialog_label] { + assert!( + contrast_ratio(composite(ink, ground), ground) >= 4.5, + "{base} {mode:?} opacity {percent} tab {destination} step {step}" + ); + } + } + assert_eq!((frame.view.viewport_top, frame.view.viewport_bottom), (t.viewport_top, t.viewport_bottom)); + } + } + } + } + } + } + + #[test] + fn tabs_cache_invalidates_for_theme_values_vision_and_viewport_overrides() { + let ctx = egui::Context::default(); + let mut file = crate::theme_files::tab_fixture("dark"); + let normalizations = Cell::new(0); + let prepare = |file: &crate::theme_files::ThemeFile, raw: Option<&BTreeMap>| { + let custom = prepare_tabs(&ctx, Some(file), raw, || { + normalizations.set(normalizations.get() + 1); + let saved = raw.into_iter().flatten().map(|(k, v)| (k.clone(), serde_json::from_value(v.clone()).unwrap())).collect(); + crate::theme_files::effective_values(file, &saved).0 + }); + set_dark(file.base.is_dark()); + set_custom(custom); + }; + let publish = || ctx.data_mut(|d| d.get_temp_mut_or_default::(egui::Id::new(TAB_STATE)).publish("SKETCH", 1.0)); + set_vision(ColorVision::Off); + set_viewport_dark(None); + set_viewport_background(None); + prepare(&file, None); + let before = publish().0.tokens; + prepare(&file, None); + assert_eq!(publish().0.tokens, before); + assert_eq!(normalizations.get(), 1); + // The content changes while identity/base remain the same, as with a followed reload. + file.tabs.get_mut("SKETCH").unwrap().insert("viewport_top".into(), serde_json::json!("#1a4232")); + prepare(&file, None); + assert_ne!(publish().0.tokens.viewport_top, before.viewport_top); + assert_eq!(normalizations.get(), 2); + set_vision(ColorVision::Tritan); + assert_eq!(publish().0.tokens.axis_x, before.with_vision(true, ColorVision::Tritan).axis_x); + set_viewport_dark(Some(false)); + assert_eq!(publish().0.tokens.viewport_top, Tokens::light().viewport_top); + set_viewport_background(Some([3, 7, 11])); + assert_eq!(publish().0.tokens.viewport_top, Color32::from_rgb(3, 7, 11)); + set_viewport_background(None); + set_viewport_dark(None); + let raw = BTreeMap::from([("tab_colours".into(), serde_json::json!(false))]); + prepare(&file, Some(&raw)); + assert_eq!(publish().0.tokens, Tokens::base()); + assert_eq!(normalizations.get(), 3); + } + + #[test] + fn tabs_publish_requests_repaints_only_during_fade_and_zero_is_instant() { + use crate::theme_files::OptionValue; + let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + let ctx = crate::fonts::test_context(); + let mut state = tabs_state("dark", BTreeMap::new()); + state.publish("MODEL", 0.0); + ctx.data_mut(|d| d.insert_temp(egui::Id::new(TAB_STATE), state)); + app.ui.tab = "SKETCH".into(); + let frame = |time| { + let mut out = ctx.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { + TabAccent::publish(&app, ui.ctx()); + crate::gpu::paint_background(ui.painter(), ui.max_rect(), &Tokens::get()); + }); + let colors: Vec<_> = out + .shapes + .iter() + .find_map(|shape| match &shape.shape { + egui::Shape::Mesh(mesh) => Some(mesh.vertices.iter().map(|vertex| vertex.color).collect()), + _ => None, + }) + .unwrap(); + let tokens = Tokens::get(); + assert_eq!(colors, [tokens.viewport_top, tokens.viewport_top, tokens.viewport_bottom, tokens.viewport_bottom]); + out.textures_delta.clear(); + out.viewport_output[&egui::ViewportId::ROOT].repaint_delay + }; + assert!(frame(1.0).is_zero()); + assert!(frame(1.12).is_zero()); + // Drain the previously requested pass, then verify the endpoint leaves the loop asleep. + for time in [1.24, 1.3, 1.4] { + frame(time); + } + assert_eq!(frame(2.0), std::time::Duration::MAX); + let (end, _, _) = ctx.data_mut(|d| d.get_temp_mut_or_default::(egui::Id::new(TAB_STATE)).publish("SKETCH", 2.0)); + assert_eq!(Tokens::get(), end.tokens); + let mut instant = tabs_state("dark", BTreeMap::from([("tab_fade_ms".into(), OptionValue::Num(0.0))])); + instant.publish("MODEL", 0.0); + let (frame, _, repaint) = instant.publish("SKETCH", 1.0); + assert!(!repaint); + assert_eq!( + frame.tokens, + crate::theme_files::resolve_for_tab(&instant.prepared.as_ref().unwrap().file, &instant.prepared.as_ref().unwrap().values, Some("SKETCH")) + ); + } + #[test] fn widget_states_and_popup_frames_follow_theme_radii_without_changing_defaults() { use super::*; @@ -1340,6 +1880,69 @@ mod tests { assert_eq!(super::TabAccent::current_icon_accent(&first), None); } + #[test] + fn tabs_surface_publication_restores_base_fills_without_restyling_widgets() { + use crate::theme_files::{OptionValue, ThemeFile}; + for base in ["dark", "light"] { + let ctx = crate::fonts::test_context(); + let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + let file = crate::theme_files::tab_fixture(base); + set_dark(file.base.is_dark()); + set_vision(ColorVision::Off); + set_viewport_dark(None); + set_viewport_background(None); + set_custom(None); + let prepare = |file: &ThemeFile, enabled: Option| { + let raw = enabled.map(|enabled| BTreeMap::from([("tab_colours".into(), serde_json::json!(enabled))])); + let custom = prepare_tabs(&ctx, Some(file), raw.as_ref(), || { + let saved = enabled.map(|enabled| BTreeMap::from([("tab_colours".into(), OptionValue::Bool(enabled))])).unwrap_or_default(); + crate::theme_files::effective_values(file, &saved).0 + }); + set_custom(custom) + }; + let publish = |app: &crate::SolveApp, time| { + ctx.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| TabAccent::publish(app, ui.ctx())).textures_delta.clear(); + }; + prepare(&file, Some(true)); + apply(&ctx); + let before = ctx.global_style().visuals.clone(); + let base_custom = CUSTOM.get(); + app.ui.tab = "MODEL".into(); + publish(&app, 0.0); + assert_eq!(ctx.global_style().visuals, before); + app.ui.tab = "SKETCH".into(); + publish(&app, 1.0); + publish(&app, 1.12); + let panel = Tokens::get().panel; + assert_ne!(panel, before.panel_fill, "exercise an actual animated panel fill"); + let mut animated = before.clone(); + animated.panel_fill = panel; + animated.window_fill = panel; + assert_eq!(ctx.global_style().visuals, animated, "all non-surface widget/selection/status visuals stay unchanged"); + // Repair either owned fill independently, even when the panel already matches. + ctx.global_style_mut(|style| style.visuals.window_fill = before.window_fill); + publish(&app, 1.12); + assert_eq!(ctx.global_style().visuals, animated); + + assert!(!prepare(&file, Some(false)), "toggling surfaces does not change the base Custom tokens"); + assert_eq!(CUSTOM.get(), base_custom); + // Deliberately omit apply(): a full restyle would conceal stale animated fills. + publish(&app, 1.13); + assert_eq!(ctx.global_style().visuals, before, "turning surfaces off must restore both base fills"); + + assert!(!prepare(&file, Some(true))); + publish(&app, 2.0); + assert_ne!(ctx.global_style().visuals.panel_fill, before.panel_fill); + let mut plain = file.clone(); + plain.tabs.clear(); + plain.options.clear(); + assert!(!prepare(&plain, None), "a no-option theme can retain the exact same base tokens"); + assert_eq!(CUSTOM.get(), base_custom); + publish(&app, 2.1); + assert_eq!(ctx.global_style().visuals, before, "restoring a no-option theme must release the surface fills"); + } + } + #[test] fn concurrent_ui_renderers_keep_their_own_theme_and_vision() { let barrier = std::sync::Barrier::new(2); diff --git a/crates/ui-egui/src/theme_files.rs b/crates/ui-egui/src/theme_files.rs index 3bc227a19..1633f3b41 100644 --- a/crates/ui-egui/src/theme_files.rs +++ b/crates/ui-egui/src/theme_files.rs @@ -85,6 +85,9 @@ pub struct ThemeFile { /// SVG display roles and three-colour semantic ramps; omitted values keep compiled defaults. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub icon_palette: BTreeMap, + /// Optional surface overrides for known ribbon tabs. Accents retain their existing tokens. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub tabs: BTreeMap>, /// Theme-owned declarations, in file order; standard ids are normalized on import. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub options: Vec, @@ -120,6 +123,7 @@ impl Default for ThemeFile { radii: BTreeMap::new(), borders: BTreeMap::new(), icon_palette: BTreeMap::new(), + tabs: BTreeMap::new(), options: Vec::new(), overlays: Vec::new(), requires: REQUIREMENTS_LEVEL, @@ -258,6 +262,12 @@ fn radius_slot<'a>(t: &'a mut Tokens, key: &str) -> Option<&'a mut u8> { } impl ThemeFile { + /// Shared by import and preference restoration; invalid saved maps are dropped as a unit. + pub(crate) fn set_tabs(&mut self, source: &Value) -> Result<(), String> { + self.tabs = parse_tabs(source.get("tabs"))?; + Ok(()) + } + /// A newer format level keeps the authored base tables but disables options and overlays. /// Computed from `requires` so it also works after restoring saved preferences. pub fn needs_newer(&self) -> bool { @@ -566,6 +576,7 @@ pub fn from_value(v: &Value) -> Result { Some(value) => value.as_u64().ok_or("`requires` must be a nonnegative integer")?, }; let layer = parse_layer(v)?; + let tabs = parse_tabs(v.get("tabs"))?; let options = if requires > REQUIREMENTS_LEVEL { Vec::new() } else { parse_options(v.get("options"))? }; let overlays = if requires > REQUIREMENTS_LEVEL { Vec::new() } else { parse_overlays(v.get("overlays"), &options)? }; Ok(ThemeFile { @@ -576,12 +587,41 @@ pub fn from_value(v: &Value) -> Result { radii: layer.radii, borders: layer.borders, icon_palette: layer.icon_palette, + tabs, options, overlays, requires, }) } +/// Keep the accepted vocabulary at the same boundary as the existing accent mapping. +fn parse_tabs(v: Option<&Value>) -> Result>, String> { + let Some(v) = v else { return Ok(BTreeMap::new()) }; + let tabs = v.as_object().ok_or("`tabs` must be an object")?; + if tabs.len() > crate::theme::TAB_NAMES.len() { + return Err("`tabs` has too many entries".into()); + } + let mut parsed = BTreeMap::new(); + for (tab, surfaces) in tabs { + if !crate::theme::TAB_NAMES.contains(&tab.as_str()) { + return Err(format!("`tabs.{tab}` is not a ribbon tab")); + } + let surfaces = surfaces.as_object().ok_or_else(|| format!("`tabs.{tab}` must be an object"))?; + let mut values = BTreeMap::new(); + for (key, value) in surfaces { + if !matches!(key.as_str(), "panel" | "viewport_top" | "viewport_bottom") { + return Err(format!("`tabs.{tab}.{key}` is not a tab surface")); + } + if value.as_str().and_then(parse_color).is_none() { + return Err(format!("`tabs.{tab}.{key}` must be #rrggbb or #rrggbbaa")); + } + values.insert(key.clone(), value.clone()); + } + parsed.insert(tab.clone(), values); + } + Ok(parsed) +} + fn parse_layer(v: &Value) -> Result { let mut src = match v.get("colors") { None => serde_json::Map::new(), @@ -710,7 +750,13 @@ fn parse_option(v: &Value) -> Result { if reserved && (min < floor || max > ceiling) { return Err(format!("`min` / `max` for {id} must stay inside {floor} to {ceiling}")); } - let step = if reserved { 1.0 } else { option_number(v, "step")? }; + let step = if id == "tab_fade_ms" { + 20.0 + } else if reserved { + 1.0 + } else { + option_number(v, "step")? + }; if step <= 0.0 { return Err("`step` must be greater than zero".into()); } @@ -997,6 +1043,12 @@ pub fn resolve(theme: &ThemeFile) -> Tokens { /// Resolve base tables, then matching overlays in file order. Later tables replace earlier /// entries by key. Saved values are normalized here too, so callers cannot bypass finite checks. pub fn resolve_with(theme: &ThemeFile, saved: &BTreeMap) -> Tokens { + resolve_for_tab(theme, saved, None) +} + +/// Resolve a tab and its base/overlays in one pass. Providers run last so opacity also protects +/// tab-authored panels. Restored/direct Rust values are revalidated before they affect tokens. +pub(crate) fn resolve_for_tab(theme: &ThemeFile, saved: &BTreeMap, tab: Option<&str>) -> Tokens { if theme.needs_newer() || (theme.options.is_empty() && theme.overlays.is_empty()) || theme.overlays.len() > MAX_OVERLAYS { return resolve_base(theme); } @@ -1023,7 +1075,25 @@ pub fn resolve_with(theme: &ThemeFile, saved: &BTreeMap) -> merged.icon_palette.extend(overlay.values.icon_palette); } let mut tokens = resolve_base(&merged); + let mut tab_panel = false; + if crate::theme_options::tab_settings(theme, &values).0 + && let Some(tab) = tab + && let Ok(tabs) = serde_json::to_value(&theme.tabs).map_err(|e| e.to_string()).and_then(|v| parse_tabs(Some(&v))) + && let Some(surfaces) = tabs.get(tab) + { + for (key, value) in surfaces { + if let Some(slot) = slot(&mut tokens, key) + && let Ok(colors) = colors_for_key(key, value, 1) + { + slot.copy_from_slice(&colors); + } + } + tab_panel = surfaces.contains_key("panel"); + } crate::theme_options::apply(theme, &values, &mut tokens); + if tab_panel { + tokens.protect_tab_panel(); + } tokens } @@ -1189,6 +1259,9 @@ pub fn export_file(theme: &ThemeFile) -> Value { if !theme.icon_palette.is_empty() { obj.insert("icon_palette".into(), json!(theme.icon_palette)); } + if !theme.tabs.is_empty() { + obj.insert("tabs".into(), json!(theme.tabs)); + } if !theme.options.is_empty() { obj.insert("options".into(), json!(theme.options)); } @@ -1212,6 +1285,12 @@ pub(crate) fn is_two_colour(id: &str) -> bool { matches!(id, "1-bit" | "1-bit-dark") } +#[cfg(test)] +pub(crate) fn tab_fixture(base: &str) -> ThemeFile { + let catalog: Value = serde_json::from_str(include_str!("../tests/fixtures/theme-tabs.json")).unwrap(); + from_value(&catalog[base]).unwrap() +} + /// The built-in themes, validated and ordered once; a test checks every shipped file. pub fn builtin() -> &'static [ThemeFile] { static THEMES: OnceLock> = OnceLock::new(); @@ -1406,6 +1485,71 @@ impl Follow { mod tests { use super::*; + #[test] + fn tabs_import_is_strict_and_roundtrips_authored_surfaces() { + for base in ["dark", "light"] { + let file = tab_fixture(base); + assert_eq!(from_value(&export_file(&file)).unwrap(), file); + let mut source = export_file(&file); + source["tabs"] = json!(crate::theme::TAB_NAMES.iter().map(|tab| (*tab, json!({"panel":"#18202aff"}))).collect::>()); + assert_eq!(from_value(&source).unwrap().tabs.len(), crate::theme::TAB_NAMES.len()); + for (tabs, offending) in [ + (json!(null), "tabs"), + (json!([]), "tabs"), + (json!({"sketch":{}}), "sketch"), + (json!({"MISSING":{}}), "MISSING"), + (json!({"SKETCH":null}), "SKETCH"), + (json!({"SKETCH":{"panel":"#bad"}}), "panel"), + (json!({"SKETCH":{"panel":["#ffffff"]}}), "panel"), + (json!({"SKETCH":{"panel":12}}), "panel"), + ] { + source["tabs"] = tabs; + assert!(from_value(&source).unwrap_err().contains(offending)); + } + // Refuse every known non-surface token, not only status colours. + for key in keys().into_iter().filter(|key| !matches!(*key, "panel" | "viewport_top" | "viewport_bottom")) { + source["tabs"] = json!({"SKETCH":{key:"#ffffff"}}); + assert!(from_value(&source).unwrap_err().contains(key), "{key}"); + } + source["tabs"] = json!({"SKETCH":{"viewport_top":"#12345678"}}); + let file = from_value(&source).unwrap(); + assert_eq!(export_file(&file)["tabs"], source["tabs"]); + } + } + + #[test] + fn tabs_resolve_only_surfaces_and_off_is_exactly_base() { + for base in ["dark", "light"] { + let file = tab_fixture(base); + let defaults = BTreeMap::new(); + let base = resolve_with(&file, &defaults); + for tab in crate::theme::TAB_NAMES { + let mut want = base; + if let Some(surfaces) = file.tabs.get(*tab) { + for (key, value) in surfaces { + slot(&mut want, key).unwrap().copy_from_slice(&colors_of(value, 1).unwrap()); + } + } + let effective = resolve_for_tab(&file, &defaults, Some(tab)); + assert_eq!(effective, want, "{tab}"); + assert_eq!(crate::theme::TabAccent::for_tab(&effective, tab), crate::theme::TabAccent::for_tab(&base, tab)); + let off = BTreeMap::from([("tab_colours".into(), OptionValue::Bool(false))]); + assert_eq!(resolve_for_tab(&file, &off, Some(tab)), resolve_with(&file, &off)); + } + let mut damaged = file.clone(); + damaged.tabs.get_mut("SKETCH").unwrap().insert("error".into(), json!("#ffffff")); + assert_eq!(resolve_for_tab(&damaged, &defaults, Some("SKETCH")), base); + let mut absent = file.clone(); + absent.tabs.clear(); + assert_eq!(resolve_for_tab(&absent, &defaults, Some("SKETCH")), base); + assert_eq!(export_file(&file)["options"][1]["default"], 240.0); + } + for file in builtin() { + assert!(file.tabs.is_empty(), "{}", file.id); + assert_eq!(resolve_for_tab(file, &BTreeMap::new(), Some("SKETCH")), resolve(file)); + } + } + fn option_theme(options: Value, overlays: Value) -> Value { json!({"format":FORMAT,"name":"Options","base":"dark","options":options,"overlays":overlays}) } @@ -1545,7 +1689,7 @@ mod tests { assert_eq!(values["tab_fade_ms"], OptionValue::Num(500.0)); let fade = file.options.iter().find(|o| o.id == "tab_fade_ms").unwrap(); assert_eq!(fade.parent.as_deref(), Some("tab_colours")); - assert!(matches!(&fade.kind, OptionKind::Range { min:100.0, max:500.0, step:1.0, unit:Some(unit), .. } if unit == "ms")); + assert!(matches!(&fade.kind, OptionKind::Range { min:100.0, max:500.0, step:20.0, unit:Some(unit), .. } if unit == "ms")); assert!( file.options .iter() diff --git a/crates/ui-egui/src/theme_options.rs b/crates/ui-egui/src/theme_options.rs index ec8767b5b..3081b7351 100644 --- a/crates/ui-egui/src/theme_options.rs +++ b/crates/ui-egui/src/theme_options.rs @@ -21,14 +21,48 @@ pub(crate) struct Provider { pub apply: fn(&mut Tokens, &OptionValue), } -// Future blur/tab_colours/tab_fade_ms implementations register their behaviour here. -pub(crate) const PROVIDERS: &[Provider] = &[Provider { - id: "opacity", - label: "prefs.theme_option_opacity", - help: "prefs.theme_option_opacity_help", - availability: || Availability::Available, - apply: apply_opacity, -}]; +pub(crate) const PROVIDERS: &[Provider] = &[ + Provider { + id: "opacity", + label: "prefs.theme_option_opacity", + help: "prefs.theme_option_opacity_help", + availability: || Availability::Available, + apply: apply_opacity, + }, + Provider { + id: "tab_colours", + label: "prefs.theme_option_tab_colours", + help: "prefs.theme_option_tab_colours_help", + availability: || Availability::Available, + apply: apply_tab_setting, + }, + Provider { + id: "tab_fade_ms", + label: "prefs.theme_option_tab_fade_ms", + help: "prefs.theme_option_tab_fade_ms_help", + availability: || Availability::Available, + apply: apply_tab_setting, + }, +]; + +/// Tab providers affect resolution/animation rather than the base palette. Undeclared values +/// and inactive parents cannot enable them, even for a directly supplied theme. +pub(crate) fn tab_settings(file: &ThemeFile, values: &BTreeMap) -> (bool, f32) { + let offered = offered(file, PROVIDERS); + let enabled = offered.iter().any(|o| o.id == "tab_colours") && values.get("tab_colours") == Some(&OptionValue::Bool(true)); + let duration = if enabled && offered.iter().any(|o| o.id == "tab_fade_ms") { + match values.get("tab_fade_ms") { + Some(OptionValue::Num(n)) if n.is_finite() => n.clamp(0.0, 600.0), + _ => 0.0, + } + } else { + 0.0 + }; + (enabled, duration) +} + +// Consumed by tab_settings at the per-tab resolution boundary; never mutate base tokens. +fn apply_tab_setting(_: &mut Tokens, _: &OptionValue) {} pub(crate) fn standard(id: &str) -> bool { matches!(id, "opacity" | "blur" | "tab_colours" | "tab_fade_ms") diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index f0d0e335f..3d534d2fb 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -1283,6 +1283,9 @@ fn ribbon_tabs(app: &mut SolveApp, ui: &mut egui::Ui, row: Rect) { } if response.clicked() { app.ui.tab = tab.to_string(); + // Floating ribbons draw after the viewport. An instant surface switch + // needs one more pass too; settled tabs never schedule their own frames. + ui.ctx().request_repaint(); } if response.secondary_clicked() { crate::context_menu::open_for( diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 1e3179dff..b2dd0697b 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -586,7 +586,7 @@ fn scene_key(app: &SolveApp) -> u64 { crate::theme::is_dark().hash(&mut h); crate::theme::vision().hash(&mut h); // Two themes may share a light/dark base while drawing different geometry colours. - crate::theme_files::color_key(&Tokens::get()).hash(&mut h); + crate::theme_files::color_key(&Tokens::base()).hash(&mut h); app.session.active_sketch.hash(&mut h); crate::edit_in_place::scene_key(app).hash(&mut h); // A reset palette arena (another design) invalidates every cached block's indices. @@ -3377,7 +3377,7 @@ fn highlight_geometry_key(app: &SolveApp) -> u64 { crate::theme::is_dark().hash(&mut h); crate::theme::vision().hash(&mut h); // Two themes may share a light/dark base while drawing different geometry colours. - crate::theme_files::color_key(&Tokens::get()).hash(&mut h); + crate::theme_files::color_key(&Tokens::base()).hash(&mut h); app.preview.effective_replaced().hash(&mut h); app.preview.rolled_back.hash(&mut h); // Where a Move dialog has moved its bodies; while its triad is dragged, only that it is. @@ -4233,16 +4233,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { let held = crate::select_other::track_hold(app, ui.ctx(), &proj, inside, primary_pressed, primary_down, hover, navigating_from_press); crate::select_other::hover_override(app); let painter = ui.painter_at(rect); - // Background gradient. - let (top, bot) = (t.viewport_top, t.viewport_bottom); - let mut mesh = egui::Mesh::default(); - mesh.colored_vertex(rect.left_top(), top); - mesh.colored_vertex(rect.right_top(), top); - mesh.colored_vertex(rect.right_bottom(), bot); - mesh.colored_vertex(rect.left_bottom(), bot); - mesh.add_triangle(0, 1, 2); - mesh.add_triangle(0, 2, 3); - painter.add(Shape::mesh(mesh)); + crate::gpu::paint_background(&painter, rect, &t); // ---- model ---- crate::frame_watch::step(app, "viewport before the model"); @@ -6271,7 +6262,7 @@ fn loose_end_markers( /// picture matches the window. The light theme's tokens (Off) are the engine's own colours, so a light /// render is unchanged. pub(crate) fn scene_palette(dark: bool, mode: crate::theme::ColorVision) -> solidcraft_engine::view::Palette { - let t = Tokens::themed(dark, mode); + let t = if dark == crate::theme::viewport_dark() && mode == crate::theme::vision() { Tokens::view() } else { Tokens::themed(dark, mode) }; let rgb = |c: Color32| Rgb(c.r(), c.g(), c.b()); solidcraft_engine::view::Palette { background: (rgb(t.viewport_top), rgb(t.viewport_bottom)), diff --git a/crates/ui-egui/tests/fixtures/theme-tabs.json b/crates/ui-egui/tests/fixtures/theme-tabs.json new file mode 100644 index 000000000..abe55890d --- /dev/null +++ b/crates/ui-egui/tests/fixtures/theme-tabs.json @@ -0,0 +1,34 @@ +{ + "dark": { + "format": "solidcraft-theme/1", + "name": "Tabs dark", + "base": "dark", + "colors": {"panel":"#18202a", "text":"#f5f7fa", "text_dim":"#dce3ec", "form_ink":"#f5f7fa", "dialog_label":"#f5f7fa"}, + "options": [ + {"id":"tab_colours", "type":"bool", "default":true}, + {"id":"tab_fade_ms", "type":"range", "default":240}, + {"id":"opacity", "type":"range", "default":100} + ], + "tabs": { + "MODEL": {"panel":"#18202a", "viewport_top":"#182430", "viewport_bottom":"#29394a"}, + "SKETCH": {"panel":"#123028", "viewport_top":"#103128", "viewport_bottom":"#204a3c"}, + "RENDER": {"panel":"#302039", "viewport_top":"#30203d", "viewport_bottom":"#493252"} + } + }, + "light": { + "format": "solidcraft-theme/1", + "name": "Tabs light", + "base": "light", + "colors": {"panel":"#fafbfc", "text":"#172333", "text_dim":"#334155", "form_ink":"#172333", "dialog_label":"#172333"}, + "options": [ + {"id":"tab_colours", "type":"bool", "default":true}, + {"id":"tab_fade_ms", "type":"range", "default":240}, + {"id":"opacity", "type":"range", "default":100} + ], + "tabs": { + "MODEL": {"panel":"#fafbfc", "viewport_top":"#e6f0fa", "viewport_bottom":"#ffffff"}, + "SKETCH": {"panel":"#e0f5e8", "viewport_top":"#cceddb", "viewport_bottom":"#f0fff7"}, + "RENDER": {"panel":"#f8e5f5", "viewport_top":"#ead1ef", "viewport_bottom":"#fff4ff"} + } + } +} diff --git a/crates/ui-egui/tests/scenarios/prefs_theme_files.json b/crates/ui-egui/tests/scenarios/prefs_theme_files.json index 7485932d9..869ac6774 100644 --- a/crates/ui-egui/tests/scenarios/prefs_theme_files.json +++ b/crates/ui-egui/tests/scenarios/prefs_theme_files.json @@ -29,5 +29,22 @@ {"expect":{"prefs":{"theme_option_values":{"enabled":false}},"theme_colors":{"panel":"#112233"}}}, {"call":"ui.prefs","params":{"theme_options":{"scenario-options":{"enabled":true}}}}, {"call":"ui.prefs","params":{"theme_options":{"scenario-options":{}}}}, - {"expect":{"prefs":{"theme_options":{},"theme_option_values":{"enabled":false}},"theme_colors":{"panel":"#112233"}}} + {"expect":{"prefs":{"theme_options":{},"theme_option_values":{"enabled":false}},"theme_colors":{"panel":"#112233"}}}, + {"note":"#9808: imported tab surfaces follow Model, Sketch and Render together; disabling them restores the exact base on every tab."}, + {"call":"ui.prefs","params":{"theme_import":{"format":"solidcraft-theme/1","name":"Scenario Tabs","base":"dark","colors":{"panel":"#18202a","viewport_top":"#182430","viewport_bottom":"#29394a"},"options":[{"id":"tab_colours","type":"bool","default":true},{"id":"tab_fade_ms","type":"range","default":0}],"tabs":{"SKETCH":{"panel":"#123028","viewport_top":"#103128","viewport_bottom":"#204a3c"},"RENDER":{"panel":"#302039","viewport_top":"#30203d","viewport_bottom":"#493252"}}}}}, + {"call":"ui.set","params":{"tab":"MODEL"}}, + {"expect":{"theme_colors":{"panel":"#18202a","viewport_top":"#182430","viewport_bottom":"#29394a"}}}, + {"call":"engine.execute","params":{"command":"sketch.create","params":{"plane":"XY"}}}, + {"expect":{"theme_colors":{"panel":"#123028","viewport_top":"#103128","viewport_bottom":"#204a3c"}}}, + {"call":"engine.execute","params":{"command":"sketch.finish","params":{}}}, + {"call":"ui.workspace","params":{"workspace":"render"}}, + {"expect":{"theme_colors":{"panel":"#302039","viewport_top":"#30203d","viewport_bottom":"#493252"}}}, + {"call":"ui.prefs","params":{"theme_options":{"scenario-tabs":{"tab_colours":false}}}}, + {"expect":{"theme_colors":{"panel":"#18202a","viewport_top":"#182430","viewport_bottom":"#29394a"}}}, + {"call":"ui.workspace","params":{"workspace":"design"}}, + {"call":"engine.execute","params":{"command":"sketch.create","params":{"plane":"XY"}}}, + {"expect":{"theme_colors":{"panel":"#18202a","viewport_top":"#182430","viewport_bottom":"#29394a"}}}, + {"call":"engine.execute","params":{"command":"sketch.finish","params":{}}}, + {"call":"ui.set","params":{"tab":"MODEL"}}, + {"expect":{"theme_colors":{"panel":"#18202a","viewport_top":"#182430","viewport_bottom":"#29394a"}}} ] diff --git a/docs/book/src/guide/ui-tour.md b/docs/book/src/guide/ui-tour.md index c168b5866..de429a941 100644 --- a/docs/book/src/guide/ui-tour.md +++ b/docs/book/src/guide/ui-tour.md @@ -387,11 +387,11 @@ Four ids are reserved for definitions owned by the app: A theme declares these with their required type and a default; it may also narrow a range's `min` and `max`. The default is clamped to those bounds. Other fields are ignored, including -presentation text, `step` (fixed at 1 for standard ranges), unit and parent. A wrong type or +presentation text, `step` (fixed at 20 for `tab_fade_ms`, 1 for other standard ranges), unit and parent. A wrong type or bounds outside the standard range are import errors. Declaring `tab_fade_ms` also requires declaring its boolean parent, `tab_colours`. Custom options cannot redefine reserved ids. -Only `opacity` currently has a registered standard behaviour. `blur`, `tab_colours` and -`tab_fade_ms` remain absent from the list until their behaviours are registered. +`opacity`, `tab_colours` and `tab_fade_ms` have registered standard behaviours. `blur` remains +absent from the list until its behaviour is registered. The resolver exposes declared standard options in the order `opacity`, `blur`, `tab_colours`, each immediately followed by its child, then custom options in declared order. @@ -405,6 +405,43 @@ white viewport extremes, each fill's actual alpha rises as necessary. This also against background overrides and busy models. A theme whose authored foreground and opaque fill already fail contrast receives full alpha; opacity never rewrites the theme's text colours. +Imported themes can also declare `tabs`, using exact ribbon registry names. Only `panel`, +`viewport_top` and `viewport_bottom` are accepted; an unknown tab or any other token is an +import error. Tabs without an entry keep the base surfaces. Existing tab accent fills, inks +and tints keep their own tokens. For example, save this original theme as a JSON file and import it: + +```json +{ + "format": "solidcraft-theme/1", + "name": "Garden tabs", + "base": "dark", + "options": [ + {"id": "tab_colours", "type": "bool", "default": true}, + {"id": "tab_fade_ms", "type": "range", "default": 240} + ], + "tabs": { + "SKETCH": {"panel": "#123028", "viewport_top": "#103128", "viewport_bottom": "#204a3c"}, + "RENDER": {"panel": "#302039", "viewport_top": "#30203d", "viewport_bottom": "#493252"} + } +} +``` + +The [imported light/dark fixtures](../../../../crates/ui-egui/tests/fixtures/theme-tabs.json) +also provide Model surfaces. No built-in theme declares tab surfaces. With `tab_colours` +off or absent, every tab keeps the base palette. With it on, `tab_fade_ms` blends panel and +viewport surfaces together in Oklab with an ease-out cubic curve; zero switches instantly. +A tab change during a fade starts from the colours currently displayed. Opacity readability +floors also apply to tab panels and interpolated alpha. A viewport set to the opposite light/dark +palette keeps that palette; a flat background preference takes precedence over tab gradients. Definitions and authored defaults +roundtrip through theme export; saved option values are excluded. + +Render's untouched, unsaved preview also uses these animated surfaces, including viewport +palette and flat-colour preferences. Explicit scene backplates, transparency, environments, +gradient backdrops and saved setups keep their existing background instead. Saved setups do +not record whether their background was explicitly chosen, so even a setup saved only for its +camera conservatively retains its scene backplate. With tab surfaces absent/off, Render keeps +its original flat scene background. Theme surfaces never change rendered images or exports. + Up to 32 overlays apply in file order, after the base palette and the theme's own value tables. Later matching entries win by key. Every overlay has one `when`: `{"opt":"id","eq":value}` for an exact, correctly typed comparison, or `gte`, `lte`, or both for inclusive range bounds.