Skip to main content

native_theme/kde/
mod.rs

1//! KDE theme reader (the `kde` feature, Linux): maps the kdeglobals INI files to a Theme.
2//!
3//! # Sources
4//!
5//! The files the reader reads that the user's settings write, each a path in
6//! the user's config directory (`$XDG_CONFIG_HOME`, else `~/.config`); the
7//! watcher observes each of them:
8//!
9//! - `kdeglobals`: the colours, fonts, icon theme, accessibility flags and caret blink rate.
10//! - `kdedefaults/kdeglobals`: the defaults Plasma keeps beneath the user's
11//!   file, read under it as KConfig cascades them.
12//! - `org.freedesktop.appearance accent-color`: the portal's accent colour,
13//!   with the `portal` feature, which lays it over the kdeglobals theme's
14//!   accent, selection and focus-ring colours where the portal gives one:
15//!   xdg-desktop-portal-kde gives the application palette's highlight
16//!   colour (`src/settings.cpp:279-283` at v6.7.5), which the colour scheme
17//!   in kdeglobals sets.
18//!
19//! # Sources not watched
20//!
21//! - `$XDG_CONFIG_DIRS/kdeglobals` (`/etc/xdg/kdeglobals`): the system's
22//!   files, which the distribution or an administrator writes, not the user's
23//!   settings.
24//! - The icon theme's `index.theme`: its sizes, which the icon theme's
25//!   package writes.
26
27/// KDE color group parsing and mapping.
28pub(crate) mod colors;
29/// Qt font string parsing with weight extraction.
30pub(crate) mod fonts;
31/// `KColorUtils::tint`: the clean-room function of `v0.8.0-rc1`, carried with
32/// its own notice.
33mod kcu_tint;
34/// The arithmetic the clean-room KDE colour functions share: Qt's colour
35/// storage, KDE's HCY space and `KColorUtils`' mix, tint and shade.
36#[allow(
37    dead_code,
38    reason = "carried as the clean room wrote it, for its functions that are not carried (kcu_mix, kcu_shade, kde_effects); kcu_tint uses part of it"
39)]
40mod kde_color_common;
41/// KColorScheme's shades of a colour, in Qt's arithmetic: the clean-room
42/// function of `v0.8.0-rc1`, carried with its vector test (its own notice).
43#[cfg_attr(
44    not(test),
45    allow(
46        dead_code,
47        reason = "the reader takes the Mid shade alone; the module is carried as the clean room wrote it, and its test builds every role"
48    )
49)]
50mod shade;
51#[cfg(test)]
52mod vector_tests;
53
54use crate::Rgba;
55use crate::model::IconSizes;
56
57/// Parse KDE kdeglobals content into a Theme without any I/O.
58///
59/// This function is intentionally `pub` (not `pub(crate)`) because integration tests
60/// in `tests/reader_kde.rs` import it from outside the crate.
61///
62/// `font_dpi` is returned as given: kdeglobals holds no font DPI
63/// (`forceFontDPI` lives in kcmfonts, `docs/platform-facts.md:717`).
64/// Icon sizes are NOT populated (requires filesystem access).
65#[doc(hidden)]
66pub fn from_kde_content_pure(
67    content: &str,
68    font_dpi: Option<f32>,
69) -> crate::Result<(crate::Theme, Option<f32>, crate::AccessibilityPreferences)> {
70    let mut ini = create_kde_parser();
71    read_kconfig(&mut ini, content);
72    let (mode, is_dark, name, accessibility) = read_kde_ini(&ini);
73    let output = crate::ReaderOutput::Single {
74        mode: Box::new(mode),
75        is_dark,
76    };
77    let theme = output.to_theme(&name, None, &crate::LayoutTheme::default());
78    Ok((theme, font_dpi, accessibility))
79}
80
81/// The variant, its darkness, the scheme name and the accessibility flags
82/// kdeglobals states, without any I/O: per-widget colors, fonts with Qt5/Qt6
83/// weight conversion, the icon theme and Breeze widget sizing constants.
84fn read_kde_ini(
85    ini: &configparser::ini::Ini,
86) -> (
87    crate::ThemeMode,
88    bool,
89    String,
90    crate::AccessibilityPreferences,
91) {
92    let mut variant = crate::ThemeMode::default();
93
94    // Populate colors, fonts, and widget sizing on the variant
95    colors::populate_colors(ini, &mut variant);
96    fonts::populate_fonts(ini, &mut variant);
97    crate::kde_metrics::populate_widget_sizing(&mut variant);
98
99    // KDE-05: Icon theme name from [Icons] Theme (per-variant)
100    variant.defaults.icon_theme = icon_theme(ini).map(std::borrow::Cow::Owned);
101
102    caret_blink(ini, &mut variant.input);
103
104    // KDE-06: Accessibility flags (pure -- no I/O)
105    let accessibility = crate::AccessibilityPreferences {
106        reduce_motion: reduce_motion(ini),
107        ..Default::default()
108    };
109
110    let name = ini
111        .get("General", "ColorScheme")
112        .unwrap_or_else(|| "KDE".to_string());
113
114    (variant, is_dark_theme(ini), name, accessibility)
115}
116
117/// The KDE reader's result for the kdeglobals in `ini`: [`read_kde_ini`],
118/// with the icon theme's sizes read from the system and the font DPI of every Linux desktop, 96.
119fn from_kde_ini(ini: &configparser::ini::Ini) -> crate::ReaderResult {
120    let (mut mode, is_dark, name, accessibility) = read_kde_ini(ini);
121
122    // I/O: icon sizes from filesystem (icon_theme is on variant defaults)
123    if let Some(ref theme_name) = mode.defaults.icon_theme {
124        mode.defaults.icon_sizes = parse_icon_sizes_from_index_theme(theme_name);
125    }
126
127    crate::ReaderResult {
128        output: crate::ReaderOutput::Single {
129            mode: Box::new(mode),
130            is_dark,
131        },
132        name: std::borrow::Cow::Owned(name),
133        icon_set: None,
134        layout: crate::LayoutTheme::default(),
135        // No I/O: the font DPI is a constant (detect::LINUX_FONT_DPI)
136        font_dpi: Some(crate::detect::LINUX_FONT_DPI),
137        accessibility,
138    }
139}
140
141/// [`from_kde_ini`] over one kdeglobals file's `content`.
142#[cfg(test)]
143pub(crate) fn from_kde_content(content: &str) -> crate::Result<crate::ReaderResult> {
144    let mut ini = create_kde_parser();
145    read_kconfig(&mut ini, content);
146    Ok(from_kde_ini(&ini))
147}
148
149/// Parse icon sizes from an icon theme's index.theme already loaded into a
150/// parser: the `[Icon Theme]` group's `<Group>Default` keys, which KIconTheme
151/// reads as each KIconLoader group's default size (kiconthemes
152/// `src/kicontheme.cpp:468-473` at v6.31.0), mapped as
153/// `docs/platform-facts.md` §2.1.8 maps the groups:
154/// - `small`: `SmallDefault`
155/// - `toolbar`: `MainToolbarDefault`
156/// - `large`: `DesktopDefault`
157/// - `dialog`: `DialogDefault`
158/// - `panel`: `PanelDefault`
159///
160/// A key the theme omits, or one that is not a size, has KIconTheme's own
161/// fallback for the group ([`KICONTHEME_DEFAULT_SIZES`]), as KConfig returns
162/// the default for a missing key or one it cannot convert. That fallback is
163/// KDE's, not the preset's, and can differ from it: a theme without
164/// `DesktopDefault` is drawn at 32 where Breeze states 48.
165pub(crate) fn parse_icon_sizes_from_content(ini: &configparser::ini::Ini) -> IconSizes {
166    let [small, toolbar, large, dialog, panel] = KICONTHEME_DEFAULT_SIZES.map(|(key, fallback)| {
167        Some(
168            ini.get("Icon Theme", key)
169                .and_then(|s| s.trim().parse::<u32>().ok())
170                .map_or(fallback, |sz| sz as f32),
171        )
172    });
173    IconSizes {
174        small,
175        toolbar,
176        large,
177        dialog,
178        panel,
179    }
180}
181
182/// The `[Icon Theme]` key of each size [`parse_icon_sizes_from_content`]
183/// reads (`small`, `toolbar`, `large`, `dialog`, `panel`, in that order) and
184/// KIconTheme's fallback for its group: `Small` 16, `MainToolbar` 22,
185/// `Desktop` 32, `Dialog` 32, `Panel` 48 (kiconthemes `src/kicontheme.cpp:160-167`
186/// at v6.31.0), the size it keeps when `readEntry` finds no key
187/// (kconfig `src/core/kconfiggroup.cpp:690-693` at v6.31.0) or cannot
188/// convert the value (:256-269).
189const KICONTHEME_DEFAULT_SIZES: [(&str, f32); 5] = [
190    ("SmallDefault", 16.0),
191    ("MainToolbarDefault", 22.0),
192    ("DesktopDefault", 32.0),
193    ("DialogDefault", 32.0),
194    ("PanelDefault", 48.0),
195];
196
197/// Parse icon sizes from the active icon theme's index.theme file
198/// ([`parse_icon_sizes_from_content`]), found where KIconTheme finds it
199/// ([`kde_icon_base_dirs`]).
200///
201/// Returns `IconSizes::default()` (all None) if no index.theme is found or
202/// the file cannot be read.
203pub(crate) fn parse_icon_sizes_from_index_theme(theme_name: &str) -> IconSizes {
204    let bases = kde_icon_base_dirs(
205        std::env::home_dir().as_deref(),
206        std::env::var_os("XDG_DATA_HOME").as_deref(),
207        std::env::var_os("XDG_DATA_DIRS").as_deref(),
208    );
209    icon_sizes_in_bases(theme_name, &bases)
210}
211
212/// The icon base directories KIconTheme searches for a theme's index.theme,
213/// in its order: `QStandardPaths::locateAll(GenericDataLocation, "icons")`
214/// (kiconthemes `src/kicontheme.cpp:382` at v6.31.0, the first holding the
215/// theme's index.theme winning, :395-405), which is the data home
216/// (`$XDG_DATA_HOME`, `data_home`), then each data dir (`$XDG_DATA_DIRS`,
217/// `data_dirs`; qtbase `src/corelib/io/qstandardpaths_unix.cpp:452` at
218/// v6.11.2), each joined with `icons`. `~/.icons`, which the freedesktop icon
219/// lookup also searches ([`crate::icons::icon_base_dirs`]) and KIconTheme
220/// does not, comes last. Without a home directory the data dirs are still
221/// searched.
222fn kde_icon_base_dirs(
223    home: Option<&std::path::Path>,
224    data_home: Option<&std::ffi::OsStr>,
225    data_dirs: Option<&std::ffi::OsStr>,
226) -> Vec<std::path::PathBuf> {
227    crate::icons::xdg_data_home(data_home, home)
228        .into_iter()
229        .chain(crate::icons::xdg_data_dirs(data_dirs))
230        .map(|dir| dir.join("icons"))
231        .chain(home.map(|home| home.join(".icons")))
232        .collect()
233}
234
235/// [`parse_icon_sizes_from_index_theme`] over the icon base directories
236/// `bases`: the first `<base>/<theme_name>/index.theme` in their order, for a
237/// `theme_name` that names a theme directory ([`crate::icons::is_theme_name`]).
238fn icon_sizes_in_bases(theme_name: &str, bases: &[std::path::PathBuf]) -> IconSizes {
239    if !crate::icons::is_theme_name(theme_name) {
240        return IconSizes::default();
241    }
242    let Some(bytes) = bases
243        .iter()
244        .find_map(|base| std::fs::read(base.join(theme_name).join("index.theme")).ok())
245    else {
246        return IconSizes::default();
247    };
248    let mut ini = create_kde_parser();
249    read_kconfig(&mut ini, &String::from_utf8_lossy(&bytes));
250    parse_icon_sizes_from_content(&ini)
251}
252
253/// Read the current KDE theme from kdeglobals.
254///
255/// Reads kdeglobals as KConfig cascades it ([`read_kdeglobals`]; no file at
256/// all reads as an empty one) and maps KDE color groups and font strings to
257/// a [`ReaderResult`](crate::ReaderResult).
258///
259/// Internal reader dispatched through the [`crate::reader::ThemeReader`] trait
260/// by [`crate::pipeline::select_reader`]; external consumers should use
261/// [`SystemTheme::from_system()`](crate::SystemTheme::from_system).
262pub(crate) struct KdeReader;
263
264#[async_trait::async_trait]
265impl crate::reader::ThemeReader for KdeReader {
266    async fn read(&self) -> crate::Result<crate::ReaderResult> {
267        Ok(from_kde_ini(
268            &read_kdeglobals().unwrap_or_else(create_kde_parser),
269        ))
270    }
271}
272
273/// kdeglobals as KConfig reads it: the files of [`kdeglobals_files`] layered
274/// in order ([`read_kconfig_files`]); `None` when none of them can be read.
275pub(crate) fn read_kdeglobals() -> Option<configparser::ini::Ini> {
276    read_kconfig_files(&kdeglobals_files())
277}
278
279/// Whether `ini` asks for reduced motion: `[KDE] AnimationDurationFactor`
280/// is 0.
281fn reduce_motion(ini: &configparser::ini::Ini) -> bool {
282    ini.get("KDE", "AnimationDurationFactor")
283        .and_then(|value| value.trim().parse::<f32>().ok())
284        == Some(0.0)
285}
286
287/// [`reduce_motion`] of kdeglobals ([`read_kdeglobals`]), as the KDE reader
288/// reads it, for [`crate::detect::detect_reduced_motion`].
289pub(crate) fn kdeglobals_reduce_motion() -> bool {
290    reduce_motion(&read_kdeglobals().unwrap_or_else(create_kde_parser))
291}
292
293/// The caret's blink `ini` states: `[KDE] CursorBlinkRate`, the cycle in
294/// milliseconds, read as an `i32`. A rate above 0 is bounded to 200..=2000
295/// (plasma-integration 6.8.2 `qt6/src/platformtheme/khintssettings.cpp:79-80`)
296/// and halved, the caret shown and hidden half the cycle each (qtbase 6.12.0
297/// `src/widgets/widgets/qwidgetlinecontrol.cpp:1497-1509`), so both
298/// durations are 100 to 1000; a rate of 0 or less states a caret that does
299/// not blink (`caret_blink_off` 0 alone). Text that is not an `i32`, or no
300/// key, states nothing, and the preset's 500 / 500 applies, which is Qt's at
301/// the unset rate's default of 1000. Qt's caret never stops blinking: no
302/// time-out is written.
303fn caret_blink(ini: &configparser::ini::Ini, input: &mut crate::model::InputTheme) {
304    let Some(rate) = ini
305        .get("KDE", "CursorBlinkRate")
306        .and_then(|value| value.trim().parse::<i32>().ok())
307    else {
308        return;
309    };
310    if rate > 0 {
311        let half = u32::try_from(rate.clamp(200, 2000))
312            .ok()
313            .and_then(|cycle| cycle.checked_div(2));
314        input.caret_blink_on = half;
315        input.caret_blink_off = half;
316    } else {
317        input.caret_blink_off = Some(0);
318    }
319}
320
321/// The icon theme `ini` names: `[Icons] Theme`, `None` where it is absent or
322/// empty.
323fn icon_theme(ini: &configparser::ini::Ini) -> Option<String> {
324    ini.get("Icons", "Theme").filter(|s| !s.is_empty())
325}
326
327/// The icon theme of kdeglobals ([`read_kdeglobals`]), the one the KDE
328/// reader states, for `detect`'s icon-theme detection; the error says why
329/// there is none.
330pub(crate) fn kdeglobals_icon_theme() -> Result<String, String> {
331    kconfig_files_icon_theme(&kdeglobals_files())
332}
333
334/// [`icon_theme`] of the KConfig files `files` layered
335/// ([`read_kconfig_files`]); the error names the files.
336fn kconfig_files_icon_theme(files: &[std::path::PathBuf]) -> Result<String, String> {
337    let listed = || {
338        files
339            .iter()
340            .map(|file| file.display().to_string())
341            .collect::<Vec<_>>()
342            .join(", ")
343    };
344    let ini =
345        read_kconfig_files(files).ok_or_else(|| format!("no file is readable: {}", listed()))?;
346    icon_theme(&ini).ok_or_else(|| format!("`[Icons] Theme` is absent or empty in {}", listed()))
347}
348
349/// Whether kdeglobals ([`read_kdeglobals`]) states a dark theme
350/// ([`window_background_is_dark`]); `None` when no kdeglobals file states a
351/// window background.
352pub(crate) fn kdeglobals_is_dark() -> Option<bool> {
353    kconfig_files_are_dark(&kdeglobals_files())
354}
355
356/// [`window_background_is_dark`] over the KConfig files `files` layered
357/// ([`read_kconfig_files`]).
358fn kconfig_files_are_dark(files: &[std::path::PathBuf]) -> Option<bool> {
359    read_kconfig_files(files)
360        .as_ref()
361        .and_then(window_background_is_dark)
362}
363
364/// The kdeglobals files KConfig reads, lowest priority first
365/// ([`kdeglobals_files_pure`] for `$XDG_CONFIG_DIRS` and [`kdeglobals_path`]).
366fn kdeglobals_files() -> Vec<std::path::PathBuf> {
367    kdeglobals_files_pure(
368        std::env::var("XDG_CONFIG_DIRS").ok().as_deref(),
369        kdeglobals_path(),
370    )
371}
372
373/// `kdeglobals` in each of `config_dirs` (`$XDG_CONFIG_DIRS`), last first,
374/// then the user's `user_file`, which is `None` without a config directory.
375///
376/// KConfig reads every `kdeglobals` `QStandardPaths::locateAll` finds, in
377/// reverse, so the user's file comes last and wins (kconfig
378/// `src/core/kconfig.cpp:740`, `:761-766` at a4e32e9d). The config dirs are
379/// `$XDG_CONFIG_DIRS`'s absolute entries without duplicates, `/etc/xdg` when
380/// none is left (qtbase `src/corelib/io/qstandardpaths_unix.cpp:370-389`,
381/// `:403-413` at 512d45ad). Plasma puts `kdedefaults` beside the user's file
382/// first in `$XDG_CONFIG_DIRS` (plasma-workspace
383/// `startkde/startplasma.cpp:419-426` at 8bd4f86a); it is added there when
384/// `config_dirs` lacks it, for a process started outside Plasma's session;
385/// without a `user_file` there is no `kdedefaults` either.
386fn kdeglobals_files_pure(
387    config_dirs: Option<&str>,
388    user_file: Option<std::path::PathBuf>,
389) -> Vec<std::path::PathBuf> {
390    let mut dirs: Vec<std::path::PathBuf> = Vec::new();
391    for dir in config_dirs
392        .unwrap_or_default()
393        .split(':')
394        .filter(|dir| dir.starts_with('/'))
395    {
396        let dir = std::path::PathBuf::from(dir);
397        if !dirs.contains(&dir) {
398            dirs.push(dir);
399        }
400    }
401    if dirs.is_empty() {
402        dirs.push(std::path::PathBuf::from("/etc/xdg"));
403    }
404    if let Some(defaults) = user_file
405        .as_deref()
406        .and_then(std::path::Path::parent)
407        .map(|dir| dir.join("kdedefaults"))
408        && !dirs.contains(&defaults)
409    {
410        dirs.insert(0, defaults);
411    }
412    let mut files: Vec<std::path::PathBuf> = dirs
413        .iter()
414        .rev()
415        .map(|dir| dir.join("kdeglobals"))
416        .collect();
417    if let Some(user_file) = user_file
418        && !files.contains(&user_file)
419    {
420        files.push(user_file);
421    }
422    files
423}
424
425/// The KConfig files `files` layered in order, later files overriding
426/// earlier keys ([`read_kconfig`]). A file that cannot be read is skipped,
427/// and its bytes are decoded lossily; `None` when no file can be read.
428fn read_kconfig_files(files: &[std::path::PathBuf]) -> Option<configparser::ini::Ini> {
429    let mut ini = create_kde_parser();
430    let mut any = false;
431    for bytes in files.iter().filter_map(|path| std::fs::read(path).ok()) {
432        read_kconfig(&mut ini, &String::from_utf8_lossy(&bytes));
433        any = true;
434    }
435    any.then_some(ini)
436}
437
438/// Parse KConfig `content` into `ini`, over the keys it already holds.
439///
440/// The lines KConfig skips are skipped (kconfig `src/core/kconfigini.cpp` at
441/// a4e32e9d): a group header without `]` (`:100-112`, the group before it
442/// stays current) and an entry with an empty key (`:168-171`). They are the
443/// only lines configparser rejects, so one stray line no longer loses the
444/// whole file.
445fn read_kconfig(ini: &mut configparser::ini::Ini, content: &str) {
446    let valid: String = content
447        .lines()
448        .filter(|line| {
449            let line = line.trim();
450            !(line.starts_with('[') && !line.contains(']')) && !line.starts_with('=')
451        })
452        .flat_map(|line| [line, "\n"])
453        .collect();
454    // Cannot fail: the filter above drops every line configparser rejects.
455    let _ = ini.read_and_append(valid);
456}
457
458/// Create a configparser Ini instance configured for KDE files.
459///
460/// Uses case-sensitive mode and equals-only delimiter to correctly
461/// handle KDE's PascalCase keys and colon-containing section names.
462/// Only a line starting with `#` is a comment, as in KConfig (kconfig
463/// `src/core/kconfigini.cpp:95-98` at a4e32e9d): a `#` or `;` inside a value,
464/// as in `ColorScheme=My#Scheme`, is part of it.
465pub(crate) fn create_kde_parser() -> configparser::ini::Ini {
466    let tmp = configparser::ini::Ini::new_cs();
467    let mut defaults = tmp.defaults();
468    defaults.delimiters = vec!['='];
469    defaults.comment_symbols = vec!['#'];
470    defaults.enable_inline_comments = false;
471    configparser::ini::Ini::new_from_defaults(defaults)
472}
473
474/// Parse a KDE "R,G,B" color string into an Rgba (opaque).
475///
476/// Returns None for malformed values (never panics).
477/// Exactly 3 comma-separated u8 components required.
478pub(crate) fn parse_rgb(value: &str) -> Option<Rgba> {
479    let parts: Vec<&str> = value.split(',').collect();
480    let [r_s, g_s, b_s] = parts.as_slice() else {
481        return None;
482    };
483    let r = r_s.trim().parse::<u8>().ok()?;
484    let g = g_s.trim().parse::<u8>().ok()?;
485    let b = b_s.trim().parse::<u8>().ok()?;
486    Some(Rgba::rgb(r, g, b))
487}
488
489/// The user's kdeglobals file, in the user's config directory
490/// ([`crate::detect::xdg_config_home`]); `None` without one.
491pub(crate) fn kdeglobals_path() -> Option<std::path::PathBuf> {
492    crate::detect::xdg_config_home().map(|dir| dir.join("kdeglobals"))
493}
494
495/// Detect whether the active KDE theme is dark based on background luminance.
496///
497/// [`window_background_is_dark`], false (light) if the section/key is
498/// missing or does not parse.
499pub(crate) fn is_dark_theme(ini: &configparser::ini::Ini) -> bool {
500    window_background_is_dark(ini).unwrap_or(false)
501}
502
503/// Whether Colors:Window/BackgroundNormal is dark, by its BT.601 luminance;
504/// `None` if the section/key is missing or does not parse.
505fn window_background_is_dark(ini: &configparser::ini::Ini) -> Option<bool> {
506    let bg = parse_rgb(&ini.get("Colors:Window", "BackgroundNormal")?)?;
507    let luma = 0.299 * (bg.r as f32) + 0.587 * (bg.g as f32) + 0.114 * (bg.b as f32);
508    Some(luma < 128.0)
509}
510
511#[cfg(test)]
512#[allow(clippy::unwrap_used, clippy::expect_used)]
513mod tests {
514    use super::*;
515    use crate::Rgba;
516    use crate::model::font::FontSize;
517
518    // === parse_rgb tests ===
519
520    #[test]
521    fn parse_rgb_valid_breeze_accent() {
522        assert_eq!(parse_rgb("61,174,233"), Some(Rgba::rgb(61, 174, 233)));
523    }
524
525    #[test]
526    fn parse_rgb_handles_whitespace() {
527        assert_eq!(parse_rgb("0, 0, 0"), Some(Rgba::rgb(0, 0, 0)));
528    }
529
530    #[test]
531    fn parse_rgb_white() {
532        assert_eq!(parse_rgb("255,255,255"), Some(Rgba::rgb(255, 255, 255)));
533    }
534
535    #[test]
536    fn parse_rgb_invalid_text() {
537        assert_eq!(parse_rgb("invalid"), None);
538    }
539
540    #[test]
541    fn parse_rgb_too_few_components() {
542        assert_eq!(parse_rgb("1,2"), None);
543    }
544
545    #[test]
546    fn parse_rgb_too_many_components() {
547        assert_eq!(parse_rgb("1,2,3,4"), None);
548    }
549
550    #[test]
551    fn parse_rgb_out_of_u8_range() {
552        assert_eq!(parse_rgb("256,0,0"), None);
553    }
554
555    #[test]
556    fn parse_rgb_empty_string() {
557        assert_eq!(parse_rgb(""), None);
558    }
559
560    // === is_dark_theme tests ===
561
562    #[test]
563    fn is_dark_theme_detects_breeze_dark() {
564        let mut ini = create_kde_parser();
565        ini.read("[Colors:Window]\nBackgroundNormal=20,22,24\n".to_string())
566            .unwrap();
567        assert!(is_dark_theme(&ini));
568    }
569
570    #[test]
571    fn is_dark_theme_detects_breeze_light() {
572        let mut ini = create_kde_parser();
573        ini.read("[Colors:Window]\nBackgroundNormal=239,240,241\n".to_string())
574            .unwrap();
575        assert!(!is_dark_theme(&ini));
576    }
577
578    #[test]
579    fn is_dark_theme_defaults_false_when_missing() {
580        let ini = create_kde_parser();
581        assert!(!is_dark_theme(&ini));
582    }
583
584    // === create_kde_parser tests ===
585
586    #[test]
587    fn create_kde_parser_is_case_sensitive() {
588        let mut ini = create_kde_parser();
589        ini.read("[Colors:View]\nBackgroundNormal=255,255,255\n".to_string())
590            .unwrap();
591        assert!(ini.get("Colors:View", "BackgroundNormal").is_some());
592    }
593
594    #[test]
595    fn create_kde_parser_preserves_section_colons() {
596        let mut ini = create_kde_parser();
597        ini.read("[Colors:Window]\nForegroundNormal=0,0,0\n".to_string())
598            .unwrap();
599        assert!(ini.get("Colors:Window", "ForegroundNormal").is_some());
600    }
601
602    #[test]
603    fn create_kde_parser_equals_only_delimiter() {
604        let mut ini = create_kde_parser();
605        ini.read("[Test]\nsome:value=actual\n".to_string()).unwrap();
606        assert_eq!(ini.get("Test", "some:value"), Some("actual".to_string()));
607    }
608
609    // === from_kde_content / from_kde integration tests ===
610
611    /// Full Breeze Dark kdeglobals fixture with all sections including
612    /// KDE-01 through KDE-06 fields.
613    const BREEZE_DARK_FULL: &str = "\
614[General]
615ColorScheme=BreezeDark
616font=Noto Sans,10,-1,5,400,0,0,0,0,0,0,0,0,0,0,1
617fixed=Hack,10,-1,5,400,0,0,0,0,0,0,0,0,0,0,1
618menuFont=Noto Sans,9,-1,5,400,0,0,0,0,0,0,0,0,0,0,1
619toolBarFont=Noto Sans,8,-1,5,400,0,0,0,0,0,0,0,0,0,0,1
620smallestReadableFont=Noto Sans,7,-1,5,400,0,0,0,0,0,0,0,0,0,0,1
621forceFontDPI=120
622
623[KDE]
624AnimationDurationFactor=0
625
626[Icons]
627Theme=breeze-dark
628
629[Colors:View]
630BackgroundNormal=35,38,41
631BackgroundAlternate=30,33,36
632ForegroundNormal=252,252,252
633ForegroundInactive=161,169,177
634ForegroundActive=61,174,233
635ForegroundLink=29,153,243
636ForegroundNegative=218,68,83
637ForegroundNeutral=246,116,0
638ForegroundPositive=39,174,96
639ForegroundVisited=155,89,182
640DecorationFocus=61,174,233
641DecorationHover=29,153,243
642
643[Colors:Window]
644BackgroundNormal=49,54,59
645BackgroundAlternate=44,49,54
646ForegroundNormal=239,240,241
647ForegroundInactive=161,169,177
648ForegroundActive=61,174,233
649ForegroundLink=29,153,243
650ForegroundNegative=218,68,83
651ForegroundNeutral=246,116,0
652ForegroundPositive=39,174,96
653DecorationFocus=61,174,233
654DecorationHover=29,153,243
655
656[Colors:Button]
657BackgroundNormal=49,54,59
658BackgroundAlternate=44,49,54
659ForegroundNormal=239,240,241
660ForegroundInactive=161,169,177
661
662[Colors:Selection]
663BackgroundNormal=61,174,233
664BackgroundAlternate=29,153,243
665ForegroundNormal=252,252,252
666ForegroundInactive=161,169,177
667
668[Colors:Tooltip]
669BackgroundNormal=49,54,59
670ForegroundNormal=252,252,252
671
672[Colors:Complementary]
673BackgroundNormal=42,46,50
674ForegroundNormal=239,240,241
675
676[Colors:Header]
677BackgroundNormal=35,38,41
678ForegroundNormal=252,252,252
679
680[WM]
681activeBackground=49,54,59
682activeForeground=239,240,241
683inactiveBackground=42,46,50
684inactiveForeground=161,169,177
685activeFont=Noto Sans,10,-1,5,75,0,0,0,0,0
686";
687
688    /// Light theme fixture with light background colors.
689    const BREEZE_LIGHT_FULL: &str = "\
690[General]
691ColorScheme=BreezeLight
692
693[Colors:View]
694BackgroundNormal=255,255,255
695ForegroundNormal=35,38,41
696DecorationFocus=61,174,233
697
698[Colors:Window]
699BackgroundNormal=239,240,241
700ForegroundNormal=35,38,41
701ForegroundInactive=127,140,141
702DecorationFocus=61,174,233
703
704[Colors:Button]
705BackgroundNormal=239,240,241
706ForegroundNormal=35,38,41
707
708[Colors:Selection]
709BackgroundNormal=61,174,233
710ForegroundNormal=255,255,255
711
712[Colors:Tooltip]
713BackgroundNormal=247,247,247
714ForegroundNormal=35,38,41
715";
716
717    /// Minimal fixture -- only Colors:Window section.
718    const MINIMAL_FIXTURE: &str = "\
719[Colors:Window]
720BackgroundNormal=49,54,59
721";
722
723    /// Helper: extract ThemeMode from a ReaderResult for test assertions.
724    fn reader_mode(result: &crate::ReaderResult) -> &crate::ThemeMode {
725        match &result.output {
726            crate::ReaderOutput::Single { mode, .. } => mode,
727            crate::ReaderOutput::Dual { light, .. } => light,
728        }
729    }
730
731    #[test]
732    fn test_dark_theme_detection() {
733        let result = from_kde_content(BREEZE_DARK_FULL).unwrap();
734        assert!(
735            matches!(
736                result.output,
737                crate::ReaderOutput::Single { is_dark: true, .. }
738            ),
739            "dark variant should be populated"
740        );
741    }
742
743    #[test]
744    fn test_light_theme_detection() {
745        let result = from_kde_content(BREEZE_LIGHT_FULL).unwrap();
746        assert!(
747            matches!(
748                result.output,
749                crate::ReaderOutput::Single { is_dark: false, .. }
750            ),
751            "light variant should be populated"
752        );
753    }
754
755    #[test]
756    fn test_theme_name_from_colorscheme() {
757        let result = from_kde_content(BREEZE_DARK_FULL).unwrap();
758        assert_eq!(result.name, "BreezeDark");
759    }
760
761    #[test]
762    fn test_theme_name_fallback() {
763        let content = "[Colors:Window]\nBackgroundNormal=49,54,59\n";
764        let result = from_kde_content(content).unwrap();
765        assert_eq!(result.name, "KDE");
766    }
767
768    #[test]
769    fn test_colors_populated() {
770        let result = from_kde_content(BREEZE_DARK_FULL).unwrap();
771        let variant = reader_mode(&result);
772        assert!(variant.defaults.accent_color.is_some());
773        assert!(variant.defaults.background_color.is_some());
774        assert!(variant.defaults.text_color.is_some());
775    }
776
777    #[test]
778    fn test_fonts_populated() {
779        let result = from_kde_content(BREEZE_DARK_FULL).unwrap();
780        let variant = reader_mode(&result);
781        assert_eq!(variant.defaults.font.family.as_deref(), Some("Noto Sans"));
782        assert_eq!(variant.defaults.font.size, Some(FontSize::Pt(10.0)));
783        assert_eq!(variant.defaults.mono_font.family.as_deref(), Some("Hack"));
784        assert_eq!(variant.defaults.mono_font.size, Some(FontSize::Pt(10.0)));
785    }
786
787    #[test]
788    fn test_minimal_fixture_no_panic() {
789        let result = from_kde_content(MINIMAL_FIXTURE);
790        assert!(
791            result.is_ok(),
792            "minimal fixture should not panic: {result:?}"
793        );
794        let r = result.unwrap();
795        assert!(matches!(
796            r.output,
797            crate::ReaderOutput::Single { is_dark: true, .. }
798        ));
799    }
800
801    #[test]
802    fn test_from_kde_content_populates_widget_sizing() {
803        let result = from_kde_content(BREEZE_DARK_FULL).unwrap();
804        let variant = reader_mode(&result);
805        assert_eq!(variant.button.min_width, Some(82.0), "Button_MinWidth");
806        assert_eq!(
807            variant.scrollbar.groove_width,
808            Some(21.0),
809            "ScrollBar_Extend"
810        );
811    }
812
813    #[test]
814    fn test_empty_content() {
815        let result = from_kde_content("");
816        assert!(
817            result.is_ok(),
818            "empty content should produce Ok: {result:?}"
819        );
820        let r = result.unwrap();
821        assert_eq!(r.name, "KDE");
822    }
823
824    // === KConfig parsing ===
825
826    /// KConfig skips a group header without `]` and keeps the group before
827    /// it; the rest of the file is still read.
828    #[test]
829    fn a_stray_group_line_is_skipped() -> crate::Result<()> {
830        let result = from_kde_content(
831            "[Colors:Window\nBackgroundNormal=49,54,59\n\n[General]\nColorScheme=BreezeDark\n",
832        )?;
833        assert_eq!(result.name, "BreezeDark");
834        Ok(())
835    }
836
837    /// KConfig skips an entry with an empty key.
838    #[test]
839    fn a_line_with_an_empty_key_is_skipped() -> crate::Result<()> {
840        let result = from_kde_content("[General]\n=stray\nColorScheme=BreezeDark\n")?;
841        assert_eq!(result.name, "BreezeDark");
842        Ok(())
843    }
844
845    /// KConfig has no inline comments: a `#` in a value is part of it.
846    #[test]
847    fn a_hash_in_a_value_is_kept() -> crate::Result<()> {
848        let result = from_kde_content("[General]\nColorScheme=My#Scheme\n")?;
849        assert_eq!(result.name, "My#Scheme");
850        Ok(())
851    }
852
853    // === KConfig cascade ===
854
855    /// A fresh directory for one test's kdeglobals files, removed on drop.
856    struct TempConfigDir(std::path::PathBuf);
857
858    impl std::ops::Deref for TempConfigDir {
859        type Target = std::path::Path;
860
861        fn deref(&self) -> &std::path::Path {
862            &self.0
863        }
864    }
865
866    impl Drop for TempConfigDir {
867        fn drop(&mut self) {
868            let _ = std::fs::remove_dir_all(&self.0);
869        }
870    }
871
872    fn temp_config_dir(tag: &str) -> TempConfigDir {
873        let dir = std::env::temp_dir().join(format!(
874            "native-theme-kdeglobals-{}-{tag}",
875            std::process::id()
876        ));
877        let _ = std::fs::remove_dir_all(&dir);
878        std::fs::create_dir_all(dir.join("kdedefaults")).unwrap();
879        TempConfigDir(dir)
880    }
881
882    fn paths(paths: &[&str]) -> Vec<std::path::PathBuf> {
883        paths.iter().map(std::path::PathBuf::from).collect()
884    }
885
886    #[test]
887    fn kdeglobals_files_follow_plasmas_config_dirs() {
888        let files = kdeglobals_files_pure(
889            Some("/home/u/.config/kdedefaults:/etc/xdg"),
890            Some("/home/u/.config/kdeglobals".into()),
891        );
892        assert_eq!(
893            files,
894            paths(&[
895                "/etc/xdg/kdeglobals",
896                "/home/u/.config/kdedefaults/kdeglobals",
897                "/home/u/.config/kdeglobals",
898            ])
899        );
900    }
901
902    /// Without `$XDG_CONFIG_DIRS`, or with only relative entries, the config
903    /// dirs are `/etc/xdg`, and `kdedefaults` is read as Plasma adds it.
904    #[test]
905    fn kdeglobals_files_default_to_etc_xdg_and_kdedefaults() {
906        let expected = paths(&[
907            "/etc/xdg/kdeglobals",
908            "/home/u/.config/kdedefaults/kdeglobals",
909            "/home/u/.config/kdeglobals",
910        ]);
911        for config_dirs in [None, Some(""), Some("relative:")] {
912            let files =
913                kdeglobals_files_pure(config_dirs, Some("/home/u/.config/kdeglobals".into()));
914            assert_eq!(files, expected, "{config_dirs:?}");
915        }
916    }
917
918    #[test]
919    fn kdeglobals_files_read_the_config_dirs_last_first_once_each() {
920        let files = kdeglobals_files_pure(
921            Some("/opt/a:/opt/b:/opt/a"),
922            Some("/home/u/.config/kdeglobals".into()),
923        );
924        assert_eq!(
925            files,
926            paths(&[
927                "/opt/b/kdeglobals",
928                "/opt/a/kdeglobals",
929                "/home/u/.config/kdedefaults/kdeglobals",
930                "/home/u/.config/kdeglobals",
931            ])
932        );
933    }
934
935    /// Without a config directory there is no user file and no
936    /// `kdedefaults` beside it: only the config dirs' files.
937    #[test]
938    fn kdeglobals_files_without_a_config_directory_are_the_config_dirs() {
939        assert_eq!(
940            kdeglobals_files_pure(None, None),
941            paths(&["/etc/xdg/kdeglobals"])
942        );
943        assert_eq!(
944            kdeglobals_files_pure(Some("/opt/a:/opt/b"), None),
945            paths(&["/opt/b/kdeglobals", "/opt/a/kdeglobals"])
946        );
947    }
948
949    /// A ColorScheme set only in `kdedefaults/kdeglobals`, as Plasma 6 writes
950    /// it, names the theme; each file overrides the keys of the ones before.
951    #[test]
952    fn the_scheme_name_and_icon_theme_cascade_from_kdedefaults() {
953        let dir = temp_config_dir("cascade");
954        std::fs::create_dir_all(dir.join("xdg")).unwrap();
955        std::fs::write(
956            dir.join("xdg/kdeglobals"),
957            "[General]\nColorScheme=SystemScheme\n\n[KDE]\nAnimationDurationFactor=0\n",
958        )
959        .unwrap();
960        std::fs::write(
961            dir.join("kdedefaults/kdeglobals"),
962            "[General]\nColorScheme=BreezeDark\n\n[Icons]\nTheme=breeze-dark\n",
963        )
964        .unwrap();
965        std::fs::write(
966            dir.join("kdeglobals"),
967            "[Colors:Window]\nBackgroundNormal=49,54,59\n",
968        )
969        .unwrap();
970        let files = kdeglobals_files_pure(
971            Some(dir.join("xdg").to_str().unwrap()),
972            Some(dir.join("kdeglobals")),
973        );
974        let result = from_kde_ini(&read_kconfig_files(&files).expect("the files are readable"));
975        assert_eq!(result.name, "BreezeDark");
976        assert!(result.accessibility.reduce_motion);
977        assert!(matches!(
978            result.output,
979            crate::ReaderOutput::Single { is_dark: true, .. }
980        ));
981        let mode = reader_mode(&result);
982        assert_eq!(mode.defaults.icon_theme.as_deref(), Some("breeze-dark"));
983        // The sizes of the theme the cascade found (all None where
984        // breeze-dark is not installed).
985        assert_eq!(
986            mode.defaults.icon_sizes,
987            parse_icon_sizes_from_index_theme("breeze-dark")
988        );
989    }
990
991    /// kdeglobals files that state no window background say nothing about
992    /// darkness, so detect's fallback goes on to the next source.
993    #[test]
994    fn a_kdeglobals_without_a_window_background_is_not_light() {
995        let dir = temp_config_dir("colourless");
996        std::fs::write(dir.join("kdeglobals"), "[General]\nColorScheme=Custom\n").unwrap();
997        std::fs::write(
998            dir.join("kdedefaults/kdeglobals"),
999            "[Colors:Window]\nBackgroundNormal=not,a,colour\n",
1000        )
1001        .unwrap();
1002        let files = [dir.join("kdedefaults/kdeglobals"), dir.join("kdeglobals")];
1003        assert_eq!(kconfig_files_are_dark(&files), None);
1004        std::fs::write(
1005            dir.join("kdeglobals"),
1006            "[Colors:Window]\nBackgroundNormal=49,54,59\n",
1007        )
1008        .unwrap();
1009        assert_eq!(kconfig_files_are_dark(&files), Some(true));
1010    }
1011
1012    /// The icon theme `detect` reports is the cascade's, as the reader's: a
1013    /// file without the key leaves the one before it; the failures name the
1014    /// files.
1015    #[test]
1016    fn the_detected_icon_theme_is_the_cascades() {
1017        let dir = temp_config_dir("icon-theme");
1018        let files = [dir.join("kdedefaults/kdeglobals"), dir.join("kdeglobals")];
1019        let failure = kconfig_files_icon_theme(&files).unwrap_err();
1020        assert!(failure.contains("no file is readable"), "got: {failure}");
1021        assert!(failure.contains("kdedefaults/kdeglobals"), "got: {failure}");
1022
1023        std::fs::write(dir.join("kdeglobals"), "[General]\nColorScheme=Custom\n").unwrap();
1024        let failure = kconfig_files_icon_theme(&files).unwrap_err();
1025        assert!(
1026            failure.contains("`[Icons] Theme` is absent or empty"),
1027            "got: {failure}"
1028        );
1029
1030        std::fs::write(
1031            dir.join("kdedefaults/kdeglobals"),
1032            "[Icons]\nTheme=breeze-dark\n",
1033        )
1034        .unwrap();
1035        assert_eq!(
1036            kconfig_files_icon_theme(&files),
1037            Ok("breeze-dark".to_string())
1038        );
1039        let (mode, ..) = read_kde_ini(&read_kconfig_files(&files).unwrap());
1040        assert_eq!(mode.defaults.icon_theme.as_deref(), Some("breeze-dark"));
1041    }
1042
1043    /// A missing file, here the user's, reads as empty; with no file at all
1044    /// there is nothing.
1045    #[test]
1046    fn a_missing_kdeglobals_file_reads_as_empty() {
1047        let dir = temp_config_dir("missing");
1048        std::fs::write(
1049            dir.join("kdeglobals"),
1050            "[General]\nColorScheme=BreezeDark\n",
1051        )
1052        .unwrap();
1053        let ini = read_kconfig_files(&[dir.join("kdeglobals"), dir.join("absent")])
1054            .expect("one file is readable");
1055        assert_eq!(
1056            ini.get("General", "ColorScheme").as_deref(),
1057            Some("BreezeDark")
1058        );
1059        assert!(read_kconfig_files(&[dir.join("absent")]).is_none());
1060    }
1061
1062    /// A byte that is not UTF-8 is replaced; the rest of the theme is read.
1063    #[test]
1064    fn a_non_utf8_byte_keeps_the_theme() {
1065        let dir = temp_config_dir("non-utf8");
1066        std::fs::write(
1067            dir.join("kdeglobals"),
1068            b"[General]\nColorScheme=Caf\xe9\n\n[Colors:Window]\nBackgroundNormal=49,54,59\n",
1069        )
1070        .unwrap();
1071        let result = from_kde_ini(
1072            &read_kconfig_files(&[dir.join("kdeglobals")]).expect("the file is readable"),
1073        );
1074        assert_eq!(result.name, "Caf\u{fffd}");
1075        assert_eq!(
1076            reader_mode(&result).defaults.background_color,
1077            Some(Rgba::rgb(49, 54, 59))
1078        );
1079    }
1080
1081    /// KConfig has no `;` comments: a `;` in a value is part of it, and a
1082    /// line starting with `;` is an entry.
1083    #[test]
1084    fn a_semicolon_is_not_a_comment() {
1085        let mut ini = create_kde_parser();
1086        read_kconfig(
1087            &mut ini,
1088            "[General]\n;ColorScheme=Hidden\nColorScheme=My;Scheme\n",
1089        );
1090        assert_eq!(
1091            ini.get("General", "ColorScheme").as_deref(),
1092            Some("My;Scheme")
1093        );
1094        assert_eq!(
1095            ini.get("General", ";ColorScheme").as_deref(),
1096            Some("Hidden")
1097        );
1098    }
1099
1100    // === Per-widget color tests ===
1101
1102    #[test]
1103    fn test_button_colors_populated() {
1104        let result = from_kde_content(BREEZE_DARK_FULL).unwrap();
1105        let v = reader_mode(&result);
1106        assert_eq!(v.button.background_color, Some(Rgba::rgb(49, 54, 59)));
1107        assert_eq!(
1108            v.button.font.as_ref().and_then(|f| f.color),
1109            Some(Rgba::rgb(239, 240, 241))
1110        );
1111    }
1112
1113    #[test]
1114    fn test_tooltip_colors_populated() {
1115        let result = from_kde_content(BREEZE_DARK_FULL).unwrap();
1116        let v = reader_mode(&result);
1117        assert_eq!(v.tooltip.background_color, Some(Rgba::rgb(49, 54, 59)));
1118        assert_eq!(
1119            v.tooltip.font.as_ref().and_then(|f| f.color),
1120            Some(Rgba::rgb(252, 252, 252))
1121        );
1122    }
1123
1124    #[test]
1125    fn test_sidebar_colors_populated() {
1126        let result = from_kde_content(BREEZE_DARK_FULL).unwrap();
1127        let v = reader_mode(&result);
1128        assert_eq!(v.sidebar.background_color, Some(Rgba::rgb(35, 38, 41)));
1129        assert_eq!(
1130            v.sidebar.font.as_ref().and_then(|f| f.color),
1131            Some(Rgba::rgb(252, 252, 252))
1132        );
1133    }
1134
1135    #[test]
1136    fn test_wm_title_bar_colors() {
1137        let result = from_kde_content(BREEZE_DARK_FULL).unwrap();
1138        let v = reader_mode(&result);
1139        assert_eq!(v.window.title_bar_background, Some(Rgba::rgb(49, 54, 59)));
1140        assert_eq!(
1141            v.window.title_bar_font.as_ref().and_then(|f| f.color),
1142            Some(Rgba::rgb(239, 240, 241))
1143        );
1144        assert_eq!(
1145            v.window.inactive_title_bar_background,
1146            Some(Rgba::rgb(42, 46, 50))
1147        );
1148        assert_eq!(
1149            v.window.inactive_title_bar_text_color,
1150            Some(Rgba::rgb(161, 169, 177))
1151        );
1152    }
1153
1154    #[test]
1155    fn test_list_header_colors_are_the_button_sets() {
1156        let result = from_kde_content(BREEZE_DARK_FULL).unwrap();
1157        let v = reader_mode(&result);
1158        assert_eq!(v.list.header_background, Some(Rgba::rgb(49, 54, 59)));
1159        assert_eq!(
1160            v.list.header_font.as_ref().and_then(|f| f.color),
1161            Some(Rgba::rgb(239, 240, 241))
1162        );
1163    }
1164
1165    #[test]
1166    fn test_link_visited() {
1167        let result = from_kde_content(BREEZE_DARK_FULL).unwrap();
1168        let v = reader_mode(&result);
1169        assert_eq!(v.link.visited_text_color, Some(Rgba::rgb(155, 89, 182)));
1170    }
1171
1172    /// Link text takes `ForegroundLink` through `defaults.link_color`, so a
1173    /// plain read resolves it to that colour, here one `kde-breeze` does not
1174    /// state.
1175    #[test]
1176    fn link_text_resolves_to_foreground_link() -> crate::Result<()> {
1177        let content = "[Colors:Window]\nBackgroundNormal=49,54,59\n\n\
1178                       [Colors:View]\nForegroundLink=246,116,0\n";
1179        let st = crate::pipeline::run_pipeline(from_kde_content(content)?, "kde-breeze")?;
1180        assert_eq!(st.dark.link.font.color, Rgba::rgb(246, 116, 0));
1181        Ok(())
1182    }
1183
1184    /// A hovered and a pressed link keep `ForegroundLink` too: `kde-breeze`
1185    /// states neither colour, so both inherit `link.font.color`.
1186    #[test]
1187    fn link_hover_and_active_text_follow_foreground_link() -> crate::Result<()> {
1188        let content = "[Colors:Window]\nBackgroundNormal=49,54,59\n\n\
1189                       [Colors:View]\nForegroundLink=246,116,0\n";
1190        let st = crate::pipeline::run_pipeline(from_kde_content(content)?, "kde-breeze")?;
1191        assert_eq!(st.dark.link.hover_text_color, Rgba::rgb(246, 116, 0));
1192        assert_eq!(st.dark.link.active_text_color, Rgba::rgb(246, 116, 0));
1193        Ok(())
1194    }
1195
1196    /// An overlay's `defaults.link_color` recolours link text on top of a
1197    /// KDE read: the reader states no `link.font.color` of its own.
1198    #[test]
1199    fn an_overlay_link_color_recolours_link_text() -> crate::Result<()> {
1200        let st = crate::pipeline::run_pipeline(from_kde_content(BREEZE_DARK_FULL)?, "kde-breeze")?;
1201        let overlay = crate::Theme::from_toml("[dark.defaults]\nlink_color = \"#ff0000\"")?;
1202        let customised = st.with_overlay(&overlay)?;
1203        assert_eq!(customised.dark.link.font.color, Rgba::rgb(255, 0, 0));
1204        Ok(())
1205    }
1206
1207    /// The colour scheme's Button and Window colours reach the combo box, the
1208    /// menu text and the popover over `kde-breeze`, which states Breeze's
1209    /// values beneath them (docs/platform-facts.md §2.24, §2.6, §2.16), and
1210    /// the separator is the border colour (§2.18).
1211    #[test]
1212    fn scheme_colours_reach_the_combo_box_menu_and_popover() -> crate::Result<()> {
1213        let content = "[Colors:Window]\nBackgroundNormal=10,20,30\nForegroundNormal=200,210,220\n\n\
1214                       [Colors:Button]\nBackgroundNormal=40,50,60\nForegroundNormal=230,240,250\n\n\
1215                       [Colors:View]\nBackgroundNormal=70,80,90\nForegroundNormal=1,2,3\n";
1216        let st = crate::pipeline::run_pipeline(from_kde_content(content)?, "kde-breeze")?;
1217        assert_eq!(st.dark.combo_box.background_color, Rgba::rgb(40, 50, 60));
1218        assert_eq!(st.dark.combo_box.font.color, Rgba::rgb(230, 240, 250));
1219        assert_eq!(st.dark.menu.font.color, Rgba::rgb(200, 210, 220));
1220        assert_eq!(st.dark.popover.background_color, Rgba::rgb(10, 20, 30));
1221        assert_eq!(st.dark.popover.font.color, Rgba::rgb(200, 210, 220));
1222        assert_eq!(st.dark.separator.line_color, st.dark.defaults.border.color);
1223        Ok(())
1224    }
1225
1226    /// A colour scheme's background and text keys, `(BackgroundNormal,
1227    /// ForegroundNormal)`, of the sets the derived leaves read, the View
1228    /// set's `DecorationFocus` and `DecorationHover`, with an optional
1229    /// `[Colors:Header]` group, `[KDE]` `contrast` and `frameContrast`, and
1230    /// `[ColorEffects:Inactive]` `ChangeSelectionColor` and `Enable`.
1231    struct Scheme {
1232        button: (&'static str, &'static str),
1233        header: Option<(&'static str, &'static str)>,
1234        selection: (&'static str, &'static str),
1235        view: (&'static str, &'static str),
1236        focus: &'static str,
1237        hover: &'static str,
1238        window: (&'static str, &'static str),
1239        frame_contrast: Option<&'static str>,
1240        contrast: Option<&'static str>,
1241        change_selection_color: Option<&'static str>,
1242        inactive_enable: Option<&'static str>,
1243    }
1244
1245    impl Scheme {
1246        fn kdeglobals(&self) -> String {
1247            let group = |name: &str, (bg, fg): (&str, &str)| {
1248                format!("[Colors:{name}]\nBackgroundNormal={bg}\nForegroundNormal={fg}\n\n")
1249            };
1250            let mut content = group("Button", self.button);
1251            if let Some(header) = self.header {
1252                content.push_str(&group("Header", header));
1253            }
1254            content.push_str(&format!(
1255                "[Colors:Selection]\nBackgroundNormal={}\nForegroundNormal={}\n\n",
1256                self.selection.0, self.selection.1
1257            ));
1258            content.push_str(&format!(
1259                "[Colors:View]\nBackgroundNormal={}\nForegroundNormal={}\n\
1260                 DecorationFocus={}\nDecorationHover={}\n\n",
1261                self.view.0, self.view.1, self.focus, self.hover
1262            ));
1263            content.push_str(&group("Window", self.window));
1264            if self.contrast.is_some() || self.frame_contrast.is_some() {
1265                content.push_str("[KDE]\n");
1266            }
1267            if let Some(contrast) = self.contrast {
1268                content.push_str(&format!("contrast={contrast}\n"));
1269            }
1270            if let Some(contrast) = self.frame_contrast {
1271                content.push_str(&format!("frameContrast={contrast}\n"));
1272            }
1273            if self.change_selection_color.is_some() || self.inactive_enable.is_some() {
1274                content.push_str("[ColorEffects:Inactive]\n");
1275            }
1276            if let Some(change) = self.change_selection_color {
1277                content.push_str(&format!("ChangeSelectionColor={change}\n"));
1278            }
1279            if let Some(enable) = self.inactive_enable {
1280                content.push_str(&format!("Enable={enable}\n"));
1281            }
1282            content
1283        }
1284    }
1285
1286    /// The keys of BreezeLight.colors at breeze v6.7.5 (LGPL-2.0-or-later)
1287    /// the derived leaves read: Button :31, :39; Header :59, :67; Selection
1288    /// :87, ForegroundNormal :95; View :115, :123, DecorationFocus :116 and
1289    /// DecorationHover :117; Window :129, :137. No `[KDE] frameContrast`
1290    /// (:193-194), so KColorScheme's 0.2. `[KDE] contrast=4`
1291    /// (BreezeLight.colors:195 at breeze f0b1d75; docs/platform-facts.md §2.15).
1292    /// `[ColorEffects:Inactive]` ChangeSelectionColor :19 and Enable :25 at
1293    /// breeze 6.8.2.
1294    const BREEZE_LIGHT_SCHEME: Scheme = Scheme {
1295        button: ("252,252,252", "35,38,41"),
1296        header: Some(("222,224,226", "35,38,41")),
1297        selection: ("61,174,233", "255,255,255"),
1298        view: ("255,255,255", "35,38,41"),
1299        focus: "61,174,233",
1300        hover: "61,174,233",
1301        window: ("239,240,241", "35,38,41"),
1302        frame_contrast: None,
1303        contrast: Some("4"),
1304        change_selection_color: Some("true"),
1305        inactive_enable: Some("false"),
1306    };
1307
1308    /// The same keys of BreezeDark.colors at breeze v6.7.5
1309    /// (LGPL-2.0-or-later): Button :32, :40; Header :60, :68; Selection :88,
1310    /// ForegroundNormal :96; View :116, :124, DecorationFocus :117 and
1311    /// DecorationHover :118; Window :130, :138; no frameContrast (:200-201).
1312    /// `[KDE] contrast=4` (BreezeDark.colors:202 at breeze f0b1d75;
1313    /// docs/platform-facts.md §2.15). `[ColorEffects:Inactive]`
1314    /// ChangeSelectionColor :20 and Enable :26 at breeze 6.8.2.
1315    const BREEZE_DARK_SCHEME: Scheme = Scheme {
1316        button: ("41,44,48", "252,252,252"),
1317        header: Some(("41,44,48", "252,252,252")),
1318        selection: ("61,174,233", "252,252,252"),
1319        view: ("20,22,24", "252,252,252"),
1320        focus: "61,174,233",
1321        hover: "61,174,233",
1322        window: ("32,35,38", "252,252,252"),
1323        frame_contrast: None,
1324        contrast: Some("4"),
1325        change_selection_color: Some("true"),
1326        inactive_enable: Some("false"),
1327    };
1328
1329    /// The sixty-two colour leaves the reader derives from, or reads
1330    /// directly from, the colour scheme.
1331    fn derived_leaves(mode: &crate::ThemeMode) -> [(&'static str, Option<Rgba>); 62] {
1332        let border = |b: &Option<crate::WidgetBorderSpec>| b.as_ref().and_then(|b| b.color);
1333        let sw = &mode.switch;
1334        [
1335            ("button.hover_background", mode.button.hover_background),
1336            ("button.hover_text_color", mode.button.hover_text_color),
1337            ("slider.thumb_color", mode.slider.thumb_color),
1338            ("switch.unchecked_background", sw.unchecked_background),
1339            ("switch.checked_background", sw.checked_background),
1340            (
1341                "switch.hover_unchecked_background",
1342                sw.hover_unchecked_background,
1343            ),
1344            (
1345                "switch.hover_checked_background",
1346                sw.hover_checked_background,
1347            ),
1348            ("switch.thumb_background", sw.thumb_background),
1349            (
1350                "switch.unchecked_track_border_color",
1351                sw.unchecked_track_border_color,
1352            ),
1353            (
1354                "switch.checked_track_border_color",
1355                sw.checked_track_border_color,
1356            ),
1357            ("switch.thumb_border_color", sw.thumb_border_color),
1358            ("toolbar.background_color", mode.toolbar.background_color),
1359            ("toolbar.border.color", border(&mode.toolbar.border)),
1360            ("popover.border.color", border(&mode.popover.border)),
1361            ("card.border.color", border(&mode.card.border)),
1362            ("button.active_background", mode.button.active_background),
1363            ("input.hover_border_color", mode.input.hover_border_color),
1364            ("input.focus_border_color", mode.input.focus_border_color),
1365            ("tab.hover_background", mode.tab.hover_background),
1366            (
1367                "segmented_control.active_background",
1368                mode.segmented_control.active_background,
1369            ),
1370            (
1371                "scrollbar.thumb_hover_color",
1372                mode.scrollbar.thumb_hover_color,
1373            ),
1374            (
1375                "scrollbar.thumb_active_color",
1376                mode.scrollbar.thumb_active_color,
1377            ),
1378            ("menu.hover_background", mode.menu.hover_background),
1379            ("menu.hover_text_color", mode.menu.hover_text_color),
1380            ("menu.separator_color", mode.menu.separator_color),
1381            ("scrollbar.thumb_color", mode.scrollbar.thumb_color),
1382            ("list.hover_background", mode.list.hover_background),
1383            ("list.header_background", mode.list.header_background),
1384            (
1385                "list.header_font.color",
1386                mode.list.header_font.as_ref().and_then(|f| f.color),
1387            ),
1388            ("list.grid_color", mode.list.grid_color),
1389            ("menu.background_color", mode.menu.background_color),
1390            ("defaults.focus_ring_color", mode.defaults.focus_ring_color),
1391            ("button.hover_border_color", mode.button.hover_border_color),
1392            ("button.focus_border_color", mode.button.focus_border_color),
1393            (
1394                "checkbox.hover_border_color",
1395                mode.checkbox.hover_border_color,
1396            ),
1397            (
1398                "combo_box.hover_border_color",
1399                mode.combo_box.hover_border_color,
1400            ),
1401            (
1402                "toolbar.button_hover_border_color",
1403                mode.toolbar.button_hover_border_color,
1404            ),
1405            (
1406                "toolbar.button_active_background",
1407                mode.toolbar.button_active_background,
1408            ),
1409            (
1410                "toolbar.button_checked_background",
1411                mode.toolbar.button_checked_background,
1412            ),
1413            (
1414                "button.default_button_background",
1415                mode.button.default_button_background,
1416            ),
1417            (
1418                "button.default_button_text_color",
1419                mode.button.default_button_text_color,
1420            ),
1421            (
1422                "button.default_button_border_color",
1423                mode.button.default_button_border_color,
1424            ),
1425            (
1426                "list.header_hover_background",
1427                mode.list.header_hover_background,
1428            ),
1429            (
1430                "list.header_active_background",
1431                mode.list.header_active_background,
1432            ),
1433            (
1434                "defaults.selection_inactive_background",
1435                mode.defaults.selection_inactive_background,
1436            ),
1437            (
1438                "defaults.selection_inactive_text_color",
1439                mode.defaults.selection_inactive_text_color,
1440            ),
1441            ("menu.hover_border_color", mode.menu.hover_border_color),
1442            ("menu.bar_hover_background", mode.menu.bar_hover_background),
1443            ("menu.bar_open_background", mode.menu.bar_open_background),
1444            ("menu.bar_hover_text_color", mode.menu.bar_hover_text_color),
1445            ("list.hover_border_color", mode.list.hover_border_color),
1446            ("menu.active_background", mode.menu.active_background),
1447            ("menu.active_text_color", mode.menu.active_text_color),
1448            ("list.hover_text_color", mode.list.hover_text_color),
1449            ("button.border.color", border(&mode.button.border)),
1450            (
1451                "list.header_separator_color",
1452                mode.list.header_separator_color,
1453            ),
1454            ("slider.thumb_border_color", mode.slider.thumb_border_color),
1455            (
1456                "slider.thumb_hover_border_color",
1457                mode.slider.thumb_hover_border_color,
1458            ),
1459            (
1460                "slider.thumb_focus_border_color",
1461                mode.slider.thumb_focus_border_color,
1462            ),
1463            (
1464                "toolbar.button_checked_border_color",
1465                mode.toolbar.button_checked_border_color,
1466            ),
1467            ("combo_box.open_background", mode.combo_box.open_background),
1468            (
1469                "combo_box.open_border_color",
1470                mode.combo_box.open_border_color,
1471            ),
1472        ]
1473    }
1474
1475    /// The same leaves resolved.
1476    fn resolved_leaves(theme: &crate::ResolvedTheme) -> [(&'static str, Option<Rgba>); 62] {
1477        let sw = &theme.switch;
1478        [
1479            (
1480                "button.hover_background",
1481                Some(theme.button.hover_background),
1482            ),
1483            (
1484                "button.hover_text_color",
1485                Some(theme.button.hover_text_color),
1486            ),
1487            ("slider.thumb_color", Some(theme.slider.thumb_color)),
1488            ("switch.unchecked_background", Some(sw.unchecked_background)),
1489            ("switch.checked_background", Some(sw.checked_background)),
1490            (
1491                "switch.hover_unchecked_background",
1492                sw.hover_unchecked_background,
1493            ),
1494            (
1495                "switch.hover_checked_background",
1496                sw.hover_checked_background,
1497            ),
1498            ("switch.thumb_background", Some(sw.thumb_background)),
1499            (
1500                "switch.unchecked_track_border_color",
1501                sw.unchecked_track_border_color,
1502            ),
1503            (
1504                "switch.checked_track_border_color",
1505                sw.checked_track_border_color,
1506            ),
1507            ("switch.thumb_border_color", sw.thumb_border_color),
1508            (
1509                "toolbar.background_color",
1510                Some(theme.toolbar.background_color),
1511            ),
1512            ("toolbar.border.color", Some(theme.toolbar.border.color)),
1513            ("popover.border.color", Some(theme.popover.border.color)),
1514            ("card.border.color", Some(theme.card.border.color)),
1515            ("button.active_background", theme.button.active_background),
1516            ("input.hover_border_color", theme.input.hover_border_color),
1517            ("input.focus_border_color", theme.input.focus_border_color),
1518            ("tab.hover_background", theme.tab.hover_background),
1519            (
1520                "segmented_control.active_background",
1521                Some(theme.segmented_control.active_background),
1522            ),
1523            (
1524                "scrollbar.thumb_hover_color",
1525                Some(theme.scrollbar.thumb_hover_color),
1526            ),
1527            (
1528                "scrollbar.thumb_active_color",
1529                theme.scrollbar.thumb_active_color,
1530            ),
1531            ("menu.hover_background", Some(theme.menu.hover_background)),
1532            ("menu.hover_text_color", Some(theme.menu.hover_text_color)),
1533            ("menu.separator_color", Some(theme.menu.separator_color)),
1534            ("scrollbar.thumb_color", Some(theme.scrollbar.thumb_color)),
1535            ("list.hover_background", Some(theme.list.hover_background)),
1536            ("list.header_background", Some(theme.list.header_background)),
1537            ("list.header_font.color", Some(theme.list.header_font.color)),
1538            ("list.grid_color", Some(theme.list.grid_color)),
1539            ("menu.background_color", Some(theme.menu.background_color)),
1540            (
1541                "defaults.focus_ring_color",
1542                Some(theme.defaults.focus_ring_color),
1543            ),
1544            ("button.hover_border_color", theme.button.hover_border_color),
1545            ("button.focus_border_color", theme.button.focus_border_color),
1546            (
1547                "checkbox.hover_border_color",
1548                theme.checkbox.hover_border_color,
1549            ),
1550            (
1551                "combo_box.hover_border_color",
1552                theme.combo_box.hover_border_color,
1553            ),
1554            (
1555                "toolbar.button_hover_border_color",
1556                theme.toolbar.button_hover_border_color,
1557            ),
1558            (
1559                "toolbar.button_active_background",
1560                theme.toolbar.button_active_background,
1561            ),
1562            (
1563                "toolbar.button_checked_background",
1564                theme.toolbar.button_checked_background,
1565            ),
1566            (
1567                "button.default_button_background",
1568                theme.button.default_button_background,
1569            ),
1570            (
1571                "button.default_button_text_color",
1572                theme.button.default_button_text_color,
1573            ),
1574            (
1575                "button.default_button_border_color",
1576                theme.button.default_button_border_color,
1577            ),
1578            (
1579                "list.header_hover_background",
1580                theme.list.header_hover_background,
1581            ),
1582            (
1583                "list.header_active_background",
1584                theme.list.header_active_background,
1585            ),
1586            (
1587                "defaults.selection_inactive_background",
1588                Some(theme.defaults.selection_inactive_background),
1589            ),
1590            (
1591                "defaults.selection_inactive_text_color",
1592                Some(theme.defaults.selection_inactive_text_color),
1593            ),
1594            ("menu.hover_border_color", theme.menu.hover_border_color),
1595            ("menu.bar_hover_background", theme.menu.bar_hover_background),
1596            ("menu.bar_open_background", theme.menu.bar_open_background),
1597            ("menu.bar_hover_text_color", theme.menu.bar_hover_text_color),
1598            ("list.hover_border_color", theme.list.hover_border_color),
1599            ("menu.active_background", theme.menu.active_background),
1600            ("menu.active_text_color", theme.menu.active_text_color),
1601            ("list.hover_text_color", Some(theme.list.hover_text_color)),
1602            ("button.border.color", Some(theme.button.border.color)),
1603            (
1604                "list.header_separator_color",
1605                theme.list.header_separator_color,
1606            ),
1607            ("slider.thumb_border_color", theme.slider.thumb_border_color),
1608            (
1609                "slider.thumb_hover_border_color",
1610                theme.slider.thumb_hover_border_color,
1611            ),
1612            (
1613                "slider.thumb_focus_border_color",
1614                theme.slider.thumb_focus_border_color,
1615            ),
1616            (
1617                "toolbar.button_checked_border_color",
1618                theme.toolbar.button_checked_border_color,
1619            ),
1620            ("combo_box.open_background", theme.combo_box.open_background),
1621            (
1622                "combo_box.open_border_color",
1623                theme.combo_box.open_border_color,
1624            ),
1625        ]
1626    }
1627
1628    /// The resolved light variant of `scheme` over `kde-breeze`.
1629    fn resolved_light(scheme: &Scheme) -> crate::Result<crate::ResolvedTheme> {
1630        let content = scheme.kdeglobals();
1631        let st = crate::pipeline::run_pipeline(from_kde_content(&content)?, "kde-breeze")?;
1632        assert_eq!(st.mode, crate::ColorMode::Light, "{content}");
1633        Ok(st.light)
1634    }
1635
1636    /// The derived leaves whose resolved value differs between `scheme` and
1637    /// Breeze Light.
1638    fn moved_leaves(scheme: &Scheme) -> crate::Result<Vec<&'static str>> {
1639        let breeze = resolved_leaves(&resolved_light(&BREEZE_LIGHT_SCHEME)?);
1640        let other = resolved_leaves(&resolved_light(scheme)?);
1641        Ok(breeze
1642            .iter()
1643            .zip(other.iter())
1644            .filter(|(a, b)| a.1 != b.1)
1645            .map(|(a, _)| a.0)
1646            .collect())
1647    }
1648
1649    /// Under Breeze Light and Breeze Dark the reader derives each leaf as
1650    /// the `kde-breeze` preset states it.
1651    #[test]
1652    fn the_derived_colours_are_the_presets_under_breeze() -> crate::Result<()> {
1653        let preset = crate::Theme::preset("kde-breeze")?;
1654        let variants = [
1655            (&BREEZE_LIGHT_SCHEME, preset.light.as_ref()),
1656            (&BREEZE_DARK_SCHEME, preset.dark.as_ref()),
1657        ];
1658        for (scheme, stated) in variants {
1659            let stated = derived_leaves(stated.expect("kde-breeze has both variants"));
1660            let result = from_kde_content(&scheme.kdeglobals())?;
1661            let read = derived_leaves(reader_mode(&result));
1662            for ((leaf, read), (_, stated)) in read.iter().zip(stated.iter()) {
1663                assert!(stated.is_some(), "kde-breeze states {leaf}");
1664                assert_eq!(read, stated, "{leaf} under {}", scheme.window.0);
1665            }
1666        }
1667        Ok(())
1668    }
1669
1670    /// Another accent moves the switch's on track, hovered or not, and its
1671    /// outline, the pressed button and the selected segment, the list's
1672    /// hover and its outline, the focus ring and the button's hover and focus border, the
1673    /// combo box's hover pen, a toolbar button's hover pen and pressed fill,
1674    /// the default button's fill and frame, the inactive selection's fill,
1675    /// tinted towards it, and an open combo box's fill and pen; the checkbox
1676    /// and the progress bar follow it as before.
1677    #[test]
1678    fn an_accent_moves_the_on_track_the_pressed_button_the_selected_segment_and_the_list_hover()
1679    -> crate::Result<()> {
1680        let scheme = Scheme {
1681            selection: ("233,84,32", "255,255,255"),
1682            ..BREEZE_LIGHT_SCHEME
1683        };
1684        assert_eq!(
1685            moved_leaves(&scheme)?,
1686            [
1687                "switch.checked_background",
1688                "switch.hover_checked_background",
1689                "switch.checked_track_border_color",
1690                "button.active_background",
1691                "segmented_control.active_background",
1692                "list.hover_background",
1693                "defaults.focus_ring_color",
1694                "button.hover_border_color",
1695                "button.focus_border_color",
1696                "combo_box.hover_border_color",
1697                "toolbar.button_hover_border_color",
1698                "toolbar.button_active_background",
1699                "button.default_button_background",
1700                "button.default_button_border_color",
1701                "defaults.selection_inactive_background",
1702                "list.hover_border_color",
1703                "combo_box.open_background",
1704                "combo_box.open_border_color",
1705            ]
1706        );
1707        Ok(())
1708    }
1709
1710    /// The Button set moves the button's fills, text and frame, the slider
1711    /// handle's fill and its outline at rest, the switch, the pressed and the
1712    /// default button, the list's header and its hovered and pressed
1713    /// sections, a checked toolbar button's fill and pen, and an open combo
1714    /// box's fill.
1715    #[test]
1716    fn the_button_set_moves_the_button_slider_switch_and_header_leaves() -> crate::Result<()> {
1717        let scheme = Scheme {
1718            button: ("200,180,150", "60,20,10"),
1719            ..BREEZE_LIGHT_SCHEME
1720        };
1721        assert_eq!(
1722            moved_leaves(&scheme)?,
1723            [
1724                "button.hover_background",
1725                "button.hover_text_color",
1726                "slider.thumb_color",
1727                "switch.unchecked_background",
1728                "switch.checked_background",
1729                "switch.hover_unchecked_background",
1730                "switch.hover_checked_background",
1731                "switch.thumb_background",
1732                "switch.unchecked_track_border_color",
1733                "switch.thumb_border_color",
1734                "button.active_background",
1735                "list.header_background",
1736                "list.header_font.color",
1737                "toolbar.button_checked_background",
1738                "button.default_button_background",
1739                "button.default_button_text_color",
1740                "button.default_button_border_color",
1741                "list.header_hover_background",
1742                "list.header_active_background",
1743                "button.border.color",
1744                "slider.thumb_border_color",
1745                "toolbar.button_checked_border_color",
1746                "combo_box.open_background",
1747            ]
1748        );
1749        Ok(())
1750    }
1751
1752    /// The Header set moves the toolbar's fill and edge, and not the list's
1753    /// header, which is the Button set's.
1754    #[test]
1755    fn the_header_set_moves_the_toolbar() -> crate::Result<()> {
1756        let scheme = Scheme {
1757            header: Some(("180,200,220", "10,40,80")),
1758            ..BREEZE_LIGHT_SCHEME
1759        };
1760        assert_eq!(
1761            moved_leaves(&scheme)?,
1762            ["toolbar.background_color", "toolbar.border.color"]
1763        );
1764        Ok(())
1765    }
1766
1767    /// The Window set moves the popover's edge, the scroll-bar handles, the
1768    /// menu's hover text, separator and panel and a hovered item's outline, the table's grid and the
1769    /// inactive selection, the window tinted and its text, the header's
1770    /// section line, and the toolbar only where the scheme has no Header group
1771    /// to take it from.
1772    #[test]
1773    fn the_window_set_moves_the_popover_edge() -> crate::Result<()> {
1774        let window = ("230,220,200", "90,40,20");
1775        let with_header = Scheme {
1776            window,
1777            ..BREEZE_LIGHT_SCHEME
1778        };
1779        assert_eq!(
1780            moved_leaves(&with_header)?,
1781            [
1782                "popover.border.color",
1783                "scrollbar.thumb_hover_color",
1784                "scrollbar.thumb_active_color",
1785                "menu.hover_text_color",
1786                "menu.separator_color",
1787                "scrollbar.thumb_color",
1788                "list.grid_color",
1789                "menu.background_color",
1790                "defaults.selection_inactive_background",
1791                "defaults.selection_inactive_text_color",
1792                "menu.hover_border_color",
1793                "list.header_separator_color",
1794            ]
1795        );
1796        let without_header = Scheme {
1797            window,
1798            header: None,
1799            ..BREEZE_LIGHT_SCHEME
1800        };
1801        assert_eq!(
1802            moved_leaves(&without_header)?,
1803            [
1804                "toolbar.background_color",
1805                "toolbar.border.color",
1806                "popover.border.color",
1807                "scrollbar.thumb_hover_color",
1808                "scrollbar.thumb_active_color",
1809                "menu.hover_text_color",
1810                "menu.separator_color",
1811                "scrollbar.thumb_color",
1812                "list.grid_color",
1813                "menu.background_color",
1814                "defaults.selection_inactive_background",
1815                "defaults.selection_inactive_text_color",
1816                "menu.hover_border_color",
1817                "list.header_separator_color",
1818            ]
1819        );
1820        Ok(())
1821    }
1822
1823    /// The View set moves the card's edge, the menu's panel and a hovered
1824    /// row's text.
1825    #[test]
1826    fn the_view_set_moves_the_card_edge_and_the_menu_panel() -> crate::Result<()> {
1827        let scheme = Scheme {
1828            view: ("250,240,230", "120,30,60"),
1829            ..BREEZE_LIGHT_SCHEME
1830        };
1831        assert_eq!(
1832            moved_leaves(&scheme)?,
1833            [
1834                "card.border.color",
1835                "menu.background_color",
1836                "list.hover_text_color",
1837            ]
1838        );
1839        Ok(())
1840    }
1841
1842    /// The View set's decorations (D7): DecorationHover moves a hovered
1843    /// field's frame, the tab hover, the scroll-bar handle, a hovered
1844    /// header section, a hovered menu-bar title and a hovered slider handle's
1845    /// outline, DecorationFocus a focused field's frame, the menu's hover and
1846    /// its outline, the check box's hover outline, a pressed header section, an
1847    /// open menu-bar title, a pressed menu item and a focused slider handle's
1848    /// outline.
1849    #[test]
1850    fn the_view_decorations_move_the_frames_the_tab_hover_and_the_handle() -> crate::Result<()> {
1851        let hover = Scheme {
1852            hover: "240,160,20",
1853            ..BREEZE_LIGHT_SCHEME
1854        };
1855        assert_eq!(
1856            moved_leaves(&hover)?,
1857            [
1858                "input.hover_border_color",
1859                "tab.hover_background",
1860                "scrollbar.thumb_hover_color",
1861                "scrollbar.thumb_active_color",
1862                "list.header_hover_background",
1863                "menu.bar_hover_background",
1864                "slider.thumb_hover_border_color",
1865            ]
1866        );
1867        let focus = Scheme {
1868            focus: "20,200,90",
1869            ..BREEZE_LIGHT_SCHEME
1870        };
1871        assert_eq!(
1872            moved_leaves(&focus)?,
1873            [
1874                "input.focus_border_color",
1875                "menu.hover_background",
1876                "checkbox.hover_border_color",
1877                "list.header_active_background",
1878                "menu.hover_border_color",
1879                "menu.bar_open_background",
1880                "menu.active_background",
1881                "slider.thumb_focus_border_color",
1882            ]
1883        );
1884        Ok(())
1885    }
1886
1887    /// `[KDE] frameContrast` moves the edges: the switch's, the toolbar's, the
1888    /// popover's and the card's, the menu's separator, the default button's
1889    /// frame, the plain button frame (the button's border, the slider handle's
1890    /// outline at rest, a checked toolbar button's pen) and the header's
1891    /// section line.
1892    #[test]
1893    fn the_frame_contrast_moves_the_edges() -> crate::Result<()> {
1894        let scheme = Scheme {
1895            frame_contrast: Some("0.5"),
1896            ..BREEZE_LIGHT_SCHEME
1897        };
1898        assert_eq!(
1899            moved_leaves(&scheme)?,
1900            [
1901                "switch.unchecked_track_border_color",
1902                "switch.thumb_border_color",
1903                "toolbar.border.color",
1904                "popover.border.color",
1905                "card.border.color",
1906                "menu.separator_color",
1907                "button.default_button_border_color",
1908                "button.border.color",
1909                "list.header_separator_color",
1910                "slider.thumb_border_color",
1911                "toolbar.button_checked_border_color",
1912            ]
1913        );
1914        Ok(())
1915    }
1916
1917    /// `[KDE] contrast` moves the table's grid and nothing else; without it
1918    /// the grid is KColorScheme's default step's.
1919    #[test]
1920    fn the_contrast_moves_the_table_grid() -> crate::Result<()> {
1921        let zero = Scheme {
1922            contrast: Some("0"),
1923            ..BREEZE_LIGHT_SCHEME
1924        };
1925        assert_eq!(moved_leaves(&zero)?, ["list.grid_color"]);
1926        let unset = Scheme {
1927            contrast: None,
1928            ..BREEZE_LIGHT_SCHEME
1929        };
1930        assert_eq!(moved_leaves(&unset)?, ["list.grid_color"]);
1931        Ok(())
1932    }
1933
1934    /// The Selection set's text moves the menu-bar titles' text under the
1935    /// pointer or open and a pressed menu item's text, and nothing else: with
1936    /// `ChangeSelectionColor=true` the inactive selection's text is the
1937    /// window's.
1938    #[test]
1939    fn the_selection_text_moves_the_pressed_item_and_the_bar_titles() -> crate::Result<()> {
1940        let scheme = Scheme {
1941            selection: ("61,174,233", "10,20,30"),
1942            ..BREEZE_LIGHT_SCHEME
1943        };
1944        assert_eq!(
1945            moved_leaves(&scheme)?,
1946            ["menu.bar_hover_text_color", "menu.active_text_color"]
1947        );
1948        Ok(())
1949    }
1950
1951    /// `[ColorEffects:Inactive] ChangeSelectionColor`, else the group's
1952    /// `Enable`, else true decides the selection of a view without the
1953    /// focus: the window tinted towards the selection under the window text,
1954    /// or the focused pair (docs/platform-facts.md §2.1.3). A value that is no
1955    /// boolean the reader accepts counts as missing.
1956    #[test]
1957    fn the_inactive_selection_follows_change_selection_color() -> crate::Result<()> {
1958        let focused = (Rgba::rgb(0x3d, 0xae, 0xe9), Rgba::rgb(0xff, 0xff, 0xff));
1959        let tinted = (Rgba::rgb(0xc2, 0xe0, 0xf5), Rgba::rgb(0x23, 0x26, 0x29));
1960        for (change, enable, expected) in [
1961            (Some("false"), None, focused),
1962            (Some("false"), Some("true"), focused),
1963            (None, Some("false"), focused),
1964            (None, None, tinted),
1965            (Some("yes"), Some("false"), focused),
1966        ] {
1967            let theme = resolved_light(&Scheme {
1968                change_selection_color: change,
1969                inactive_enable: enable,
1970                ..BREEZE_LIGHT_SCHEME
1971            })?;
1972            assert_eq!(
1973                (
1974                    theme.defaults.selection_inactive_background,
1975                    theme.defaults.selection_inactive_text_color,
1976                ),
1977                expected,
1978                "ChangeSelectionColor {change:?}, Enable {enable:?}"
1979            );
1980        }
1981        Ok(())
1982    }
1983
1984    /// Without a `[Colors:Header]` group KColorScheme's Header set is the
1985    /// Window group's (kcolorscheme.cpp:330-332 at 27066d47) and Breeze
1986    /// draws no tools-area fill (breezestyle.cpp:1322 at breeze f0b1d75), so
1987    /// the toolbar shows the window and its edge is the Window set's
1988    /// separator colour.
1989    #[test]
1990    fn without_a_header_group_the_toolbar_is_the_windows() -> crate::Result<()> {
1991        let window = ("230,220,200", "90,40,20");
1992        let without_header = resolved_light(&Scheme {
1993            window,
1994            header: None,
1995            ..BREEZE_LIGHT_SCHEME
1996        })?;
1997        let header_as_window = resolved_light(&Scheme {
1998            window,
1999            header: Some(window),
2000            ..BREEZE_LIGHT_SCHEME
2001        })?;
2002        assert_eq!(
2003            without_header.toolbar.background_color,
2004            Rgba::rgb(230, 220, 200)
2005        );
2006        assert_eq!(
2007            without_header.toolbar.background_color,
2008            header_as_window.toolbar.background_color
2009        );
2010        assert_eq!(
2011            without_header.toolbar.border.color,
2012            header_as_window.toolbar.border.color
2013        );
2014        Ok(())
2015    }
2016
2017    /// A `[Colors:Header]` group that lacks a key takes that key from
2018    /// `[Colors:Window]` (kcolorscheme.cpp:330-332 at 27066d47), the other
2019    /// from the group.
2020    #[test]
2021    fn a_header_group_takes_a_missing_key_from_the_window() -> crate::Result<()> {
2022        let window = ("230,220,200", "90,40,20");
2023        let without_header = Scheme {
2024            window,
2025            header: None,
2026            ..BREEZE_LIGHT_SCHEME
2027        };
2028        let with_one_key = |key: &str| -> crate::Result<crate::ResolvedTheme> {
2029            let content = format!(
2030                "{}[Colors:Header]\n{key}=180,200,220\n",
2031                without_header.kdeglobals()
2032            );
2033            let st = crate::pipeline::run_pipeline(from_kde_content(&content)?, "kde-breeze")?;
2034            Ok(st.light)
2035        };
2036        let no_text = with_one_key("BackgroundNormal")?;
2037        let expected = resolved_light(&Scheme {
2038            header: Some(("180,200,220", window.1)),
2039            ..without_header
2040        })?;
2041        assert_eq!(no_text.toolbar.background_color, Rgba::rgb(180, 200, 220));
2042        assert_eq!(no_text.toolbar.border.color, expected.toolbar.border.color);
2043        let no_fill = with_one_key("ForegroundNormal")?;
2044        let expected = resolved_light(&Scheme {
2045            header: Some((window.0, "180,200,220")),
2046            ..without_header
2047        })?;
2048        assert_eq!(no_fill.toolbar.background_color, Rgba::rgb(230, 220, 200));
2049        assert_eq!(no_fill.toolbar.border.color, expected.toolbar.border.color);
2050        Ok(())
2051    }
2052
2053    /// A colour scheme moves none of the sizes and shadows `kde-breeze`
2054    /// states beside the derived colours: the toolbar edge's width and
2055    /// shadow, the popover's padding, the card's width, radius, shadow and
2056    /// padding, the progress bar's padding: each is the resolved preset's.
2057    #[test]
2058    fn a_colour_scheme_keeps_the_stated_edge_geometry() -> crate::Result<()> {
2059        let preset = crate::Theme::preset("kde-breeze")?
2060            .resolve(crate::ColorMode::Light)?
2061            .variant;
2062        let other = resolved_light(&Scheme {
2063            button: ("200,180,150", "60,20,10"),
2064            header: Some(("180,200,220", "10,40,80")),
2065            selection: ("233,84,32", "255,255,255"),
2066            view: ("250,240,230", "120,30,60"),
2067            focus: "20,200,90",
2068            hover: "240,160,20",
2069            window: ("230,220,200", "90,40,20"),
2070            frame_contrast: Some("0.5"),
2071            contrast: None,
2072            change_selection_color: None,
2073            inactive_enable: None,
2074        })?;
2075        let geometry = |b: &crate::ResolvedWidgetBorder| {
2076            (b.corner_radius, b.line_width, b.shadow_enabled, b.padding)
2077        };
2078        for (leaf, a, b) in [
2079            ("toolbar", &preset.toolbar.border, &other.toolbar.border),
2080            ("popover", &preset.popover.border, &other.popover.border),
2081            ("card", &preset.card.border, &other.card.border),
2082            (
2083                "progress_bar",
2084                &preset.progress_bar.border,
2085                &other.progress_bar.border,
2086            ),
2087        ] {
2088            assert_eq!(geometry(a), geometry(b), "{leaf}.border");
2089        }
2090        Ok(())
2091    }
2092
2093    /// `menuFont` sets the menu's family, size, weight and style and keeps
2094    /// the colour the colour scheme gave it.
2095    #[test]
2096    fn the_menu_font_keeps_the_window_text_colour() -> crate::Result<()> {
2097        let result = from_kde_content(BREEZE_DARK_FULL)?;
2098        let font = reader_mode(&result).menu.font.clone().unwrap_or_default();
2099        assert_eq!(font.family.as_deref(), Some("Noto Sans"));
2100        assert_eq!(font.color, Some(Rgba::rgb(239, 240, 241)));
2101        Ok(())
2102    }
2103
2104    // === KDE-06: Accessibility ===
2105
2106    #[test]
2107    fn test_animation_duration_factor_zero_sets_reduce_motion_true() {
2108        let (_theme, _dpi, accessibility) = from_kde_content_pure(BREEZE_DARK_FULL, None).unwrap();
2109        assert!(accessibility.reduce_motion);
2110    }
2111
2112    #[test]
2113    fn test_animation_duration_factor_nonzero_sets_reduce_motion_false() {
2114        let content = "\
2115[Colors:Window]
2116BackgroundNormal=49,54,59
2117
2118[KDE]
2119AnimationDurationFactor=1.0
2120";
2121        let (_theme, _dpi, accessibility) = from_kde_content_pure(content, None).unwrap();
2122        assert!(!accessibility.reduce_motion);
2123    }
2124
2125    /// `forceFontDPI` lives in kcmfonts, which the fonts KCM writes it to
2126    /// and krdb reads it from (docs/platform-facts.md:717); a kdeglobals key
2127    /// of that name is no font DPI and does not replace the one given.
2128    #[test]
2129    fn a_kdeglobals_force_font_dpi_is_not_the_font_dpi() -> crate::Result<()> {
2130        let content = "[General]\nforceFontDPI=120\n";
2131        let (_theme, dpi, _accessibility) = from_kde_content_pure(content, None)?;
2132        assert_eq!(dpi, None);
2133        let (_theme, dpi, _accessibility) = from_kde_content_pure(content, Some(144.0))?;
2134        assert_eq!(dpi, Some(144.0));
2135        Ok(())
2136    }
2137
2138    /// The reader reports the font DPI of every Linux desktop, 96, on any
2139    /// session; the fixture's kdeglobals `forceFontDPI=120` stays ignored.
2140    #[test]
2141    fn the_reader_reports_a_font_dpi_of_96() -> crate::Result<()> {
2142        let result = from_kde_content(BREEZE_DARK_FULL)?;
2143        assert_eq!(result.font_dpi, Some(96.0));
2144        let sys = crate::pipeline::run_pipeline(result, "kde-breeze")?;
2145        // Noto Sans 10 pt at 96 DPI, 13.33 px, which kde-breeze's
2146        // `font_whole_pixels` rounds to 13 as Qt does.
2147        let size = sys.dark.defaults.font.size;
2148        assert_eq!(size, 13.0, "drawn at {size} px");
2149        Ok(())
2150    }
2151
2152    /// `[KDE] CursorBlinkRate` is bounded to 200..=2000 and halved into both
2153    /// durations; 0 or less states no blink; text that is not an integer, or
2154    /// no key, states nothing; no time-out is ever written.
2155    #[test]
2156    fn the_blink_rate_is_halved_within_qts_bound() -> crate::Result<()> {
2157        let cases: [(&str, Option<u32>, Option<u32>); 8] = [
2158            ("[KDE]\nCursorBlinkRate=1000\n", Some(500), Some(500)),
2159            ("[KDE]\nCursorBlinkRate=1001\n", Some(500), Some(500)),
2160            ("[KDE]\nCursorBlinkRate=100\n", Some(100), Some(100)),
2161            ("[KDE]\nCursorBlinkRate=5000\n", Some(1000), Some(1000)),
2162            ("[KDE]\nCursorBlinkRate=0\n", None, Some(0)),
2163            ("[KDE]\nCursorBlinkRate=-1\n", None, Some(0)),
2164            ("[KDE]\nCursorBlinkRate=fast\n", None, None),
2165            (MINIMAL_FIXTURE, None, None),
2166        ];
2167        for (content, on, off) in cases {
2168            let result = from_kde_content(content)?;
2169            let input = &reader_mode(&result).input;
2170            assert_eq!(
2171                (
2172                    input.caret_blink_on,
2173                    input.caret_blink_off,
2174                    input.caret_blink_timeout
2175                ),
2176                (on, off, None),
2177                "{content:?}"
2178            );
2179        }
2180        Ok(())
2181    }
2182
2183    /// A rate of 0 resolves over kde-breeze to a caret that does not blink,
2184    /// the shown duration the preset's.
2185    #[test]
2186    fn a_kde_blink_rate_of_0_resolves_to_no_blink() -> crate::Result<()> {
2187        let result = from_kde_content("[KDE]\nCursorBlinkRate=0\n")?;
2188        let sys = crate::pipeline::run_pipeline(result, "kde-breeze")?;
2189        assert_eq!(sys.light.input.caret_blink_off, Some(0));
2190        assert_eq!(sys.light.input.caret_blink_on, Some(500));
2191        Ok(())
2192    }
2193
2194    #[test]
2195    fn test_missing_accessibility_leaves_defaults() {
2196        let content = "\
2197[Colors:Window]
2198BackgroundNormal=49,54,59
2199";
2200        let (_theme, dpi, accessibility) = from_kde_content_pure(content, None).unwrap();
2201        assert!(!accessibility.reduce_motion);
2202        assert_eq!(accessibility.text_scaling_factor, 1.0);
2203        // No font DPI given -> None from pure function
2204        assert!(dpi.is_none());
2205    }
2206
2207    // === KDE-05: Icon set ===
2208
2209    #[test]
2210    fn test_icon_theme_from_icons_theme() {
2211        let result = from_kde_content(BREEZE_DARK_FULL).unwrap();
2212        // icon_set is on ReaderResult, icon_theme is on variant defaults
2213        assert!(result.icon_set.is_none());
2214        let v = reader_mode(&result);
2215        assert_eq!(v.defaults.icon_theme.as_deref(), Some("breeze-dark"));
2216    }
2217
2218    #[test]
2219    fn test_icon_theme_none_when_missing() {
2220        let content = "\
2221[Colors:Window]
2222BackgroundNormal=49,54,59
2223";
2224        let result = from_kde_content(content).unwrap();
2225        assert!(result.icon_set.is_none());
2226        let v = reader_mode(&result);
2227        assert!(v.defaults.icon_theme.is_none());
2228    }
2229
2230    // === KDE-05: Icon sizes from index.theme ===
2231
2232    /// Breeze's index.theme from breeze-icons 6.30.0
2233    /// (`/usr/share/icons/breeze/index.theme`): its `[Icon Theme]` group
2234    /// (:1-145), `[actions/12]` (:146-150) and `[apps/32]` (:329-332).
2235    const BREEZE_INDEX_THEME: &str = include_str!("../../tests/fixtures/kde/breeze-index.theme");
2236
2237    /// The sizes are the `[Icon Theme]` group's `*Default` keys, as
2238    /// KIconTheme reads them, not the smallest directories the theme lists.
2239    #[test]
2240    fn icon_sizes_are_the_icon_themes_default_keys() {
2241        let mut ini = create_kde_parser();
2242        read_kconfig(&mut ini, BREEZE_INDEX_THEME);
2243        assert_eq!(
2244            parse_icon_sizes_from_content(&ini),
2245            IconSizes {
2246                toolbar: Some(22.0),
2247                small: Some(16.0),
2248                large: Some(48.0),
2249                dialog: Some(32.0),
2250                panel: Some(48.0),
2251            }
2252        );
2253    }
2254
2255    #[test]
2256    fn test_parse_icon_sizes_missing_theme() {
2257        let sizes =
2258            parse_icon_sizes_from_index_theme("nonexistent_theme_that_does_not_exist_12345");
2259        assert!(
2260            sizes.small.is_none(),
2261            "small should be None for missing theme"
2262        );
2263        assert!(
2264            sizes.toolbar.is_none(),
2265            "toolbar should be None for missing theme"
2266        );
2267        assert!(
2268            sizes.large.is_none(),
2269            "large should be None for missing theme"
2270        );
2271        assert!(
2272            sizes.dialog.is_none(),
2273            "dialog should be None for missing theme"
2274        );
2275        assert!(
2276            sizes.panel.is_none(),
2277            "panel should be None for missing theme"
2278        );
2279    }
2280
2281    /// A theme that states no default sizes has KIconTheme's fallbacks,
2282    /// whatever directories it lists.
2283    #[test]
2284    fn an_icon_theme_without_default_keys_has_kiconthemes_fallbacks() {
2285        let content = "\
2286[Icon Theme]
2287Name=sizeless
2288Directories=actions/12
2289
2290[actions/12]
2291Size=12
2292Context=Actions
2293Type=Fixed
2294";
2295        let mut ini = create_kde_parser();
2296        read_kconfig(&mut ini, content);
2297        assert_eq!(
2298            parse_icon_sizes_from_content(&ini),
2299            IconSizes {
2300                toolbar: Some(22.0),
2301                small: Some(16.0),
2302                large: Some(32.0),
2303                dialog: Some(32.0),
2304                panel: Some(48.0),
2305            }
2306        );
2307    }
2308
2309    /// The index.theme is found in any base directory, `~/.icons` among
2310    /// them, the first base holding it winning.
2311    #[test]
2312    fn the_index_theme_is_found_in_any_icon_base_dir() {
2313        let dir = temp_config_dir("icon-bases");
2314        let data_icons = dir.join("share/icons");
2315        let dot_icons = dir.join("home/.icons");
2316        std::fs::create_dir_all(dot_icons.join("dotted")).unwrap();
2317        std::fs::create_dir_all(data_icons.join("both")).unwrap();
2318        std::fs::create_dir_all(dot_icons.join("both")).unwrap();
2319        std::fs::write(
2320            dot_icons.join("dotted/index.theme"),
2321            "[Icon Theme]\nSmallDefault=24\n",
2322        )
2323        .unwrap();
2324        std::fs::write(
2325            data_icons.join("both/index.theme"),
2326            "[Icon Theme]\nDesktopDefault=64\n",
2327        )
2328        .unwrap();
2329        std::fs::write(
2330            dot_icons.join("both/index.theme"),
2331            "[Icon Theme]\nDesktopDefault=32\n",
2332        )
2333        .unwrap();
2334        let bases = [data_icons, dot_icons];
2335
2336        let dotted = icon_sizes_in_bases("dotted", &bases);
2337        assert_eq!(dotted.small, Some(24.0));
2338        assert_eq!(icon_sizes_in_bases("both", &bases).large, Some(64.0));
2339        assert_eq!(icon_sizes_in_bases("absent", &bases), IconSizes::default());
2340    }
2341
2342    /// KIconTheme's order: the user's data home, then each data dir, then
2343    /// `~/.icons`, which KDE does not search, last; with no home directory
2344    /// the data dirs are still searched.
2345    #[test]
2346    fn kde_icon_base_dirs_follow_kiconthemes_order() {
2347        use std::ffi::OsStr;
2348        use std::path::Path;
2349
2350        assert_eq!(
2351            kde_icon_base_dirs(Some(Path::new("/h")), None, Some(OsStr::new("/a:rel:/b"))),
2352            paths(&["/h/.local/share/icons", "/a/icons", "/b/icons", "/h/.icons"])
2353        );
2354        assert_eq!(
2355            kde_icon_base_dirs(
2356                Some(Path::new("/h")),
2357                Some(OsStr::new("/data")),
2358                Some(OsStr::new(""))
2359            ),
2360            paths(&[
2361                "/data/icons",
2362                "/usr/local/share/icons",
2363                "/usr/share/icons",
2364                "/h/.icons"
2365            ])
2366        );
2367        assert_eq!(
2368            kde_icon_base_dirs(None, Some(OsStr::new("rel")), Some(OsStr::new("/a"))),
2369            paths(&["/a/icons"])
2370        );
2371    }
2372
2373    /// A theme the user installed over a system one, as "Get New Icons"
2374    /// does into `~/.local/share/icons`, gives the user copy's sizes, the
2375    /// copy KIconTheme reads.
2376    #[test]
2377    fn the_users_copy_of_an_icon_theme_wins() {
2378        let dir = temp_config_dir("icon-user-copy");
2379        let home = dir.join("home");
2380        let system = dir.join("usr/share");
2381        std::fs::create_dir_all(home.join(".local/share/icons/copied")).unwrap();
2382        std::fs::create_dir_all(system.join("icons/copied")).unwrap();
2383        std::fs::write(
2384            home.join(".local/share/icons/copied/index.theme"),
2385            "[Icon Theme]\nDesktopDefault=64\n",
2386        )
2387        .unwrap();
2388        std::fs::write(
2389            system.join("icons/copied/index.theme"),
2390            "[Icon Theme]\nDesktopDefault=48\n",
2391        )
2392        .unwrap();
2393        let bases = kde_icon_base_dirs(Some(&home), None, Some(system.as_os_str()));
2394        assert_eq!(icon_sizes_in_bases("copied", &bases).large, Some(64.0));
2395    }
2396
2397    /// A key a found theme omits, or one that is no size, has KIconTheme's
2398    /// own fallback for its group.
2399    #[test]
2400    fn a_key_the_icon_theme_omits_has_kiconthemes_fallback() {
2401        let mut ini = create_kde_parser();
2402        read_kconfig(
2403            &mut ini,
2404            "[Icon Theme]\nName=partial\nSmallDefault=24\nPanelDefault=big\n",
2405        );
2406        assert_eq!(
2407            parse_icon_sizes_from_content(&ini),
2408            IconSizes {
2409                toolbar: Some(22.0),
2410                small: Some(24.0),
2411                large: Some(32.0),
2412                dialog: Some(32.0),
2413                panel: Some(48.0),
2414            }
2415        );
2416    }
2417
2418    /// A name that is not one directory, as `../dotted`, is no theme: the
2419    /// search never leaves the base directories.
2420    #[test]
2421    fn an_icon_theme_name_with_a_path_is_not_searched() {
2422        let dir = temp_config_dir("icon-name");
2423        std::fs::create_dir_all(dir.join("icons")).unwrap();
2424        std::fs::create_dir_all(dir.join("dotted")).unwrap();
2425        std::fs::write(
2426            dir.join("dotted/index.theme"),
2427            "[Icon Theme]\nSmallDefault=24\n",
2428        )
2429        .unwrap();
2430        let bases = [dir.join("icons")];
2431        assert_eq!(
2432            icon_sizes_in_bases("../dotted", &bases),
2433            IconSizes::default()
2434        );
2435    }
2436
2437    #[test]
2438    fn test_parse_icon_sizes_no_icon_theme_section() {
2439        let content = "\
2440[General]
2441Name=whatever
2442";
2443        let mut ini = create_kde_parser();
2444        ini.read(content.to_string()).unwrap();
2445        let sizes = parse_icon_sizes_from_content(&ini);
2446        assert_eq!(sizes.small, Some(16.0));
2447        assert_eq!(sizes.toolbar, Some(22.0));
2448        assert_eq!(sizes.large, Some(32.0));
2449    }
2450
2451    #[test]
2452    fn test_icon_sizes_populated_in_full_parse() {
2453        // This test checks that from_kde_content wires icon sizes from index.theme.
2454        // On systems with breeze-dark installed, icon_sizes will be populated.
2455        // On systems without it, icon_sizes will be None. Both are valid.
2456        let result = from_kde_content(BREEZE_DARK_FULL).unwrap();
2457        let v = reader_mode(&result);
2458
2459        if let Some(small) = v.defaults.icon_sizes.small {
2460            // If populated, they should be reasonable pixel values
2461            assert!(
2462                (8.0..=32.0).contains(&small),
2463                "small icon size should be reasonable: {small}"
2464            );
2465
2466            if let Some(large) = v.defaults.icon_sizes.large {
2467                assert!(
2468                    (24.0..=128.0).contains(&large),
2469                    "large icon size should be reasonable: {large}"
2470                );
2471                assert!(large > small, "large should be bigger than small");
2472            }
2473        }
2474        // else: theme not installed on this system, icon_sizes remain None -- acceptable
2475    }
2476
2477    // === Dialog button order ===
2478
2479    #[test]
2480    fn test_dialog_button_order_not_set_by_reader() {
2481        let result = from_kde_content(BREEZE_DARK_FULL).unwrap();
2482        let v = reader_mode(&result);
2483        assert_eq!(
2484            v.dialog.button_order, None,
2485            "reader must not hardcode button_order -- resolver handles it"
2486        );
2487    }
2488
2489    // === Widget sizing from Breeze metrics ===
2490
2491    #[test]
2492    fn test_widget_sizing_checkbox_indicator() {
2493        let result = from_kde_content(BREEZE_DARK_FULL).unwrap();
2494        let v = reader_mode(&result);
2495        assert_eq!(v.checkbox.indicator_width, Some(20.0));
2496    }
2497
2498    #[test]
2499    fn test_widget_sizing_splitter() {
2500        let result = from_kde_content(BREEZE_DARK_FULL).unwrap();
2501        let v = reader_mode(&result);
2502        assert_eq!(v.splitter.divider_width, Some(1.0));
2503    }
2504
2505    // === Per-widget fonts (KDE-03) ===
2506
2507    #[test]
2508    fn test_menu_font_from_menufont() {
2509        let result = from_kde_content(BREEZE_DARK_FULL).unwrap();
2510        let v = reader_mode(&result);
2511        let mf = v.menu.font.as_ref().expect("menu.font should be set");
2512        assert_eq!(mf.family.as_deref(), Some("Noto Sans"));
2513        assert_eq!(mf.size, Some(FontSize::Pt(9.0)));
2514    }
2515
2516    #[test]
2517    fn test_toolbar_font_from_toolbarfont() {
2518        let result = from_kde_content(BREEZE_DARK_FULL).unwrap();
2519        let v = reader_mode(&result);
2520        let tf = v.toolbar.font.as_ref().expect("toolbar.font should be set");
2521        assert_eq!(tf.family.as_deref(), Some("Noto Sans"));
2522        assert_eq!(tf.size, Some(FontSize::Pt(8.0)));
2523    }
2524
2525    #[test]
2526    fn test_title_bar_font_from_wm_activefont() {
2527        let result = from_kde_content(BREEZE_DARK_FULL).unwrap();
2528        let v = reader_mode(&result);
2529        let tbf = v
2530            .window
2531            .title_bar_font
2532            .as_ref()
2533            .expect("title_bar_font should be set");
2534        assert_eq!(tbf.family.as_deref(), Some("Noto Sans"));
2535        assert_eq!(tbf.size, Some(FontSize::Pt(10.0)));
2536        assert_eq!(tbf.weight, Some(700)); // Qt5 75 -> CSS 700
2537    }
2538
2539    // === Integration test: resolve() + validate() pipeline ===
2540
2541    #[test]
2542    fn test_kde_resolve_validate() {
2543        // Load the KDE Breeze preset as a base (provides geometry, spacing, icon sizes,
2544        // and other fields that KDE's kdeglobals doesn't carry).
2545        let mut base = crate::Theme::preset("kde-breeze").unwrap();
2546        let result = from_kde_content(BREEZE_DARK_FULL).unwrap();
2547        let kde_theme = result
2548            .output
2549            .to_theme(&result.name, result.icon_set, &result.layout);
2550
2551        // Merge KDE reader output on top of the base preset.
2552        // The KDE variant is dark-only; merge will clone it into the base.
2553        base.merge(&kde_theme);
2554
2555        // Extract the dark variant (KDE's output merged on top of default dark).
2556        let mut dark = base
2557            .dark
2558            .clone()
2559            .expect("dark variant should exist after merge");
2560
2561        // Run the resolution pipeline.
2562        dark.resolve_all();
2563
2564        // Validate should produce Ok(ResolvedTheme) with all fields filled.
2565        let resolved = dark.validate().unwrap_or_else(|e| {
2566            panic!("KDE resolve/validate pipeline failed: {e}");
2567        });
2568
2569        // Spot-check: KDE-sourced fields should be present.
2570        // accent from Colors:View/DecorationFocus = 61,174,233
2571        assert_eq!(
2572            resolved.defaults.accent_color,
2573            crate::Rgba::rgb(61, 174, 233),
2574            "accent should be from KDE reader"
2575        );
2576
2577        // font.family from [General] font
2578        assert_eq!(
2579            resolved.defaults.font.family.as_ref(),
2580            "Noto Sans",
2581            "font family should be from KDE reader"
2582        );
2583
2584        // button.background from Colors:Button/BackgroundNormal = 49,54,59
2585        assert_eq!(
2586            resolved.button.background_color,
2587            crate::Rgba::rgb(49, 54, 59),
2588            "button bg should be from KDE reader"
2589        );
2590
2591        // window.title_bar_background from WM/activeBackground = 49,54,59
2592        assert_eq!(
2593            resolved.window.title_bar_background,
2594            crate::Rgba::rgb(49, 54, 59),
2595            "title bar bg should be from KDE reader"
2596        );
2597
2598        // input.caret from Colors:View/DecorationFocus = 61,174,233
2599        assert_eq!(
2600            resolved.input.caret_color,
2601            crate::Rgba::rgb(61, 174, 233),
2602            "input.caret should be from KDE reader (DecorationFocus)"
2603        );
2604
2605        // icon_set is now on Theme/SystemTheme, not on ResolvedTheme
2606
2607        // dialog.button_order should be from KDE reader
2608        assert_eq!(
2609            resolved.dialog.button_order,
2610            crate::DialogButtonOrder::PrimaryLeft,
2611            "dialog button order should be leading affirmative for KDE"
2612        );
2613    }
2614
2615    // === Plan 94-03 (G8): KdeReader ThemeReader impl ===
2616    //
2617    // Locks the G8 contract on the KDE side: a unit struct `KdeReader` exists
2618    // at the module root and implements `crate::reader::ThemeReader`. Before
2619    // Task 2 lands, this fails to compile (`no struct KdeReader` / `unresolved
2620    // module crate::reader`).
2621    #[test]
2622    fn kde_reader_exists_and_implements_theme_reader() {
2623        // Object-safe coercion: proves the trait is consumable via dyn.
2624        let r: Box<dyn crate::reader::ThemeReader> = Box::new(super::KdeReader);
2625        // read() is async — drive it to completion on a simple pollster runtime.
2626        // On systems without a readable kdeglobals the result may legitimately be
2627        // Err(ReaderFailed); either outcome validates the trait dispatch path,
2628        // the strictly-tested invariant is that `r.read()` type-checks and can
2629        // be awaited without runtime panics.
2630        let _: crate::Result<crate::ReaderResult> = pollster::block_on(r.read());
2631    }
2632}