Skip to main content

i3status_rs/blocks/
custom_dbus.rs

1//! A block controlled by the DBus
2//!
3//! This block creates a new DBus object in `rs.i3status` service. This object implements
4//! `rs.i3status.custom` interface which allows you to set block's icon, text and state.
5//!
6//! Output of `busctl --user introspect rs.i3status /<path> rs.i3status.custom`:
7//! ```text
8//! NAME                                TYPE      SIGNATURE RESULT/VALUE FLAGS
9//! rs.i3status.custom                  interface -         -            -
10//! .SetIcon                            method    s         s            -
11//! .SetState                           method    s         s            -
12//! .SetText                            method    ss        s            -
13//! ```
14//!
15//! # Configuration
16//!
17//! Key | Values | Default
18//! ----|--------|--------
19//! `format` | A string to customise the output of this block. | <code>\"{ $icon\|}{ $text.pango-str()\|} \"</code>
20//!
21//! Placeholder  | Value                                  | Type   | Unit
22//! -------------|-------------------------------------------------------------------|--------|---------------
23//! `icon`       | Value of icon set via `SetIcon` if the value is non-empty string. | Icon   | -
24//! `text`       | Value of the first string from SetText                            | Text   | -
25//! `short_text` | Value of the second string from SetText                           | Text   | -
26//!
27//! # Example
28//!
29//! Config:
30//! ```toml
31//! [[block]]
32//! block = "custom_dbus"
33//! path = "/my_path"
34//! ```
35//!
36//! Usage:
37//! ```sh
38//! # set full text to 'hello' and short text to 'hi'
39//! busctl --user call rs.i3status /my_path rs.i3status.custom SetText ss hello hi
40//! # set icon to 'music'
41//! busctl --user call rs.i3status /my_path rs.i3status.custom SetIcon s music
42//! # set state to 'good'
43//! busctl --user call rs.i3status /my_path rs.i3status.custom SetState s good
44//! ```
45//!
46//! Because it's impossible to publish objects to the same name from different
47//! processes, having multiple dbus blocks in different bars won't work. As a workaround,
48//! you can set the env var `I3RS_DBUS_NAME` to set the interface a bar works on to
49//! differentiate between different processes. For example, setting this to 'top', will allow you
50//! to use `rs.i3status.top`.
51//!
52//! # TODO
53//! - Send a signal on click?
54
55use super::prelude::*;
56use std::env;
57use zbus::fdo;
58
59// Share DBus connection between multiple block instances
60static DBUS_CONNECTION: tokio::sync::OnceCell<Result<zbus::Connection>> =
61    tokio::sync::OnceCell::const_new();
62
63const DBUS_NAME: &str = "rs.i3status";
64
65#[derive(Deserialize, Debug)]
66#[serde(deny_unknown_fields)]
67pub struct Config {
68    #[serde(default)]
69    pub format: FormatConfig,
70    pub path: String,
71}
72
73struct Block {
74    widget: Widget,
75    api: CommonApi,
76    icon: Option<String>,
77    text: Option<String>,
78    short_text: Option<String>,
79}
80
81fn block_values(block: &Block) -> HashMap<Cow<'static, str>, Value> {
82    map! {
83        [if let Some(icon) = &block.icon] "icon" => Value::icon(icon.to_string()),
84        [if let Some(text) = &block.text] "text" => Value::text(text.to_string()),
85        [if let Some(short_text) = &block.short_text] "short_text" => Value::text(short_text.to_string()),
86    }
87}
88
89#[zbus::interface(name = "rs.i3status.custom")]
90impl Block {
91    async fn set_icon(&mut self, icon: &str) -> fdo::Result<()> {
92        self.icon = if icon.is_empty() {
93            None
94        } else {
95            Some(icon.to_string())
96        };
97        self.widget.set_values(block_values(self));
98        self.api.set_widget(self.widget.clone())?;
99        Ok(())
100    }
101
102    async fn set_text(&mut self, full: String, short: String) -> fdo::Result<()> {
103        self.text = Some(full);
104        self.short_text = Some(short);
105        self.widget.set_values(block_values(self));
106        self.api.set_widget(self.widget.clone())?;
107        Ok(())
108    }
109
110    async fn set_state(&mut self, state: &str) -> fdo::Result<()> {
111        self.widget.state = match state {
112            "idle" => State::Idle,
113            "info" => State::Info,
114            "good" => State::Good,
115            "warning" => State::Warning,
116            "critical" => State::Critical,
117            _ => return Err(Error::new(format!("'{state}' is not a valid state")).into()),
118        };
119        self.api.set_widget(self.widget.clone())?;
120        Ok(())
121    }
122}
123
124pub(crate) fn prepare(config: &Config) -> Result<Arc<BlockPlan>> {
125    // The icon name arrives over D-Bus at runtime, so any name is permitted;
126    // it resolves through the normal icon set and override rules.
127    BlockPlan::new(vec![
128        OutputPlan::new(
129            "main",
130            config.format.with_defaults(
131                "{ $icon|}{ $text.pango-str()|} ",
132                "{ $icon|} $short_text.pango-str() | ",
133            )?,
134        )
135        .icon("icon", IconChoices::OpenResolvable),
136    ])
137}
138
139pub(crate) async fn run(config: &Config, api: &CommonApi, plan: &Arc<BlockPlan>) -> Result<()> {
140    let output = plan.output("main")?;
141    let widget = output.new_widget();
142
143    let dbus_conn = DBUS_CONNECTION
144        .get_or_init(dbus_conn)
145        .await
146        .as_ref()
147        .map_err(Clone::clone)?;
148    dbus_conn
149        .object_server()
150        .at(
151            config.path.clone(),
152            Block {
153                widget,
154                api: api.clone(),
155                icon: None,
156                text: None,
157                short_text: None,
158            },
159        )
160        .await
161        .error("Failed to setup DBus server")?;
162    Ok(())
163}
164
165/// Doctor-only override, set in-process by the doctor worker before the
166/// block runs. It never touches the environment, so if_command and custom
167/// commands observe exactly what the user's shell exported.
168static DOCTOR_NAME_OVERRIDE: std::sync::OnceLock<String> = std::sync::OnceLock::new();
169
170pub(crate) fn set_doctor_dbus_suffix(suffix: String) {
171    let _ = DOCTOR_NAME_OVERRIDE.set(suffix);
172}
173
174/// The well-known name to request. The doctor override takes precedence
175/// over the documented public `I3RS_DBUS_NAME`; it is not part of the
176/// public interface.
177fn dbus_name(doctor_override: Option<&str>, public: Option<&str>) -> String {
178    match doctor_override.or(public) {
179        Some(v) => format!("{DBUS_NAME}.{v}"),
180        None => DBUS_NAME.to_string(),
181    }
182}
183
184async fn dbus_conn() -> Result<zbus::Connection> {
185    let public = env::var("I3RS_DBUS_NAME").ok();
186    let dbus_interface_name = dbus_name(
187        DOCTOR_NAME_OVERRIDE.get().map(String::as_str),
188        public.as_deref(),
189    );
190
191    let conn = new_dbus_connection().await?;
192    conn.request_name(dbus_interface_name)
193        .await
194        .error("Failed to request DBus name")?;
195    Ok(conn)
196}
197
198#[cfg(test)]
199mod tests {
200    use super::*;
201
202    fn config(toml: &str) -> Config {
203        toml::from_str(toml).unwrap()
204    }
205
206    #[test]
207    fn plan_declares_an_open_icon_because_the_name_arrives_over_dbus() {
208        let plan = prepare(&config(r#"path = "/my_path""#)).unwrap();
209        let ids: Vec<_> = plan.outputs().map(|o| o.id()).collect();
210        assert_eq!(ids, ["main"]);
211
212        let output = plan.output("main").unwrap();
213        let choices = output.output().choices_for("icon").unwrap();
214        assert!(matches!(choices, IconChoices::OpenResolvable));
215        assert!(choices.permits("any_name_set_over_dbus"));
216        // Whatever name arrives over D-Bus passes the publish-time check,
217        // which is where the contract is enforced.
218        let mut widget = output.new_widget();
219        widget.set_values(map!("icon" => Value::icon("whatever_was_sent")));
220        widget.check_contract().unwrap();
221    }
222
223    #[test]
224    fn custom_format_is_respected() {
225        // The default short format also carries `$icon`, so both halves have
226        // to be overridden for the icon to be gone from the output.
227        let plan = prepare(&config(
228            r#"
229            path = "/my_path"
230            format = { full = " $text.pango-str() ", short = " $short_text.pango-str() " }
231            "#,
232        ))
233        .unwrap();
234        let output = plan.output("main").unwrap();
235        assert!(output.format().contains_key("text"));
236        assert!(output.format().contains_key("short_text"));
237        assert!(!output.format().contains_key("icon"));
238    }
239
240    #[test]
241    fn doctor_override_wins_without_touching_the_public_name() {
242        assert_eq!(dbus_name(None, None), "rs.i3status");
243        assert_eq!(dbus_name(None, Some("top")), "rs.i3status.top");
244        // Doctor workers set only the internal override; the public
245        // variable keeps whatever value the user's environment has.
246        assert_eq!(dbus_name(Some("doctor3"), None), "rs.i3status.doctor3");
247        assert_eq!(
248            dbus_name(Some("doctor3"), Some("top")),
249            "rs.i3status.doctor3"
250        );
251    }
252}