1use std::collections::{BTreeMap, HashSet};
9
10use serde::{Deserialize, Serialize};
11use thiserror::Error;
12
13pub const SCHEMA_VERSION: u32 = 1;
15
16pub const SEMANTIC_COLOR_ROLES: [&str; 18] = [
18 "window_background",
19 "window_text",
20 "surface_background",
21 "surface_text",
22 "input_background",
23 "input_text",
24 "selection_background",
25 "selection_text",
26 "accent",
27 "accent_text",
28 "border",
29 "disabled_text",
30 "tooltip_background",
31 "tooltip_text",
32 "link",
33 "error",
34 "warning",
35 "success",
36];
37
38#[cxx::bridge(namespace = "native_theme_qt")]
39mod ffi {
40 unsafe extern "C++" {
41 include!("probe.h");
42
43 fn probe_theme() -> Result<UniquePtr<CxxString>>;
44 }
45}
46
47#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
49pub struct Rgba {
50 pub red: f32,
52 pub green: f32,
54 pub blue: f32,
56 pub alpha: f32,
58}
59
60#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
62pub struct ThemeIdentity {
63 pub style_name: String,
65 pub toolkit_version: String,
67 pub platform_backend: String,
69 pub platform_theme: Option<String>,
71 pub style_override: Option<String>,
73}
74
75#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
77pub struct FontSnapshot {
78 pub family: String,
80 pub point_size: f32,
82 pub pixel_size: i32,
84 pub weight: i32,
86 pub italic: bool,
88 pub stretch: i32,
90}
91
92#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
94pub struct QtSettingsSnapshot {
95 pub font: FontSnapshot,
97 pub fixed_font: FontSnapshot,
99 pub icon_theme_name: String,
101 pub cursor_flash_time_ms: i32,
103 pub double_click_interval_ms: i32,
105 pub wheel_scroll_lines: i32,
107 pub application_stylesheet: String,
109}
110
111#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
113pub struct PaletteBrush {
114 pub color: Rgba,
116 pub brush_style: i32,
118}
119
120#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
122pub struct SemanticPalette {
123 pub window_background: Option<Rgba>,
125 pub window_text: Option<Rgba>,
127 pub surface_background: Option<Rgba>,
129 pub surface_text: Option<Rgba>,
131 pub input_background: Option<Rgba>,
133 pub input_text: Option<Rgba>,
135 pub selection_background: Option<Rgba>,
137 pub selection_text: Option<Rgba>,
139 pub accent: Option<Rgba>,
141 pub accent_text: Option<Rgba>,
143 pub border: Option<Rgba>,
145 pub disabled_text: Option<Rgba>,
147 pub tooltip_background: Option<Rgba>,
149 pub tooltip_text: Option<Rgba>,
151 pub link: Option<Rgba>,
153 pub error: Option<Rgba>,
155 pub warning: Option<Rgba>,
157 pub success: Option<Rgba>,
159}
160
161pub type PaletteSnapshot = BTreeMap<String, BTreeMap<String, PaletteBrush>>;
163
164#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
166pub struct SizeSnapshot {
167 pub width: i32,
169 pub height: i32,
171}
172
173#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
175pub struct ControlSnapshot {
176 pub size_hint: SizeSnapshot,
178 pub minimum_size_hint: SizeSnapshot,
180 pub font: FontSnapshot,
182 pub palette: PaletteSnapshot,
184}
185
186#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
188pub struct ThemeSnapshot {
189 pub schema_version: u32,
191 pub backend: String,
193 pub identity: ThemeIdentity,
195 pub settings: QtSettingsSnapshot,
197 pub palette: PaletteSnapshot,
199 #[serde(default)]
201 pub semantic_palette: SemanticPalette,
202 #[serde(default)]
204 pub controls: BTreeMap<String, ControlSnapshot>,
205 pub metrics: BTreeMap<String, i32>,
207 pub hints: BTreeMap<String, i32>,
209 pub diagnostics: Vec<String>,
211}
212
213#[derive(Debug, Error, PartialEq, Eq)]
215#[error("invalid Qt theme snapshot: {reason}")]
216pub struct SnapshotValidationError {
217 reason: String,
218}
219
220impl SnapshotValidationError {
221 pub fn reason(&self) -> &str {
223 &self.reason
224 }
225}
226
227fn validation_error(reason: impl Into<String>) -> SnapshotValidationError {
228 SnapshotValidationError {
229 reason: reason.into(),
230 }
231}
232
233fn validate_rgba(path: &str, color: Rgba) -> Result<(), SnapshotValidationError> {
234 for (channel, value) in [
235 ("red", color.red),
236 ("green", color.green),
237 ("blue", color.blue),
238 ("alpha", color.alpha),
239 ] {
240 if !value.is_finite() || !(0.0..=1.0).contains(&value) {
241 return Err(validation_error(format!(
242 "{path}.{channel} must be finite and in 0..=1, got {value}"
243 )));
244 }
245 }
246 Ok(())
247}
248
249fn validate_palette(path: &str, palette: &PaletteSnapshot) -> Result<(), SnapshotValidationError> {
250 for required in ["active", "inactive", "disabled"] {
251 if !palette.contains_key(required) {
252 return Err(validation_error(format!(
253 "{path} is missing color group {required}"
254 )));
255 }
256 }
257 for (group, roles) in palette {
258 for (role, brush) in roles {
259 validate_rgba(&format!("{path}.{group}.{role}"), brush.color)?;
260 if brush.brush_style < 0 {
261 return Err(validation_error(format!(
262 "{path}.{group}.{role}.brush_style must not be negative"
263 )));
264 }
265 }
266 }
267 Ok(())
268}
269
270fn validate_font(path: &str, font: &FontSnapshot) -> Result<(), SnapshotValidationError> {
271 if font.family.trim().is_empty() {
272 return Err(validation_error(format!("{path}.family must not be empty")));
273 }
274 if !font.point_size.is_finite() {
275 return Err(validation_error(format!(
276 "{path}.point_size must be finite"
277 )));
278 }
279 if font.stretch < 0 {
280 return Err(validation_error(format!(
281 "{path}.stretch must not be negative"
282 )));
283 }
284 Ok(())
285}
286
287impl ThemeSnapshot {
288 pub fn validate(&self) -> Result<(), SnapshotValidationError> {
290 if self.schema_version != SCHEMA_VERSION {
291 return Err(validation_error(format!(
292 "unsupported schema version {}; expected {SCHEMA_VERSION}",
293 self.schema_version
294 )));
295 }
296 if self.backend != "qt6" {
297 return Err(validation_error(format!(
298 "backend must be qt6, got {:?}",
299 self.backend
300 )));
301 }
302 if self.identity.style_name.trim().is_empty()
303 || self.identity.toolkit_version.trim().is_empty()
304 || self.identity.platform_backend.trim().is_empty()
305 {
306 return Err(validation_error(
307 "style name, toolkit version, and platform backend must not be empty",
308 ));
309 }
310 validate_font("settings.font", &self.settings.font)?;
311 validate_font("settings.fixed_font", &self.settings.fixed_font)?;
312 validate_palette("palette", &self.palette)?;
313 for role in [
314 "window",
315 "window_text",
316 "button",
317 "button_text",
318 "base",
319 "text",
320 "highlight",
321 "highlighted_text",
322 ] {
323 if !self.palette["active"].contains_key(role) {
324 return Err(validation_error(format!(
325 "palette.active is missing role {role}"
326 )));
327 }
328 }
329
330 for (name, color) in [
331 ("window_background", self.semantic_palette.window_background),
332 ("window_text", self.semantic_palette.window_text),
333 (
334 "surface_background",
335 self.semantic_palette.surface_background,
336 ),
337 ("surface_text", self.semantic_palette.surface_text),
338 ("input_background", self.semantic_palette.input_background),
339 ("input_text", self.semantic_palette.input_text),
340 (
341 "selection_background",
342 self.semantic_palette.selection_background,
343 ),
344 ("selection_text", self.semantic_palette.selection_text),
345 ("accent", self.semantic_palette.accent),
346 ("accent_text", self.semantic_palette.accent_text),
347 ("border", self.semantic_palette.border),
348 ("disabled_text", self.semantic_palette.disabled_text),
349 (
350 "tooltip_background",
351 self.semantic_palette.tooltip_background,
352 ),
353 ("tooltip_text", self.semantic_palette.tooltip_text),
354 ("link", self.semantic_palette.link),
355 ("error", self.semantic_palette.error),
356 ("warning", self.semantic_palette.warning),
357 ("success", self.semantic_palette.success),
358 ] {
359 if let Some(color) = color {
360 validate_rgba(&format!("semantic_palette.{name}"), color)?;
361 }
362 }
363
364 let required_controls: HashSet<_> = [
365 "button",
366 "line_edit",
367 "check_box",
368 "radio_button",
369 "combo_box",
370 "spin_box",
371 "slider",
372 "progress_bar",
373 "scroll_bar",
374 "tab_bar",
375 "tool_button",
376 ]
377 .into_iter()
378 .collect();
379 for required in required_controls {
380 if !self.controls.contains_key(required) {
381 return Err(validation_error(format!(
382 "missing representative control {required}"
383 )));
384 }
385 }
386 for (name, control) in &self.controls {
387 for (kind, size) in [
388 ("size_hint", control.size_hint),
389 ("minimum_size_hint", control.minimum_size_hint),
390 ] {
391 if size.width < -1 || size.height < -1 {
392 return Err(validation_error(format!(
393 "controls.{name}.{kind} contains a dimension below -1"
394 )));
395 }
396 }
397 validate_font(&format!("controls.{name}.font"), &control.font)?;
398 validate_palette(&format!("controls.{name}.palette"), &control.palette)?;
399 }
400 if self.metrics.is_empty() || self.hints.is_empty() {
401 return Err(validation_error(
402 "style metrics and hints must not be empty",
403 ));
404 }
405 Ok(())
406 }
407}
408
409#[derive(Clone, Debug)]
411pub struct NativeThemeBridge {
412 pub name: String,
414 pub mode: native_theme::theme::ColorMode,
416 pub resolved: native_theme::theme::ResolvedTheme,
418 pub reduce_transparency: bool,
420 pub reduce_motion: bool,
422 pub high_contrast: bool,
424}
425
426impl NativeThemeBridge {
427 #[cfg(feature = "gpui")]
429 #[must_use = "this returns the GPUI theme; it does not install it globally"]
430 pub fn to_gpui_theme(&self) -> gpui_component::theme::Theme {
431 native_theme_gpui::to_theme(
432 &self.resolved,
433 &self.name,
434 self.mode.is_dark(),
435 self.reduce_transparency,
436 )
437 }
438}
439
440#[derive(Debug, Error)]
442pub enum NativeThemeBridgeError {
443 #[error(transparent)]
445 InvalidSnapshot(#[from] SnapshotValidationError),
446 #[error("Qt snapshot is missing required semantic color {0}")]
448 MissingColor(&'static str),
449 #[error("native-theme resolution failed: {0}")]
451 Resolution(#[from] native_theme::error::Error),
452}
453
454fn to_native_color(color: Rgba) -> native_theme::color::Rgba {
455 native_theme::color::Rgba::from_f32(color.red, color.green, color.blue, color.alpha)
456}
457
458fn native_font(font: &FontSnapshot, color: Rgba) -> native_theme::theme::FontSpec {
459 use native_theme::theme::{FontSize, FontSpec, FontStyle, intern_font_family};
460
461 FontSpec {
462 family: Some(intern_font_family(&font.family)),
463 size: if font.point_size > 0.0 {
464 Some(FontSize::Pt(font.point_size))
465 } else if font.pixel_size > 0 {
466 Some(FontSize::Px(font.pixel_size as f32))
467 } else {
468 None
469 },
470 weight: u16::try_from(font.weight).ok(),
471 style: Some(if font.italic {
472 FontStyle::Italic
473 } else {
474 FontStyle::Normal
475 }),
476 color: Some(to_native_color(color)),
477 }
478}
479
480fn relative_luminance(color: Rgba) -> f32 {
481 fn linear(channel: f32) -> f32 {
482 if channel <= 0.04045 {
483 channel / 12.92
484 } else {
485 ((channel + 0.055) / 1.055).powf(2.4)
486 }
487 }
488 0.2126 * linear(color.red) + 0.7152 * linear(color.green) + 0.0722 * linear(color.blue)
489}
490
491impl ThemeSnapshot {
492 pub fn to_native_theme_mode(&self) -> native_theme::theme::ThemeMode {
498 use native_theme::theme::{ThemeMode, WidgetBorderSpec};
499
500 let mut mode = ThemeMode::default();
501 let semantic = &self.semantic_palette;
502 let native = |color: Option<Rgba>| color.map(to_native_color);
503
504 mode.defaults.background_color = native(semantic.window_background);
505 mode.defaults.text_color = native(semantic.window_text);
506 mode.defaults.accent_color = native(semantic.accent);
507 mode.defaults.accent_text_color = native(semantic.accent_text);
508 mode.defaults.surface_color = native(semantic.surface_background);
509 mode.defaults.muted_color = native(semantic.disabled_text.or(semantic.window_text));
510 mode.defaults.link_color = native(semantic.link);
511 mode.defaults.selection_background = native(semantic.selection_background);
512 mode.defaults.selection_text_color = native(semantic.selection_text);
513 mode.defaults.selection_inactive_background =
514 palette_color(&self.palette, "inactive", "highlight").map(to_native_color);
515 mode.defaults.text_selection_background = native(semantic.selection_background);
516 mode.defaults.text_selection_color = native(semantic.selection_text);
517 mode.defaults.disabled_text_color = native(semantic.disabled_text);
518 mode.defaults.danger_color = native(semantic.error);
519 mode.defaults.warning_color = native(semantic.warning);
520 mode.defaults.success_color = native(semantic.success);
521 mode.defaults.info_color = native(semantic.accent);
522 mode.defaults.focus_ring_color = native(semantic.accent);
523 mode.defaults.border.color = native(semantic.border);
524 mode.defaults.border.line_width = self
525 .metrics
526 .get("default_frame_width")
527 .copied()
528 .map(|value| value as f32);
529 mode.defaults.icon_sizes.toolbar = self
530 .metrics
531 .get("toolbar_icon_size")
532 .copied()
533 .map(|value| value as f32);
534 mode.defaults.icon_sizes.small = self
535 .metrics
536 .get("small_icon_size")
537 .copied()
538 .map(|value| value as f32);
539 mode.defaults.icon_sizes.large = self
540 .metrics
541 .get("large_icon_size")
542 .copied()
543 .map(|value| value as f32);
544 if let Some(text) = semantic.window_text {
545 mode.defaults.font = native_font(&self.settings.font, text);
546 mode.defaults.mono_font = native_font(&self.settings.fixed_font, text);
547 }
548 mode.defaults.icon_theme = (!self.settings.icon_theme_name.is_empty())
549 .then(|| self.settings.icon_theme_name.clone().into());
550
551 mode.window.background_color = native(semantic.window_background);
552 mode.window.title_bar_background = native(semantic.surface_background);
553 mode.window.inactive_title_bar_background =
554 palette_color(&self.palette, "inactive", "window").map(to_native_color);
555 mode.window.inactive_title_bar_text_color =
556 palette_color(&self.palette, "inactive", "window_text").map(to_native_color);
557
558 mode.button.background_color = native(semantic.surface_background);
559 mode.button.primary_background = native(semantic.accent);
560 mode.button.primary_text_color = native(semantic.accent_text);
561 mode.button.disabled_text_color = native(semantic.disabled_text);
562 if let Some(control) = self.controls.get("button") {
563 mode.button.min_width = Some(control.minimum_size_hint.width.max(0) as f32);
564 mode.button.min_height = Some(control.minimum_size_hint.height.max(0) as f32);
565 mode.button.font = semantic
566 .surface_text
567 .map(|color| native_font(&control.font, color));
568 mode.button.border = Some(WidgetBorderSpec {
569 color: native(semantic.border),
570 line_width: mode.defaults.border.line_width,
571 padding_horizontal: self
572 .metrics
573 .get("button_margin")
574 .map(|value| *value as f32 / 2.0),
575 padding_vertical: self
576 .metrics
577 .get("button_margin")
578 .map(|value| *value as f32 / 2.0),
579 ..Default::default()
580 });
581 }
582
583 mode.input.background_color = native(semantic.input_background);
584 mode.input.caret_color = native(semantic.input_text);
585 mode.input.selection_background = native(semantic.selection_background);
586 mode.input.selection_text_color = native(semantic.selection_text);
587 mode.input.disabled_text_color = native(semantic.disabled_text);
588 mode.input.focus_border_color = native(semantic.accent);
589 if let Some(control) = self.controls.get("line_edit") {
590 mode.input.min_height = Some(control.minimum_size_hint.height.max(0) as f32);
591 mode.input.font = semantic
592 .input_text
593 .map(|color| native_font(&control.font, color));
594 }
595
596 mode.checkbox.checked_background = native(semantic.accent);
597 mode.checkbox.indicator_color = native(semantic.accent_text);
598 mode.checkbox.disabled_text_color = native(semantic.disabled_text);
599 mode.checkbox.indicator_width = self
600 .metrics
601 .get("indicator_width")
602 .copied()
603 .map(|value| value as f32);
604
605 mode.menu.background_color = native(semantic.surface_background);
606 mode.menu.separator_color = native(semantic.border);
607 mode.menu.hover_background = native(semantic.selection_background);
608 mode.menu.hover_text_color = native(semantic.selection_text);
609 mode.menu.disabled_text_color = native(semantic.disabled_text);
610 mode.tooltip.background_color = native(semantic.tooltip_background);
611 if let Some(text) = semantic.tooltip_text {
612 mode.tooltip.font = Some(native_font(&self.settings.font, text));
613 }
614
615 mode.scrollbar.track_color = native(semantic.window_background);
616 mode.scrollbar.thumb_color = native(semantic.border.or(semantic.disabled_text));
617 mode.scrollbar.thumb_hover_color = native(semantic.accent);
618 mode.scrollbar.groove_width = self
619 .metrics
620 .get("scrollbar_extent")
621 .copied()
622 .map(|value| value as f32);
623 mode.scrollbar.min_thumb_length = self
624 .metrics
625 .get("scrollbar_slider_min")
626 .copied()
627 .map(|value| value as f32);
628 mode.scrollbar.overlay_mode = Some(false);
629
630 mode.slider.fill_color = native(semantic.accent);
631 mode.slider.track_color = native(semantic.border);
632 mode.slider.thumb_color = native(semantic.surface_background);
633 mode.slider.track_height = self
634 .metrics
635 .get("slider_control_thickness")
636 .copied()
637 .map(|value| value as f32);
638 mode.slider.thumb_diameter = self
639 .metrics
640 .get("slider_length")
641 .copied()
642 .map(|value| value as f32);
643
644 mode.progress_bar.fill_color = native(semantic.accent);
645 mode.progress_bar.track_color = native(semantic.window_background);
646 if let Some(control) = self.controls.get("progress_bar") {
647 mode.progress_bar.track_height = Some(control.size_hint.height.max(0) as f32);
648 mode.progress_bar.min_width = Some(control.minimum_size_hint.width.max(0) as f32);
649 }
650 mode.tab.background_color = native(semantic.window_background);
651 mode.tab.active_background = native(semantic.surface_background);
652 mode.tab.active_text_color = native(semantic.window_text);
653 mode.tab.bar_background = native(semantic.window_background);
654 if let Some(control) = self.controls.get("tab_bar") {
655 mode.tab.min_width = Some(control.minimum_size_hint.width.max(0) as f32);
656 mode.tab.min_height = Some(control.minimum_size_hint.height.max(0) as f32);
657 }
658 mode.separator.line_color = native(semantic.border);
659 mode.separator.line_width = mode.defaults.border.line_width;
660 mode.combo_box.background_color = native(semantic.surface_background);
661 mode.combo_box.disabled_text_color = native(semantic.disabled_text);
662 if let Some(control) = self.controls.get("combo_box") {
663 mode.combo_box.min_width = Some(control.minimum_size_hint.width.max(0) as f32);
664 mode.combo_box.min_height = Some(control.minimum_size_hint.height.max(0) as f32);
665 }
666 mode
667 }
668
669 pub fn resolve_native_theme(&self) -> Result<NativeThemeBridge, NativeThemeBridgeError> {
672 use native_theme::resolve::ResolutionContext;
673 use native_theme::theme::{ColorMode, Theme};
674
675 self.validate()?;
676 let background = self
677 .semantic_palette
678 .window_background
679 .ok_or(NativeThemeBridgeError::MissingColor("window_background"))?;
680 self.semantic_palette
681 .window_text
682 .ok_or(NativeThemeBridgeError::MissingColor("window_text"))?;
683 let mode = if relative_luminance(background) < 0.5 {
684 ColorMode::Dark
685 } else {
686 ColorMode::Light
687 };
688 let mut variant = Theme::preset("kde-breeze")?.into_variant(mode)?;
689 variant.merge(&self.to_native_theme_mode());
690 let resolved = variant.into_resolved(&ResolutionContext::from_system())?;
691 Ok(NativeThemeBridge {
692 name: format!("Qt {}", self.identity.style_name),
693 mode,
694 resolved,
695 reduce_transparency: false,
696 reduce_motion: false,
697 high_contrast: false,
698 })
699 }
700
701 #[cfg(feature = "gpui")]
703 pub fn to_gpui_theme(&self) -> Result<gpui_component::theme::Theme, NativeThemeBridgeError> {
704 Ok(self.resolve_native_theme()?.to_gpui_theme())
705 }
706}
707
708fn palette_color(palette: &PaletteSnapshot, group: &str, role: &str) -> Option<Rgba> {
709 palette.get(group)?.get(role).map(|brush| brush.color)
710}
711
712fn semantic_palette(palette: &PaletteSnapshot) -> SemanticPalette {
713 let active = |role| palette_color(palette, "active", role);
714 SemanticPalette {
715 window_background: active("window"),
716 window_text: active("window_text"),
717 surface_background: active("button"),
718 surface_text: active("button_text"),
719 input_background: active("base"),
720 input_text: active("text"),
721 selection_background: active("highlight"),
722 selection_text: active("highlighted_text"),
723 accent: active("accent").or_else(|| active("highlight")),
724 accent_text: active("highlighted_text"),
725 border: active("mid"),
726 disabled_text: palette_color(palette, "disabled", "text"),
727 tooltip_background: active("tooltip_base"),
728 tooltip_text: active("tooltip_text"),
729 link: active("link"),
730 error: None,
731 warning: None,
732 success: None,
733 }
734}
735
736#[derive(Debug, Error)]
738pub enum ProbeError {
739 #[error("Qt theme probe failed: {0}")]
741 Native(String),
742 #[error("Qt theme probe returned no data")]
744 Empty,
745 #[error("Qt theme probe returned invalid JSON: {0}")]
747 InvalidJson(#[from] serde_json::Error),
748 #[error("unsupported snapshot schema version {actual}; expected {expected}")]
750 SchemaVersion {
751 actual: u32,
753 expected: u32,
755 },
756 #[error(transparent)]
758 InvalidSnapshot(#[from] SnapshotValidationError),
759}
760
761pub fn probe() -> Result<ThemeSnapshot, ProbeError> {
768 let json = ffi::probe_theme().map_err(|error| ProbeError::Native(error.what().to_owned()))?;
769 let json = json.as_ref().ok_or(ProbeError::Empty)?.to_string_lossy();
770 let mut snapshot: ThemeSnapshot = serde_json::from_str(&json)?;
771 if snapshot.schema_version != SCHEMA_VERSION {
772 return Err(ProbeError::SchemaVersion {
773 actual: snapshot.schema_version,
774 expected: SCHEMA_VERSION,
775 });
776 }
777 snapshot.semantic_palette = semantic_palette(&snapshot.palette);
778 snapshot.validate()?;
779 Ok(snapshot)
780}
781
782#[cfg(test)]
783mod tests {
784 use super::*;
785
786 #[test]
787 fn contract_fixture_deserializes() {
788 let json = r#"{
789 "schema_version": 1,
790 "backend": "qt6",
791 "identity": {
792 "style_name": "fusion",
793 "toolkit_version": "6.2.0",
794 "platform_backend": "offscreen",
795 "platform_theme": null,
796 "style_override": null
797 },
798 "settings": {
799 "font": {"family":"Sans","point_size":10.0,"pixel_size":-1,"weight":400,"italic":false,"stretch":100},
800 "fixed_font": {"family":"Monospace","point_size":10.0,"pixel_size":-1,"weight":400,"italic":false,"stretch":100},
801 "icon_theme_name": "",
802 "cursor_flash_time_ms": 1000,
803 "double_click_interval_ms": 400,
804 "wheel_scroll_lines": 3,
805 "application_stylesheet": ""
806 },
807 "palette": {},
808 "semantic_palette": {},
809 "controls": {},
810 "metrics": {},
811 "hints": {},
812 "diagnostics": []
813 }"#;
814 let snapshot: ThemeSnapshot = serde_json::from_str(json).unwrap();
815 assert_eq!(snapshot.schema_version, SCHEMA_VERSION);
816 assert_eq!(snapshot.identity.style_name, "fusion");
817 }
818
819 #[test]
820 fn semantic_palette_maps_qt_roles() {
821 let red = Rgba {
822 red: 1.0,
823 green: 0.0,
824 blue: 0.0,
825 alpha: 1.0,
826 };
827 let mut roles = BTreeMap::new();
828 roles.insert(
829 "window".to_owned(),
830 PaletteBrush {
831 color: red,
832 brush_style: 1,
833 },
834 );
835 let palette = BTreeMap::from([("active".to_owned(), roles)]);
836 assert_eq!(semantic_palette(&palette).window_background, Some(red));
837 }
838
839 #[test]
840 fn semantic_palette_contract_has_stable_role_names() {
841 let value = serde_json::to_value(SemanticPalette::default()).unwrap();
842 let mut actual: Vec<_> = value
843 .as_object()
844 .unwrap()
845 .keys()
846 .map(String::as_str)
847 .collect();
848 let mut expected = SEMANTIC_COLOR_ROLES.to_vec();
849 actual.sort_unstable();
850 expected.sort_unstable();
851 assert_eq!(actual, expected);
852 }
853
854 #[test]
855 fn invalid_color_channels_are_rejected() {
856 let error = validate_rgba(
857 "test",
858 Rgba {
859 red: 0.0,
860 green: 1.01,
861 blue: 0.0,
862 alpha: 1.0,
863 },
864 )
865 .unwrap_err();
866 assert!(error.reason().contains("test.green"));
867 }
868
869 #[test]
870 fn incomplete_snapshot_is_rejected() {
871 let json = r#"{
872 "schema_version": 1,
873 "backend": "qt6",
874 "identity": {
875 "style_name": "fusion", "toolkit_version": "6.2.0",
876 "platform_backend": "offscreen", "platform_theme": null,
877 "style_override": null
878 },
879 "settings": {
880 "font": {"family":"Sans","point_size":10.0,"pixel_size":-1,"weight":400,"italic":false,"stretch":100},
881 "fixed_font": {"family":"Mono","point_size":10.0,"pixel_size":-1,"weight":400,"italic":false,"stretch":100},
882 "icon_theme_name":"", "cursor_flash_time_ms":1000,
883 "double_click_interval_ms":400, "wheel_scroll_lines":3,
884 "application_stylesheet":""
885 },
886 "palette": {}, "semantic_palette": {}, "controls": {},
887 "metrics": {}, "hints": {}, "diagnostics": []
888 }"#;
889 let snapshot: ThemeSnapshot = serde_json::from_str(json).unwrap();
890 assert!(
891 snapshot
892 .validate()
893 .unwrap_err()
894 .reason()
895 .contains("missing color group")
896 );
897 }
898}