SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Viewport theme: a light 3D view in a dark window, and the reverse (#4146) (#4147)
CamWightab80a410a16d
diff --git a/assets/locales/de.json b/assets/locales/de.jsonindex f1d6dae03f..54e52d6067 100644--- a/assets/locales/de.json+++ b/assets/locales/de.json@@ -2234,6 +2234,7 @@"ui.up_axis_note": "Welche Achse in den Ansichten nach oben zeigt (Achsenansicht, Home, Ansehen). Designs bleiben unverändert.","ui.updateToCurrentView": "Auf aktuelle Ansicht aktualisieren","ui.view_centre": "Ansichtszentrum",+ "ui.viewport_theme_follow": "Dem Design folgen","ui.visual_shaded_hidden_edges": "Schattiert mit verdeckten Kanten","ui.visual_shaded_with_edges": "Schattiert mit Kanten","ui.visual_style": "Ansichtsstil",diff --git a/assets/locales/en.json b/assets/locales/en.jsonindex 11a61a8101..65e3de57b2 100644--- a/assets/locales/en.json+++ b/assets/locales/en.json@@ -3116,6 +3116,7 @@"ui.updateToCurrentView": "Update to Current View","ui.vertical_constraint": "Vertical Constraint","ui.view_centre": "View centre",+ "ui.viewport_theme_follow": "Follow theme","ui.visual_shaded_hidden_edges": "Shaded with hidden edges","ui.visual_shaded_with_edges": "Shaded with edges","ui.visual_style": "Visual style",diff --git a/assets/locales/ja.json b/assets/locales/ja.jsonindex 7ec9d3c985..255581ae04 100644--- a/assets/locales/ja.json+++ b/assets/locales/ja.json@@ -3116,6 +3116,7 @@"ui.updateToCurrentView": "現在のビューに更新","ui.vertical_constraint": "垂直拘束","ui.view_centre": "ビュー中心",+ "ui.viewport_theme_follow": "テーマに従う","ui.visual_shaded_hidden_edges": "隠線付きシェーディング","ui.visual_shaded_with_edges": "エッジ付きシェーディング","ui.visual_style": "表示スタイル",diff --git a/assets/locales/ko.json b/assets/locales/ko.jsonindex 794a2b2a01..30d7f3d3bc 100644--- a/assets/locales/ko.json+++ b/assets/locales/ko.json@@ -2402,6 +2402,7 @@"ui.up_axis_note": "뷰(축 뷰, 홈, 보기)에서 위쪽을 가리키는 축입니다. 디자인은 변경되지 않습니다.","ui.updateToCurrentView": "현재 보기로 업데이트","ui.view_centre": "뷰 중심",+ "ui.viewport_theme_follow": "테마 따르기","ui.visual_shaded_hidden_edges": "음영 처리 및 숨겨진 모서리","ui.visual_shaded_with_edges": "음영 처리 및 모서리","ui.visual_style": "시각 스타일",diff --git a/assets/locales/zh.json b/assets/locales/zh.jsonindex 0470d9ebb6..b303dddee8 100644--- a/assets/locales/zh.json+++ b/assets/locales/zh.json@@ -3116,6 +3116,7 @@"ui.updateToCurrentView": "更新为当前视图","ui.vertical_constraint": "垂直约束","ui.view_centre": "视图中心",+ "ui.viewport_theme_follow": "跟随主题","ui.visual_shaded_hidden_edges": "带隐藏边的着色","ui.visual_shaded_with_edges": "带边着色","ui.visual_style": "视觉样式",diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rsindex f08f9bd925..677bb31322 100644--- a/crates/ui-egui/src/control.rs+++ b/crates/ui-egui/src/control.rs@@ -292,7 +292,7 @@ pub(crate) fn view_scene(app: &SolveApp, guides: solidcraft_engine::view::Guides&app.cam,crate::viewport::section_plane(app),solidcraft_engine::view::world_curve_parts,- &crate::viewport::scene_palette(app.ui.dark, app.preferences.color_vision),+ &crate::viewport::scene_palette(app.viewport_dark(), app.preferences.color_vision),guides,app.preferences.cosmetic_threads,);@@ -1168,7 +1168,7 @@ mod tests {}/// `ui.render` draws in the window's theme (#974): its background is the viewport's, light- /// or dark.+ /// or dark, and with the 3D view in the other theme's colours, the view's (#4146).#[test]fn model_render_is_in_the_windows_theme() {if !crate::gpu::test_picture_renderer() {@@ -1179,9 +1179,15 @@ mod tests {let mut app = SolveApp::new(s, Services::default());let dir = std::env::temp_dir().join(format!("solidcraft-render-theme-{}", std::process::id()));std::fs::create_dir_all(&dir).unwrap();- for dark in [false, true, false] {- app.ui.dark = dark;- let png = render(&mut app, &dir.join(format!("dark-{dark}.png")));+ use crate::theme::ViewportTheme;+ for (window, view) in+ [(false, ViewportTheme::Theme), (true, ViewportTheme::Theme), (true, ViewportTheme::Light), (false, ViewportTheme::Dark)]+ {+ app.ui.dark = window;+ app.preferences.viewport_theme = view;+ let dark = app.viewport_dark();+ let theme = format!("{window}-{}", view.id());+ let png = render(&mut app, &dir.join(format!("{theme}.png")));let img = image::load_from_memory(&png).unwrap().to_rgba8();// The top row is the background's top: its most common colour.let mut counts = std::collections::HashMap::new();@@ -1191,7 +1197,7 @@ mod tests {let top = counts.into_iter().max_by_key(|(_, n)| *n).map(|(c, _)| c).unwrap();let want = if dark { crate::theme::Tokens::dark() } else { crate::theme::Tokens::light() }.viewport_top;let near = top.iter().zip([want.r(), want.g(), want.b()]).all(|(a, b)| a.abs_diff(b) <= 2);- assert!(near, "dark {dark}: the render's top row is {top:?}, the window's background {want:?}");+ assert!(near, "{theme}: the render's top row is {top:?}, the view's background {want:?}");}std::fs::remove_dir_all(&dir).ok();}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 35f08f9ae8..53dee5388d 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -1676,6 +1676,11 @@ impl SolveApp {self.cam_anim = None;}+ /// Is the 3D view dark? As the window, unless Preferences give the view its own (#4146).+ pub fn viewport_dark(&self) -> bool {+ self.preferences.viewport_theme.dark().unwrap_or(self.ui.dark)+ }+/// Hand the view to an external navigation device without a pending mouse orbit or spin/// immediately taking it back on the next frame.pub fn begin_external_navigation(&mut self) {@@ -1710,6 +1715,8 @@ impl SolveApp {open_meshing::refresh(self, ctx.input(|i| i.time));self.esc_handled = false;prefs::apply(self, ctx);+ // The view's own dark or light only changes tokens, not egui's visuals: no restyle.+ theme::set_viewport_dark(self.preferences.viewport_theme.dark());if !self.styled || theme::is_dark() != self.ui.dark || theme::vision() != self.preferences.color_vision {theme::set_dark(self.ui.dark);theme::set_vision(self.preferences.color_vision);diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rsindex 64eaa80448..dfd6e01ff7 100644--- a/crates/ui-egui/src/prefs.rs+++ b/crates/ui-egui/src/prefs.rs@@ -550,6 +550,9 @@ preference_settings! {/// `dark`, `light` or `system` (follow the operating system), or a theme file's id: a/// built-in one (`gruvbox-dark`, …) or one of `custom_themes` (#2255).theme: String = "dark".into(), PAGE_INTERFACE;+ /// 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_INTERFACE;/// Imported theme files (`theme_files`), kept here so they also work in the browser.custom_themes: Vec<crate::theme_files::ThemeFile> = Vec::new();/// Interface language (a registered locale ID).@@ -1972,6 +1975,7 @@ pub fn control(app: &mut SolveApp, p: &serde_json::Value) -> Result<serde_json::o.insert("dialog".into(), json!(app.prefs_window.open.then(|| PAGES.get(app.prefs_window.section).copied().unwrap_or_default())));o.insert("stand_up_offer".into(), json!(app.stand_up));o.insert("dark".into(), json!(app.ui.dark));+ o.insert("viewport_dark".into(), json!(app.viewport_dark()));o.insert("theme_ids".into(), json!(theme_choices(app).into_iter().map(|(id, _)| id).collect::<Vec<_>>()));if let Some(id) = imported {o.insert("theme_imported".into(), json!(id));@@ -2166,12 +2170,17 @@ pub fn set(app: &mut SolveApp, p: &serde_json::Value) -> Result<serde_json::Valuo.insert(k.clone(), v.clone());}}- // Saved preferences read an unknown mode as Off; asked for here, it is an error.+ // Saved preferences read an unknown mode as the default; asked for here, it is an error.if let Some(v) = p.get("color_vision")&& v.as_str().and_then(crate::theme::ColorVision::from_id).is_none(){return Err("`color_vision` must be off, protan, deutan or tritan".into());}+ if let Some(v) = p.get("viewport_theme")+ && v.as_str().and_then(crate::theme::ViewportTheme::from_id).is_none()+ {+ return Err("`viewport_theme` must be theme, light or dark".into());+ }let new: Prefs = migrate(serde_json::from_value(cur).map_err(|e| e.to_string())?);if !UNITS.contains(&new.default_units.as_str()) {return Err(format!("units must be one of {}", UNITS.join(", ")));@@ -3281,6 +3290,7 @@ mod tests {("timeline_under_browser", json!(true), PAGE_INTERFACE),("browser_float", json!(true), PAGE_INTERFACE),("color_vision", json!("protan"), PAGE_INTERFACE),+ ("viewport_theme", json!("light"), PAGE_INTERFACE),("nav", json!("blender"), PAGE_NAVIGATION),("look_at_anim", json!(false), PAGE_NAVIGATION),("selection_shift_add_only", json!(true), PAGE_SKETCH),@@ -3359,6 +3369,41 @@ mod tests {assert!(!app.ui.dark);}+ /// The 3D view in the other theme's colours (#4146): `ui.prefs` sets it, the window keeps its+ /// theme and the next frame draws the view from the other side, and it is saved with the+ /// preferences. With a theme file on, the view takes the built-in Light or Dark colours.+ #[test]+ fn the_3d_view_takes_the_light_or_dark_themes_colours() {+ use crate::theme::{ColorVision, Tokens};+ use serde_json::json;+ let mut h = crate::scenario::Harness::new();+ for (theme, view, dark, view_dark) in+ [("light", "theme", false, false), ("dark", "light", true, false), ("dark", "dark", true, true), ("light", "dark", false, true)]+ {+ let out = h.call("ui.prefs", json!({"theme": theme, "viewport_theme": view}));+ assert_eq!((out["result"]["dark"].as_bool(), out["result"]["viewport_dark"].as_bool()), (Some(dark), Some(view_dark)), "{out}");+ h.frames(2);+ let t = Tokens::get();+ assert_eq!(t.panel, Tokens::themed(dark, ColorVision::Off).panel, "{theme}, {view}: the window");+ assert_eq!(t.viewport_top, Tokens::themed(view_dark, ColorVision::Off).viewport_top, "{theme}, {view}: the view");+ }++ let mut other = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default());+ other.load_prefs(&h.app.prefs());+ assert_eq!((other.preferences.theme.as_str(), other.ui.dark, other.viewport_dark()), ("light", false, true));++ let out = h.call("ui.prefs", json!({"theme": "gruvbox-dark-hard", "viewport_theme": "light"}));+ assert_eq!((out["result"]["dark"].as_bool(), out["result"]["viewport_dark"].as_bool()), (Some(true), Some(false)), "{out}");+ h.frames(2);+ let hard = crate::theme_files::find("gruvbox-dark-hard", &[]).map(crate::theme_files::resolve).unwrap();+ assert_eq!((Tokens::get().panel, Tokens::get().viewport_top), (hard.panel, Tokens::light().viewport_top));++ // Asked for, an unknown value is refused; read from saved preferences, it is the default.+ assert!(h.call("ui.prefs", json!({"viewport_theme": "dim"}))["error"].is_string());+ let read: crate::theme::ViewportTheme = serde_json::from_value(json!("dim")).unwrap();+ assert_eq!(read, crate::theme::ViewportTheme::Theme);+ }+#[test]fn theme_files_import_apply_export_save_and_remove() {use crate::theme::{ColorVision, Tokens};diff --git a/crates/ui-egui/src/prefs/interface.rs b/crates/ui-egui/src/prefs/interface.rsindex 34d13978f4..fb2e3f8f70 100644--- a/crates/ui-egui/src/prefs/interface.rs+++ b/crates/ui-egui/src/prefs/interface.rs@@ -5,6 +5,20 @@ pub(super) fn interface(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) {ui_kit::settings_section(ui, "theme", app.tr("ui.theme"), |ui| {theme_row(app, ui);ui_kit::tab_accent_strip(ui);+ // The 3D view in the theme's colours, or the Light or Dark theme's (#4146).+ ui_kit::settings_form(ui, t.form_label_width + t.space_16 + t.space_6, |ui| {+ let label = app.tr("prefs.viewport");+ ui_kit::row(ui, label, |ui| {+ let views = crate::theme::ViewportTheme::ALL;+ let labels: Vec<_> = views.iter().map(|v| crate::i18n::tr(v.label_id())).collect();+ let mut selected = views.iter().position(|v| *v == app.preferences.viewport_theme).unwrap_or(0);+ if ui_kit::settings_segments(ui, label, &mut selected, &labels)+ && let Some(view) = views.get(selected)+ {+ app.preferences.viewport_theme = *view;+ }+ });+ });});ui_kit::settings_section(ui, "layout", app.tr("prefs.layout"), |ui| {ui_kit::settings_pair(diff --git a/crates/ui-egui/src/sketch3d.rs b/crates/ui-egui/src/sketch3d.rsindex 64584420ed..de2377014a 100644--- a/crates/ui-egui/src/sketch3d.rs+++ b/crates/ui-egui/src/sketch3d.rs@@ -196,7 +196,8 @@ pub fn preview(app: &SolveApp, t: &Tool, painter: &egui::Painter, proj: &Proj) -if !takes(t.cmd) || !active(app) {return false;}- let tk = Tokens::get();+ // Drawn straight onto the view: its side's colours (#4146).+ let tk = Tokens::view();let stroke = Stroke::new(1.5, tk.sketch_accent);let pts = if CHAIN.with(|c| c.borrow().0) == Some(t.cmd) { chain() } else { Vec::new() };let hover = HOVER.with(|h| *h.borrow());@@ -355,7 +356,8 @@ pub fn show(app: &SolveApp, painter: &egui::Painter, proj: &Proj) {if app.session.active_sketch.is_none() {return;}- let tk = Tokens::get();+ // Drawn straight onto the view: its side's colours (#4146).+ let tk = Tokens::view();let sel = TRIAD.with(|t| t.borrow().clone());for (w, i, p) in drawn_points(app) {if let Some(s) = proj.to_screen(p) {diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rsindex 975428bd29..c1c8591976 100644--- a/crates/ui-egui/src/theme.rs+++ b/crates/ui-egui/src/theme.rs@@ -25,6 +25,9 @@ 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<Option<Custom>> = const { Cell::new(None) };+ /// The 3D view's own dark or light when Preferences give it one ([`ViewportTheme`], #4146),+ /// per thread like the rest. `None`: the view is as dark as the window.+ static VIEWPORT_DARK: Cell<Option<bool>> = const { Cell::new(None) };}/// Three structural border levels plus independent content and control outlines.@@ -348,6 +351,11 @@ pub fn is_dark() -> bool {DARK.get()}+/// Is the 3D view dark? As the window, unless Preferences give the view its own (#4146).+pub fn viewport_dark() -> bool {+ VIEWPORT_DARK.get().unwrap_or_else(is_dark)+}+/// 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])@@ -415,6 +423,60 @@ impl<'de> Deserialize<'de> for ColorVision {}}+/// The 3D view's colours (#4146): the theme's own, or the built-in Light or Dark theme's whatever+/// the window uses, so a dark window can show the model on a light view and the other way round.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum ViewportTheme {+ #[default]+ Theme,+ Light,+ Dark,+}++impl ViewportTheme {+ pub const ALL: [ViewportTheme; 3] = [ViewportTheme::Theme, ViewportTheme::Light, ViewportTheme::Dark];++ /// The saved value (`ui.prefs` `viewport_theme`).+ pub fn id(self) -> &'static str {+ match self {+ ViewportTheme::Theme => "theme",+ ViewportTheme::Light => "light",+ ViewportTheme::Dark => "dark",+ }+ }++ pub fn from_id(id: &str) -> Option<ViewportTheme> {+ ViewportTheme::ALL.into_iter().find(|m| m.id() == id)+ }++ /// Its name in the Preferences (a message id).+ pub fn label_id(self) -> &'static str {+ match self {+ ViewportTheme::Theme => "ui.viewport_theme_follow",+ ViewportTheme::Light => "ui.light",+ ViewportTheme::Dark => "ui.dark",+ }+ }++ /// The view's own dark or light, or `None` to draw it as the window ([`set_viewport_dark`]).+ pub fn dark(self) -> Option<bool> {+ match self {+ ViewportTheme::Theme => None,+ ViewportTheme::Light => Some(false),+ ViewportTheme::Dark => Some(true),+ }+ }+}++/// From saved preferences: an unknown value is Theme, as [`ColorVision`]'s is Off.+impl<'de> Deserialize<'de> for ViewportTheme {+ fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let v = serde_json::Value::deserialize(d)?;+ Ok(v.as_str().and_then(ViewportTheme::from_id).unwrap_or_default())+ }+}+/// The colour vision mode on now (on this thread).pub fn vision() -> ColorVision {VISION.with(Cell::get)@@ -443,6 +505,9 @@ pub struct IconColors {pub marker_halo: Color32,}+/// Every colour and size the UI draws with. The colours drawn in the 3D view are listed again in+/// [`Tokens::with_viewport`], which takes them from the other side when the 3D view is set to the+/// other one's colours (#4146): a new colour drawn in the view goes in both.#[derive(Clone, Copy, Debug, PartialEq)]pub struct Tokens {/// Optional structural/control strokes. None retains each surface’s legacy styling.@@ -772,9 +837,89 @@ impl Tokens {[self.axis_x, self.axis_y, self.axis_z]}- /// The tokens of the current theme and colour vision mode.+ /// The tokens of the current theme and colour vision mode, the colours drawn in the 3D view+ /// from the view's own dark or light ([`viewport_dark`]).pub fn get() -> Tokens {- Tokens::themed(is_dark(), vision())+ let window = Tokens::themed(is_dark(), vision());+ if viewport_dark() == is_dark() { window } else { window.with_viewport(Tokens::themed(viewport_dark(), vision())) }+ }++ /// The tokens of the 3D view's side (#4146), for a window colour drawn straight onto the view+ /// 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 {+ Tokens::themed(viewport_dark(), vision())+ }++ /// These tokens with the colours drawn in the 3D view taken from `view`: the background and+ /// grid, bodies, selection and hover, the origin and construction geometry, previews, sketches+ /// and their dimensions and glyphs, the navigation cube and triads, box selection and the+ /// analysis colours. The window keeps its own: panels, dialogs, menus, and the chips and cards+ /// over the view (`overlay` with its text, icons and borders).+ pub fn with_viewport(self, view: Tokens) -> Tokens {+ Tokens {+ sel_face: view.sel_face,+ sel_edge: view.sel_edge,+ sel_edge_rim: view.sel_edge_rim,+ hover_edge: view.hover_edge,+ hover_edge_halo: view.hover_edge_halo,+ hover_face_lift: view.hover_face_lift,+ sel_profile: view.sel_profile,+ sel_profile_edge: view.sel_profile_edge,+ hover_profile: view.hover_profile,+ hover_profile_edge: view.hover_profile_edge,+ sel_vertex: view.sel_vertex,+ origin_plane: view.origin_plane,+ origin_plane_edge: view.origin_plane_edge,+ origin_plane_hover: view.origin_plane_hover,+ origin_point: view.origin_point,+ axis_x: view.axis_x,+ axis_y: view.axis_y,+ axis_z: view.axis_z,+ construction_plane: view.construction_plane,+ construction_geom: view.construction_geom,+ body: view.body,+ body_edge: view.body_edge,+ manipulator: view.manipulator,+ preview_add: view.preview_add,+ preview_new: view.preview_new,+ preview_sketch: view.preview_sketch,+ preview_cut: view.preview_cut,+ cube_face: view.cube_face,+ cube_border: view.cube_border,+ cube_text: view.cube_text,+ cube_hover: view.cube_hover,+ viewport_top: view.viewport_top,+ viewport_bottom: view.viewport_bottom,+ grid: view.grid,+ grid_major: view.grid_major,+ body_selected: view.body_selected,+ sketch: view.sketch,+ sketch_fixed: view.sketch_fixed,+ sketch_locked: view.sketch_locked,+ dimension: view.dimension,+ dimension_driven: view.dimension_driven,+ sketch_point: view.sketch_point,+ sketch_point_free: view.sketch_point_free,+ section_cap: view.section_cap,+ profile_fill: view.profile_fill,+ glyph_bg: view.glyph_bg,+ glyph_edge: view.glyph_edge,+ glyph_text: view.glyph_text,+ rubber_band: view.rubber_band,+ box_window: view.box_window,+ box_crossing: view.box_crossing,+ sketch_projected: view.sketch_projected,+ sketch_lost: view.sketch_lost,+ sketch_construction: view.sketch_construction,+ sketch_centerline: view.sketch_centerline,+ bend_up: view.bend_up,+ bend_down: view.bend_down,+ interference: view.interference,+ continuity: view.continuity,+ analysis: view.analysis,+ ..self+ }}/// The tokens of a theme and colour vision mode: a theme file's palette when one is on for@@ -820,6 +965,11 @@ pub fn set_dark(dark: bool) {DARK.set(dark);}+/// Give the 3D view its own dark or light (#4146), or `None` to draw it as dark as the window.+pub fn set_viewport_dark(dark: Option<bool>) {+ VIEWPORT_DARK.set(dark);+}+fn visuals(dark: bool) -> egui::Visuals {let t = Tokens::themed(dark, vision());let mut v = if dark { egui::Visuals::dark() } else { egui::Visuals::light() };@@ -1092,4 +1242,62 @@ mod tests {}});}++ /// A 3D view set to the other side's colours (#4146): the view's colours come from the other+ /// side and everything else stays the window's, in every colour vision mode. A view as dark as+ /// the window gives the window's tokens unchanged.+ #[test]+ fn a_view_on_the_other_side_takes_its_colours() {+ use super::{ColorVision, Tokens};+ for mode in ColorVision::ALL {+ super::set_vision(mode);+ for window in [false, true] {+ super::set_dark(window);+ for same in [None, Some(window)] {+ super::set_viewport_dark(same);+ assert_eq!(super::viewport_dark(), window);+ assert_eq!(Tokens::get(), Tokens::themed(window, mode), "{mode:?} {window} {same:?}");+ assert_eq!(Tokens::view(), Tokens::get(), "{mode:?} {window} {same:?}");+ }+ super::set_viewport_dark(Some(!window));+ assert_eq!(super::viewport_dark(), !window);+ let (t, w, v) = (Tokens::get(), Tokens::themed(window, mode), Tokens::themed(!window, mode));+ // What is drawn straight onto the view takes all of its side's colours.+ assert_eq!(Tokens::view(), v);+ // The two sides differ, so the checks below tell them apart.+ assert_ne!((w.viewport_top, w.panel), (v.viewport_top, v.panel));+ // The view's: background and grid, bodies, selection and hover, sketches with their+ // dimensions and glyphs, the origin, the cube and triads, box selection, analysis.+ assert_eq!((t.viewport_top, t.viewport_bottom, t.grid, t.grid_major), (v.viewport_top, v.viewport_bottom, v.grid, v.grid_major));+ assert_eq!(+ (t.body, t.body_edge, t.body_selected, t.sel_face, t.sel_edge, t.hover_edge),+ (v.body, v.body_edge, v.body_selected, v.sel_face, v.sel_edge, v.hover_edge)+ );+ assert_eq!(+ (t.sketch, t.sketch_fixed, t.dimension, t.glyph_bg, t.glyph_text, t.profile_fill),+ (v.sketch, v.sketch_fixed, v.dimension, v.glyph_bg, v.glyph_text, v.profile_fill)+ );+ assert_eq!(+ (t.origin_plane, t.axis_x, t.cube_face, t.cube_text, t.axis_y, t.axis_z),+ (v.origin_plane, v.axis_x, v.cube_face, v.cube_text, v.axis_y, v.axis_z)+ );+ assert_eq!(+ (t.box_window, t.section_cap, t.preview_add, t.sketch_construction, t.continuity),+ (v.box_window, v.section_cap, v.preview_add, v.sketch_construction, v.continuity)+ );+ assert_eq!(t.analysis, v.analysis);+ // The window's: panels, text, accents, dialogs, and the chips over the view with+ // their borders and icons.+ assert_eq!(+ (t.panel, t.text, t.border, t.accent, t.accent_soft, t.icon),+ (w.panel, w.text, w.border, w.accent, w.accent_soft, w.icon)+ );+ assert_eq!(+ (t.overlay, t.hover, t.dialog_bg, t.field, t.timeline, t.app_bar),+ (w.overlay, w.hover, w.dialog_bg, w.field, w.timeline, w.app_bar)+ );+ }+ }+ super::set_viewport_dark(None);+ }}diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rsindex c8b00ba1e3..0673ec1d3a 100644--- a/crates/ui-egui/src/tools.rs+++ b/crates/ui-egui/src/tools.rs@@ -979,7 +979,8 @@ pub fn preview(app: &SolveApp, t: &Tool, painter: &egui::Painter, proj: &Proj) {let st = app.session.world_state();let Some(ss) = st.sketch(sid) else { return };let to = |p: Vec2| proj.to_screen(ss.plane.to_world(p));- let tk = crate::theme::Tokens::get();+ // Drawn straight onto the view: its side's colours (#4146).+ let tk = crate::theme::Tokens::view();let stroke = Stroke::new(1.5, tk.sketch_accent);if let Some((hp, snap)) = &t.hover&& let Some(sp) = to(*hp)diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rsindex 7c5b8f8783..20726a9e7e 100644--- a/crates/ui-egui/src/viewport.rs+++ b/crates/ui-egui/src/viewport.rs@@ -1044,9 +1044,9 @@ pub(crate) fn build_scene(app: &SolveApp) -> GpuScene {if app.ui.ground_shadow && app.ui.visual_style != 2 && app.cam.pitch > 0.0 {ground_shadow(&mut sc, app, &st);}- // Section: the outline of each body where the plane cuts it.+ // Section: the outline of each body where the plane cuts it, in the view's text colour (#4146).if let Some((o, n)) = section_plane(app) {- let col = c4(tk.text.gamma_multiply(0.9));+ let col = c4(Tokens::view().text.gamma_multiply(0.9));let mut kept = app.viewport.section_index.lock().map(|mut k| std::mem::take(&mut *k)).unwrap_or_default();let mut made = Vec::new();for b in st.bodies.iter().filter(|b| app.session.body_visible(&b.name)) {@@ -1232,7 +1232,7 @@ fn ground_shadow(sc: &mut GpuScene, app: &SolveApp, st: &std::sync::Arc<solidcraif !(rx > 0.0 && ry > 0.0) {return;}- let dark = if crate::theme::is_dark() { 150 } else { 80 };+ let dark = if crate::theme::viewport_dark() { 150 } else { 80 };// Rings from the middle out, fading to nothing.let rings = [(0.0, dark), (0.55, dark * 3 / 4), (0.85, dark / 3), (1.0, 0)];let n = 48;@@ -3813,7 +3813,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {Align2::CENTER_BOTTOM,"Saved sketch plane — attachment lost",FontId::proportional(t.font_body),- t.warning,+ Tokens::view().warning,);}if let Some(bx) = app.viewport.boxsel {@@ -4630,16 +4630,18 @@ fn overlays(app: &SolveApp, painter: &egui::Painter, proj: &Proj) {painter.rect_filled(Rect::from_center_size(sp, vec2(5.0, 5.0)), 0.0, c);}}+ // The markers and the status line are drawn straight onto the view: its side's colours (#4146).+ let v = Tokens::view();for selected in &app.session.selection {if let Sel::SketchMidpoint { id } = selected&& let Some(line) = sk.curve_index(id)&& let Some(at) = crate::selection::line_midpoint(sk, line)&& let Some(screen) = proj.to_screen(ss.plane.to_world(at)){- midpoint_marker(painter, screen, t.sel_edge);+ midpoint_marker(painter, screen, v.sel_edge);}}- loose_end_markers(sk, &ss.ends, &ss.plane, painter, proj, &t);+ loose_end_markers(sk, &ss.ends, &ss.plane, painter, proj, &v);// Sketch status.if let Some(r) = app.viewport.layout.as_ref().map(|l| l.content) {let msg = if !ss.report.ok() {@@ -4649,7 +4651,7 @@ fn overlays(app: &SolveApp, painter: &egui::Painter, proj: &Proj) {} else {format!("{} — {} degrees of freedom", ss.name, ss.report.dof)};- let c = if ss.report.ok() { t.sketch_accent } else { t.error };+ let c = if ss.report.ok() { v.sketch_accent } else { v.error };painter.text(pos2(r.left() + 12.0, r.top() + 12.0), Align2::LEFT_TOP, msg, FontId::proportional(t.font_button), c);}}@@ -5756,6 +5758,37 @@ mod tests {}}+ /// Changing only the 3D view's dark or light (#4146) rebuilds the view's scene and highlights+ /// in its colours, as a change of the window's theme does.+ #[test]+ fn changing_only_the_views_dark_or_light_rebuilds_its_scene() {+ let mut h = crate::scenario::Harness::new();+ h.app.run("solid.box", json!({"length": 40, "width": 30, "height": 20})).unwrap();+ h.call("ui.prefs", json!({"theme": "dark"}));+ h.frames(2);+ let before = (scene_key(&h.app), highlight_geometry_key(&h.app));+ h.call("ui.prefs", json!({"viewport_theme": "light"}));+ h.frames(2);+ assert!(h.app.ui.dark, "the window stays dark");+ assert_ne!(scene_key(&h.app), before.0, "the scene is rebuilt");+ assert_ne!(highlight_geometry_key(&h.app), before.1, "and so are the highlights");+ }++ /// A section's cut outlines are drawn onto the view, so a light view in a dark window draws+ /// them in the light side's text colour (#4146): the window's would be pale on the light view.+ #[test]+ fn a_sections_outlines_take_the_views_text_colour() {+ let mut h = crate::scenario::Harness::new();+ h.app.run("solid.box", json!({"length": 40, "width": 30, "height": 20})).unwrap();+ h.app.run("inspect.section", json!({"plane": "XZ", "at": 15})).unwrap();+ h.call("ui.prefs", json!({"theme": "dark", "viewport_theme": "light"}));+ h.frames(2);+ let colours: Vec<[u8; 4]> = build_scene(&h.app).lines.as_chunks::<32>().0.iter().map(|l| [l[24], l[25], l[26], l[27]]).collect();+ let (view, window) = (Tokens::light().text.gamma_multiply(0.9), Tokens::dark().text.gamma_multiply(0.9));+ assert!(colours.contains(&c4(view)), "the outlines in the view's text colour");+ assert!(!colours.contains(&c4(window)), "none in the window's");+ }+/// The view's picture is cut by the section the viewport shows: an open Section Analysis/// dialog's preview, a sketch's Slice.#[cfg(not(target_arch = "wasm32"))]diff --git a/crates/ui-egui/tests/scenarios/prefs_viewport_theme.json b/crates/ui-egui/tests/scenarios/prefs_viewport_theme.jsonnew file mode 100644index 0000000000..6d150bafc6--- /dev/null+++ b/crates/ui-egui/tests/scenarios/prefs_viewport_theme.json@@ -0,0 +1,13 @@+[+ {"note": "#4146: under the theme tiles, Viewport draws the 3D view in the Light or Dark theme's colours whatever the window uses; it applies at once, and Cancel puts it back."},+ {"click": {"handle": "titlebar:preferences"}},+ {"widget": "Interface"},+ {"expect": {"prefs": {"theme": "dark", "dark": true, "viewport_theme": "theme", "viewport_dark": true}}},+ {"widget": "Light", "near": "Viewport"},+ {"expect": {"prefs": {"theme": "dark", "dark": true, "viewport_theme": "light", "viewport_dark": false}}},+ {"widget": "Dark", "near": "Viewport"},+ {"expect": {"prefs": {"viewport_theme": "dark", "viewport_dark": true}}},+ {"widget": "Light", "near": "Viewport"},+ {"widget": "Cancel"},+ {"expect": {"prefs": {"dialog": null, "theme": "dark", "viewport_theme": "theme", "viewport_dark": true}}}+]diff --git a/docs/book/src/guide/ui-tour.md b/docs/book/src/guide/ui-tour.mdindex 95d42e94d8..379f608a2e 100644--- a/docs/book/src/guide/ui-tour.md+++ b/docs/book/src/guide/ui-tour.md@@ -118,7 +118,7 @@ and command menus remain available.### Colour themesInterface › **Theme** lists Dark, Light and System (follows the operating system), the built-in-themes and any themes you have imported. A choice applies at once. The built-in themes are Gruvbox+themes and any themes you have imported. A choice applies at once. Under the themes, **Viewport** draws the 3D view in the Light or Dark theme's colours whatever the window uses, for example the model on a light view in a dark window (**Follow theme**, the default, keeps the theme's own). The built-in themes are Gruvbox(dark and light, each in hard, normal and soft contrast), SolidCraft 95, Platinum 9, Cupertino,Green Phosphor, Amber Phosphor, Blueprint, One Dark, Tokyo Night, Solarized Light, Nord, HighContrast, Graphite, Nosferatu, Catppuccin Mocha, and Okibi and Akari (dark and light, from thediff --git a/docs/control-protocol.md b/docs/control-protocol.mdindex 48d81ef370..4539c6081e 100644--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@ -245,7 +245,7 @@ labels; `prefs:measure_axis_distances` identifies the checkbox.| `ui.home` | `open?`: bool; `sample?`: index | the start page: show or hide it, open a built-in sample (once built); returns `open` and the recent designs || `ui.shortcut` | `command`, `key?`, `replace?` | a command's key, or rebinds it (`""` clears; a key another command uses is refused unless `replace`) || `ui.help` | `item?`: `about`, `shortcuts` (read only), `report` (opens a report draft for review), `crashes` (the Crash Reports window) | the version, commit, build date and diagnostic text |-| `ui.prefs` | any of `default_units`, `nav` (`fusion`, `solidworks`, `inventor`, `alias`, `blender`, `tinkercad`, `openscad`, `touchpad`), `zoom_reverse`, `pan_reverse_x` (default false: horizontal scrolling pans the other way), `zoom_to_cursor`, `smooth_wheel_zoom` (default true), `trackpad_pan` (default true: two-finger scroll pans, except Touchpad always zooms; pinch zooms), `orbit_around` (`view_centre` (default: what Pan moves and Fit frames), `origin` (the world origin stays still on screen), `cursor` (the model point under the pointer when the drag began); the older `orbit_cursor` boolean still sets `cursor` when true), `look_at_anim`, `look_at_speed`, `middle_double_click` (`home` (default), `fit`, `off`), `msaa`, `show_frame_rate` (default false: frames per second in the view's bottom-right corner, counting the frames the view draws anyway; it reads 0 FPS once the view is idle), `window_system` (Linux: `auto` (default: XWayland whenever there is an X display, native Wayland on niri), `wayland`, `x11`; saved in `graphics.json`, applies at the next start; `SOLIDCRAFT_WAYLAND` overrides it), `graphics_adapter` (exact card name, or empty for Automatic; applies after restart; `WGPU_ADAPTER_NAME` takes precedence), `frame_rate_details` (default false: with the frame rate, a frame-time graph of the frames drawn with the triangles over it, a frame-time histogram and what the GPU drew; clicking the readout switches it), `length_decimals`, `angle_decimals`, `step_values` (default false: Up/Down and the wheel step a plain number in a focused value field), `theme` (`dark`, `light`, `system` or a theme file's id: a built-in one such as `gruvbox-dark`, or an imported one; the reply's `theme_ids` lists them), `theme_import` (a `solidcraft-theme/1` file's JSON or text: adds the theme and turns it on; the reply's `theme_imported` is its id), `theme_remove` (an imported theme's id), `theme_export: true` (the reply's `theme_file` is the theme on now as a complete file; see [colour themes](book/src/guide/ui-tour.md#colour-themes)), `language` (`en`, `ja`, `de`, `fr`, `ko`, `ms`, `ru`, `uk`, `zh`; see [localization](localization.md)), `ui_scale`, `ui_font` (an installed font family or a font file for the interface; empty for the built-in font), `up_axis` (`z`, `y`), `offer_stand_up`, `extrude_auto_to_object` (default false: in the Extrude dialog, with a profile picked, a face, vertex or parallel plane picked off its plane switches the extent to To Object; it applies to Extrude dialogs opened afterwards), `hole_snaps` (default false: a Single hole snaps to its face's middle and round edges' centres), `hole_moves` (default false: a placed Single hole has a drag handle (`hole:<n>`), and a pick on a face that has a hole moves it there), `color_vision` (`off` (default), `protan`, `deutan`, `tritan`: colour vision modes, #778), `check_updates` (default true; [updates](book/src/guide/updates.md)); `open` (a page: General, Interface, Design, Navigation, Keyboard Shortcuts, Sketch, Graphics, AI, Plugins; Shortcuts, Assistant and Sketch & selection are aliases, and the former Selection page opens Sketch) opens the Preferences dialog there; `button`: `ok`, `cancel`, `apply`, `defaults`; `stand_up: true` stands up a just-opened Y-up file, `stand_up: false` leaves it as it is ("Leave it": the offer closes and `offer_stand_up` stays on); the offer's buttons are the handles `stand_up:stand`, `stand_up:leave` and `stand_up:never` | sets preferences (kept between runs), returns them all plus `dialog` (the open page or null), `dark` and `stand_up_offer` |+| `ui.prefs` | any of `default_units`, `nav` (`fusion`, `solidworks`, `inventor`, `alias`, `blender`, `tinkercad`, `openscad`, `touchpad`), `zoom_reverse`, `pan_reverse_x` (default false: horizontal scrolling pans the other way), `zoom_to_cursor`, `smooth_wheel_zoom` (default true), `trackpad_pan` (default true: two-finger scroll pans, except Touchpad always zooms; pinch zooms), `orbit_around` (`view_centre` (default: what Pan moves and Fit frames), `origin` (the world origin stays still on screen), `cursor` (the model point under the pointer when the drag began); the older `orbit_cursor` boolean still sets `cursor` when true), `look_at_anim`, `look_at_speed`, `middle_double_click` (`home` (default), `fit`, `off`), `msaa`, `show_frame_rate` (default false: frames per second in the view's bottom-right corner, counting the frames the view draws anyway; it reads 0 FPS once the view is idle), `window_system` (Linux: `auto` (default: XWayland whenever there is an X display, native Wayland on niri), `wayland`, `x11`; saved in `graphics.json`, applies at the next start; `SOLIDCRAFT_WAYLAND` overrides it), `graphics_adapter` (exact card name, or empty for Automatic; applies after restart; `WGPU_ADAPTER_NAME` takes precedence), `frame_rate_details` (default false: with the frame rate, a frame-time graph of the frames drawn with the triangles over it, a frame-time histogram and what the GPU drew; clicking the readout switches it), `length_decimals`, `angle_decimals`, `step_values` (default false: Up/Down and the wheel step a plain number in a focused value field), `theme` (`dark`, `light`, `system` or a theme file's id: a built-in one such as `gruvbox-dark`, or an imported one; the reply's `theme_ids` lists them), `viewport_theme` (`theme` (default: the theme's own), `light`, `dark`: the 3D view in the Light or Dark theme's colours whatever the window uses, #4146), `theme_import` (a `solidcraft-theme/1` file's JSON or text: adds the theme and turns it on; the reply's `theme_imported` is its id), `theme_remove` (an imported theme's id), `theme_export: true` (the reply's `theme_file` is the theme on now as a complete file; see [colour themes](book/src/guide/ui-tour.md#colour-themes)), `language` (`en`, `ja`, `de`, `fr`, `ko`, `ms`, `ru`, `uk`, `zh`; see [localization](localization.md)), `ui_scale`, `ui_font` (an installed font family or a font file for the interface; empty for the built-in font), `up_axis` (`z`, `y`), `offer_stand_up`, `extrude_auto_to_object` (default false: in the Extrude dialog, with a profile picked, a face, vertex or parallel plane picked off its plane switches the extent to To Object; it applies to Extrude dialogs opened afterwards), `hole_snaps` (default false: a Single hole snaps to its face's middle and round edges' centres), `hole_moves` (default false: a placed Single hole has a drag handle (`hole:<n>`), and a pick on a face that has a hole moves it there), `color_vision` (`off` (default), `protan`, `deutan`, `tritan`: colour vision modes, #778), `check_updates` (default true; [updates](book/src/guide/updates.md)); `open` (a page: General, Interface, Design, Navigation, Keyboard Shortcuts, Sketch, Graphics, AI, Plugins; Shortcuts, Assistant and Sketch & selection are aliases, and the former Selection page opens Sketch) opens the Preferences dialog there; `button`: `ok`, `cancel`, `apply`, `defaults`; `stand_up: true` stands up a just-opened Y-up file, `stand_up: false` leaves it as it is ("Leave it": the offer closes and `offer_stand_up` stays on); the offer's buttons are the handles `stand_up:stand`, `stand_up:leave` and `stand_up:never` | sets preferences (kept between runs), returns them all plus `dialog` (the open page or null), `dark`, `viewport_dark` (whether the 3D view is dark) and `stand_up_offer` || `ui.capture` | `action?`: `capture`, `revert`, `cancel` | answers the Capture Position question (asked when a command starts or the design is saved while components were moved without capturing); without `action`, what waits || `ui.window` | `action`: minimize, maximize, restore, toggle, close | what the title bar's caption buttons do (on Windows and Linux the application bar is the title bar); close asks about unsaved designs first || `ui.agent_cursor` | `show` (bool), `speed`: a number from 1 to 5 (times the normal speed) or `"instant"` (no animation: the command runs at once and the pointer jumps to where it acted), `follow_camera` (bool); all optional | the settings. While the cursor is shown, `engine.execute` first glides to the command's toolbar button and to each pick, then runs and replies; later requests wait their turn. The pointer shows the command's localized name, including commands inside a closed toolbar group; an animated batch names each command it visits. It also follows the pointer input sent with `ui.move`, `ui.click`, `ui.drag` and `ui.scroll`, as each event reaches the app, and a press leaves a ripple. `"animate": false` on a call skips it |