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