Skip to main content

native_theme/detect/
icon_theme.rs

1// Icon set and icon theme detection: the native icon set per OS, and the
2// icon theme each Linux desktop keeps in its settings.
3
4use crate::model::IconSet;
5
6/// Detect the native icon set for the current operating system.
7///
8/// Returns the platform-appropriate icon set at runtime using `cfg!()` macros:
9/// - macOS / iOS: [`IconSet::SfSymbols`]
10/// - Windows: [`IconSet::SegoeFluent`]
11/// - Linux: [`IconSet::Freedesktop`]
12/// - Other: [`IconSet::Material`] (safe cross-platform fallback)
13///
14/// # Examples
15///
16/// ```
17/// use native_theme::detect::system_icon_set;
18///
19/// let set = system_icon_set();
20/// // On Linux, this returns Freedesktop
21/// ```
22#[must_use]
23pub fn system_icon_set() -> IconSet {
24    if cfg!(any(target_os = "macos", target_os = "ios")) {
25        IconSet::SfSymbols
26    } else if cfg!(target_os = "windows") {
27        IconSet::SegoeFluent
28    } else if cfg!(target_os = "linux") {
29        IconSet::Freedesktop
30    } else {
31        IconSet::Material
32    }
33}
34
35/// Detect the icon theme name for the current platform (cached).
36///
37/// Returns the name of the icon theme that provides the actual icon files:
38/// - **macOS / iOS:** `"sf-symbols"` (no user-configurable icon theme)
39/// - **Windows:** `"segoe-fluent"` (no user-configurable icon theme)
40/// - **Linux:** DE-specific detection (e.g., `"breeze-dark"`, `"Adwaita"`)
41/// - **Other:** an error; there is no icon theme to detect
42///
43/// On Linux, the detection method depends on the desktop environment, the
44/// one the reader is chosen by: an unrecognised `XDG_CURRENT_DESKTOP` counts
45/// as the desktop of its portal backend (once a system read such as
46/// [`SystemTheme::from_system`](crate::SystemTheme::from_system) has asked
47/// it, with the `portal` feature), else as KDE where the user's `kdeglobals`
48/// exists (with the `kde` feature):
49/// - KDE: `[Icons] Theme` of kdeglobals as KConfig cascades it, the KDE
50///   reader's read (with the `kde` feature); without the feature, from
51///   `kdeglobals`, then from `kdedefaults/kdeglobals`
52/// - GNOME/Budgie: `gsettings get org.gnome.desktop.interface icon-theme`
53/// - Cinnamon: `gsettings get org.cinnamon.desktop.interface icon-theme`
54/// - XFCE: `xfconf-query -c xsettings -p /Net/IconThemeName`
55/// - MATE: `gsettings get org.mate.interface icon-theme`
56/// - LXQt: reads `icon_theme` from `~/.config/lxqt/lxqt.conf`
57/// - Unknown (still): tries KDE, then GNOME gsettings
58///
59/// No theme stands in for one that cannot be detected: the error says why,
60/// and what to do without a theme is the caller's decision.
61///
62/// Delegates to [`DetectionContext::icon_theme()`](crate::detect::DetectionContext::icon_theme)
63/// which caches the outcome, a failure included, and supports per-field
64/// invalidation via [`invalidate_caches()`](crate::detect::invalidate_caches).
65///
66/// # Errors
67///
68/// - [`Error::ReaderFailed`](crate::Error::ReaderFailed) with `reader`
69///   `"icon-theme"` on Linux when no source names a theme. Its message names
70///   each source tried and why it gave no name: the config directory could
71///   not be resolved (no absolute `$XDG_CONFIG_HOME`, and `$HOME` unset or
72///   empty), a file could not be read or lacks the key, or a command was not
73///   found, exited unsuccessfully, printed no name or did not finish within
74///   2 s. On an unrecognised desktop it names both attempts, KDE's and
75///   GNOME's.
76/// - [`Error::PlatformUnsupported`](crate::Error::PlatformUnsupported) on a
77///   platform other than Linux, macOS, iOS and Windows.
78///
79/// # Examples
80///
81/// ```
82/// use native_theme::detect::system_icon_theme;
83///
84/// match system_icon_theme() {
85///     // On a KDE system with Breeze Dark: "breeze-dark"; on macOS: "sf-symbols"
86///     Ok(theme) => println!("icon theme: {theme}"),
87///     Err(e) => println!("no icon theme: {e}"),
88/// }
89/// ```
90pub fn system_icon_theme() -> crate::Result<String> {
91    crate::detect::system().icon_theme()
92}
93
94/// Detect the icon theme name for the current platform without caching.
95///
96/// Unlike [`system_icon_theme()`], this function queries the OS every time it
97/// is called and never caches the result. Use this when polling for icon theme
98/// changes (e.g., the user switches from Breeze to Breeze Dark in system
99/// settings).
100///
101/// See [`system_icon_theme()`] for platform behavior details.
102///
103/// # Errors
104///
105/// As [`system_icon_theme()`].
106pub fn detect_icon_theme() -> crate::Result<String> {
107    detect_icon_theme_outcome().map_err(|failure| failure.to_error())
108}
109
110/// [`detect_icon_theme()`]'s outcome in the form the detection cache keeps.
111pub(crate) fn detect_icon_theme_outcome() -> Result<String, IconThemeFailure> {
112    #[cfg(any(target_os = "macos", target_os = "ios"))]
113    {
114        Ok("sf-symbols".to_string())
115    }
116
117    #[cfg(target_os = "windows")]
118    {
119        Ok("segoe-fluent".to_string())
120    }
121
122    #[cfg(target_os = "linux")]
123    {
124        detect_linux_icon_theme()
125    }
126
127    #[cfg(not(any(
128        target_os = "linux",
129        target_os = "windows",
130        target_os = "macos",
131        target_os = "ios"
132    )))]
133    {
134        Err(IconThemeFailure::Unsupported(std::env::consts::OS))
135    }
136}
137
138/// One source's failure to name an icon theme: the source, and why it gave
139/// no name.
140#[derive(Debug, Clone, PartialEq, Eq)]
141#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
142pub(crate) struct SourceFailure {
143    source: String,
144    reason: String,
145}
146
147impl std::fmt::Display for SourceFailure {
148    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149        write!(f, "{}: {}", self.source, self.reason)
150    }
151}
152
153/// Why no icon theme was detected: each source tried, in order, with why it
154/// gave no name. The source of the
155/// [`Error::ReaderFailed`](crate::Error::ReaderFailed) a failed detection
156/// reports.
157#[derive(Debug, Clone, PartialEq, Eq)]
158#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
159pub(crate) struct IconThemeUndetected(Vec<SourceFailure>);
160
161impl std::fmt::Display for IconThemeUndetected {
162    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
163        let mut sources = self.0.iter();
164        if let Some(first) = sources.next() {
165            write!(f, "{first}")?;
166        }
167        for failure in sources {
168            write!(f, "; {failure}")?;
169        }
170        Ok(())
171    }
172}
173
174impl std::error::Error for IconThemeUndetected {}
175
176/// A failed icon-theme detection as the detection cache keeps it. Unlike
177/// [`crate::Error`] it is `Clone`, so the cache can hand out the failure it
178/// holds; [`to_error`](Self::to_error) builds the error from it.
179#[derive(Debug, Clone, PartialEq, Eq)]
180pub(crate) enum IconThemeFailure {
181    /// No source named a theme.
182    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
183    Undetected(IconThemeUndetected),
184    /// The platform has no icon theme to detect.
185    #[cfg_attr(
186        any(
187            target_os = "linux",
188            target_os = "windows",
189            target_os = "macos",
190            target_os = "ios"
191        ),
192        allow(dead_code)
193    )]
194    Unsupported(&'static str),
195}
196
197impl IconThemeFailure {
198    /// The error [`system_icon_theme()`] and [`detect_icon_theme()`] report.
199    pub(crate) fn to_error(&self) -> crate::Error {
200        match self {
201            Self::Undetected(undetected) => crate::Error::ReaderFailed {
202                reader: crate::error::reader_names::ICON_THEME,
203                source: Box::new(undetected.clone()),
204            },
205            Self::Unsupported(platform) => crate::Error::PlatformUnsupported { platform },
206        }
207    }
208
209    /// A failure with `reason`, for tests of the code that keeps and
210    /// reports failures.
211    #[cfg(test)]
212    pub(crate) fn for_tests(reason: &str) -> Self {
213        Self::Undetected(IconThemeUndetected(vec![SourceFailure {
214            source: "test".to_string(),
215            reason: reason.to_string(),
216        }]))
217    }
218}
219
220/// The schema GNOME, and the desktops that follow its settings, keep the
221/// icon theme in.
222#[cfg(target_os = "linux")]
223const GNOME_INTERFACE_SCHEMA: &str = "org.gnome.desktop.interface";
224
225/// Where a Linux desktop keeps its icon theme.
226#[cfg(target_os = "linux")]
227#[derive(Debug, Clone, Copy, PartialEq, Eq)]
228enum IconThemeSource {
229    /// KDE's kdeglobals.
230    Kde,
231    /// `gsettings get <schema> icon-theme`.
232    Gsettings(&'static str),
233    /// XFCE's xfconf.
234    Xfce,
235    /// LXQt's `lxqt.conf`.
236    LxQt,
237    /// KDE's, else GNOME's: a desktop that nothing names.
238    KdeThenGnome,
239}
240
241/// The icon-theme source of `desktop`, the refined desktop
242/// ([`crate::detect::refine_linux_desktop`]) the reader is chosen by.
243#[cfg(target_os = "linux")]
244fn icon_theme_source(desktop: crate::detect::LinuxDesktop) -> IconThemeSource {
245    use crate::detect::LinuxDesktop;
246
247    match desktop {
248        LinuxDesktop::Kde => IconThemeSource::Kde,
249        LinuxDesktop::Gnome
250        | LinuxDesktop::Budgie
251        | LinuxDesktop::Hyprland
252        | LinuxDesktop::Sway
253        | LinuxDesktop::River
254        | LinuxDesktop::Niri
255        | LinuxDesktop::Wayfire
256        | LinuxDesktop::CosmicDe => IconThemeSource::Gsettings(GNOME_INTERFACE_SCHEMA),
257        LinuxDesktop::Cinnamon => IconThemeSource::Gsettings("org.cinnamon.desktop.interface"),
258        LinuxDesktop::Xfce => IconThemeSource::Xfce,
259        LinuxDesktop::Mate => IconThemeSource::Gsettings("org.mate.interface"),
260        LinuxDesktop::LxQt => IconThemeSource::LxQt,
261        LinuxDesktop::Unknown => IconThemeSource::KdeThenGnome,
262    }
263}
264
265/// Linux icon theme detection, dispatched by the refined desktop.
266#[cfg(target_os = "linux")]
267fn detect_linux_icon_theme() -> Result<String, IconThemeFailure> {
268    let desktop = crate::detect::system().refined_linux_desktop_sync();
269    let found = match icon_theme_source(desktop) {
270        IconThemeSource::Kde => detect_kde_icon_theme(),
271        IconThemeSource::Gsettings(schema) => gsettings_icon_theme(schema),
272        IconThemeSource::Xfce => detect_xfce_icon_theme(),
273        IconThemeSource::LxQt => detect_lxqt_icon_theme(),
274        IconThemeSource::KdeThenGnome => {
275            return unknown_desktop_icon_theme(detect_kde_icon_theme, || {
276                gsettings_icon_theme(GNOME_INTERFACE_SCHEMA)
277            });
278        }
279    };
280    found.map_err(|failure| IconThemeFailure::Undetected(IconThemeUndetected(vec![failure])))
281}
282
283/// The icon theme of a desktop that is not recognised: KDE's, else GNOME's.
284/// Where both fail, the failure names both attempts.
285#[cfg(target_os = "linux")]
286fn unknown_desktop_icon_theme(
287    kde: impl FnOnce() -> Result<String, SourceFailure>,
288    gnome: impl FnOnce() -> Result<String, SourceFailure>,
289) -> Result<String, IconThemeFailure> {
290    let kde_failure = match kde() {
291        Ok(theme) => return Ok(theme),
292        Err(failure) => failure,
293    };
294    let gnome_failure = match gnome() {
295        Ok(theme) => return Ok(theme),
296        Err(failure) => failure,
297    };
298    Err(IconThemeFailure::Undetected(IconThemeUndetected(vec![
299        kde_failure,
300        gnome_failure,
301    ])))
302}
303
304/// The failure of a config-file source when there is no config directory.
305#[cfg(target_os = "linux")]
306fn config_dir_unresolved(source: &str) -> SourceFailure {
307    SourceFailure {
308        source: source.to_string(),
309        reason: crate::detect::CONFIG_HOME_UNRESOLVED.to_string(),
310    }
311}
312
313/// The source name of KDE's icon theme in a failure.
314#[cfg(target_os = "linux")]
315const KDE_SOURCE: &str = "KDE kdeglobals";
316
317/// The icon theme of kdeglobals as the KDE reader reads it
318/// ([`crate::kde::kdeglobals_icon_theme`]), so the two cannot disagree.
319#[cfg(all(target_os = "linux", feature = "kde"))]
320fn detect_kde_icon_theme() -> Result<String, SourceFailure> {
321    crate::kde::kdeglobals_icon_theme().map_err(|reason| SourceFailure {
322        source: KDE_SOURCE.to_string(),
323        reason,
324    })
325}
326
327/// Read the icon theme from KDE's kdeglobals INI file, without the `kde`
328/// feature, so without the KDE reader.
329#[cfg(all(target_os = "linux", not(feature = "kde")))]
330fn detect_kde_icon_theme() -> Result<String, SourceFailure> {
331    kde_icon_theme(crate::detect::xdg_config_home().as_deref(), |path| {
332        std::fs::read_to_string(path)
333    })
334}
335
336/// `[Icons] Theme` from `kdeglobals` in `config_dir`, then from
337/// `kdedefaults/kdeglobals` (Plasma 6 stores distro defaults there,
338/// including the icon theme), each file read by `read`.
339///
340/// Uses simple line parsing — no `configparser` dependency required — so this
341/// works without the `kde` feature enabled.
342#[cfg(all(target_os = "linux", not(feature = "kde")))]
343fn kde_icon_theme(
344    config_dir: Option<&std::path::Path>,
345    read: impl Fn(&std::path::Path) -> std::io::Result<String>,
346) -> Result<String, SourceFailure> {
347    let config_dir = config_dir.ok_or_else(|| config_dir_unresolved(KDE_SOURCE))?;
348    let paths = [
349        config_dir.join("kdeglobals"),
350        config_dir.join("kdedefaults").join("kdeglobals"),
351    ];
352
353    let mut reasons = Vec::new();
354    for path in &paths {
355        match read(path) {
356            Ok(content) => match crate::icons::ini_value(&content, "Icons", "Theme") {
357                Some(theme) => return Ok(theme.to_string()),
358                None => reasons.push(format!(
359                    "{}: `[Icons] Theme` is absent or empty",
360                    path.display()
361                )),
362            },
363            Err(e) => reasons.push(format!("{}: unreadable ({e})", path.display())),
364        }
365    }
366    Err(SourceFailure {
367        source: KDE_SOURCE.to_string(),
368        reason: reasons.join(", "),
369    })
370}
371
372/// Query gsettings for icon-theme with the given schema.
373#[cfg(target_os = "linux")]
374fn gsettings_icon_theme(schema: &str) -> Result<String, SourceFailure> {
375    gsettings_icon_theme_from(
376        schema,
377        crate::detect::run_with_timeout(
378            "gsettings",
379            &["get", schema, "icon-theme"],
380            crate::detect::SUBPROCESS_TIMEOUT,
381        ),
382    )
383}
384
385/// The icon theme in `gsettings get <schema> icon-theme`'s `output`, which
386/// prints it quoted (`'Adwaita'`).
387#[cfg(target_os = "linux")]
388fn gsettings_icon_theme_from(
389    schema: &str,
390    output: std::io::Result<std::process::Output>,
391) -> Result<String, SourceFailure> {
392    command_icon_theme(
393        format!("`gsettings get {schema} icon-theme`"),
394        output,
395        |printed| printed.trim().trim_matches('\''),
396    )
397}
398
399/// `xfconf-query`'s arguments that print XFCE's icon theme.
400#[cfg(target_os = "linux")]
401const XFCONF_ICON_THEME_ARGS: [&str; 4] = ["-c", "xsettings", "-p", "/Net/IconThemeName"];
402
403/// Read icon theme from XFCE's xfconf-query.
404#[cfg(target_os = "linux")]
405fn detect_xfce_icon_theme() -> Result<String, SourceFailure> {
406    xfce_icon_theme_from(crate::detect::run_with_timeout(
407        "xfconf-query",
408        &XFCONF_ICON_THEME_ARGS,
409        crate::detect::SUBPROCESS_TIMEOUT,
410    ))
411}
412
413/// The icon theme in `xfconf-query -c xsettings -p /Net/IconThemeName`'s
414/// `output`.
415#[cfg(target_os = "linux")]
416fn xfce_icon_theme_from(
417    output: std::io::Result<std::process::Output>,
418) -> Result<String, SourceFailure> {
419    command_icon_theme(
420        format!("`xfconf-query {}`", XFCONF_ICON_THEME_ARGS.join(" ")),
421        output,
422        str::trim,
423    )
424}
425
426/// The icon theme the command `source` names printed, taken out of its
427/// `output` by `parse`, or why there is none.
428#[cfg(target_os = "linux")]
429fn command_icon_theme(
430    source: String,
431    output: std::io::Result<std::process::Output>,
432    parse: fn(&str) -> &str,
433) -> Result<String, SourceFailure> {
434    let reason = match output {
435        Err(e) if e.kind() == std::io::ErrorKind::NotFound => "command not found".to_string(),
436        Err(e) if e.kind() == std::io::ErrorKind::TimedOut => e.to_string(),
437        Err(e) => format!("could not run ({e})"),
438        Ok(output) if !output.status.success() => {
439            let stderr = String::from_utf8_lossy(&output.stderr);
440            match stderr.trim() {
441                "" => format!("unsuccessful ({})", output.status),
442                stderr => format!("unsuccessful ({}): {stderr}", output.status),
443            }
444        }
445        Ok(output) => match String::from_utf8(output.stdout) {
446            Err(_) => "printed output that is not UTF-8".to_string(),
447            Ok(printed) => match parse(&printed) {
448                "" => "printed no theme name".to_string(),
449                theme => return Ok(theme.to_string()),
450            },
451        },
452    };
453    Err(SourceFailure { source, reason })
454}
455
456/// Read icon theme from LXQt's config file.
457#[cfg(target_os = "linux")]
458fn detect_lxqt_icon_theme() -> Result<String, SourceFailure> {
459    lxqt_icon_theme(crate::detect::xdg_config_home().as_deref(), |path| {
460        std::fs::read_to_string(path)
461    })
462}
463
464/// `icon_theme` from `lxqt/lxqt.conf` in `config_dir`, read by `read`.
465///
466/// LXQt uses a flat `key=value` format (no section headers for the icon_theme
467/// key), so we scan for the bare `icon_theme=` prefix.
468#[cfg(target_os = "linux")]
469fn lxqt_icon_theme(
470    config_dir: Option<&std::path::Path>,
471    read: impl Fn(&std::path::Path) -> std::io::Result<String>,
472) -> Result<String, SourceFailure> {
473    const SOURCE: &str = "LXQt lxqt.conf";
474    let config_dir = config_dir.ok_or_else(|| config_dir_unresolved(SOURCE))?;
475    let path = config_dir.join("lxqt").join("lxqt.conf");
476    let failure = |reason: String| SourceFailure {
477        source: SOURCE.to_string(),
478        reason: format!("{}: {reason}", path.display()),
479    };
480
481    let content = read(&path).map_err(|e| failure(format!("unreadable ({e})")))?;
482    content
483        .lines()
484        .filter_map(|line| line.trim().strip_prefix("icon_theme="))
485        .map(str::trim)
486        .find(|value| !value.is_empty())
487        .map(str::to_string)
488        .ok_or_else(|| failure("`icon_theme` is absent or empty".to_string()))
489}
490
491#[cfg(test)]
492#[cfg(target_os = "linux")]
493#[allow(clippy::unwrap_used, clippy::expect_used)]
494mod tests {
495    use super::*;
496    use std::os::unix::process::ExitStatusExt;
497    use std::path::{Path, PathBuf};
498    use std::process::{ExitStatus, Output};
499
500    // === system_icon_set() tests ===
501
502    #[test]
503    fn system_icon_set_returns_freedesktop_on_linux() {
504        assert_eq!(system_icon_set(), IconSet::Freedesktop);
505    }
506
507    fn missing(_: &Path) -> std::io::Result<String> {
508        Err(std::io::Error::from(std::io::ErrorKind::NotFound))
509    }
510
511    fn printed(stdout: &str) -> std::io::Result<Output> {
512        Ok(Output {
513            status: ExitStatus::from_raw(0),
514            stdout: stdout.as_bytes().to_vec(),
515            stderr: Vec::new(),
516        })
517    }
518
519    fn exited_1(stderr: &str) -> std::io::Result<Output> {
520        Ok(Output {
521            status: ExitStatus::from_raw(1 << 8),
522            stdout: Vec::new(),
523            stderr: stderr.as_bytes().to_vec(),
524        })
525    }
526
527    fn not_found() -> std::io::Result<Output> {
528        Err(std::io::Error::from(std::io::ErrorKind::NotFound))
529    }
530
531    fn timed_out() -> std::io::Result<Output> {
532        Err(std::io::Error::new(
533            std::io::ErrorKind::TimedOut,
534            "timed out after 2s",
535        ))
536    }
537
538    // === KDE: kdeglobals ===
539
540    #[cfg(not(feature = "kde"))]
541    #[test]
542    fn kde_without_a_config_dir_names_kdeglobals_and_the_config_dir() {
543        let failure = kde_icon_theme(None, missing).unwrap_err().to_string();
544        assert!(failure.contains("kdeglobals"), "got: {failure}");
545        assert!(failure.contains("config directory"), "got: {failure}");
546        assert!(failure.contains("XDG_CONFIG_HOME"), "got: {failure}");
547    }
548
549    #[cfg(not(feature = "kde"))]
550    #[test]
551    fn kde_with_no_readable_file_names_both_files() {
552        let dir = PathBuf::from("/cfg");
553        let failure = kde_icon_theme(Some(&dir), missing).unwrap_err().to_string();
554        assert!(failure.contains("/cfg/kdeglobals"), "got: {failure}");
555        assert!(
556            failure.contains("/cfg/kdedefaults/kdeglobals"),
557            "got: {failure}"
558        );
559        assert!(failure.contains("unreadable"), "got: {failure}");
560    }
561
562    #[cfg(not(feature = "kde"))]
563    #[test]
564    fn kde_with_no_icons_theme_key_says_the_key_is_absent() {
565        let dir = PathBuf::from("/cfg");
566        let failure = kde_icon_theme(Some(&dir), |_: &Path| {
567            Ok("[General]\nTheme=not-this-one\n".to_string())
568        })
569        .unwrap_err()
570        .to_string();
571        assert!(failure.contains("kdeglobals"), "got: {failure}");
572        assert!(
573            failure.contains("`[Icons] Theme` is absent or empty"),
574            "got: {failure}"
575        );
576    }
577
578    #[cfg(not(feature = "kde"))]
579    #[test]
580    fn kde_takes_the_defaults_file_where_kdeglobals_lacks_the_key() {
581        let dir = PathBuf::from("/cfg");
582        let theme = kde_icon_theme(Some(&dir), |path: &Path| {
583            if path.ends_with("kdedefaults/kdeglobals") {
584                Ok("[Icons]\nTheme=breeze-dark\n".to_string())
585            } else {
586                Ok("[General]\n".to_string())
587            }
588        });
589        assert_eq!(theme, Ok("breeze-dark".to_string()));
590    }
591
592    // === gsettings ===
593
594    #[test]
595    fn gsettings_not_found_names_the_command() {
596        let failure = gsettings_icon_theme_from("org.gnome.desktop.interface", not_found())
597            .unwrap_err()
598            .to_string();
599        assert!(
600            failure.contains("gsettings get org.gnome.desktop.interface icon-theme"),
601            "got: {failure}"
602        );
603        assert!(failure.contains("command not found"), "got: {failure}");
604    }
605
606    #[test]
607    fn gsettings_that_timed_out_says_so() {
608        let failure = gsettings_icon_theme_from("org.gnome.desktop.interface", timed_out())
609            .unwrap_err()
610            .to_string();
611        assert!(
612            failure.contains("gsettings get org.gnome.desktop.interface icon-theme"),
613            "got: {failure}"
614        );
615        assert!(failure.contains("timed out after 2s"), "got: {failure}");
616        assert!(!failure.contains("could not run"), "got: {failure}");
617    }
618
619    #[test]
620    fn gsettings_nonzero_exit_gives_the_status_and_stderr() {
621        let failure = gsettings_icon_theme_from(
622            "org.mate.interface",
623            exited_1("No such schema “org.mate.interface”\n"),
624        )
625        .unwrap_err()
626        .to_string();
627        assert!(
628            failure.contains("gsettings get org.mate.interface icon-theme"),
629            "got: {failure}"
630        );
631        assert!(
632            failure.contains("unsuccessful (exit status: 1)"),
633            "got: {failure}"
634        );
635        assert!(failure.contains("No such schema"), "got: {failure}");
636    }
637
638    #[test]
639    fn gsettings_empty_output_says_it_printed_no_name() {
640        let failure = gsettings_icon_theme_from("org.cinnamon.desktop.interface", printed("''\n"))
641            .unwrap_err()
642            .to_string();
643        assert!(
644            failure.contains("gsettings get org.cinnamon.desktop.interface icon-theme"),
645            "got: {failure}"
646        );
647        assert!(failure.contains("printed no theme name"), "got: {failure}");
648    }
649
650    #[test]
651    fn gsettings_output_is_unquoted() {
652        assert_eq!(
653            gsettings_icon_theme_from("org.gnome.desktop.interface", printed("'Adwaita'\n")),
654            Ok("Adwaita".to_string())
655        );
656    }
657
658    // === XFCE: xfconf-query ===
659
660    #[test]
661    fn xfconf_not_found_names_the_command() {
662        let failure = xfce_icon_theme_from(not_found()).unwrap_err().to_string();
663        assert!(
664            failure.contains("xfconf-query -c xsettings -p /Net/IconThemeName"),
665            "got: {failure}"
666        );
667        assert!(failure.contains("command not found"), "got: {failure}");
668    }
669
670    #[test]
671    fn xfconf_nonzero_exit_gives_the_status() {
672        let failure = xfce_icon_theme_from(exited_1("")).unwrap_err().to_string();
673        assert!(failure.contains("xfconf-query"), "got: {failure}");
674        assert!(
675            failure.contains("unsuccessful (exit status: 1)"),
676            "got: {failure}"
677        );
678    }
679
680    #[test]
681    fn xfconf_empty_output_says_it_printed_no_name() {
682        let failure = xfce_icon_theme_from(printed("\n")).unwrap_err().to_string();
683        assert!(failure.contains("xfconf-query"), "got: {failure}");
684        assert!(failure.contains("printed no theme name"), "got: {failure}");
685    }
686
687    #[test]
688    fn xfconf_output_is_trimmed() {
689        assert_eq!(
690            xfce_icon_theme_from(printed("elementary\n")),
691            Ok("elementary".to_string())
692        );
693    }
694
695    // === LXQt: lxqt.conf ===
696
697    #[test]
698    fn lxqt_without_a_config_dir_names_lxqt_conf_and_the_config_dir() {
699        let failure = lxqt_icon_theme(None, missing).unwrap_err().to_string();
700        assert!(failure.contains("lxqt.conf"), "got: {failure}");
701        assert!(failure.contains("config directory"), "got: {failure}");
702    }
703
704    #[test]
705    fn lxqt_unreadable_file_names_the_file() {
706        let dir = PathBuf::from("/cfg");
707        let failure = lxqt_icon_theme(Some(&dir), missing)
708            .unwrap_err()
709            .to_string();
710        assert!(failure.contains("/cfg/lxqt/lxqt.conf"), "got: {failure}");
711        assert!(failure.contains("unreadable"), "got: {failure}");
712    }
713
714    #[test]
715    fn lxqt_without_the_key_says_the_key_is_absent() {
716        let dir = PathBuf::from("/cfg");
717        let failure = lxqt_icon_theme(Some(&dir), |_: &Path| Ok("theme=frost\n".to_string()))
718            .unwrap_err()
719            .to_string();
720        assert!(failure.contains("/cfg/lxqt/lxqt.conf"), "got: {failure}");
721        assert!(
722            failure.contains("`icon_theme` is absent or empty"),
723            "got: {failure}"
724        );
725    }
726
727    #[test]
728    fn lxqt_reads_the_icon_theme_key() {
729        let dir = PathBuf::from("/cfg");
730        assert_eq!(
731            lxqt_icon_theme(Some(&dir), |_: &Path| Ok(
732                "[General]\nicon_theme=Papirus\n".to_string()
733            )),
734            Ok("Papirus".to_string())
735        );
736    }
737
738    // === Unknown desktop: KDE, then GNOME ===
739
740    fn kde_failed() -> Result<String, SourceFailure> {
741        Err(SourceFailure {
742            source: KDE_SOURCE.to_string(),
743            reason: "no file is readable".to_string(),
744        })
745    }
746
747    #[test]
748    fn unknown_desktop_error_names_both_attempts() {
749        let error = unknown_desktop_icon_theme(kde_failed, || {
750            gsettings_icon_theme_from("org.gnome.desktop.interface", not_found())
751        })
752        .unwrap_err()
753        .to_error();
754        let message = error.to_string();
755        assert!(message.contains("kdeglobals"), "got: {message}");
756        assert!(
757            message.contains("gsettings get org.gnome.desktop.interface icon-theme"),
758            "got: {message}"
759        );
760        assert!(
761            matches!(
762                error,
763                crate::Error::ReaderFailed {
764                    reader: crate::error::reader_names::ICON_THEME,
765                    ..
766                }
767            ),
768            "got: {error:?}"
769        );
770    }
771
772    #[test]
773    fn unknown_desktop_takes_kde_first() {
774        let theme = unknown_desktop_icon_theme(
775            || Ok("breeze".to_string()),
776            || gsettings_icon_theme_from("org.gnome.desktop.interface", printed("'Adwaita'")),
777        );
778        assert_eq!(theme, Ok("breeze".to_string()));
779    }
780
781    #[test]
782    fn unknown_desktop_takes_gnome_where_kde_fails() {
783        let theme = unknown_desktop_icon_theme(kde_failed, || {
784            gsettings_icon_theme_from("org.gnome.desktop.interface", printed("'Adwaita'"))
785        });
786        assert_eq!(theme, Ok("Adwaita".to_string()));
787    }
788
789    // === The refined desktop decides the source, as it decides the reader ===
790
791    fn source_of(
792        portal_backend: Option<crate::detect::LinuxDesktop>,
793        kdeglobals: bool,
794    ) -> IconThemeSource {
795        icon_theme_source(crate::detect::refine_linux_desktop(
796            crate::detect::LinuxDesktop::Unknown,
797            portal_backend,
798            || kdeglobals,
799        ))
800    }
801
802    /// An unrecognised desktop with a KDE portal backend is read as KDE,
803    /// as the reader reads it, `kdeglobals` or not.
804    #[test]
805    fn an_unknown_desktop_with_a_kde_portal_has_kdes_icon_theme() {
806        let kde = Some(crate::detect::LinuxDesktop::Kde);
807        assert_eq!(source_of(kde, false), IconThemeSource::Kde);
808        assert_eq!(source_of(kde, true), IconThemeSource::Kde);
809    }
810
811    /// An unrecognised desktop with a GNOME portal backend is read from
812    /// GNOME's gsettings, as the GNOME reader reads it, though a
813    /// `kdeglobals` exists (M4-49).
814    #[test]
815    fn an_unknown_desktop_with_a_gnome_portal_has_gnomes_icon_theme() {
816        let gnome = Some(crate::detect::LinuxDesktop::Gnome);
817        let gsettings = IconThemeSource::Gsettings(GNOME_INTERFACE_SCHEMA);
818        assert_eq!(source_of(gnome, true), gsettings);
819        assert_eq!(source_of(gnome, false), gsettings);
820    }
821
822    /// Without a portal answer, `kdeglobals` makes it KDE; with neither, both
823    /// are tried.
824    #[test]
825    fn an_unknown_desktop_without_a_portal_answer() {
826        assert_eq!(source_of(None, true), IconThemeSource::Kde);
827        assert_eq!(source_of(None, false), IconThemeSource::KdeThenGnome);
828    }
829
830    // === The public result ===
831
832    #[test]
833    fn system_icon_theme_is_a_name_or_the_reason_for_none() {
834        match system_icon_theme() {
835            Ok(theme) => assert!(!theme.is_empty(), "detection named an empty theme"),
836            Err(e) => assert!(!e.to_string().is_empty(), "a failure gave no reason"),
837        }
838    }
839}