use std::collections::HashSet;
use gtk::gdk;
use gtk::glib;
use gtk::prelude::*;
use serde::{Deserialize, Serialize};
use thiserror::Error;
pub const SCHEMA_VERSION: u32 = 1;
pub const SEMANTIC_COLOR_ROLES: [&str; 18] = [
"window_background",
"window_text",
"surface_background",
"surface_text",
"input_background",
"input_text",
"selection_background",
"selection_text",
"accent",
"accent_text",
"border",
"disabled_text",
"tooltip_background",
"tooltip_text",
"link",
"error",
"warning",
"success",
];
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
pub struct Rgba {
pub red: f32,
pub green: f32,
pub blue: f32,
pub alpha: f32,
}
impl From<gdk::RGBA> for Rgba {
fn from(value: gdk::RGBA) -> Self {
Self {
red: value.red(),
green: value.green(),
blue: value.blue(),
alpha: value.alpha(),
}
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct ThemeIdentity {
pub theme_name: String,
pub toolkit_version: String,
pub display_backend: Option<String>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct EnumSetting {
pub value: i32,
pub name: String,
pub nick: String,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct GtkSettingsSnapshot {
pub font_name: Option<String>,
pub icon_theme_name: Option<String>,
pub cursor_theme_name: Option<String>,
pub cursor_theme_size: Option<i32>,
pub enable_animations: Option<bool>,
pub overlay_scrolling: Option<bool>,
pub primary_button_warps_slider: Option<bool>,
pub double_click_time_ms: Option<i32>,
pub cursor_blink_time_ms: Option<i32>,
pub prefer_dark: Option<bool>,
#[serde(default)]
pub interface_color_scheme: Option<EnumSetting>,
#[serde(default)]
pub interface_contrast: Option<EnumSetting>,
#[serde(default)]
pub interface_reduced_motion: Option<EnumSetting>,
#[serde(default)]
pub interface_accent_color: Option<Rgba>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct NamedColor {
pub name: String,
pub value: Rgba,
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct SemanticPalette {
pub window_background: Option<Rgba>,
pub window_text: Option<Rgba>,
pub surface_background: Option<Rgba>,
pub surface_text: Option<Rgba>,
pub input_background: Option<Rgba>,
pub input_text: Option<Rgba>,
pub selection_background: Option<Rgba>,
pub selection_text: Option<Rgba>,
pub accent: Option<Rgba>,
pub accent_text: Option<Rgba>,
pub border: Option<Rgba>,
pub disabled_text: Option<Rgba>,
pub tooltip_background: Option<Rgba>,
pub tooltip_text: Option<Rgba>,
pub link: Option<Rgba>,
pub error: Option<Rgba>,
pub warning: Option<Rgba>,
pub success: Option<Rgba>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct WidgetState {
pub state: String,
pub foreground: Rgba,
}
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
pub struct WidgetMetrics {
pub minimum_width: i32,
pub natural_width: i32,
pub minimum_height: i32,
pub natural_height: i32,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct WidgetSnapshot {
pub control: String,
pub css_name: String,
pub metrics: WidgetMetrics,
pub states: Vec<WidgetState>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct ThemeSnapshot {
pub schema_version: u32,
pub backend: String,
pub identity: ThemeIdentity,
pub settings: GtkSettingsSnapshot,
pub named_colors: Vec<NamedColor>,
pub semantic_palette: SemanticPalette,
pub widgets: Vec<WidgetSnapshot>,
pub diagnostics: Vec<String>,
}
#[derive(Debug, Error, PartialEq, Eq)]
#[error("invalid GTK theme snapshot: {reason}")]
pub struct SnapshotValidationError {
reason: String,
}
impl SnapshotValidationError {
pub fn reason(&self) -> &str {
&self.reason
}
}
fn validation_error(reason: impl Into<String>) -> SnapshotValidationError {
SnapshotValidationError {
reason: reason.into(),
}
}
fn validate_rgba(path: &str, color: Rgba) -> Result<(), SnapshotValidationError> {
for (channel, value) in [
("red", color.red),
("green", color.green),
("blue", color.blue),
("alpha", color.alpha),
] {
if !value.is_finite() || !(0.0..=1.0).contains(&value) {
return Err(validation_error(format!(
"{path}.{channel} must be finite and in 0..=1, got {value}"
)));
}
}
Ok(())
}
impl ThemeSnapshot {
pub fn validate(&self) -> Result<(), SnapshotValidationError> {
if self.schema_version != SCHEMA_VERSION {
return Err(validation_error(format!(
"unsupported schema version {}; expected {SCHEMA_VERSION}",
self.schema_version
)));
}
if self.backend != "gtk4" {
return Err(validation_error(format!(
"backend must be gtk4, got {:?}",
self.backend
)));
}
if self.identity.theme_name.trim().is_empty()
|| self.identity.toolkit_version.trim().is_empty()
{
return Err(validation_error(
"theme name and toolkit version must not be empty",
));
}
let mut color_names = HashSet::new();
for color in &self.named_colors {
if color.name.is_empty() || !color_names.insert(color.name.as_str()) {
return Err(validation_error(format!(
"symbolic color name {:?} is empty or duplicated",
color.name
)));
}
validate_rgba(&format!("named_colors.{}", color.name), color.value)?;
}
for (name, color) in [
("window_background", self.semantic_palette.window_background),
("window_text", self.semantic_palette.window_text),
(
"surface_background",
self.semantic_palette.surface_background,
),
("surface_text", self.semantic_palette.surface_text),
("input_background", self.semantic_palette.input_background),
("input_text", self.semantic_palette.input_text),
(
"selection_background",
self.semantic_palette.selection_background,
),
("selection_text", self.semantic_palette.selection_text),
("accent", self.semantic_palette.accent),
("accent_text", self.semantic_palette.accent_text),
("border", self.semantic_palette.border),
("disabled_text", self.semantic_palette.disabled_text),
(
"tooltip_background",
self.semantic_palette.tooltip_background,
),
("tooltip_text", self.semantic_palette.tooltip_text),
("link", self.semantic_palette.link),
("error", self.semantic_palette.error),
("warning", self.semantic_palette.warning),
("success", self.semantic_palette.success),
] {
if let Some(color) = color {
validate_rgba(&format!("semantic_palette.{name}"), color)?;
}
}
if let Some(color) = self.settings.interface_accent_color {
validate_rgba("settings.interface_accent_color", color)?;
}
let mut controls = HashSet::new();
for widget in &self.widgets {
if widget.control.is_empty() || !controls.insert(widget.control.as_str()) {
return Err(validation_error(format!(
"widget name {:?} is empty or duplicated",
widget.control
)));
}
if widget.css_name.is_empty() {
return Err(validation_error(format!(
"widget {} has an empty CSS node name",
widget.control
)));
}
let metrics = widget.metrics;
if metrics.minimum_width < 0
|| metrics.natural_width < metrics.minimum_width
|| metrics.minimum_height < 0
|| metrics.natural_height < metrics.minimum_height
{
return Err(validation_error(format!(
"widget {} has inconsistent preferred dimensions",
widget.control
)));
}
let mut states = HashSet::new();
for state in &widget.states {
if state.state.is_empty() || !states.insert(state.state.as_str()) {
return Err(validation_error(format!(
"widget {} has an empty or duplicated state {:?}",
widget.control, state.state
)));
}
validate_rgba(
&format!("widgets.{}.{}", widget.control, state.state),
state.foreground,
)?;
}
}
for required in [
"window",
"button",
"input",
"checkbox",
"switch",
"progress-bar",
"slider",
] {
if !controls.contains(required) {
return Err(validation_error(format!(
"missing representative widget {required}"
)));
}
}
Ok(())
}
}
#[derive(Clone, Debug)]
pub struct NativeThemeBridge {
pub name: String,
pub mode: native_theme::theme::ColorMode,
pub resolved: native_theme::theme::ResolvedTheme,
pub reduce_transparency: bool,
pub reduce_motion: bool,
pub high_contrast: bool,
}
impl NativeThemeBridge {
#[cfg(feature = "gpui")]
#[must_use = "this returns the GPUI theme; it does not install it globally"]
pub fn to_gpui_theme(&self) -> gpui_component::theme::Theme {
native_theme_gpui::to_theme(
&self.resolved,
&self.name,
self.mode.is_dark(),
self.reduce_transparency,
)
}
}
#[derive(Debug, Error)]
pub enum NativeThemeBridgeError {
#[error(transparent)]
InvalidSnapshot(#[from] SnapshotValidationError),
#[error("GTK snapshot is missing required semantic color {0}")]
MissingColor(&'static str),
#[error("native-theme resolution failed: {0}")]
Resolution(#[from] native_theme::error::Error),
}
fn to_native_color(color: Rgba) -> native_theme::color::Rgba {
native_theme::color::Rgba::from_f32(color.red, color.green, color.blue, color.alpha)
}
fn native_font(name: &str, color: Rgba) -> Option<native_theme::theme::FontSpec> {
use gtk::glib::translate::IntoGlib;
use native_theme::theme::{FontSize, FontSpec, FontStyle, intern_font_family};
let description = gtk::pango::FontDescription::from_string(name);
let family = description.family()?;
let size = description.size();
Some(FontSpec {
family: Some(intern_font_family(&family)),
size: (size > 0).then(|| {
let value = size as f32 / gtk::pango::SCALE as f32;
if description.is_size_absolute() {
FontSize::Px(value)
} else {
FontSize::Pt(value)
}
}),
weight: u16::try_from(description.weight().into_glib()).ok(),
style: Some(match description.style() {
gtk::pango::Style::Italic => FontStyle::Italic,
gtk::pango::Style::Oblique => FontStyle::Oblique,
_ => FontStyle::Normal,
}),
color: Some(to_native_color(color)),
})
}
fn relative_luminance(color: Rgba) -> f32 {
fn linear(channel: f32) -> f32 {
if channel <= 0.04045 {
channel / 12.92
} else {
((channel + 0.055) / 1.055).powf(2.4)
}
}
0.2126 * linear(color.red) + 0.7152 * linear(color.green) + 0.0722 * linear(color.blue)
}
impl ThemeSnapshot {
fn widget(&self, control: &str) -> Option<&WidgetSnapshot> {
self.widgets.iter().find(|widget| widget.control == control)
}
fn state_color(&self, control: &str, state: &str) -> Option<Rgba> {
self.widget(control)?
.states
.iter()
.find(|item| item.state == state)
.map(|item| item.foreground)
}
pub fn to_native_theme_mode(&self) -> native_theme::theme::ThemeMode {
use native_theme::theme::ThemeMode;
let mut mode = ThemeMode::default();
let semantic = &self.semantic_palette;
let native = |color: Option<Rgba>| color.map(to_native_color);
mode.defaults.background_color = native(semantic.window_background);
mode.defaults.text_color = native(semantic.window_text);
mode.defaults.accent_color = native(semantic.accent);
mode.defaults.accent_text_color = native(semantic.accent_text);
mode.defaults.surface_color = native(semantic.surface_background);
mode.defaults.muted_color = native(semantic.disabled_text.or(semantic.window_text));
mode.defaults.link_color = native(semantic.link);
mode.defaults.selection_background = native(semantic.selection_background);
mode.defaults.selection_text_color = native(semantic.selection_text);
mode.defaults.selection_inactive_background = native(semantic.selection_background);
mode.defaults.text_selection_background = native(semantic.selection_background);
mode.defaults.text_selection_color = native(semantic.selection_text);
mode.defaults.disabled_text_color = native(semantic.disabled_text);
mode.defaults.danger_color = native(semantic.error);
mode.defaults.warning_color = native(semantic.warning);
mode.defaults.success_color = native(semantic.success);
mode.defaults.info_color = native(semantic.accent);
mode.defaults.focus_ring_color = native(semantic.accent);
mode.defaults.border.color = native(semantic.border);
mode.defaults.icon_theme = self
.settings
.icon_theme_name
.as_ref()
.map(|name| name.clone().into());
if let (Some(font_name), Some(text)) = (&self.settings.font_name, semantic.window_text)
&& let Some(font) = native_font(font_name, text)
{
mode.defaults.font = font;
}
mode.window.background_color = native(semantic.window_background);
mode.window.title_bar_background = first_color(
&self.named_colors,
&["headerbar_bg_color", "window_bg_color", "theme_bg_color"],
)
.map(to_native_color);
mode.window.inactive_title_bar_background = mode.window.title_bar_background;
mode.window.inactive_title_bar_text_color = native(semantic.window_text);
mode.button.background_color = native(semantic.surface_background);
mode.button.primary_background = native(semantic.accent);
mode.button.primary_text_color = native(semantic.accent_text);
mode.button.hover_text_color = native(self.state_color("button", "hovered"));
mode.button.active_text_color = native(self.state_color("button", "pressed"));
mode.button.disabled_text_color = native(
self.state_color("button", "disabled")
.or(semantic.disabled_text),
);
if let Some(widget) = self.widget("button") {
mode.button.min_width = Some(widget.metrics.minimum_width as f32);
mode.button.min_height = Some(widget.metrics.minimum_height as f32);
if let (Some(font_name), Some(text)) = (
&self.settings.font_name,
self.state_color("button", "normal"),
) {
mode.button.font = native_font(font_name, text);
}
}
mode.input.background_color = native(semantic.input_background);
mode.input.caret_color = native(semantic.input_text);
mode.input.selection_background = native(semantic.selection_background);
mode.input.selection_text_color = native(semantic.selection_text);
mode.input.disabled_text_color = native(
self.state_color("input", "disabled")
.or(semantic.disabled_text),
);
mode.input.focus_border_color = native(semantic.accent);
if let Some(widget) = self.widget("input") {
mode.input.min_height = Some(widget.metrics.minimum_height as f32);
}
mode.checkbox.background_color = native(semantic.window_background);
mode.checkbox.checked_background = native(semantic.accent);
mode.checkbox.indicator_color = native(semantic.accent_text);
mode.checkbox.disabled_text_color = native(
self.state_color("checkbox", "disabled")
.or(semantic.disabled_text),
);
mode.menu.background_color = native(semantic.surface_background);
mode.menu.separator_color = native(semantic.border);
mode.menu.hover_background = native(semantic.selection_background);
mode.menu.hover_text_color = native(semantic.selection_text);
mode.menu.disabled_text_color = native(semantic.disabled_text);
mode.tooltip.background_color = native(semantic.tooltip_background);
if let (Some(font_name), Some(text)) = (&self.settings.font_name, semantic.tooltip_text) {
mode.tooltip.font = native_font(font_name, text);
}
mode.scrollbar.track_color = native(semantic.window_background);
mode.scrollbar.thumb_color = native(semantic.border.or(semantic.disabled_text));
mode.scrollbar.thumb_hover_color = native(semantic.accent);
mode.scrollbar.overlay_mode = self.settings.overlay_scrolling;
if let Some(widget) = self.widget("scrollbar") {
mode.scrollbar.groove_width = Some(widget.metrics.natural_width as f32);
}
mode.slider.fill_color = native(semantic.accent);
mode.slider.track_color = native(semantic.border);
mode.slider.thumb_color = native(semantic.surface_background);
mode.progress_bar.fill_color = native(semantic.accent);
mode.progress_bar.track_color = native(semantic.window_background);
if let Some(widget) = self.widget("progress-bar") {
mode.progress_bar.track_height = Some(widget.metrics.natural_height as f32);
mode.progress_bar.min_width = Some(widget.metrics.minimum_width as f32);
}
mode.switch.checked_background = native(semantic.accent);
mode.switch.unchecked_background = native(semantic.border);
mode.switch.thumb_background = native(semantic.surface_background);
if let Some(widget) = self.widget("switch") {
mode.switch.track_width = Some(widget.metrics.natural_width as f32);
mode.switch.track_height = Some(widget.metrics.natural_height as f32);
}
mode.separator.line_color = native(semantic.border);
mode.combo_box.background_color = native(semantic.surface_background);
mode.combo_box.disabled_text_color = native(semantic.disabled_text);
mode
}
pub fn resolve_native_theme(&self) -> Result<NativeThemeBridge, NativeThemeBridgeError> {
use native_theme::resolve::ResolutionContext;
use native_theme::theme::{ColorMode, Theme};
self.validate()?;
let background = self
.semantic_palette
.window_background
.ok_or(NativeThemeBridgeError::MissingColor("window_background"))?;
self.semantic_palette
.window_text
.ok_or(NativeThemeBridgeError::MissingColor("window_text"))?;
let mode = if relative_luminance(background) < 0.5 {
ColorMode::Dark
} else {
ColorMode::Light
};
let mut variant = Theme::preset("adwaita")?.into_variant(mode)?;
variant.merge(&self.to_native_theme_mode());
let resolved = variant.into_resolved(&ResolutionContext::from_system())?;
Ok(NativeThemeBridge {
name: format!("GTK {}", self.identity.theme_name),
mode,
resolved,
reduce_transparency: false,
reduce_motion: self
.settings
.interface_reduced_motion
.as_ref()
.is_some_and(|setting| setting.value != 0),
high_contrast: self
.settings
.interface_contrast
.as_ref()
.is_some_and(|setting| setting.nick != "no-preference"),
})
}
#[cfg(feature = "gpui")]
pub fn to_gpui_theme(&self) -> Result<gpui_component::theme::Theme, NativeThemeBridgeError> {
Ok(self.resolve_native_theme()?.to_gpui_theme())
}
}
fn first_color(colors: &[NamedColor], names: &[&str]) -> Option<Rgba> {
names.iter().find_map(|name| {
colors
.iter()
.find(|color| color.name == *name)
.map(|color| color.value)
})
}
fn semantic_palette(colors: &[NamedColor]) -> SemanticPalette {
SemanticPalette {
window_background: first_color(colors, &["window_bg_color", "theme_bg_color"]),
window_text: first_color(colors, &["window_fg_color", "theme_fg_color"]),
surface_background: first_color(
colors,
&[
"card_bg_color",
"popover_bg_color",
"window_bg_color",
"theme_bg_color",
],
),
surface_text: first_color(
colors,
&[
"card_fg_color",
"popover_fg_color",
"window_fg_color",
"theme_fg_color",
],
),
input_background: first_color(colors, &["view_bg_color", "theme_base_color"]),
input_text: first_color(colors, &["view_fg_color", "theme_text_color"]),
selection_background: first_color(colors, &["accent_bg_color", "theme_selected_bg_color"]),
selection_text: first_color(colors, &["accent_fg_color", "theme_selected_fg_color"]),
accent: first_color(
colors,
&["accent_bg_color", "accent_color", "theme_selected_bg_color"],
),
accent_text: first_color(colors, &["accent_fg_color", "theme_selected_fg_color"]),
border: first_color(colors, &["borders"]),
disabled_text: first_color(colors, &["insensitive_fg_color"]),
tooltip_background: first_color(
colors,
&[
"popover_bg_color",
"card_bg_color",
"window_bg_color",
"theme_bg_color",
],
),
tooltip_text: first_color(
colors,
&[
"popover_fg_color",
"card_fg_color",
"window_fg_color",
"theme_fg_color",
],
),
link: first_color(colors, &["link_color", "accent_color"]),
error: first_color(colors, &["error_color", "destructive_color"]),
warning: first_color(colors, &["warning_color"]),
success: first_color(colors, &["success_color"]),
}
}
#[derive(Debug, Error)]
pub enum ProbeError {
#[error("failed to initialize GTK: {0}")]
Initialization(String),
#[error("GTK did not provide a default settings object")]
MissingSettings,
#[error(transparent)]
InvalidSnapshot(#[from] SnapshotValidationError),
}
fn setting<T>(settings: >k::Settings, name: &str) -> Option<T>
where
for<'a> T: glib::value::FromValue<'a> + 'static,
{
settings
.find_property(name)
.and_then(|_| settings.property_value(name).get::<T>().ok())
}
fn enum_setting(settings: >k::Settings, name: &str) -> Option<EnumSetting> {
settings.find_property(name)?;
let value = settings.property_value(name);
let (_, value) = glib::EnumValue::from_value(&value)?;
Some(EnumSetting {
value: value.value(),
name: value.name().to_owned(),
nick: value.nick().to_owned(),
})
}
fn requested_dark_variant(color_scheme: Option<&EnumSetting>) -> Option<bool> {
match color_scheme?.nick.as_str() {
"dark" => Some(true),
"light" => Some(false),
_ => None,
}
}
fn apply_interface_color_scheme(settings: >k::Settings) -> Option<bool> {
if std::env::var_os("GTK_THEME").is_some() {
return None;
}
let prefer_dark =
requested_dark_variant(enum_setting(settings, "gtk-interface-color-scheme").as_ref())?;
settings.set_property("gtk-application-prefer-dark-theme", prefer_dark);
Some(prefer_dark)
}
#[allow(deprecated)]
fn named_colors(widget: >k::Widget) -> Vec<NamedColor> {
const NAMES: &[&str] = &[
"theme_fg_color",
"theme_bg_color",
"theme_base_color",
"theme_text_color",
"theme_selected_bg_color",
"theme_selected_fg_color",
"link_color",
"insensitive_bg_color",
"insensitive_fg_color",
"borders",
"warning_color",
"error_color",
"destructive_color",
"success_color",
"accent_color",
"accent_bg_color",
"accent_fg_color",
"window_bg_color",
"window_fg_color",
"view_bg_color",
"view_fg_color",
"headerbar_bg_color",
"headerbar_fg_color",
"card_bg_color",
"card_fg_color",
"popover_bg_color",
"popover_fg_color",
"dialog_bg_color",
"dialog_fg_color",
];
let context = widget.style_context();
NAMES
.iter()
.filter_map(|name| {
context.lookup_color(name).map(|value| NamedColor {
name: (*name).to_owned(),
value: value.into(),
})
})
.collect()
}
fn widget_metrics(widget: >k::Widget) -> WidgetMetrics {
let (minimum_width, natural_width, _, _) = widget.measure(gtk::Orientation::Horizontal, -1);
let (minimum_height, natural_height, _, _) =
widget.measure(gtk::Orientation::Vertical, natural_width);
WidgetMetrics {
minimum_width,
natural_width,
minimum_height,
natural_height,
}
}
fn widget_states(widget: >k::Widget) -> Vec<WidgetState> {
const STATES: &[(&str, gtk::StateFlags)] = &[
("normal", gtk::StateFlags::NORMAL),
("hovered", gtk::StateFlags::PRELIGHT),
("pressed", gtk::StateFlags::ACTIVE),
("focused", gtk::StateFlags::FOCUSED),
("focus-visible", gtk::StateFlags::FOCUS_VISIBLE),
("checked", gtk::StateFlags::CHECKED),
("selected", gtk::StateFlags::SELECTED),
("disabled", gtk::StateFlags::INSENSITIVE),
("inactive", gtk::StateFlags::BACKDROP),
];
let previous = widget.state_flags();
let all = gtk::StateFlags::all();
let mut result = Vec::with_capacity(STATES.len());
for (name, flags) in STATES {
widget.unset_state_flags(all);
widget.set_state_flags(*flags, true);
result.push(WidgetState {
state: (*name).to_owned(),
foreground: widget.color().into(),
});
}
widget.unset_state_flags(all);
widget.set_state_flags(previous, true);
result
}
fn widget_snapshot(control: &str, widget: >k::Widget) -> WidgetSnapshot {
WidgetSnapshot {
control: control.to_owned(),
css_name: widget.css_name().to_string(),
metrics: widget_metrics(widget),
states: widget_states(widget),
}
}
pub fn probe() -> Result<ThemeSnapshot, ProbeError> {
gtk::init().map_err(|error| ProbeError::Initialization(error.to_string()))?;
let settings = gtk::Settings::default().ok_or(ProbeError::MissingSettings)?;
let applied_interface_scheme = apply_interface_color_scheme(&settings);
let window = gtk::Window::new();
let container = gtk::Box::new(gtk::Orientation::Vertical, 0);
let button = gtk::Button::with_label("Button");
let entry = gtk::Entry::new();
entry.set_text("Text");
let checkbox = gtk::CheckButton::with_label("Check box");
let toggle = gtk::Switch::new();
let progress = gtk::ProgressBar::new();
progress.set_fraction(0.5);
let scale = gtk::Scale::with_range(gtk::Orientation::Horizontal, 0.0, 100.0, 1.0);
let scrollbar = gtk::Scrollbar::new(gtk::Orientation::Vertical, None::<>k::Adjustment>);
for widget in [
button.upcast_ref::<gtk::Widget>(),
entry.upcast_ref(),
checkbox.upcast_ref(),
toggle.upcast_ref(),
progress.upcast_ref(),
scale.upcast_ref(),
scrollbar.upcast_ref(),
] {
container.append(widget);
}
window.set_child(Some(&container));
let display_backend = gdk::Display::default().map(|display| {
let type_name = display.type_().name();
type_name
.strip_suffix("Display")
.unwrap_or(type_name)
.to_ascii_lowercase()
});
let theme_name =
setting::<String>(&settings, "gtk-theme-name").unwrap_or_else(|| "Default".to_owned());
let widgets = [
("window", window.upcast_ref::<gtk::Widget>()),
("button", button.upcast_ref()),
("input", entry.upcast_ref()),
("checkbox", checkbox.upcast_ref()),
("switch", toggle.upcast_ref()),
("progress-bar", progress.upcast_ref()),
("slider", scale.upcast_ref()),
("scrollbar", scrollbar.upcast_ref()),
]
.into_iter()
.map(|(name, widget)| widget_snapshot(name, widget))
.collect();
let named_colors = named_colors(window.upcast_ref());
let semantic_palette = semantic_palette(&named_colors);
let mut diagnostics = Vec::new();
if named_colors.is_empty() {
diagnostics
.push("the active theme did not expose any recognized symbolic colors".to_owned());
}
if let Some(prefer_dark) = applied_interface_scheme {
let scheme = if prefer_dark { "dark" } else { "light" };
diagnostics.push(format!(
"applied the desktop {scheme} color scheme before sampling GTK styles"
));
}
let snapshot = ThemeSnapshot {
schema_version: SCHEMA_VERSION,
backend: "gtk4".to_owned(),
identity: ThemeIdentity {
theme_name,
toolkit_version: format!(
"{}.{}.{}",
gtk::major_version(),
gtk::minor_version(),
gtk::micro_version()
),
display_backend,
},
settings: GtkSettingsSnapshot {
font_name: setting(&settings, "gtk-font-name"),
icon_theme_name: setting(&settings, "gtk-icon-theme-name"),
cursor_theme_name: setting(&settings, "gtk-cursor-theme-name"),
cursor_theme_size: setting(&settings, "gtk-cursor-theme-size"),
enable_animations: setting(&settings, "gtk-enable-animations"),
overlay_scrolling: setting(&settings, "gtk-overlay-scrolling"),
primary_button_warps_slider: setting(&settings, "gtk-primary-button-warps-slider"),
double_click_time_ms: setting(&settings, "gtk-double-click-time"),
cursor_blink_time_ms: setting(&settings, "gtk-cursor-blink-time"),
prefer_dark: setting(&settings, "gtk-application-prefer-dark-theme"),
interface_color_scheme: enum_setting(&settings, "gtk-interface-color-scheme"),
interface_contrast: enum_setting(&settings, "gtk-interface-contrast"),
interface_reduced_motion: enum_setting(&settings, "gtk-interface-reduced-motion"),
interface_accent_color: setting::<gdk::RGBA>(&settings, "gtk-accent-color")
.map(Into::into),
},
named_colors,
semantic_palette,
widgets,
diagnostics,
};
snapshot.validate()?;
Ok(snapshot)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rgba_serializes_with_explicit_channels() {
let json = serde_json::to_value(Rgba {
red: 0.1,
green: 0.2,
blue: 0.3,
alpha: 1.0,
})
.unwrap();
assert_eq!(json["alpha"], 1.0);
let red = json["red"].as_f64().unwrap();
assert!((red - 0.1).abs() < f64::from(f32::EPSILON));
}
#[test]
fn explicit_interface_color_schemes_select_the_matching_variant() {
let setting = |nick: &str| EnumSetting {
value: 0,
name: String::new(),
nick: nick.to_owned(),
};
assert_eq!(requested_dark_variant(Some(&setting("dark"))), Some(true));
assert_eq!(requested_dark_variant(Some(&setting("light"))), Some(false));
assert_eq!(requested_dark_variant(Some(&setting("default"))), None);
assert_eq!(requested_dark_variant(None), None);
}
#[test]
fn snapshot_contract_round_trips() {
let snapshot = ThemeSnapshot {
schema_version: SCHEMA_VERSION,
backend: "gtk4".to_owned(),
identity: ThemeIdentity {
theme_name: "Test".to_owned(),
toolkit_version: "4.0.0".to_owned(),
display_backend: None,
},
settings: GtkSettingsSnapshot {
font_name: None,
icon_theme_name: None,
cursor_theme_name: None,
cursor_theme_size: None,
enable_animations: None,
overlay_scrolling: None,
primary_button_warps_slider: None,
double_click_time_ms: None,
cursor_blink_time_ms: None,
prefer_dark: None,
interface_color_scheme: None,
interface_contrast: None,
interface_reduced_motion: None,
interface_accent_color: None,
},
named_colors: Vec::new(),
semantic_palette: SemanticPalette::default(),
widgets: Vec::new(),
diagnostics: Vec::new(),
};
let json = serde_json::to_string(&snapshot).unwrap();
assert_eq!(
serde_json::from_str::<ThemeSnapshot>(&json).unwrap(),
snapshot
);
}
#[test]
fn semantic_palette_prefers_modern_gtk_names() {
let modern = Rgba {
red: 1.0,
green: 0.0,
blue: 0.0,
alpha: 1.0,
};
let legacy = Rgba {
red: 0.0,
green: 0.0,
blue: 1.0,
alpha: 1.0,
};
let palette = semantic_palette(&[
NamedColor {
name: "theme_bg_color".to_owned(),
value: legacy,
},
NamedColor {
name: "window_bg_color".to_owned(),
value: modern,
},
]);
assert_eq!(palette.window_background, Some(modern));
}
#[test]
fn semantic_palette_contract_has_stable_role_names() {
let value = serde_json::to_value(SemanticPalette::default()).unwrap();
let mut actual: Vec<_> = value
.as_object()
.unwrap()
.keys()
.map(String::as_str)
.collect();
let mut expected = SEMANTIC_COLOR_ROLES.to_vec();
actual.sort_unstable();
expected.sort_unstable();
assert_eq!(actual, expected);
}
#[test]
fn invalid_color_channels_are_rejected() {
let error = validate_rgba(
"test",
Rgba {
red: f32::NAN,
green: 0.0,
blue: 0.0,
alpha: 1.0,
},
)
.unwrap_err();
assert!(error.reason().contains("test.red"));
}
#[test]
fn incomplete_snapshot_is_rejected() {
let snapshot = ThemeSnapshot {
schema_version: SCHEMA_VERSION,
backend: "gtk4".to_owned(),
identity: ThemeIdentity {
theme_name: "Test".to_owned(),
toolkit_version: "4.22.0".to_owned(),
display_backend: None,
},
settings: GtkSettingsSnapshot {
font_name: None,
icon_theme_name: None,
cursor_theme_name: None,
cursor_theme_size: None,
enable_animations: None,
overlay_scrolling: None,
primary_button_warps_slider: None,
double_click_time_ms: None,
cursor_blink_time_ms: None,
prefer_dark: None,
interface_color_scheme: None,
interface_contrast: None,
interface_reduced_motion: None,
interface_accent_color: None,
},
named_colors: Vec::new(),
semantic_palette: SemanticPalette::default(),
widgets: Vec::new(),
diagnostics: Vec::new(),
};
assert!(
snapshot
.validate()
.unwrap_err()
.reason()
.contains("missing representative widget")
);
}
}