Skip to main content

i3status_rs/
blocks.rs

1//! The collection of blocks
2//!
3//! Blocks are defined as a [TOML array of tables](https://github.com/toml-lang/toml/blob/main/toml.md#user-content-array-of-tables): `[[block]]`
4//!
5//! Key | Description | Default
6//! ----|-------------|----------
7//! `block` | Name of the i3status-rs block you want to use. See [modules](#modules) below for valid block names. | -
8//! `signal` | Signal value that causes an update for this block with `0` corresponding to `-SIGRTMIN+0` and the largest value being `-SIGRTMAX` | None
9//! `if_command` | Only display the block if the supplied command returns 0 on startup. | None
10//! `merge_with_next` | If true this will group the block with the next one, so rendering such as alternating_tint will apply to the whole group | `false`
11//! `icons_format` | Overrides global `icons_format` | None
12//! `error_format` | Overrides global `error_format` | None
13//! `error_fullscreen_format` | Overrides global `error_fullscreen_format` | None
14//! `error_interval` | How long to wait until restarting the block after an error occurred. | `5`
15//! `max_retries` | How many times should a block be restarted the block after an error occurred. If no limit is specified none will be enforced. | `None`
16//! `[block.theme_overrides]` | Same as the top-level config option, but for this block only. Refer to `Themes and Icons` below. | None
17//! `[block.icons_overrides]` | Same as the top-level config option, but for this block only. Refer to `Themes and Icons` below. | None
18//! `[[block.click]]` | Set or override click action for the block. See below for details. | Block default / None
19//!
20//! Per block click configuration `[[block.click]]`:
21//!
22//! Key | Description | Default
23//! ----|-------------|----------
24//! `button` | `left`, `middle`, `right`, `up`/`wheel_up`, `down`/`wheel_down`, `wheel_left`, `wheel_right`, `forward`, `back` or [`double_left`](MouseButton). | -
25//! `widget` | To which part of the block this entry applies (accepts regex) | `"block"`
26//! `cmd` | Command to run when the mouse button event is detected. | None
27//! `action` | Which block action to trigger | None
28//! `sync` | Whether to wait for command to exit or not. | `false`
29//! `update` | Whether to update the block on click. | `false`
30
31mod prelude;
32
33use futures::future::FutureExt as _;
34use futures::stream::FuturesUnordered;
35use serde::de::{self, Deserialize};
36use tokio::sync::{Notify, mpsc};
37
38use std::borrow::Cow;
39use std::sync::Arc;
40use std::time::Duration;
41
42use crate::click::MouseButton;
43use crate::errors::*;
44use crate::geolocator::{Geolocator, IPAddressInfo};
45use crate::widget::Widget;
46use crate::{BoxedFuture, Request, RequestCmd};
47
48pub(super) const RESTART_BLOCK_BTN: &str = "restart_block_btn";
49
50macro_rules! define_blocks {
51    {
52        $(
53            $(#[cfg(feature = $feat: literal)])?
54            $(#[deprecated($($dep_k: ident = $dep_v: literal),+)])?
55            $block: ident $(,)?
56        )*
57    } => {
58        $(
59            $(#[cfg(feature = $feat)])?
60            $(#[cfg_attr(docsrs, doc(cfg(feature = $feat)))])?
61            $(#[deprecated($($dep_k = $dep_v),+)])?
62            pub mod $block;
63        )*
64
65        #[derive(Debug)]
66        pub enum BlockConfig {
67            $(
68                $(#[cfg(feature = $feat)])?
69                #[allow(non_camel_case_types)]
70                #[allow(deprecated)]
71                $block($block::Config),
72            )*
73            Err(&'static str, Error),
74        }
75
76        impl BlockConfig {
77            pub fn name(&self) -> &'static str {
78                match self {
79                    $(
80                        $(#[cfg(feature = $feat)])?
81                        Self::$block { .. } => stringify!($block),
82                    )*
83                    Self::Err(name, _err) => name,
84                }
85            }
86
87            /// The prepared output contract of this block instance (see
88            /// [`crate::block_plan`]), which is what `--doctor` analyzes.
89            pub(crate) fn plan(&self) -> Result<Arc<crate::block_plan::BlockPlan>> {
90                match self {
91                    $(
92                        $(#[cfg(feature = $feat)])?
93                        #[allow(deprecated)]
94                        Self::$block(config) => $block::prepare(config),
95                    )*
96                    Self::Err(_name, err) => Err(err.clone()),
97                }
98            }
99
100            pub fn spawn(self, api: CommonApi, futures: &mut FuturesUnordered<BoxedFuture<()>>) {
101                match self {
102                    $(
103                        $(#[cfg(feature = $feat)])?
104                        #[allow(deprecated)]
105                        Self::$block(config) => futures.push(async move {
106                            // The block's declared output contract, resolved
107                            // once and passed into run. Every block module
108                            // must define `prepare(config) ->
109                            // Result<Arc<BlockPlan>>`; a block without one
110                            // fails to compile here.
111                            let plan = match $block::prepare(&config) {
112                                Ok(plan) => plan,
113                                Err(err) => {
114                                    let _ = api.set_error(Error {
115                                        message: Some("Failed to prepare block".into()),
116                                        cause: Some(Arc::new(err)),
117                                    });
118                                    return;
119                                }
120                            };
121                            let mut error_count: u8 = 0;
122                            while let Err(mut err) = $block::run(&config, &api, &plan).await {
123                                let Ok(mut actions) = api.get_actions() else { return };
124                                if api.set_default_actions(&[
125                                    (MouseButton::Left, Some(RESTART_BLOCK_BTN), "error_count_reset"),
126                                ]).is_err() {
127                                    return;
128                                }
129                                let should_retry = api
130                                    .max_retries
131                                    .map_or(true, |max_retries| error_count < max_retries);
132                                if !should_retry {
133                                    err = Error {
134                                        message: Some("Block terminated".into()),
135                                        cause: Some(Arc::new(err)),
136                                    };
137                                }
138                                if api.set_error_with_restartable(err, !should_retry).is_err() {
139                                    return;
140                                }
141                                tokio::select! {
142                                    _ = tokio::time::sleep(api.error_interval), if should_retry => (),
143                                    Some(action) = actions.recv(), if !should_retry  => match action.as_ref(){
144                                        "error_count_reset" => {
145                                            error_count = 0;
146                                        },
147                                        _ => (),
148                                    },
149                                    _ = api.wait_for_update_request() => (),
150                                }
151                                error_count = error_count.saturating_add(1);
152                            }
153                        }.boxed_local()),
154                    )*
155                    Self::Err(_name, err) => {
156                        let _ = api.set_error(Error {
157                            message: Some("Configuration error".into()),
158                            cause: Some(Arc::new(err)),
159                        });
160                    },
161                }
162            }
163        }
164
165        impl<'de> Deserialize<'de> for BlockConfig {
166            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
167            where
168                D: de::Deserializer<'de>,
169            {
170                use de::Error as _;
171
172                let mut table = toml::Table::deserialize(deserializer)?;
173                let block_name = table.remove("block").ok_or_else(|| D::Error::missing_field("block"))?;
174                let block_name = block_name.as_str().ok_or_else(|| D::Error::custom("block must be a string"))?;
175
176                match block_name {
177                    $(
178                        $(#[cfg(feature = $feat)])?
179                        #[allow(deprecated)]
180                        stringify!($block) => match $block::Config::deserialize(table) {
181                            Ok(config) => Ok(BlockConfig::$block(config)),
182                            Err(err) => Ok(BlockConfig::Err(stringify!($block), crate::errors::Error::new(err.to_string().trim_end().to_string()))),
183                        }
184                        $(
185                            #[cfg(not(feature = $feat))]
186                            stringify!($block) => Err(D::Error::custom(format!(
187                                "block {} is behind a feature gate '{}' which must be enabled at compile time",
188                                stringify!($block),
189                                $feat,
190                            ))),
191                        )?
192                    )*
193                    other => Err(D::Error::custom(format!("unknown block '{other}'")))
194                }
195            }
196        }
197    };
198}
199
200define_blocks!(
201    amd_gpu,
202    backlight,
203    battery,
204    bluetooth,
205    calendar,
206    cpu,
207    custom,
208    custom_dbus,
209    disk_iostats,
210    disk_space,
211    docker,
212    external_ip,
213    focused_window,
214    github,
215    hueshift,
216    kdeconnect,
217    load,
218    #[cfg(feature = "maildir")]
219    maildir,
220    menu,
221    memory,
222    music,
223    net,
224    notify,
225    #[cfg(feature = "notmuch")]
226    notmuch,
227    nvidia_gpu,
228    packages,
229    pomodoro,
230    privacy,
231    rofication,
232    service_status,
233    scratchpad,
234    sound,
235    #[cfg(feature = "speedtest")]
236    speedtest,
237    keyboard_layout,
238    taskwarrior,
239    temperature,
240    time,
241    tea_timer,
242    toggle,
243    uptime,
244    vpn,
245    watson,
246    weather,
247    xrandr,
248);
249
250/// An error which originates from a block
251#[derive(Debug, thiserror::Error)]
252#[error("In block {}: {}", .block_name, .error)]
253pub struct BlockError {
254    pub block_id: usize,
255    pub block_name: &'static str,
256    pub error: Error,
257}
258
259pub type BlockAction = Cow<'static, str>;
260
261#[derive(Clone)]
262pub struct CommonApi {
263    pub(crate) id: usize,
264    pub(crate) update_request: Arc<Notify>,
265    pub(crate) request_sender: mpsc::UnboundedSender<Request>,
266    pub(crate) error_interval: Duration,
267    pub(crate) geolocator: Arc<Geolocator>,
268    pub(crate) max_retries: Option<u8>,
269}
270
271impl CommonApi {
272    /// Sends the widget to be displayed.
273    pub fn set_widget(&self, widget: Widget) -> Result<()> {
274        widget.check_contract()?;
275        self.request_sender
276            .send(Request {
277                block_id: self.id,
278                cmd: RequestCmd::SetWidget(widget),
279            })
280            .error("Failed to send Request")
281    }
282
283    /// Hides the block. Send new widget to make it visible again.
284    pub fn hide(&self) -> Result<()> {
285        self.request_sender
286            .send(Request {
287                block_id: self.id,
288                cmd: RequestCmd::UnsetWidget,
289            })
290            .error("Failed to send Request")
291    }
292
293    /// Sends the error to be displayed, no restart button will be shown.
294    pub fn set_error(&self, error: Error) -> Result<()> {
295        self.set_error_with_restartable(error, false)
296    }
297
298    /// Sends the error to be displayed.
299    pub fn set_error_with_restartable(&self, error: Error, restartable: bool) -> Result<()> {
300        self.request_sender
301            .send(Request {
302                block_id: self.id,
303                cmd: RequestCmd::SetError { error, restartable },
304            })
305            .error("Failed to send Request")
306    }
307
308    pub fn set_default_actions(
309        &self,
310        actions: &'static [(MouseButton, Option<&'static str>, &'static str)],
311    ) -> Result<()> {
312        self.request_sender
313            .send(Request {
314                block_id: self.id,
315                cmd: RequestCmd::SetDefaultActions(actions),
316            })
317            .error("Failed to send Request")
318    }
319
320    pub fn get_actions(&self) -> Result<mpsc::UnboundedReceiver<BlockAction>> {
321        let (tx, rx) = mpsc::unbounded_channel();
322        self.request_sender
323            .send(Request {
324                block_id: self.id,
325                cmd: RequestCmd::SubscribeToActions(tx),
326            })
327            .error("Failed to send Request")?;
328        Ok(rx)
329    }
330
331    pub async fn wait_for_update_request(&self) {
332        self.update_request.notified().await;
333    }
334
335    fn locator_name(&self) -> Cow<'static, str> {
336        self.geolocator.name()
337    }
338
339    fn locator_rate_limit_interval(&self) -> Duration {
340        self.geolocator.rate_limit_interval()
341    }
342
343    /// No-op if last API call was made in the last `interval` seconds.
344    pub async fn find_ip_location(
345        &self,
346        client: &reqwest::Client,
347        interval: Duration,
348    ) -> Result<IPAddressInfo> {
349        self.geolocator.find_ip_location(client, interval).await
350    }
351}