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