use std::collections::{BTreeMap, HashSet};
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",
];
#[cxx::bridge(namespace = "native_theme_qt")]
mod ffi {
unsafe extern "C++" {
include!("probe.h");
fn probe_theme() -> Result<UniquePtr<CxxString>>;
}
}
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
pub struct Rgba {
pub red: f32,
pub green: f32,
pub blue: f32,
pub alpha: f32,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct ThemeIdentity {
pub style_name: String,
pub toolkit_version: String,
pub platform_backend: String,
pub platform_theme: Option<String>,
pub style_override: Option<String>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct FontSnapshot {
pub family: String,
pub point_size: f32,
pub pixel_size: i32,
pub weight: i32,
pub italic: bool,
pub stretch: i32,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct QtSettingsSnapshot {
pub font: FontSnapshot,
pub fixed_font: FontSnapshot,
pub icon_theme_name: String,
pub cursor_flash_time_ms: i32,
pub double_click_interval_ms: i32,
pub wheel_scroll_lines: i32,
pub application_stylesheet: String,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct PaletteBrush {
pub color: Rgba,
pub brush_style: i32,
}
#[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>,
}
pub type PaletteSnapshot = BTreeMap<String, BTreeMap<String, PaletteBrush>>;
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
pub struct SizeSnapshot {
pub width: i32,
pub height: i32,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct ControlSnapshot {
pub size_hint: SizeSnapshot,
pub minimum_size_hint: SizeSnapshot,
pub font: FontSnapshot,
pub palette: PaletteSnapshot,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct ThemeSnapshot {
pub schema_version: u32,
pub backend: String,
pub identity: ThemeIdentity,
pub settings: QtSettingsSnapshot,
pub palette: PaletteSnapshot,
#[serde(default)]
pub semantic_palette: SemanticPalette,
#[serde(default)]
pub controls: BTreeMap<String, ControlSnapshot>,
pub metrics: BTreeMap<String, i32>,
pub hints: BTreeMap<String, i32>,
pub diagnostics: Vec<String>,
}
#[derive(Debug, Error, PartialEq, Eq)]
#[error("invalid Qt 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(())
}
fn validate_palette(path: &str, palette: &PaletteSnapshot) -> Result<(), SnapshotValidationError> {
for required in ["active", "inactive", "disabled"] {
if !palette.contains_key(required) {
return Err(validation_error(format!(
"{path} is missing color group {required}"
)));
}
}
for (group, roles) in palette {
for (role, brush) in roles {
validate_rgba(&format!("{path}.{group}.{role}"), brush.color)?;
if brush.brush_style < 0 {
return Err(validation_error(format!(
"{path}.{group}.{role}.brush_style must not be negative"
)));
}
}
}
Ok(())
}
fn validate_font(path: &str, font: &FontSnapshot) -> Result<(), SnapshotValidationError> {
if font.family.trim().is_empty() {
return Err(validation_error(format!("{path}.family must not be empty")));
}
if !font.point_size.is_finite() {
return Err(validation_error(format!(
"{path}.point_size must be finite"
)));
}
if font.stretch < 0 {
return Err(validation_error(format!(
"{path}.stretch must not be negative"
)));
}
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 != "qt6" {
return Err(validation_error(format!(
"backend must be qt6, got {:?}",
self.backend
)));
}
if self.identity.style_name.trim().is_empty()
|| self.identity.toolkit_version.trim().is_empty()
|| self.identity.platform_backend.trim().is_empty()
{
return Err(validation_error(
"style name, toolkit version, and platform backend must not be empty",
));
}
validate_font("settings.font", &self.settings.font)?;
validate_font("settings.fixed_font", &self.settings.fixed_font)?;
validate_palette("palette", &self.palette)?;
for role in [
"window",
"window_text",
"button",
"button_text",
"base",
"text",
"highlight",
"highlighted_text",
] {
if !self.palette["active"].contains_key(role) {
return Err(validation_error(format!(
"palette.active is missing role {role}"
)));
}
}
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)?;
}
}
let required_controls: HashSet<_> = [
"button",
"line_edit",
"check_box",
"radio_button",
"combo_box",
"spin_box",
"slider",
"progress_bar",
"scroll_bar",
"tab_bar",
"tool_button",
]
.into_iter()
.collect();
for required in required_controls {
if !self.controls.contains_key(required) {
return Err(validation_error(format!(
"missing representative control {required}"
)));
}
}
for (name, control) in &self.controls {
for (kind, size) in [
("size_hint", control.size_hint),
("minimum_size_hint", control.minimum_size_hint),
] {
if size.width < -1 || size.height < -1 {
return Err(validation_error(format!(
"controls.{name}.{kind} contains a dimension below -1"
)));
}
}
validate_font(&format!("controls.{name}.font"), &control.font)?;
validate_palette(&format!("controls.{name}.palette"), &control.palette)?;
}
if self.metrics.is_empty() || self.hints.is_empty() {
return Err(validation_error(
"style metrics and hints must not be empty",
));
}
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("Qt 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(font: &FontSnapshot, color: Rgba) -> native_theme::theme::FontSpec {
use native_theme::theme::{FontSize, FontSpec, FontStyle, intern_font_family};
FontSpec {
family: Some(intern_font_family(&font.family)),
size: if font.point_size > 0.0 {
Some(FontSize::Pt(font.point_size))
} else if font.pixel_size > 0 {
Some(FontSize::Px(font.pixel_size as f32))
} else {
None
},
weight: u16::try_from(font.weight).ok(),
style: Some(if font.italic {
FontStyle::Italic
} else {
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 {
pub fn to_native_theme_mode(&self) -> native_theme::theme::ThemeMode {
use native_theme::theme::{ThemeMode, WidgetBorderSpec};
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 =
palette_color(&self.palette, "inactive", "highlight").map(to_native_color);
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.border.line_width = self
.metrics
.get("default_frame_width")
.copied()
.map(|value| value as f32);
mode.defaults.icon_sizes.toolbar = self
.metrics
.get("toolbar_icon_size")
.copied()
.map(|value| value as f32);
mode.defaults.icon_sizes.small = self
.metrics
.get("small_icon_size")
.copied()
.map(|value| value as f32);
mode.defaults.icon_sizes.large = self
.metrics
.get("large_icon_size")
.copied()
.map(|value| value as f32);
if let Some(text) = semantic.window_text {
mode.defaults.font = native_font(&self.settings.font, text);
mode.defaults.mono_font = native_font(&self.settings.fixed_font, text);
}
mode.defaults.icon_theme = (!self.settings.icon_theme_name.is_empty())
.then(|| self.settings.icon_theme_name.clone().into());
mode.window.background_color = native(semantic.window_background);
mode.window.title_bar_background = native(semantic.surface_background);
mode.window.inactive_title_bar_background =
palette_color(&self.palette, "inactive", "window").map(to_native_color);
mode.window.inactive_title_bar_text_color =
palette_color(&self.palette, "inactive", "window_text").map(to_native_color);
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.disabled_text_color = native(semantic.disabled_text);
if let Some(control) = self.controls.get("button") {
mode.button.min_width = Some(control.minimum_size_hint.width.max(0) as f32);
mode.button.min_height = Some(control.minimum_size_hint.height.max(0) as f32);
mode.button.font = semantic
.surface_text
.map(|color| native_font(&control.font, color));
mode.button.border = Some(WidgetBorderSpec {
color: native(semantic.border),
line_width: mode.defaults.border.line_width,
padding_horizontal: self
.metrics
.get("button_margin")
.map(|value| *value as f32 / 2.0),
padding_vertical: self
.metrics
.get("button_margin")
.map(|value| *value as f32 / 2.0),
..Default::default()
});
}
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(semantic.disabled_text);
mode.input.focus_border_color = native(semantic.accent);
if let Some(control) = self.controls.get("line_edit") {
mode.input.min_height = Some(control.minimum_size_hint.height.max(0) as f32);
mode.input.font = semantic
.input_text
.map(|color| native_font(&control.font, color));
}
mode.checkbox.checked_background = native(semantic.accent);
mode.checkbox.indicator_color = native(semantic.accent_text);
mode.checkbox.disabled_text_color = native(semantic.disabled_text);
mode.checkbox.indicator_width = self
.metrics
.get("indicator_width")
.copied()
.map(|value| value as f32);
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(text) = semantic.tooltip_text {
mode.tooltip.font = Some(native_font(&self.settings.font, 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.groove_width = self
.metrics
.get("scrollbar_extent")
.copied()
.map(|value| value as f32);
mode.scrollbar.min_thumb_length = self
.metrics
.get("scrollbar_slider_min")
.copied()
.map(|value| value as f32);
mode.scrollbar.overlay_mode = Some(false);
mode.slider.fill_color = native(semantic.accent);
mode.slider.track_color = native(semantic.border);
mode.slider.thumb_color = native(semantic.surface_background);
mode.slider.track_height = self
.metrics
.get("slider_control_thickness")
.copied()
.map(|value| value as f32);
mode.slider.thumb_diameter = self
.metrics
.get("slider_length")
.copied()
.map(|value| value as f32);
mode.progress_bar.fill_color = native(semantic.accent);
mode.progress_bar.track_color = native(semantic.window_background);
if let Some(control) = self.controls.get("progress_bar") {
mode.progress_bar.track_height = Some(control.size_hint.height.max(0) as f32);
mode.progress_bar.min_width = Some(control.minimum_size_hint.width.max(0) as f32);
}
mode.tab.background_color = native(semantic.window_background);
mode.tab.active_background = native(semantic.surface_background);
mode.tab.active_text_color = native(semantic.window_text);
mode.tab.bar_background = native(semantic.window_background);
if let Some(control) = self.controls.get("tab_bar") {
mode.tab.min_width = Some(control.minimum_size_hint.width.max(0) as f32);
mode.tab.min_height = Some(control.minimum_size_hint.height.max(0) as f32);
}
mode.separator.line_color = native(semantic.border);
mode.separator.line_width = mode.defaults.border.line_width;
mode.combo_box.background_color = native(semantic.surface_background);
mode.combo_box.disabled_text_color = native(semantic.disabled_text);
if let Some(control) = self.controls.get("combo_box") {
mode.combo_box.min_width = Some(control.minimum_size_hint.width.max(0) as f32);
mode.combo_box.min_height = Some(control.minimum_size_hint.height.max(0) as f32);
}
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("kde-breeze")?.into_variant(mode)?;
variant.merge(&self.to_native_theme_mode());
let resolved = variant.into_resolved(&ResolutionContext::from_system())?;
Ok(NativeThemeBridge {
name: format!("Qt {}", self.identity.style_name),
mode,
resolved,
reduce_transparency: false,
reduce_motion: false,
high_contrast: false,
})
}
#[cfg(feature = "gpui")]
pub fn to_gpui_theme(&self) -> Result<gpui_component::theme::Theme, NativeThemeBridgeError> {
Ok(self.resolve_native_theme()?.to_gpui_theme())
}
}
fn palette_color(palette: &PaletteSnapshot, group: &str, role: &str) -> Option<Rgba> {
palette.get(group)?.get(role).map(|brush| brush.color)
}
fn semantic_palette(palette: &PaletteSnapshot) -> SemanticPalette {
let active = |role| palette_color(palette, "active", role);
SemanticPalette {
window_background: active("window"),
window_text: active("window_text"),
surface_background: active("button"),
surface_text: active("button_text"),
input_background: active("base"),
input_text: active("text"),
selection_background: active("highlight"),
selection_text: active("highlighted_text"),
accent: active("accent").or_else(|| active("highlight")),
accent_text: active("highlighted_text"),
border: active("mid"),
disabled_text: palette_color(palette, "disabled", "text"),
tooltip_background: active("tooltip_base"),
tooltip_text: active("tooltip_text"),
link: active("link"),
error: None,
warning: None,
success: None,
}
}
#[derive(Debug, Error)]
pub enum ProbeError {
#[error("Qt theme probe failed: {0}")]
Native(String),
#[error("Qt theme probe returned no data")]
Empty,
#[error("Qt theme probe returned invalid JSON: {0}")]
InvalidJson(#[from] serde_json::Error),
#[error("unsupported snapshot schema version {actual}; expected {expected}")]
SchemaVersion {
actual: u32,
expected: u32,
},
#[error(transparent)]
InvalidSnapshot(#[from] SnapshotValidationError),
}
pub fn probe() -> Result<ThemeSnapshot, ProbeError> {
let json = ffi::probe_theme().map_err(|error| ProbeError::Native(error.what().to_owned()))?;
let json = json.as_ref().ok_or(ProbeError::Empty)?.to_string_lossy();
let mut snapshot: ThemeSnapshot = serde_json::from_str(&json)?;
if snapshot.schema_version != SCHEMA_VERSION {
return Err(ProbeError::SchemaVersion {
actual: snapshot.schema_version,
expected: SCHEMA_VERSION,
});
}
snapshot.semantic_palette = semantic_palette(&snapshot.palette);
snapshot.validate()?;
Ok(snapshot)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn contract_fixture_deserializes() {
let json = r#"{
"schema_version": 1,
"backend": "qt6",
"identity": {
"style_name": "fusion",
"toolkit_version": "6.2.0",
"platform_backend": "offscreen",
"platform_theme": null,
"style_override": null
},
"settings": {
"font": {"family":"Sans","point_size":10.0,"pixel_size":-1,"weight":400,"italic":false,"stretch":100},
"fixed_font": {"family":"Monospace","point_size":10.0,"pixel_size":-1,"weight":400,"italic":false,"stretch":100},
"icon_theme_name": "",
"cursor_flash_time_ms": 1000,
"double_click_interval_ms": 400,
"wheel_scroll_lines": 3,
"application_stylesheet": ""
},
"palette": {},
"semantic_palette": {},
"controls": {},
"metrics": {},
"hints": {},
"diagnostics": []
}"#;
let snapshot: ThemeSnapshot = serde_json::from_str(json).unwrap();
assert_eq!(snapshot.schema_version, SCHEMA_VERSION);
assert_eq!(snapshot.identity.style_name, "fusion");
}
#[test]
fn semantic_palette_maps_qt_roles() {
let red = Rgba {
red: 1.0,
green: 0.0,
blue: 0.0,
alpha: 1.0,
};
let mut roles = BTreeMap::new();
roles.insert(
"window".to_owned(),
PaletteBrush {
color: red,
brush_style: 1,
},
);
let palette = BTreeMap::from([("active".to_owned(), roles)]);
assert_eq!(semantic_palette(&palette).window_background, Some(red));
}
#[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: 0.0,
green: 1.01,
blue: 0.0,
alpha: 1.0,
},
)
.unwrap_err();
assert!(error.reason().contains("test.green"));
}
#[test]
fn incomplete_snapshot_is_rejected() {
let json = r#"{
"schema_version": 1,
"backend": "qt6",
"identity": {
"style_name": "fusion", "toolkit_version": "6.2.0",
"platform_backend": "offscreen", "platform_theme": null,
"style_override": null
},
"settings": {
"font": {"family":"Sans","point_size":10.0,"pixel_size":-1,"weight":400,"italic":false,"stretch":100},
"fixed_font": {"family":"Mono","point_size":10.0,"pixel_size":-1,"weight":400,"italic":false,"stretch":100},
"icon_theme_name":"", "cursor_flash_time_ms":1000,
"double_click_interval_ms":400, "wheel_scroll_lines":3,
"application_stylesheet":""
},
"palette": {}, "semantic_palette": {}, "controls": {},
"metrics": {}, "hints": {}, "diagnostics": []
}"#;
let snapshot: ThemeSnapshot = serde_json::from_str(json).unwrap();
assert!(
snapshot
.validate()
.unwrap_err()
.reason()
.contains("missing color group")
);
}
}