1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
use std::{borrow::Cow, fmt};

use super::{percent::decode_percents_str, DBusAddr, KeyValFmt, KeyValFmtAdd};
use crate::{Error, Result};

/// Scope of autolaunch (Windows only)
#[derive(Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum AutolaunchScope<'a> {
    /// Limit session bus to dbus installation path.
    InstallPath,
    /// Limit session bus to the recent user.
    User,
    /// other values - specify dedicated session bus like "release", "debug" or other.
    Other(Cow<'a, str>),
}

impl fmt::Display for AutolaunchScope<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InstallPath => write!(f, "*install-path"),
            Self::User => write!(f, "*user"),
            Self::Other(o) => write!(f, "{o}"),
        }
    }
}

impl<'a> TryFrom<Cow<'a, str>> for AutolaunchScope<'a> {
    type Error = Error;

    fn try_from(s: Cow<'a, str>) -> Result<Self> {
        match s.as_ref() {
            "*install-path" => Ok(Self::InstallPath),
            "*user" => Ok(Self::User),
            _ => Ok(Self::Other(s)),
        }
    }
}

/// `autolaunch:` D-Bus transport.
#[derive(Debug, PartialEq, Eq, Default)]
pub struct Autolaunch<'a> {
    scope: Option<AutolaunchScope<'a>>,
}

impl<'a> Autolaunch<'a> {
    /// Scope of autolaunch (Windows only)
    pub fn scope(&self) -> Option<&AutolaunchScope<'a>> {
        self.scope.as_ref()
    }
}

impl<'a> TryFrom<&'a DBusAddr<'a>> for Autolaunch<'a> {
    type Error = Error;

    fn try_from(s: &'a DBusAddr<'a>) -> Result<Self> {
        let mut res = Autolaunch::default();

        for (k, v) in s.key_val_iter() {
            match (k, v) {
                ("scope", Some(v)) => {
                    res.scope = Some(decode_percents_str(v)?.try_into()?);
                }
                _ => continue,
            }
        }

        Ok(res)
    }
}

impl KeyValFmtAdd for Autolaunch<'_> {
    fn key_val_fmt_add<'a: 'b, 'b>(&'a self, kv: KeyValFmt<'b>) -> KeyValFmt<'b> {
        kv.add("scope", self.scope())
    }
}