From 535a43ab3cb70a57fe511fcaf746153f9882cc40 Mon Sep 17 00:00:00 2001 From: fugazister Date: Sun, 18 Oct 2026 16:01:39 +0200 Subject: [PATCH] Custom colour themes: theme files, Gruvbox built in (#2255) (#2405) Thanks @fugazister. --- ATTRIBUTION.md | 6 + .../styles/ui/themes/gruvbox-dark-hard.json | 119 ++++++ .../styles/ui/themes/gruvbox-dark-soft.json | 119 ++++++ assets/styles/ui/themes/gruvbox-dark.json | 119 ++++++ .../styles/ui/themes/gruvbox-light-hard.json | 119 ++++++ .../styles/ui/themes/gruvbox-light-soft.json | 119 ++++++ assets/styles/ui/themes/gruvbox-light.json | 119 ++++++ crates/ui-egui/src/colour_tokens_tests.rs | 1 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/prefs.rs | 242 ++++++++++- crates/ui-egui/src/theme.rs | 26 +- crates/ui-egui/src/theme_files.rs | 377 ++++++++++++++++++ .../tests/scenarios/prefs_theme_files.json | 13 + .../tests/scenarios/s45_preferences.json | 3 +- docs/book/src/guide/ui-tour.md | 38 ++ docs/control-protocol.md | 2 +- 16 files changed, 1401 insertions(+), 22 deletions(-) create mode 100644 assets/styles/ui/themes/gruvbox-dark-hard.json create mode 100644 assets/styles/ui/themes/gruvbox-dark-soft.json create mode 100644 assets/styles/ui/themes/gruvbox-dark.json create mode 100644 assets/styles/ui/themes/gruvbox-light-hard.json create mode 100644 assets/styles/ui/themes/gruvbox-light-soft.json create mode 100644 assets/styles/ui/themes/gruvbox-light.json create mode 100644 crates/ui-egui/src/theme_files.rs create mode 100644 crates/ui-egui/tests/scenarios/prefs_theme_files.json diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index ca761a29b..c37f17c35 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -111,6 +111,12 @@ Editable drawing code, native projects and shipped exports are collected under ` | assets/platforms/windows/solidcraft.wxs | PhotoCraft / SolidCraft contributors | PhotoCraft packaging templates (https://github.com/storytold/photocraft), adapted for SolidCraft | Apache-2.0 | | assets/shaders/viewport.wgsl | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 | | assets/styles/ui/palettes.rs | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 | +| assets/styles/ui/themes/gruvbox-dark.json | SolidCraft contributors | original SolidCraft theme file mapping SolidCraft's UI colours to the Gruvbox palette's colour values (Gruvbox by Pavel Pertsev, https://github.com/morhetz/gruvbox, MIT) | MIT OR Apache-2.0 | +| assets/styles/ui/themes/gruvbox-dark-hard.json | SolidCraft contributors | original SolidCraft theme file mapping SolidCraft's UI colours to the Gruvbox palette's colour values (Gruvbox by Pavel Pertsev, https://github.com/morhetz/gruvbox, MIT) | MIT OR Apache-2.0 | +| assets/styles/ui/themes/gruvbox-dark-soft.json | SolidCraft contributors | original SolidCraft theme file mapping SolidCraft's UI colours to the Gruvbox palette's colour values (Gruvbox by Pavel Pertsev, https://github.com/morhetz/gruvbox, MIT) | MIT OR Apache-2.0 | +| assets/styles/ui/themes/gruvbox-light.json | SolidCraft contributors | original SolidCraft theme file mapping SolidCraft's UI colours to the Gruvbox palette's colour values (Gruvbox by Pavel Pertsev, https://github.com/morhetz/gruvbox, MIT) | MIT OR Apache-2.0 | +| assets/styles/ui/themes/gruvbox-light-hard.json | SolidCraft contributors | original SolidCraft theme file mapping SolidCraft's UI colours to the Gruvbox palette's colour values (Gruvbox by Pavel Pertsev, https://github.com/morhetz/gruvbox, MIT) | MIT OR Apache-2.0 | +| assets/styles/ui/themes/gruvbox-light-soft.json | SolidCraft contributors | original SolidCraft theme file mapping SolidCraft's UI colours to the Gruvbox palette's colour values (Gruvbox by Pavel Pertsev, https://github.com/morhetz/gruvbox, MIT) | MIT OR Apache-2.0 | | assets/styles/web/loading-logo.svg | SolidCraft contributors | Animation of the SolidCraft mark, built from the paths and gradients of assets/icons/app/macos/source/SolidCraft.icon/Assets/03-solid-blue-cutout.svg; original animation | MIT OR Apache-2.0 | | assets/styles/web/loading.css | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 | | crates/io/src/native_cad/fixtures/block.FCStd | SolidCraft contributors | original 10 × 20 × 30 mm test box saved by FreeCAD 1.1.4 run as an external program (`make_block_fcstd.py` beside it); no third-party geometry | MIT OR Apache-2.0 | diff --git a/assets/styles/ui/themes/gruvbox-dark-hard.json b/assets/styles/ui/themes/gruvbox-dark-hard.json new file mode 100644 index 000000000..29033943d --- /dev/null +++ b/assets/styles/ui/themes/gruvbox-dark-hard.json @@ -0,0 +1,119 @@ +{ + "format": "solidcraft-theme/1", + "name": "Gruvbox Dark Hard", + "base": "dark", + "colors": { + "app_bar": "#141617", + "toolbar": "#1d2021", + "panel": "#1d2021", + "panel_header": "#3c3836", + "border": "#504945", + "text": "#ebdbb2", + "text_dim": "#a89984", + "accent": "#83a598", + "accent_soft": "#414f4b", + "sketch_accent": "#83a598", + "error": "#fb4934", + "warning": "#fabd2f", + "icon": "#d5c4a1", + "icon_fill": "#458588", + "timeline": "#141617", + "hover": "#46403e", + "sel_face": "#458588", + "sel_edge": "#83a598", + "sel_edge_rim": "#aec4bc", + "sel_profile": "#076678", + "sel_profile_edge": "#458588", + "hover_profile": "#83a59830", + "hover_profile_edge": "#83a598", + "sel_vertex": "#83a598", + "origin_plane": "#fe801950", + "origin_plane_edge": "#d65d0ec8", + "origin_plane_hover": "#83a59896", + "origin_point": "#d5c4a1", + "axis_x": "#fb4934", + "axis_y": "#b8bb26", + "axis_z": "#83a598", + "construction_plane": "#fe801940", + "construction_geom": "#fe8019", + "body": "#a89984", + "body_edge": "#141617", + "manipulator": "#83a598", + "preview_add": "#83a598", + "preview_new": "#fabd2f", + "preview_sketch": "#b8bb26", + "preview_cut": "#fb49346e", + "cube_face": "#ebdbb2", + "cube_border": "#665c54", + "cube_text": "#282828", + "cube_hover": "#83a598", + "viewport_top": "#2c2c2c", + "viewport_bottom": "#2c2c2c", + "grid": "#443f3c", + "grid_major": "#504945", + "body_selected": "#83a598", + "sketch": "#83a598", + "sketch_fixed": "#ebdbb2", + "sketch_locked": "#b8bb26", + "dimension": "#ebdbb2", + "dimension_driven": "#928374", + "sketch_point": "#ebdbb2", + "sketch_point_free": "#83a598", + "dialog_bg": "#3c3836", + "dialog_border": "#504945", + "chip": "#458588", + "heading_bg": "#1d2021", + "subheading_bg": "#2c2c2c", + "section_cap": "#d65d0e", + "profile_fill": "#83a59828", + "glyph_bg": "#2c2c2c", + "glyph_edge": "#d65d0e", + "glyph_text": "#fe8019", + "overlay": "#1d2021f0", + "rubber_band": "#83a598", + "app_bar_text": "#ebdbb2", + "app_bar_hover": "#ebdbb21c", + "timeline_item": "#3c3836", + "timeline_item_error": "#63221f", + "timeline_marker": "#bdae93", + "field": "#141617", + "box_window": "#83a598", + "box_crossing": "#b8bb26", + "sketch_projected": "#d3869b", + "sketch_lost": "#fb4934", + "sketch_construction": "#fe8019", + "sketch_centerline": "#d65d0e", + "bend_up": "#b8bb26", + "bend_down": "#fe8019", + "interference": "#fb4934", + "triad": [ + "#fb4934", + "#b8bb26", + "#83a598" + ], + "gizmo": [ + "#fb4934", + "#b8bb26", + "#83a598" + ], + "app_bar_icon": [ + "#ebdbb2", + "#928374", + "#83a598" + ], + "icons.folder": "#d79921", + "icons.axes": [ + "#fb4934", + "#b8bb26", + "#83a598" + ], + "icons.agent": "#d3869b", + "icons.warning": "#fabd2f", + "icons.interference": "#fb4934", + "icons.paint": [ + "#fb4934", + "#83a598", + "#fabd2f" + ] + } +} diff --git a/assets/styles/ui/themes/gruvbox-dark-soft.json b/assets/styles/ui/themes/gruvbox-dark-soft.json new file mode 100644 index 000000000..ac5042e19 --- /dev/null +++ b/assets/styles/ui/themes/gruvbox-dark-soft.json @@ -0,0 +1,119 @@ +{ + "format": "solidcraft-theme/1", + "name": "Gruvbox Dark Soft", + "base": "dark", + "colors": { + "app_bar": "#1d2021", + "toolbar": "#32302f", + "panel": "#32302f", + "panel_header": "#3c3836", + "border": "#504945", + "text": "#ebdbb2", + "text_dim": "#a89984", + "accent": "#83a598", + "accent_soft": "#4e5954", + "sketch_accent": "#83a598", + "error": "#fb4934", + "warning": "#fabd2f", + "icon": "#d5c4a1", + "icon_fill": "#458588", + "timeline": "#1d2021", + "hover": "#46403e", + "sel_face": "#458588", + "sel_edge": "#83a598", + "sel_edge_rim": "#aec4bc", + "sel_profile": "#076678", + "sel_profile_edge": "#458588", + "hover_profile": "#83a59830", + "hover_profile_edge": "#83a598", + "sel_vertex": "#83a598", + "origin_plane": "#fe801950", + "origin_plane_edge": "#d65d0ec8", + "origin_plane_hover": "#83a59896", + "origin_point": "#d5c4a1", + "axis_x": "#fb4934", + "axis_y": "#b8bb26", + "axis_z": "#83a598", + "construction_plane": "#fe801940", + "construction_geom": "#fe8019", + "body": "#a89984", + "body_edge": "#1d2021", + "manipulator": "#83a598", + "preview_add": "#83a598", + "preview_new": "#fabd2f", + "preview_sketch": "#b8bb26", + "preview_cut": "#fb49346e", + "cube_face": "#ebdbb2", + "cube_border": "#665c54", + "cube_text": "#282828", + "cube_hover": "#83a598", + "viewport_top": "#373432", + "viewport_bottom": "#373432", + "grid": "#443f3c", + "grid_major": "#504945", + "body_selected": "#83a598", + "sketch": "#83a598", + "sketch_fixed": "#ebdbb2", + "sketch_locked": "#b8bb26", + "dimension": "#ebdbb2", + "dimension_driven": "#928374", + "sketch_point": "#ebdbb2", + "sketch_point_free": "#83a598", + "dialog_bg": "#3c3836", + "dialog_border": "#504945", + "chip": "#458588", + "heading_bg": "#32302f", + "subheading_bg": "#373432", + "section_cap": "#d65d0e", + "profile_fill": "#83a59828", + "glyph_bg": "#373432", + "glyph_edge": "#d65d0e", + "glyph_text": "#fe8019", + "overlay": "#32302ff0", + "rubber_band": "#83a598", + "app_bar_text": "#ebdbb2", + "app_bar_hover": "#ebdbb21c", + "timeline_item": "#3c3836", + "timeline_item_error": "#702b28", + "timeline_marker": "#bdae93", + "field": "#1d2021", + "box_window": "#83a598", + "box_crossing": "#b8bb26", + "sketch_projected": "#d3869b", + "sketch_lost": "#fb4934", + "sketch_construction": "#fe8019", + "sketch_centerline": "#d65d0e", + "bend_up": "#b8bb26", + "bend_down": "#fe8019", + "interference": "#fb4934", + "triad": [ + "#fb4934", + "#b8bb26", + "#83a598" + ], + "gizmo": [ + "#fb4934", + "#b8bb26", + "#83a598" + ], + "app_bar_icon": [ + "#ebdbb2", + "#928374", + "#83a598" + ], + "icons.folder": "#d79921", + "icons.axes": [ + "#fb4934", + "#b8bb26", + "#83a598" + ], + "icons.agent": "#d3869b", + "icons.warning": "#fabd2f", + "icons.interference": "#fb4934", + "icons.paint": [ + "#fb4934", + "#83a598", + "#fabd2f" + ] + } +} diff --git a/assets/styles/ui/themes/gruvbox-dark.json b/assets/styles/ui/themes/gruvbox-dark.json new file mode 100644 index 000000000..4c55a6b23 --- /dev/null +++ b/assets/styles/ui/themes/gruvbox-dark.json @@ -0,0 +1,119 @@ +{ + "format": "solidcraft-theme/1", + "name": "Gruvbox Dark", + "base": "dark", + "colors": { + "app_bar": "#1d2021", + "toolbar": "#282828", + "panel": "#282828", + "panel_header": "#3c3836", + "border": "#504945", + "text": "#ebdbb2", + "text_dim": "#a89984", + "accent": "#83a598", + "accent_soft": "#48544f", + "sketch_accent": "#83a598", + "error": "#fb4934", + "warning": "#fabd2f", + "icon": "#d5c4a1", + "icon_fill": "#458588", + "timeline": "#1d2021", + "hover": "#46403e", + "sel_face": "#458588", + "sel_edge": "#83a598", + "sel_edge_rim": "#aec4bc", + "sel_profile": "#076678", + "sel_profile_edge": "#458588", + "hover_profile": "#83a59830", + "hover_profile_edge": "#83a598", + "sel_vertex": "#83a598", + "origin_plane": "#fe801950", + "origin_plane_edge": "#d65d0ec8", + "origin_plane_hover": "#83a59896", + "origin_point": "#d5c4a1", + "axis_x": "#fb4934", + "axis_y": "#b8bb26", + "axis_z": "#83a598", + "construction_plane": "#fe801940", + "construction_geom": "#fe8019", + "body": "#a89984", + "body_edge": "#1d2021", + "manipulator": "#83a598", + "preview_add": "#83a598", + "preview_new": "#fabd2f", + "preview_sketch": "#b8bb26", + "preview_cut": "#fb49346e", + "cube_face": "#ebdbb2", + "cube_border": "#665c54", + "cube_text": "#282828", + "cube_hover": "#83a598", + "viewport_top": "#32302f", + "viewport_bottom": "#32302f", + "grid": "#443f3c", + "grid_major": "#504945", + "body_selected": "#83a598", + "sketch": "#83a598", + "sketch_fixed": "#ebdbb2", + "sketch_locked": "#b8bb26", + "dimension": "#ebdbb2", + "dimension_driven": "#928374", + "sketch_point": "#ebdbb2", + "sketch_point_free": "#83a598", + "dialog_bg": "#3c3836", + "dialog_border": "#504945", + "chip": "#458588", + "heading_bg": "#282828", + "subheading_bg": "#32302f", + "section_cap": "#d65d0e", + "profile_fill": "#83a59828", + "glyph_bg": "#32302f", + "glyph_edge": "#d65d0e", + "glyph_text": "#fe8019", + "overlay": "#282828f0", + "rubber_band": "#83a598", + "app_bar_text": "#ebdbb2", + "app_bar_hover": "#ebdbb21c", + "timeline_item": "#3c3836", + "timeline_item_error": "#6a2624", + "timeline_marker": "#bdae93", + "field": "#1d2021", + "box_window": "#83a598", + "box_crossing": "#b8bb26", + "sketch_projected": "#d3869b", + "sketch_lost": "#fb4934", + "sketch_construction": "#fe8019", + "sketch_centerline": "#d65d0e", + "bend_up": "#b8bb26", + "bend_down": "#fe8019", + "interference": "#fb4934", + "triad": [ + "#fb4934", + "#b8bb26", + "#83a598" + ], + "gizmo": [ + "#fb4934", + "#b8bb26", + "#83a598" + ], + "app_bar_icon": [ + "#ebdbb2", + "#928374", + "#83a598" + ], + "icons.folder": "#d79921", + "icons.axes": [ + "#fb4934", + "#b8bb26", + "#83a598" + ], + "icons.agent": "#d3869b", + "icons.warning": "#fabd2f", + "icons.interference": "#fb4934", + "icons.paint": [ + "#fb4934", + "#83a598", + "#fabd2f" + ] + } +} diff --git a/assets/styles/ui/themes/gruvbox-light-hard.json b/assets/styles/ui/themes/gruvbox-light-hard.json new file mode 100644 index 000000000..adbe04d4b --- /dev/null +++ b/assets/styles/ui/themes/gruvbox-light-hard.json @@ -0,0 +1,119 @@ +{ + "format": "solidcraft-theme/1", + "name": "Gruvbox Light Hard", + "base": "light", + "colors": { + "app_bar": "#3c3836", + "toolbar": "#f9f5d7", + "panel": "#f9f5d7", + "panel_header": "#ebdbb2", + "border": "#d5c4a1", + "text": "#3c3836", + "text_dim": "#7c6f64", + "accent": "#076678", + "accent_soft": "#c9d8c4", + "sketch_accent": "#076678", + "error": "#9d0006", + "warning": "#b57614", + "icon": "#504945", + "icon_fill": "#bdae93", + "timeline": "#ebdbb2", + "hover": "#f1e5c1", + "sel_face": "#458588", + "sel_edge": "#076678", + "sel_edge_rim": "#83a598", + "sel_profile": "#076678", + "sel_profile_edge": "#458588", + "hover_profile": "#45858830", + "hover_profile_edge": "#458588", + "sel_vertex": "#076678", + "origin_plane": "#fe80195e", + "origin_plane_edge": "#d65d0ec8", + "origin_plane_hover": "#45858896", + "origin_point": "#d5c4a1", + "axis_x": "#cc241d", + "axis_y": "#98971a", + "axis_z": "#458588", + "construction_plane": "#fe801946", + "construction_geom": "#af3a03", + "body": "#bdae93", + "body_edge": "#3c3836", + "manipulator": "#076678", + "preview_add": "#458588", + "preview_new": "#d79921", + "preview_sketch": "#98971a", + "preview_cut": "#cc241d6e", + "cube_face": "#fbf1c7", + "cube_border": "#7c6f64", + "cube_text": "#3c3836", + "cube_hover": "#83a598", + "viewport_top": "#fbf8e3", + "viewport_bottom": "#ebdbb2", + "grid": "#d5c4a1", + "grid_major": "#bdae93", + "body_selected": "#83a598", + "sketch": "#076678", + "sketch_fixed": "#282828", + "sketch_locked": "#79740e", + "dimension": "#3c3836", + "dimension_driven": "#7c6f64", + "sketch_point": "#282828", + "sketch_point_free": "#076678", + "dialog_bg": "#f9f5d7", + "dialog_border": "#d5c4a1", + "chip": "#458588", + "heading_bg": "#d5c4a1", + "subheading_bg": "#ebdbb2", + "section_cap": "#d65d0e", + "profile_fill": "#fabd2f46", + "glyph_bg": "#fcfaeb", + "glyph_edge": "#af3a03", + "glyph_text": "#af3a03", + "overlay": "#f9f5d7eb", + "rubber_band": "#076678", + "app_bar_text": "#fbf1c7", + "app_bar_hover": "#fbf1c71c", + "timeline_item": "#f9f5d7", + "timeline_item_error": "#f0cbb2", + "timeline_marker": "#504945", + "field": "#fcfaeb", + "box_window": "#076678", + "box_crossing": "#79740e", + "sketch_projected": "#8f3f71", + "sketch_lost": "#9d0006", + "sketch_construction": "#af3a03", + "sketch_centerline": "#d65d0e", + "bend_up": "#79740e", + "bend_down": "#af3a03", + "interference": "#cc241d", + "triad": [ + "#cc241d", + "#98971a", + "#458588" + ], + "gizmo": [ + "#cc241d", + "#98971a", + "#458588" + ], + "app_bar_icon": [ + "#fbf1c7", + "#a89984", + "#83a598" + ], + "icons.folder": "#d79921", + "icons.axes": [ + "#cc241d", + "#98971a", + "#458588" + ], + "icons.agent": "#8f3f71", + "icons.warning": "#d79921", + "icons.interference": "#cc241d", + "icons.paint": [ + "#cc241d", + "#458588", + "#d79921" + ] + } +} diff --git a/assets/styles/ui/themes/gruvbox-light-soft.json b/assets/styles/ui/themes/gruvbox-light-soft.json new file mode 100644 index 000000000..14891bc6b --- /dev/null +++ b/assets/styles/ui/themes/gruvbox-light-soft.json @@ -0,0 +1,119 @@ +{ + "format": "solidcraft-theme/1", + "name": "Gruvbox Light Soft", + "base": "light", + "colors": { + "app_bar": "#3c3836", + "toolbar": "#f2e5bc", + "panel": "#f2e5bc", + "panel_header": "#ebdbb2", + "border": "#d5c4a1", + "text": "#3c3836", + "text_dim": "#7c6f64", + "accent": "#076678", + "accent_soft": "#c3ccae", + "sketch_accent": "#076678", + "error": "#9d0006", + "warning": "#b57614", + "icon": "#504945", + "icon_fill": "#bdae93", + "timeline": "#ebdbb2", + "hover": "#eedfb6", + "sel_face": "#458588", + "sel_edge": "#076678", + "sel_edge_rim": "#83a598", + "sel_profile": "#076678", + "sel_profile_edge": "#458588", + "hover_profile": "#45858830", + "hover_profile_edge": "#458588", + "sel_vertex": "#076678", + "origin_plane": "#fe80195e", + "origin_plane_edge": "#d65d0ec8", + "origin_plane_hover": "#45858896", + "origin_point": "#d5c4a1", + "axis_x": "#cc241d", + "axis_y": "#98971a", + "axis_z": "#458588", + "construction_plane": "#fe801946", + "construction_geom": "#af3a03", + "body": "#bdae93", + "body_edge": "#3c3836", + "manipulator": "#076678", + "preview_add": "#458588", + "preview_new": "#d79921", + "preview_sketch": "#98971a", + "preview_cut": "#cc241d6e", + "cube_face": "#fbf1c7", + "cube_border": "#7c6f64", + "cube_text": "#3c3836", + "cube_hover": "#83a598", + "viewport_top": "#f6edd0", + "viewport_bottom": "#ebdbb2", + "grid": "#d5c4a1", + "grid_major": "#bdae93", + "body_selected": "#83a598", + "sketch": "#076678", + "sketch_fixed": "#282828", + "sketch_locked": "#79740e", + "dimension": "#3c3836", + "dimension_driven": "#7c6f64", + "sketch_point": "#282828", + "sketch_point_free": "#076678", + "dialog_bg": "#f2e5bc", + "dialog_border": "#d5c4a1", + "chip": "#458588", + "heading_bg": "#d5c4a1", + "subheading_bg": "#ebdbb2", + "section_cap": "#d65d0e", + "profile_fill": "#fabd2f46", + "glyph_bg": "#f8f2de", + "glyph_edge": "#af3a03", + "glyph_text": "#af3a03", + "overlay": "#f2e5bceb", + "rubber_band": "#076678", + "app_bar_text": "#fbf1c7", + "app_bar_hover": "#fbf1c71c", + "timeline_item": "#f2e5bc", + "timeline_item_error": "#eabe9c", + "timeline_marker": "#504945", + "field": "#f8f2de", + "box_window": "#076678", + "box_crossing": "#79740e", + "sketch_projected": "#8f3f71", + "sketch_lost": "#9d0006", + "sketch_construction": "#af3a03", + "sketch_centerline": "#d65d0e", + "bend_up": "#79740e", + "bend_down": "#af3a03", + "interference": "#cc241d", + "triad": [ + "#cc241d", + "#98971a", + "#458588" + ], + "gizmo": [ + "#cc241d", + "#98971a", + "#458588" + ], + "app_bar_icon": [ + "#fbf1c7", + "#a89984", + "#83a598" + ], + "icons.folder": "#d79921", + "icons.axes": [ + "#cc241d", + "#98971a", + "#458588" + ], + "icons.agent": "#8f3f71", + "icons.warning": "#d79921", + "icons.interference": "#cc241d", + "icons.paint": [ + "#cc241d", + "#458588", + "#d79921" + ] + } +} diff --git a/assets/styles/ui/themes/gruvbox-light.json b/assets/styles/ui/themes/gruvbox-light.json new file mode 100644 index 000000000..bd5191a46 --- /dev/null +++ b/assets/styles/ui/themes/gruvbox-light.json @@ -0,0 +1,119 @@ +{ + "format": "solidcraft-theme/1", + "name": "Gruvbox Light", + "base": "light", + "colors": { + "app_bar": "#3c3836", + "toolbar": "#fbf1c7", + "panel": "#fbf1c7", + "panel_header": "#ebdbb2", + "border": "#d5c4a1", + "text": "#3c3836", + "text_dim": "#7c6f64", + "accent": "#076678", + "accent_soft": "#cad5b7", + "sketch_accent": "#076678", + "error": "#9d0006", + "warning": "#b57614", + "icon": "#504945", + "icon_fill": "#bdae93", + "timeline": "#ebdbb2", + "hover": "#f1e4ba", + "sel_face": "#458588", + "sel_edge": "#076678", + "sel_edge_rim": "#83a598", + "sel_profile": "#076678", + "sel_profile_edge": "#458588", + "hover_profile": "#45858830", + "hover_profile_edge": "#458588", + "sel_vertex": "#076678", + "origin_plane": "#fe80195e", + "origin_plane_edge": "#d65d0ec8", + "origin_plane_hover": "#45858896", + "origin_point": "#d5c4a1", + "axis_x": "#cc241d", + "axis_y": "#98971a", + "axis_z": "#458588", + "construction_plane": "#fe801946", + "construction_geom": "#af3a03", + "body": "#bdae93", + "body_edge": "#3c3836", + "manipulator": "#076678", + "preview_add": "#458588", + "preview_new": "#d79921", + "preview_sketch": "#98971a", + "preview_cut": "#cc241d6e", + "cube_face": "#fbf1c7", + "cube_border": "#7c6f64", + "cube_text": "#3c3836", + "cube_hover": "#83a598", + "viewport_top": "#fcf5d8", + "viewport_bottom": "#ebdbb2", + "grid": "#d5c4a1", + "grid_major": "#bdae93", + "body_selected": "#83a598", + "sketch": "#076678", + "sketch_fixed": "#282828", + "sketch_locked": "#79740e", + "dimension": "#3c3836", + "dimension_driven": "#7c6f64", + "sketch_point": "#282828", + "sketch_point_free": "#076678", + "dialog_bg": "#fbf1c7", + "dialog_border": "#d5c4a1", + "chip": "#458588", + "heading_bg": "#d5c4a1", + "subheading_bg": "#ebdbb2", + "section_cap": "#d65d0e", + "profile_fill": "#fabd2f46", + "glyph_bg": "#fdf8e3", + "glyph_edge": "#af3a03", + "glyph_text": "#af3a03", + "overlay": "#fbf1c7eb", + "rubber_band": "#076678", + "app_bar_text": "#fbf1c7", + "app_bar_hover": "#fbf1c71c", + "timeline_item": "#fbf1c7", + "timeline_item_error": "#f2c8a5", + "timeline_marker": "#504945", + "field": "#fdf8e3", + "box_window": "#076678", + "box_crossing": "#79740e", + "sketch_projected": "#8f3f71", + "sketch_lost": "#9d0006", + "sketch_construction": "#af3a03", + "sketch_centerline": "#d65d0e", + "bend_up": "#79740e", + "bend_down": "#af3a03", + "interference": "#cc241d", + "triad": [ + "#cc241d", + "#98971a", + "#458588" + ], + "gizmo": [ + "#cc241d", + "#98971a", + "#458588" + ], + "app_bar_icon": [ + "#fbf1c7", + "#a89984", + "#83a598" + ], + "icons.folder": "#d79921", + "icons.axes": [ + "#cc241d", + "#98971a", + "#458588" + ], + "icons.agent": "#8f3f71", + "icons.warning": "#d79921", + "icons.interference": "#cc241d", + "icons.paint": [ + "#cc241d", + "#458588", + "#d79921" + ] + } +} diff --git a/crates/ui-egui/src/colour_tokens_tests.rs b/crates/ui-egui/src/colour_tokens_tests.rs index f6fc0bb5c..1576eb97d 100644 --- a/crates/ui-egui/src/colour_tokens_tests.rs +++ b/crates/ui-egui/src/colour_tokens_tests.rs @@ -83,6 +83,7 @@ const ALLOWED_LITERALS: &[(&str, usize, &str)] = &[ ("ref_images.rs", 1, "a reference image's opacity tint"), ("sketch_palette.rs", 1, "white text on the accent button"), ("sketch_text.rs", 1, "white text on the selection chip"), + ("theme_files.rs", 1, "a colour read from a theme file, which sets tokens"), ("titlebar.rs", 4, "the window close button's red hover (the system's convention), white hovers and ink"), ("toolbar.rs", 3, "white hover overlays and the version text"), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 510ef9688..36f728675 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -175,6 +175,7 @@ pub mod stand_up; #[cfg(test)] mod sweep_dialog_tests; pub mod theme; +pub mod theme_files; #[cfg(test)] mod thin_extrude_tests; pub mod timeline; diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index ca72509a8..1789fe22d 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -299,8 +299,11 @@ pub struct Prefs { /// Decimals shown for lengths and angles. pub length_decimals: u8, pub angle_decimals: u8, - /// `dark`, `light` or `system` (follow the operating system). + /// `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). pub theme: String, + /// Imported theme files (`theme_files`), kept here so they also work in the browser. + pub custom_themes: Vec, /// Interface language (a registered locale ID). pub language: String, /// Interface scale (1 = 100 %). @@ -430,6 +433,7 @@ impl Default for Prefs { length_decimals: 2, angle_decimals: 1, theme: "dark".into(), + custom_themes: Vec::new(), language: "en".into(), ui_scale: 1.0, ui_font: String::new(), @@ -547,6 +551,81 @@ impl Snapshot { } } +/// The colour theme (#2255): Dark, Light, System, the built-in theme files and the imported +/// ones, with Import…, Export… (the theme on now as a complete file, to start a new one from) +/// and Remove (an imported theme). Like the other preferences, a choice applies at once. +fn theme_row(app: &mut SolveApp, ui: &mut egui::Ui) { + let choices = theme_choices(app); + let current = choices.iter().find(|(id, _)| *id == app.preferences.theme).map_or_else(|| app.preferences.theme.clone(), |(_, name)| name.clone()); + let first_imported = THEMES.len() + crate::theme_files::builtin().len(); + let imported = app.preferences.custom_themes.iter().any(|t| t.id == app.preferences.theme); + let mut chosen: Option = None; + let mut action: Option<&str> = None; + ui.horizontal(|ui| { + let combo = egui::ComboBox::from_id_salt("pref_theme").width(200.0).height(340.0).selected_text(current).show_ui(ui, |ui| { + for (i, (id, name)) in choices.iter().enumerate() { + if i == THEMES.len() || i == first_imported { + ui.separator(); + } + let item = ui.selectable_label(app.preferences.theme == *id, name); + crate::scenario::publish_handle(&format!("prefs:theme:{id}"), item.rect.center()); + if item.clicked() { + chosen = Some(id.clone()); + } + } + }); + crate::scenario::publish_handle("prefs:theme", combo.response.rect.center()); + if ui.button(app.tr_label("Import…")).on_hover_text(app.tr_label("Add a theme file (.json) and use it")).clicked() { + action = Some("import"); + } + if ui + .button(app.tr_label("Export…")) + .on_hover_text(app.tr_label("Save the theme on now as a complete theme file, to start a new one from")) + .clicked() + { + action = Some("export"); + } + if imported && ui.button(app.tr_label("Remove")).on_hover_text(app.tr_label("Remove this imported theme")).clicked() { + action = Some("remove"); + } + }); + if let Some(id) = chosen { + select_theme(app, &id); + } + match action { + Some("import") => app.pick_open_for(&["json"], |app, path| { + let Some(path) = path else { return }; + let r = std::fs::read_to_string(&path).map_err(|e| e.to_string()).and_then(|text| import_theme(app, &serde_json::Value::String(text))); + match r { + Ok(id) => { + let name = crate::theme_files::find(&id, &app.preferences.custom_themes).map(|t| t.name.clone()).unwrap_or(id); + app.set_status(format!("Theme imported: {name}"), false); + } + Err(e) => app.set_status(format!("Theme import: {e}"), true), + } + }), + Some("export") => { + let file = current_theme_file(app); + let name = file.get("name").and_then(serde_json::Value::as_str).unwrap_or("Theme").to_string(); + let text = serde_json::to_string_pretty(&file).unwrap_or_default(); + app.pick_save(&format!("{name}.json"), &["json"], move |app, path| { + if let Some(path) = path + && let Err(e) = std::fs::write(&path, text) + { + app.set_status(format!("Theme export: {e}"), true); + } + }); + } + Some("remove") => { + let id = app.preferences.theme.clone(); + if let Err(e) = remove_theme(app, &id) { + app.set_status(e, true); + } + } + _ => {} + } +} + /// The interface font (#1290): the built-in font first, then the installed families, with a /// search box. The choice applies at once, like the other preferences. fn ui_font_row(app: &mut SolveApp, ui: &mut egui::Ui) { @@ -700,6 +779,15 @@ pub fn apply(app: &mut SolveApp, ctx: &egui::Context) { { app.ui.dark = t == egui::Theme::Dark; } + // A theme file's palette, in place of its base's (dark or light); the visuals follow. + let file = crate::theme_files::find(&app.preferences.theme, &app.preferences.custom_themes); + if let Some(f) = file { + app.ui.dark = f.base.is_dark(); + } + let custom = file.map(|f| crate::theme::Custom { dark: f.base.is_dark(), tokens: crate::theme_files::resolve(f) }); + if crate::theme::set_custom(custom) { + app.styled = false; + } // egui's end-of-frame shortcuts only change its context; the saved preference would // overwrite that change next frame. Consume the desktop shortcuts into the preference. if ctx.options(|o| o.zoom_with_keyboard) && !crate::keymap::capturing(app) { @@ -1080,16 +1168,7 @@ fn page(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) { ); ui.end_row(); ui.label(app.tr("ui.theme")); - ui.horizontal(|ui| { - for (id, label) in THEMES { - if ui.radio(app.preferences.theme == id, app.tr_label(label)).clicked() { - app.preferences.theme = id.to_string(); - if id != "system" { - app.ui.dark = id == "dark"; - } - } - } - }); + theme_row(app, ui); ui.end_row(); ui.label(app.tr("ui.ui_scale")); let scale = ui.add( @@ -1459,8 +1538,10 @@ fn colour_vision_sample(ui: &mut egui::Ui, t: &Tokens) { /// The control channel's `ui.prefs`: `open` (a page name) opens the dialog there, `button` /// presses OK, Cancel, Apply or Restore Defaults, `stand_up: true` answers the stand-up offer -/// (`false` leaves the file as it is, like "Leave it"); any other keys set preferences. Returns -/// them all, the open page and the offer. +/// (`false` leaves the file as it is, like "Leave it"), `theme_import` (a theme file's JSON or +/// text) adds a theme and turns it on, `theme_remove` (an id) removes an imported one and +/// `theme_export: true` returns the theme on now as `theme_file`; any other keys set +/// preferences. Returns them all, the open page, the offer and the theme ids. pub fn control(app: &mut SolveApp, p: &serde_json::Value) -> Result { let mut rest = p.as_object().cloned().unwrap_or_default(); if let Some(page) = rest.remove("open") { @@ -1476,6 +1557,14 @@ pub fn control(app: &mut SolveApp, p: &serde_json::Value) -> Result crate::stand_up::leave(app), None => {} } + let imported = match rest.remove("theme_import") { + Some(v) => Some(import_theme(app, &v)?), + None => None, + }; + if let Some(id) = rest.remove("theme_remove") { + remove_theme(app, id.as_str().unwrap_or_default())?; + } + let export = rest.remove("theme_export").and_then(|v| v.as_bool()).unwrap_or(false); let button = rest.remove("button"); let mut out = set(app, &serde_json::Value::Object(rest))?; match button.as_ref().and_then(|b| b.as_str()) { @@ -1493,10 +1582,69 @@ pub fn control(app: &mut SolveApp, p: &serde_json::Value) -> Result>())); + if let Some(id) = imported { + o.insert("theme_imported".into(), json!(id)); + } + if export { + o.insert("theme_file".into(), current_theme_file(app)); + } } Ok(out) } +/// Every theme the Theme list offers, as (id, name): the modes, the built-in theme files, then +/// the imported ones. +fn theme_choices(app: &SolveApp) -> Vec<(String, String)> { + let modes = THEMES.iter().map(|(id, label)| ((*id).to_string(), crate::i18n::tr_label(label).to_string())); + let files = crate::theme_files::builtin().iter().chain(&app.preferences.custom_themes).map(|t| (t.id.clone(), t.name.clone())); + modes.chain(files).collect() +} + +/// Turn a theme on (a mode or a theme file's id); dark follows it. +fn select_theme(app: &mut SolveApp, id: &str) { + app.preferences.theme = id.to_string(); + match crate::theme_files::find(id, &app.preferences.custom_themes) { + Some(f) => app.ui.dark = f.base.is_dark(), + None if id != "system" => app.ui.dark = id == "dark", + None => {} + } +} + +/// Import a theme file (its text, or its JSON) into the preferences and turn it on; returns +/// the id it is kept under. +pub fn import_theme(app: &mut SolveApp, v: &serde_json::Value) -> Result { + let theme = match v { + serde_json::Value::String(text) => crate::theme_files::parse(text)?, + other => crate::theme_files::from_value(other)?, + }; + let id = crate::theme_files::add(&mut app.preferences.custom_themes, theme)?; + select_theme(app, &id); + Ok(id) +} + +/// Remove an imported theme; when it is on, its base (dark or light) takes over. +fn remove_theme(app: &mut SolveApp, id: &str) -> Result<(), String> { + let Some(i) = app.preferences.custom_themes.iter().position(|t| t.id == id) else { + return Err(format!("no imported theme `{id}`")); + }; + let gone = app.preferences.custom_themes.remove(i); + if app.preferences.theme == id { + select_theme(app, if gone.base.is_dark() { "dark" } else { "light" }); + } + Ok(()) +} + +/// The theme on now as a complete theme file, a starting point for a new one. +fn current_theme_file(app: &SolveApp) -> serde_json::Value { + use crate::theme_files::{Base, export, find, resolve}; + match find(&app.preferences.theme, &app.preferences.custom_themes) { + Some(f) => export(&f.name, f.base, &resolve(f)), + None if app.ui.dark => export("Dark", Base::Dark, &crate::theme::Tokens::dark()), + None => export("Light", Base::Light, &crate::theme::Tokens::light()), + } +} + /// Fold a setting an older release kept in its own field into the one this version reads. /// `orbit_cursor` (`true` = the point under the cursor) became `orbit_around`. /// The cap's physical axes, in the order of `Prefs::space_mouse_reverse`. @@ -1559,8 +1707,12 @@ pub fn set(app: &mut SolveApp, p: &serde_json::Value) -> Result crate::theme_files::MAX_CUSTOM || new.custom_themes.iter().any(|t| t.colors.len() > crate::theme_files::MAX_COLORS) { + return Err(format!("at most {} imported themes of {} colours each", crate::theme_files::MAX_CUSTOM, crate::theme_files::MAX_COLORS)); } if !crate::i18n::is_supported(&new.language) { return Err(format!("`language` must be one of: {}", crate::i18n::LOCALES.iter().map(|locale| locale.id).collect::>().join(", "))); @@ -1581,7 +1733,7 @@ pub fn set(app: &mut SolveApp, p: &serde_json::Value) -> Result = const { Cell::new(ColorVision::Off) }; + /// 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) }; +} + +/// A theme file's palette and whether it is dark. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Custom { + pub dark: bool, + pub tokens: Tokens, +} + +/// 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) } /// Is the dark theme on? @@ -306,9 +322,11 @@ impl Tokens { Tokens::themed(is_dark(), vision()) } - /// The tokens of a theme and colour vision mode. + /// The tokens of a theme and colour vision mode: a theme file's palette when one is on for + /// that base ([`set_custom`]), else the built-in one; the colour vision mode on top. pub fn themed(dark: bool, mode: ColorVision) -> Tokens { - (if dark { Tokens::dark() } else { Tokens::light() }).with_vision(dark, mode) + let custom = CUSTOM.get().filter(|c| c.dark == dark).map(|c| c.tokens); + custom.unwrap_or(if dark { Tokens::dark() } else { Tokens::light() }).with_vision(dark, mode) } /// These tokens with a colour vision mode's values on top (the tables in `palettes.rs`); Off diff --git a/crates/ui-egui/src/theme_files.rs b/crates/ui-egui/src/theme_files.rs new file mode 100644 index 000000000..d3faad948 --- /dev/null +++ b/crates/ui-egui/src/theme_files.rs @@ -0,0 +1,377 @@ +//! Colour themes as files (#2255): a `solidcraft-theme/1` JSON file names a base palette (the +//! built-in Dark or Light) and sets any of its [`Tokens`] by name, so a theme can be a handful of +//! lines. Built-in themes (the Gruvbox family) are such files under `assets/styles/ui/themes/`; +//! imported ones are kept in the preferences (`Prefs::custom_themes`), so they also work in the +//! browser. Colour vision modes still apply on top of a theme (`Tokens::with_vision`). +//! +//! ```json +//! {"format": "solidcraft-theme/1", "name": "Mine", "base": "dark", +//! "colors": {"panel": "#282828", "triad": ["#fb4934", "#b8bb26", "#83a598"]}} +//! ``` + +use std::collections::BTreeMap; +use std::sync::OnceLock; + +use egui::Color32; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use crate::theme::{IconColors, Tokens}; + +/// The `format` tag of a theme file. +pub const FORMAT: &str = "solidcraft-theme/1"; +/// Hostile-input caps: file size, colours per file, name length, imported themes kept. +const MAX_BYTES: usize = 256 * 1024; +pub const MAX_COLORS: usize = 512; +const MAX_NAME: usize = 80; +pub const MAX_CUSTOM: usize = 64; + +/// The palette a theme starts from. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Base { + #[default] + Dark, + Light, +} + +impl Base { + pub fn is_dark(self) -> bool { + self == Base::Dark + } +} + +/// A theme: its id (the `theme` preference's value), name, base and colour overrides, each a +/// `#rrggbb` / `#rrggbbaa` string or a list of them, keyed by [`keys`]. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct ThemeFile { + pub id: String, + pub name: String, + pub base: Base, + pub colors: BTreeMap, +} + +/// The settable colours: a key, and where it lives in [`Tokens`]. `one` keys take a colour, +/// `many` keys a list of exactly as many colours as the token has; `icons.*` are the colours +/// icons draw of their own. The destructuring below fails to build when a token is added +/// without a key here, so every colour stays themeable. +macro_rules! theme_keys { + (one: [$($one:ident),* $(,)?], many: [$($many:ident),* $(,)?], + icons_one: [$($ione:ident),* $(,)?], icons_many: [$($imany:ident),* $(,)?] $(,)?) => { + /// Every key a theme file may set, in the order an export writes them. + pub fn keys() -> Vec<&'static str> { + let mut k = vec![$(stringify!($one),)* $(stringify!($many),)*]; + k.extend([$(concat!("icons.", stringify!($ione)),)* $(concat!("icons.", stringify!($imany)),)*]); + k + } + + fn slot<'a>(t: &'a mut Tokens, key: &str) -> Option<&'a mut [Color32]> { + match key { + $(stringify!($one) => Some(std::slice::from_mut(&mut t.$one)),)* + $(stringify!($many) => Some(&mut t.$many[..]),)* + $(concat!("icons.", stringify!($ione)) => Some(std::slice::from_mut(&mut t.icons.$ione)),)* + $(concat!("icons.", stringify!($imany)) => Some(&mut t.icons.$imany[..]),)* + _ => None, + } + } + + #[allow(dead_code)] + fn every_colour_has_a_key(t: &Tokens) { + // Not colours: the hover lift is a grey step, the analysis colours belong to shaders. + let Tokens { $($one: _,)* $($many: _,)* hover_face_lift: _, analysis: _, icons: _ } = t; + let IconColors { $($ione: _,)* $($imany: _,)* } = &t.icons; + } + }; +} + +theme_keys! { + one: [ + app_bar, toolbar, panel, panel_header, border, text, text_dim, accent, accent_soft, sketch_accent, error, warning, + icon, icon_fill, timeline, hover, sel_face, sel_edge, sel_edge_rim, hover_edge, hover_edge_halo, sel_profile, + sel_profile_edge, hover_profile, hover_profile_edge, sel_vertex, origin_plane, origin_plane_edge, origin_plane_hover, + origin_point, axis_x, axis_y, axis_z, construction_plane, construction_geom, body, body_edge, manipulator, + preview_add, preview_new, preview_sketch, preview_cut, cube_face, cube_border, cube_text, cube_hover, viewport_top, + viewport_bottom, grid, grid_major, body_selected, sketch, sketch_fixed, sketch_locked, dimension, dimension_driven, + sketch_point, sketch_point_free, dialog_bg, dialog_border, chip, heading_bg, subheading_bg, section_cap, + profile_fill, glyph_bg, glyph_edge, glyph_text, overlay, rubber_band, app_bar_text, app_bar_hover, timeline_item, + timeline_item_error, timeline_marker, field, box_window, box_crossing, sketch_projected, sketch_lost, + sketch_construction, sketch_centerline, bend_up, bend_down, interference, + ], + many: [triad, gizmo, continuity, app_bar_icon, logo], + icons_one: [ + sheet, sheet_2, sheet_light, sheet_line, highlight, glint, folder, plane, fold, stripe, sky, floor, interference, + warning, agent, marker_halo, + ], + icons_many: [paint, axes, access, draft, curvature], +} + +/// `#rrggbb` or `#rrggbbaa` (alpha not premultiplied). +fn parse_color(s: &str) -> Option { + let hex = s.trim().strip_prefix('#')?; + if !(hex.len() == 6 || hex.len() == 8) || !hex.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } + let byte = |i: usize| hex.get(i..i + 2).and_then(|h| u8::from_str_radix(h, 16).ok()); + let a = if hex.len() == 8 { byte(6)? } else { 255 }; + Some(Color32::from_rgba_unmultiplied(byte(0)?, byte(2)?, byte(4)?, a)) +} + +fn format_color(c: Color32) -> String { + let [r, g, b, a] = c.to_srgba_unmultiplied(); + if a == 255 { format!("#{r:02x}{g:02x}{b:02x}") } else { format!("#{r:02x}{g:02x}{b:02x}{a:02x}") } +} + +/// The colours a value gives for a slot of `len` colours, or why not. +fn colors_of(v: &Value, len: usize) -> Result, String> { + let list: Vec<&Value> = match v { + Value::String(_) if len == 1 => vec![v], + Value::Array(a) if a.len() == len => a.iter().collect(), + _ if len == 1 => return Err("must be a colour such as \"#282828\"".into()), + _ => return Err(format!("must be a list of {len} colours")), + }; + list.into_iter().map(|c| c.as_str().and_then(parse_color).ok_or_else(|| format!("`{c}` is not a colour such as \"#282828\""))).collect() +} + +/// A theme file's text, checked: the format tag, a name, a base and only known keys with valid +/// colours. Nothing is taken from a file with any error; the message names every bad key. +pub fn parse(text: &str) -> Result { + if text.len() > MAX_BYTES { + return Err(format!("a theme file is at most {} KiB", MAX_BYTES / 1024)); + } + let v: Value = serde_json::from_str(text).map_err(|e| format!("not a theme file: {e}"))?; + from_value(&v) +} + +/// [`parse`] for JSON already read (`ui.prefs` `theme_import`). +pub fn from_value(v: &Value) -> Result { + if v.get("format").and_then(Value::as_str) != Some(FORMAT) { + return Err(format!("not a theme file: `format` must be \"{FORMAT}\"")); + } + let name = v.get("name").and_then(Value::as_str).map(str::trim).unwrap_or_default(); + if name.is_empty() || name.chars().count() > MAX_NAME { + return Err(format!("`name` must be 1 to {MAX_NAME} characters")); + } + let base = match v.get("base").and_then(Value::as_str) { + Some("dark") => Base::Dark, + Some("light") => Base::Light, + _ => return Err("`base` must be \"dark\" or \"light\"".into()), + }; + let src = match v.get("colors") { + None => serde_json::Map::new(), + Some(Value::Object(o)) => o.clone(), + Some(_) => return Err("`colors` must be an object of colour names and values".into()), + }; + if src.len() > MAX_COLORS { + return Err(format!("`colors` has more than {MAX_COLORS} entries")); + } + let mut probe = Tokens::light(); + let mut bad = Vec::new(); + for (k, c) in &src { + match slot(&mut probe, k) { + None => bad.push(format!("`{k}` is not a theme colour")), + Some(s) => { + if let Err(e) = colors_of(c, s.len()) { + bad.push(format!("`{k}` {e}")); + } + } + } + } + if !bad.is_empty() { + bad.truncate(8); + return Err(bad.join("; ")); + } + Ok(ThemeFile { id: slug(name), name: name.to_string(), base, colors: src.into_iter().collect() }) +} + +/// An id from a name: lower-case letters, digits and dashes. +fn slug(name: &str) -> String { + let mut s = String::new(); + for c in name.chars().flat_map(char::to_lowercase) { + if c.is_ascii_alphanumeric() { + s.push(c); + } else if !s.ends_with('-') && !s.is_empty() { + s.push('-'); + } + } + let s = s.trim_end_matches('-').to_string(); + if s.is_empty() { "theme".into() } else { s } +} + +/// The theme's palette: its base with its colours on top. A colour the saved preferences hold +/// that this version can't read (a hand edit) is skipped, never an error. +pub fn resolve(theme: &ThemeFile) -> Tokens { + let mut t = if theme.base.is_dark() { Tokens::dark() } else { Tokens::light() }; + for (k, v) in &theme.colors { + if let Some(s) = slot(&mut t, k) + && let Ok(c) = colors_of(v, s.len()) + { + s.copy_from_slice(&c); + } + } + t +} + +/// A complete theme file of a palette: every key, so it is a starting point for a new theme. +pub fn export(name: &str, base: Base, t: &Tokens) -> Value { + let mut t = *t; + let mut colors = serde_json::Map::new(); + for k in keys() { + if let Some(s) = slot(&mut t, k) { + let v = if let [c] = s { json!(format_color(*c)) } else { json!(s.iter().map(|c| format_color(*c)).collect::>()) }; + colors.insert(k.to_string(), v); + } + } + json!({"format": FORMAT, "name": name, "base": base, "colors": colors}) +} + +/// The theme files that come with SolidCraft (original files; Gruvbox's palette, MIT). +const BUILTIN: [(&str, &str); 6] = [ + ("gruvbox-dark", include_str!("../../../assets/styles/ui/themes/gruvbox-dark.json")), + ("gruvbox-dark-hard", include_str!("../../../assets/styles/ui/themes/gruvbox-dark-hard.json")), + ("gruvbox-dark-soft", include_str!("../../../assets/styles/ui/themes/gruvbox-dark-soft.json")), + ("gruvbox-light", include_str!("../../../assets/styles/ui/themes/gruvbox-light.json")), + ("gruvbox-light-hard", include_str!("../../../assets/styles/ui/themes/gruvbox-light-hard.json")), + ("gruvbox-light-soft", include_str!("../../../assets/styles/ui/themes/gruvbox-light-soft.json")), +]; + +/// The built-in themes, read once (one that fails to read is left out; a test reads them all). +pub fn builtin() -> &'static [ThemeFile] { + static THEMES: OnceLock> = OnceLock::new(); + THEMES.get_or_init(|| { + BUILTIN + .iter() + .filter_map(|(id, text)| match parse(text) { + Ok(t) => Some(ThemeFile { id: (*id).to_string(), ..t }), + Err(e) => { + log::error!("built-in theme {id}: {e}"); + None + } + }) + .collect() + }) +} + +/// The theme a `theme` preference names: built in, or imported. `None` for dark, light, system +/// or an unknown id. +pub fn find<'a>(id: &str, custom: &'a [ThemeFile]) -> Option<&'a ThemeFile> { + builtin().iter().find(|t| t.id == id).or_else(|| custom.iter().find(|t| t.id == id)) +} + +/// Add an imported theme to `custom`, replacing one with the same id (importing a file again +/// updates it). Its id never takes a built-in one's or the modes' (dark, light, system). +/// Returns the id it is kept under. +pub fn add(custom: &mut Vec, mut theme: ThemeFile) -> Result { + if ["dark", "light", "system"].contains(&theme.id.as_str()) || builtin().iter().any(|t| t.id == theme.id) { + theme.id = format!("custom-{}", theme.id); + } + let id = theme.id.clone(); + match custom.iter().position(|t| t.id == id) { + Some(i) => { + if let Some(old) = custom.get_mut(i) { + *old = theme; + } + } + None if custom.len() >= MAX_CUSTOM => return Err(format!("at most {MAX_CUSTOM} imported themes; remove one first")), + None => custom.push(theme), + } + Ok(id) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn built_in_themes_read_and_differ_from_their_base() { + assert_eq!(builtin().len(), BUILTIN.len(), "every built-in theme file reads"); + for t in builtin() { + let base = if t.base.is_dark() { Tokens::dark() } else { Tokens::light() }; + assert_ne!(resolve(t), base, "{}", t.id); + assert_eq!(t.base.is_dark(), t.id.contains("dark"), "{}", t.id); + } + } + + /// Title and section bands stand out from a dialog in every built-in theme, as in Dark and + /// Light (`heading_bands_are_darker_than_the_dialog_in_order`). + #[test] + fn built_in_themes_keep_heading_bands_in_order() { + let luma = |c: Color32| u32::from(c.r()) * 3 + u32::from(c.g()) * 6 + u32::from(c.b()); + for t in builtin().iter().map(resolve) { + assert!(luma(t.heading_bg) < luma(t.subheading_bg) && luma(t.subheading_bg) < luma(t.dialog_bg), "{t:?}"); + } + } + + #[test] + fn a_short_file_sets_only_its_colours() { + let t = parse(r##"{"format":"solidcraft-theme/1","name":"My Theme!","base":"light","colors":{"panel":"#102030","triad":["#ff0000","#00ff00","#0000ff80"]}}"##).unwrap(); + assert_eq!((t.id.as_str(), t.name.as_str(), t.base), ("my-theme", "My Theme!", Base::Light)); + let p = resolve(&t); + assert_eq!(p.panel, Color32::from_rgb(0x10, 0x20, 0x30)); + assert_eq!(p.triad[2], Color32::from_rgba_unmultiplied(0, 0, 255, 0x80)); + assert_eq!(p.text, Tokens::light().text); + } + + #[test] + fn bad_files_are_refused_naming_every_bad_key() { + let ok = r#""format":"solidcraft-theme/1","name":"x","base":"dark""#; + for (text, want) in [ + ("[]".to_string(), "format"), + (r#"{"format":"solidcraft-theme/2","name":"x","base":"dark"}"#.into(), "format"), + (r#"{"format":"solidcraft-theme/1","name":" ","base":"dark"}"#.into(), "name"), + (r#"{"format":"solidcraft-theme/1","name":"x","base":"blue"}"#.into(), "base"), + (format!(r#"{{{ok},"colors":[]}}"#), "colors"), + (format!(r##"{{{ok},"colors":{{"panle":"#000000","text":"red","triad":["#000000"],"icons.axes":"#000000"}}}}"##), "panle"), + ("x".repeat(MAX_BYTES + 1), "KiB"), + ] { + let e = parse(&text).unwrap_err(); + assert!(e.contains(want), "{text:.80}: {e}"); + } + let e = parse(&format!(r##"{{{ok},"colors":{{"panle":"#000000","text":"red","triad":["#000000"]}}}}"##)).unwrap_err(); + for k in ["panle", "text", "triad"] { + assert!(e.contains(k), "{e}"); + } + for c in ["#12345", "#1234567", "#gggggg", "282828", "#2828281"] { + assert!(parse_color(c).is_none(), "{c}"); + } + } + + /// An export is a complete theme: importing it gives the same palette (to a unit of rounding + /// for translucent colours), on either base. + #[test] + fn export_then_import_gives_the_palette_back() { + for (base, palette) in [(Base::Dark, Tokens::dark()), (Base::Light, Tokens::light())] { + let file = export("Round trip", base, &palette); + let t = from_value(&file).unwrap(); + assert_eq!(t.colors.len(), keys().len()); + let other = ThemeFile { base: if base.is_dark() { Base::Light } else { Base::Dark }, ..t.clone() }; + for back in [resolve(&t), resolve(&other)] { + let (mut a, mut b) = (palette, back); + for k in keys() { + let (Some(x), Some(y)) = (slot(&mut a, k).map(|s| s.to_vec()), slot(&mut b, k).map(|s| s.to_vec())) else { continue }; + for (x, y) in x.iter().zip(&y) { + let close = x.to_array().iter().zip(y.to_array()).all(|(p, q)| p.abs_diff(q) <= 1); + assert!(close, "{k}: {x:?} vs {y:?}"); + } + } + } + } + } + + #[test] + fn imported_ids_never_take_a_built_in_or_mode_id_and_replace_their_own() { + let mut custom = Vec::new(); + let mk = |name: &str| ThemeFile { id: slug(name), name: name.into(), ..Default::default() }; + assert_eq!(add(&mut custom, mk("Gruvbox Dark")).unwrap(), "custom-gruvbox-dark"); + assert_eq!(add(&mut custom, mk("Dark")).unwrap(), "custom-dark"); + assert_eq!(add(&mut custom, mk("Nord")).unwrap(), "nord"); + let again = ThemeFile { base: Base::Light, ..mk("Nord") }; + assert_eq!(add(&mut custom, again).unwrap(), "nord"); + assert_eq!(custom.len(), 3); + assert_eq!(custom.iter().find(|t| t.id == "nord").map(|t| t.base), Some(Base::Light)); + for i in custom.len()..MAX_CUSTOM { + add(&mut custom, mk(&format!("t{i}"))).unwrap(); + } + assert!(add(&mut custom, mk("one too many")).is_err()); + assert!(find("gruvbox-dark", &custom).is_some() && find("nord", &custom).is_some() && find("dark", &custom).is_none()); + } +} diff --git a/crates/ui-egui/tests/scenarios/prefs_theme_files.json b/crates/ui-egui/tests/scenarios/prefs_theme_files.json new file mode 100644 index 000000000..4b105e097 --- /dev/null +++ b/crates/ui-egui/tests/scenarios/prefs_theme_files.json @@ -0,0 +1,13 @@ +[ + {"note": "#2255: the Theme list offers the built-in theme files (Gruvbox) after Dark, Light and System; picking one applies at once, Cancel puts the theme back."}, + {"click": {"handle": "titlebar:preferences"}}, + {"expect": {"prefs": {"dialog": "General", "theme": "dark", "dark": true}}}, + {"click": {"handle": "prefs:theme"}}, + {"click": {"handle": "prefs:theme:gruvbox-light-soft"}}, + {"expect": {"prefs": {"theme": "gruvbox-light-soft", "dark": false}, "shown_handles": ["prefs:theme"], "hidden_handles": ["prefs:theme:dark"]}}, + {"click": {"handle": "prefs:theme"}}, + {"click": {"handle": "prefs:theme:gruvbox-dark"}}, + {"expect": {"prefs": {"theme": "gruvbox-dark", "dark": true}}}, + {"widget": "Cancel"}, + {"expect": {"prefs": {"dialog": null, "theme": "dark", "dark": true}}} +] diff --git a/crates/ui-egui/tests/scenarios/s45_preferences.json b/crates/ui-egui/tests/scenarios/s45_preferences.json index 133cf7efe..1c5ea2749 100644 --- a/crates/ui-egui/tests/scenarios/s45_preferences.json +++ b/crates/ui-egui/tests/scenarios/s45_preferences.json @@ -2,7 +2,8 @@ {"note": "#36: one Preferences dialog, from the gear at the top right (and Ctrl+,). Changes apply at once; Cancel puts them back, OK keeps them."}, {"click": {"handle": "titlebar:preferences"}}, {"expect": {"shown": "Restore Defaults", "prefs": {"dialog": "General", "theme": "dark", "dark": true}}}, - {"widget": "Light"}, + {"click": {"handle": "prefs:theme"}}, + {"click": {"handle": "prefs:theme:light"}}, {"expect": {"prefs": {"theme": "light", "dark": false}}}, {"widget": "Cancel"}, {"expect": {"not_shown": "Restore Defaults", "prefs": {"dialog": null, "theme": "dark", "dark": true}}}, diff --git a/docs/book/src/guide/ui-tour.md b/docs/book/src/guide/ui-tour.md index 423b9ed07..d2aa5f2a6 100644 --- a/docs/book/src/guide/ui-tour.md +++ b/docs/book/src/guide/ui-tour.md @@ -66,6 +66,44 @@ Tritan. In a mode, the faces Draft and Accessibility Analysis mark as failing ar Help › Keyboard Shortcuts lists every key, and File › Keyboard Shortcuts changes them. +### Colour themes + +General › **Theme** lists Dark, Light and System (follows the operating system), the built-in +Gruvbox themes (dark and light, each in hard, normal and soft contrast) and any themes you have +imported. A choice applies at once. + +A theme is a small JSON file that starts from the Dark or Light palette and changes any of its +colours by name: + +```json +{ + "format": "solidcraft-theme/1", + "name": "My Theme", + "base": "dark", + "colors": { + "panel": "#282828", + "text": "#ebdbb2", + "accent": "#83a598", + "viewport_top": "#32302f", + "viewport_bottom": "#32302f", + "triad": ["#fb4934", "#b8bb26", "#83a598"] + } +} +``` + +Colours are `#rrggbb`, or `#rrggbbaa` for translucent ones. A few colours, such as the view +triad's X, Y and Z, take a list. Any colour the file leaves out keeps the base palette's value. + +- **Import…** adds a theme file and turns it on. Importing a file with the same name again updates + that theme. A file with an unknown colour name or a malformed colour is refused, and the message + names every problem. +- **Export…** saves the theme on now as a complete file listing every colour. It is a good starting + point for your own theme. +- **Remove** deletes the selected imported theme. + +Imported themes are kept with your preferences, so they work in the browser app too. Colour +vision modes still apply on top of any theme. + Navigation › **Smooth wheel zoom** is on by default. Turn it off to apply each wheel or trackpad event immediately, with no smoothing tail. It is independent of **Animate view changes**, which controls axis views, Look At, Home and Fit. Re-enabling smoothing during diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 9e8f311fa..855f752b0 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -152,7 +152,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; the view redraws every frame while it is on), `length_decimals`, `angle_decimals`, `theme` (`dark`, `light`, `system`), `language` (`en`, `ja`, `de`, `fr`, `ko`, `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`, `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, Navigation, Keyboard Shortcuts, Design, Graphics, Sketch, Selection, AI) 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; the view redraws every frame while it is on), `length_decimals`, `angle_decimals`, `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`, `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`, `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, Navigation, Keyboard Shortcuts, Design, Graphics, Sketch, Selection, AI) 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.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. `"animate": false` on a call skips it |