Skip to main content

i3status_rs/themes/color/
sway.rs

1//! Sway colors
2//!
3//! Sway colors are picked up using sway IPC for the current bar.
4//!
5//! These are the available sway colors:
6//!
7//! * `active_workspace_bg`
8//! * `active_workspace_border`
9//! * `active_workspace_text`
10//! * `background`
11//! * `binding_mode_bg`
12//! * `binding_mode_border`
13//! * `binding_mode_text`
14//! * `focused_background`
15//! * `focused_separator`
16//! * `focused_statusline`
17//! * `focused_workspace_bg`
18//! * `focused_workspace_border`
19//! * `focused_workspace_text`
20//! * `inactive_workspace_bg`
21//! * `inactive_workspace_border`
22//! * `inactive_workspace_text`
23//! * `separator`
24//! * `statusline`
25//! * `urgent_workspace_bg`
26//! * `urgent_workspace_border`
27//! * `urgent_workspace_text`
28//!
29//! You can see the current values for your bar with `swaymsg -t get_bar_config <bar-name>`.
30
31use swayipc_async::ColorableBarPart;
32
33use std::sync::LazyLock;
34
35use crate::errors::*;
36
37#[cfg(not(test))]
38use std::{fs::read_to_string, os::unix::process::parent_id, path::Path};
39
40#[cfg(not(test))]
41static COLORS: LazyLock<Result<ColorableBarPart>> = LazyLock::new(|| {
42    let mut current_pid = parent_id().to_string();
43    let bar_id =
44        loop {
45            if current_pid == "1" {
46                return Err(Error::new(
47                    "Unable to find swaybar process in parent process tree",
48                ));
49            }
50            let cmdline = read_to_string(Path::new("/proc").join(&current_pid).join("cmdline"))
51                .or_error(|| format!("Failed to read /proc/{current_pid}/cmdline"))?;
52            let cmdline_parts: Vec<_> = cmdline.split('\0').collect();
53            if let Some(bar_id) = cmdline_parts
54                .iter()
55                .position(|&s| s == "-b" || s == "--bar_id")
56                .and_then(|pos| cmdline_parts.get(pos + 1))
57            {
58                break bar_id.to_string();
59            }
60            let stat = read_to_string(Path::new("/proc").join(&current_pid).join("stat"))
61                .or_error(|| format!("Failed to read /proc/{current_pid}/stat"))?;
62
63            current_pid =
64                stat.split(' ').nth(3).unwrap().parse().or_error(|| {
65                    format!("Failed to parse parent PID from /proc/{current_pid}/stat")
66                })?;
67        };
68
69    crate::util::run_sync(async move {
70        let mut swayipc_connection = swayipc_async::Connection::new()
71            .await
72            .error("Failed to open swayipc connection")?;
73        let bar_config = swayipc_connection
74            .get_bar_config(bar_id)
75            .await
76            .error("Failed to get swaybar config")?;
77        Ok(bar_config.colors)
78    })
79});
80
81#[cfg(test)]
82use tests::COLORS;
83
84pub fn get_color(name: &str) -> Result<String> {
85    COLORS.as_ref().map_err(Clone::clone).and_then(|colors| {
86        Ok(match name {
87            "background" => colors.background.clone(),
88            "statusline" => colors.statusline.clone(),
89            "separator" => colors.separator.clone(),
90            "focused_background" => colors.focused_background.clone(),
91            "focused_statusline" => colors.focused_statusline.clone(),
92            "focused_separator" => colors.focused_separator.clone(),
93            "focused_workspace_border" => colors.focused_workspace_border.clone(),
94            "focused_workspace_bg" => colors.focused_workspace_bg.clone(),
95            "focused_workspace_text" => colors.focused_workspace_text.clone(),
96            "inactive_workspace_border" => colors.inactive_workspace_border.clone(),
97            "inactive_workspace_bg" => colors.inactive_workspace_bg.clone(),
98            "inactive_workspace_text" => colors.inactive_workspace_text.clone(),
99            "active_workspace_border" => colors.active_workspace_border.clone(),
100            "active_workspace_bg" => colors.active_workspace_bg.clone(),
101            "active_workspace_text" => colors.active_workspace_text.clone(),
102            "urgent_workspace_border" => colors.urgent_workspace_border.clone(),
103            "urgent_workspace_bg" => colors.urgent_workspace_bg.clone(),
104            "urgent_workspace_text" => colors.urgent_workspace_text.clone(),
105            "binding_mode_border" => colors.binding_mode_border.clone(),
106            "binding_mode_bg" => colors.binding_mode_bg.clone(),
107            "binding_mode_text" => colors.binding_mode_text.clone(),
108            _ => {
109                return Err(Error::new(format!(
110                    "color '{}' is not a valid sway color name",
111                    name
112                )));
113            }
114        })
115    })
116}
117
118#[cfg(test)]
119mod tests {
120
121    use super::*;
122
123    pub(crate) static COLORS: LazyLock<Result<ColorableBarPart>> = LazyLock::new(|| {
124        let json_str = include_str!("../../../testdata/sway_colors.json");
125        serde_json::from_str(json_str).error("Failed to parse sway colors JSON")
126    });
127
128    #[test]
129    fn test_deserializing_xcolors() {
130        use crate::themes::color::*;
131        let mut parsed_color = "sway:separator".parse::<Color>().unwrap();
132        assert_eq!(
133            parsed_color,
134            Color::Rgba(Rgba {
135                r: 0x93,
136                g: 0xa1,
137                b: 0xa1,
138                a: 0xff
139            })
140        );
141        parsed_color = "sway:focused_workspace_border".parse::<Color>().unwrap();
142        assert_eq!(
143            parsed_color,
144            Color::Rgba(Rgba {
145                r: 0x00,
146                g: 0x88,
147                b: 0xcc,
148                a: 0xff,
149            })
150        );
151    }
152}