Skip to main content

i3status_rs/
lib.rs

1// The block plan is internal (see `block_plan`). Denying this turns any
2// future leak of it into a public signature — which would put an
3// unnameable type in the published API — into a compile error.
4#![deny(private_interfaces)]
5#![warn(clippy::match_same_arms)]
6#![warn(clippy::semicolon_if_nothing_returned)]
7#![warn(clippy::unnecessary_wraps)]
8#![warn(clippy::unused_trait_names)]
9#![allow(clippy::single_match)]
10#![cfg_attr(docsrs, feature(doc_cfg))]
11
12#[macro_use]
13pub mod util;
14/// The per-block output contracts the framework prepares and enforces.
15/// Internal: the published surface is the blocks' own configuration and
16/// output.
17pub(crate) mod block_plan;
18pub mod blocks;
19pub mod click;
20pub mod config;
21pub mod doctor;
22pub mod errors;
23pub mod escape;
24pub mod formatting;
25pub mod geolocator;
26pub mod icons;
27mod netlink;
28#[cfg(feature = "pipewire")]
29pub mod pipewire;
30pub mod protocol;
31mod signals;
32mod subprocess;
33mod term_graphics;
34pub mod themes;
35pub mod widget;
36mod wrappers;
37
38pub use env_logger;
39pub use serde_json;
40pub use tokio;
41
42use std::borrow::Cow;
43use std::pin::Pin;
44use std::sync::{Arc, LazyLock};
45use std::time::Duration;
46
47use futures::Stream;
48use futures::stream::{FuturesUnordered, StreamExt as _};
49use tokio::process::Command;
50use tokio::sync::{Notify, mpsc};
51
52use crate::blocks::{BlockAction, BlockError, CommonApi, RESTART_BLOCK_BTN};
53use crate::click::{ClickHandler, MouseButton};
54use crate::config::{BlockConfigEntry, Config, SharedConfig};
55use crate::errors::*;
56use crate::formatting::value::Value;
57use crate::protocol::i3bar_block::I3BarBlock;
58use crate::protocol::i3bar_event::{self, I3BarEvent};
59use crate::signals::Signal;
60use crate::widget::{State, Widget};
61
62const APP_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"),);
63const REQWEST_TIMEOUT: Duration = Duration::from_secs(10);
64
65static REQWEST_CLIENT: LazyLock<reqwest::Client> = LazyLock::new(|| {
66    reqwest::Client::builder()
67        .user_agent(APP_USER_AGENT)
68        .timeout(REQWEST_TIMEOUT)
69        .build()
70        .unwrap()
71});
72
73static REQWEST_CLIENT_IPV4: LazyLock<reqwest::Client> = LazyLock::new(|| {
74    reqwest::Client::builder()
75        .user_agent(APP_USER_AGENT)
76        .local_address(Some(std::net::Ipv4Addr::UNSPECIFIED.into()))
77        .timeout(REQWEST_TIMEOUT)
78        .build()
79        .unwrap()
80});
81
82type BoxedFuture<T> = Pin<Box<dyn Future<Output = T>>>;
83
84type BoxedStream<T> = Pin<Box<dyn Stream<Item = T>>>;
85
86type WidgetUpdatesSender = mpsc::UnboundedSender<(usize, Vec<u64>)>;
87
88/// A feature-rich and resource-friendly replacement for i3status(1), written in Rust. The
89/// i3status-rs program writes a stream of configurable "blocks" of system information (time,
90/// battery status, volume, etc.) to standard output in the JSON format understood by i3bar(1) and
91/// sway-bar(5).
92#[derive(Debug, clap::Parser)]
93#[clap(author, about, long_about, version = env!("VERSION"))]
94pub struct CliArgs {
95    /// Sets a TOML config file
96    ///
97    /// 1. If full absolute path given, then use it as is: `/home/foo/i3rs-config.toml`
98    ///
99    /// 2. If filename given, e.g. "custom_theme.toml", then first look in `$XDG_CONFIG_HOME/i3status-rust`
100    ///
101    /// 3. Then look for it in `$XDG_DATA_HOME/i3status-rust`
102    ///
103    /// 4. Otherwise look for it in `/usr/share/i3status-rust`
104    #[clap(default_value = "config.toml")]
105    pub config: String,
106    /// Ignore any attempts by i3 to pause the bar when hidden/fullscreen
107    #[clap(long = "never-pause")]
108    pub never_pause: bool,
109    /// Diagnose configuration problems and exit: runs every configured
110    /// block for one cycle, resolves every icon glyph to the font that will
111    /// draw it, and reports problems with concrete fixes
112    #[clap(long = "doctor")]
113    pub doctor: bool,
114    /// The font your bar is configured with: the i3/sway `font` directive,
115    /// fallback list and all, e.g. "pango:DejaVu Sans Mono, Font Awesome 5
116    /// Free 10". Used by --doctor to tell configured font fallbacks apart
117    /// from fontconfig silently substituting a font that is not configured.
118    /// When omitted, --doctor auto-detects it from a running i3/sway
119    #[clap(long = "font", requires = "doctor")]
120    pub font: Option<String>,
121    /// Make --doctor skip the live block test (which runs every configured
122    /// block for one cycle, performing real network requests, commands and
123    /// D-Bus calls)
124    #[clap(long = "doctor-skip-live", requires = "doctor")]
125    pub doctor_skip_live: bool,
126    /// Make --doctor show icon names instead of glyphs. The terminal draws
127    /// glyphs with its own fonts, which may not be the bar's
128    #[clap(long = "noicons", requires = "doctor")]
129    pub doctor_noicons: bool,
130    /// Internal: run one block's live test in this process (spawned by
131    /// --doctor for process isolation)
132    #[clap(hide = true, long = "doctor-worker")]
133    pub doctor_worker: Option<usize>,
134    /// Do not send the init sequence
135    #[clap(hide = true, long = "no-init")]
136    pub no_init: bool,
137    /// The maximum number of blocking threads spawned by tokio
138    #[clap(long = "threads", short = 'j', default_value = "2")]
139    pub blocking_threads: usize,
140}
141
142pub struct BarState {
143    config: Config,
144
145    blocks: Vec<Block>,
146    fullscreen_block: Option<usize>,
147    running_blocks: FuturesUnordered<BoxedFuture<()>>,
148
149    widget_updates_sender: WidgetUpdatesSender,
150    blocks_render_cache: Vec<RenderedBlock>,
151
152    request_sender: mpsc::UnboundedSender<Request>,
153    request_receiver: mpsc::UnboundedReceiver<Request>,
154
155    widget_updates_stream: BoxedStream<Vec<usize>>,
156    signals_stream: BoxedStream<Signal>,
157    events_stream: BoxedStream<I3BarEvent>,
158}
159
160#[derive(Debug)]
161struct Request {
162    block_id: usize,
163    cmd: RequestCmd,
164}
165
166#[derive(Debug)]
167enum RequestCmd {
168    SetWidget(Widget),
169    UnsetWidget,
170    SetError { error: Error, restartable: bool },
171    SetDefaultActions(&'static [(MouseButton, Option<&'static str>, &'static str)]),
172    SubscribeToActions(mpsc::UnboundedSender<BlockAction>),
173}
174
175#[derive(Debug, Clone)]
176struct RenderedBlock {
177    pub segments: Vec<I3BarBlock>,
178    pub merge_with_next: bool,
179}
180
181#[derive(Debug)]
182pub struct Block {
183    id: usize,
184    name: &'static str,
185
186    update_request: Arc<Notify>,
187    action_sender: Option<mpsc::UnboundedSender<BlockAction>>,
188
189    click_handler: ClickHandler,
190    default_actions: &'static [(MouseButton, Option<&'static str>, &'static str)],
191    signal: Option<i32>,
192    shared_config: SharedConfig,
193
194    error_outputs: block_plan::ErrorOutputs,
195
196    state: BlockState,
197}
198
199#[derive(Debug)]
200enum BlockState {
201    None,
202    Normal { widget: Widget },
203    Error { widget: Widget },
204}
205
206impl Block {
207    fn notify_intervals(&self, tx: &WidgetUpdatesSender) {
208        let intervals = match &self.state {
209            BlockState::None => Vec::new(),
210            BlockState::Normal { widget } | BlockState::Error { widget } => widget.intervals(),
211        };
212        let _ = tx.send((self.id, intervals));
213    }
214
215    fn send_action(&mut self, action: BlockAction) {
216        if let Some(sender) = &self.action_sender
217            && sender.send(action).is_err()
218        {
219            self.action_sender = None;
220        }
221    }
222
223    fn set_error(&mut self, fullscreen: bool, error: Error) {
224        self.set_error_with_restartable(fullscreen, false, error);
225    }
226
227    fn set_error_with_restartable(&mut self, fullscreen: bool, restartable: bool, error: Error) {
228        let error = BlockError {
229            block_id: self.id,
230            block_name: self.name,
231            error,
232        };
233
234        let output = if fullscreen {
235            &self.error_outputs.fullscreen
236        } else {
237            &self.error_outputs.error
238        };
239        let mut widget = output.new_widget().with_state(State::Critical);
240        let restart_icon =
241            restartable.then(|| Value::icon(icons::REFRESH).with_instance(RESTART_BLOCK_BTN));
242        widget.set_values(map! {
243            "full_error_message" => Value::text(error.to_string()),
244            [if let Some(v) = &error.error.message] "short_error_message" => Value::text(v.to_string()),
245            [if let Some(icon) = restart_icon] "restart_block_icon" => icon,
246        });
247        // The bar renders this widget itself rather than through
248        // `CommonApi::set_widget`, so nothing downstream would catch drift
249        // between `error_plan` and this renderer.
250        if let Err(err) = widget.check_contract() {
251            log::error!("error widget: {err}");
252            debug_assert!(false, "error widget: {err}");
253        }
254        self.state = BlockState::Error { widget };
255    }
256}
257
258impl BarState {
259    pub fn new(config: Config) -> Self {
260        let (request_sender, request_receiver) = mpsc::unbounded_channel();
261        let (widget_updates_sender, widget_updates_stream) =
262            formatting::scheduling::manage_widgets_updates();
263        Self {
264            blocks: Vec::new(),
265            fullscreen_block: None,
266            running_blocks: FuturesUnordered::new(),
267
268            widget_updates_sender,
269            blocks_render_cache: Vec::new(),
270
271            request_sender,
272            request_receiver,
273
274            widget_updates_stream,
275            signals_stream: signals::signals_stream(),
276            events_stream: i3bar_event::events_stream(
277                config.invert_scrolling,
278                Duration::from_millis(config.double_click_delay),
279            ),
280
281            config,
282        }
283    }
284
285    pub async fn spawn_block(&mut self, block_config: BlockConfigEntry) -> Result<()> {
286        if let Some(cmd) = &block_config.common.if_command {
287            // TODO: async
288            if !Command::new("sh")
289                .args(["-c", cmd])
290                .output()
291                .await
292                .error("failed to run if_command")?
293                .status
294                .success()
295            {
296                return Ok(());
297            }
298        }
299
300        let mut shared_config = self.config.shared.clone();
301
302        // Overrides
303        if let Some(icons_format) = block_config.common.icons_format {
304            shared_config.icons_format = Arc::new(icons_format);
305        }
306        if let Some(theme_overrides) = block_config.common.theme_overrides {
307            Arc::make_mut(&mut shared_config.theme).apply_overrides(theme_overrides)?;
308        }
309        if let Some(icons_overrides) = block_config.common.icons_overrides {
310            Arc::make_mut(&mut shared_config.icons).apply_overrides(icons_overrides);
311        }
312
313        let update_request = Arc::new(Notify::new());
314
315        let api = CommonApi {
316            id: self.blocks.len(),
317            update_request: update_request.clone(),
318            request_sender: self.request_sender.clone(),
319            error_interval: Duration::from_secs(block_config.common.error_interval),
320            geolocator: self.config.geolocator.clone(),
321            max_retries: block_config.common.max_retries,
322        };
323
324        let error_outputs = block_plan::error_outputs(
325            block_config
326                .common
327                .error_format
328                .with_default_config(&self.config.error_format),
329            block_config
330                .common
331                .error_fullscreen_format
332                .with_default_config(&self.config.error_fullscreen_format),
333            // Without a retry limit the block retries forever and the
334            // restart button is never rendered.
335            block_config.common.max_retries.is_some(),
336        );
337
338        let block = Block {
339            id: self.blocks.len(),
340            name: block_config.config.name(),
341
342            update_request,
343            action_sender: None,
344
345            click_handler: block_config.common.click,
346            default_actions: &[],
347            signal: block_config.common.signal,
348            shared_config,
349
350            error_outputs,
351
352            state: BlockState::None,
353        };
354
355        block_config.config.spawn(api, &mut self.running_blocks);
356
357        self.blocks.push(block);
358        self.blocks_render_cache.push(RenderedBlock {
359            segments: Vec::new(),
360            merge_with_next: block_config.common.merge_with_next,
361        });
362
363        Ok(())
364    }
365
366    fn process_request(&mut self, request: Request) {
367        let block = &mut self.blocks[request.block_id];
368        match request.cmd {
369            RequestCmd::SetWidget(widget) => {
370                block.state = BlockState::Normal { widget };
371                if self.fullscreen_block == Some(request.block_id) {
372                    self.fullscreen_block = None;
373                }
374            }
375            RequestCmd::UnsetWidget => {
376                block.state = BlockState::None;
377                if self.fullscreen_block == Some(request.block_id) {
378                    self.fullscreen_block = None;
379                }
380            }
381            RequestCmd::SetError { error, restartable } => {
382                block.set_error_with_restartable(
383                    self.fullscreen_block == Some(request.block_id),
384                    restartable,
385                    error,
386                );
387            }
388            RequestCmd::SetDefaultActions(actions) => {
389                block.default_actions = actions;
390            }
391            RequestCmd::SubscribeToActions(action_sender) => {
392                block.action_sender = Some(action_sender);
393            }
394        }
395        block.notify_intervals(&self.widget_updates_sender);
396    }
397
398    fn render_block(&mut self, id: usize) -> Result<(), BlockError> {
399        let block = &mut self.blocks[id];
400        let data = &mut self.blocks_render_cache[id].segments;
401        match &block.state {
402            BlockState::None => {
403                data.clear();
404            }
405            BlockState::Normal { widget } | BlockState::Error { widget, .. } => {
406                *data = widget
407                    .get_data(&block.shared_config, id)
408                    .map_err(|error| BlockError {
409                        block_id: id,
410                        block_name: block.name,
411                        error,
412                    })?;
413            }
414        }
415        Ok(())
416    }
417
418    fn render(&self) {
419        if let Some(id) = self.fullscreen_block {
420            protocol::print_blocks(&[&self.blocks_render_cache[id]], &self.config.shared);
421        } else {
422            protocol::print_blocks(&self.blocks_render_cache, &self.config.shared);
423        }
424    }
425
426    async fn process_event(&mut self, restart: fn() -> !) -> Result<(), BlockError> {
427        tokio::select! {
428            // Poll blocks
429            Some(()) = self.running_blocks.next() => (),
430            // Receive messages from blocks
431            Some(request) = self.request_receiver.recv() => {
432                let id = request.block_id;
433                self.process_request(request);
434                self.render_block(id)?;
435                self.render();
436            }
437            // Handle scheduled updates
438            Some(ids) = self.widget_updates_stream.next() => {
439                for id in ids {
440                    self.render_block(id)?;
441                }
442                self.render();
443            }
444            // Handle clicks
445            Some(event) = self.events_stream.next() => {
446                let block = self.blocks.get_mut(event.id).expect("Events receiver: ID out of bounds");
447                match &mut block.state {
448                    BlockState::None => (),
449                    BlockState::Normal { .. } => {
450                        let result = block.click_handler.handle(&event).await.map_err(|error| BlockError {
451                            block_id: event.id,
452                            block_name: block.name,
453                            error,
454                        })?;
455                        match result {
456                            Some(post_actions) => {
457                                if let Some(action) = post_actions.action {
458                                    block.send_action(Cow::Owned(action));
459                                }
460                                if post_actions.update {
461                                    block.update_request.notify_one();
462                                }
463                            }
464                            None => {
465                                if let Some((_, _, action)) = block.default_actions
466                                    .iter()
467                                    .find(|(btn, widget, _)| *btn == event.button && *widget == event.instance.as_deref()) {
468                                    block.send_action(Cow::Borrowed(action));
469                                }
470                            }
471                        }
472                    }
473                    BlockState::Error { widget } => {
474                        if let Some((_, _, action)) = block.default_actions
475                            .iter()
476                            .find(|(btn, widget, _)| *btn == event.button && *widget == event.instance.as_deref()) {
477                            block.send_action(Cow::Borrowed(action));
478                        } else {
479                            if self.fullscreen_block == Some(event.id) {
480                                self.fullscreen_block = None;
481                                widget.set_output(&block.error_outputs.error);
482                            } else {
483                                self.fullscreen_block = Some(event.id);
484                                widget.set_output(&block.error_outputs.fullscreen);
485                            }
486                            block.notify_intervals(&self.widget_updates_sender);
487                            self.render_block(event.id)?;
488                            self.render();
489                        }
490                    }
491                }
492            }
493            // Handle signals
494            Some(signal) = self.signals_stream.next() => match signal {
495                Signal::Usr1 => {
496                    for block in &self.blocks {
497                        block.update_request.notify_one();
498                    }
499                }
500                Signal::Usr2 => restart(),
501                Signal::Custom(signal) => {
502                    for block in &self.blocks {
503                        if block.signal == Some(signal) {
504                            block.update_request.notify_one();
505                        }
506                    }
507                }
508            }
509        }
510        Ok(())
511    }
512
513    pub async fn run_event_loop(mut self, restart: fn() -> !) -> Result<(), BlockError> {
514        loop {
515            if let Err(error) = self.process_event(restart).await {
516                let block = &mut self.blocks[error.block_id];
517
518                if matches!(block.state, BlockState::Error { .. }) {
519                    // This should never happen. If this code runs, it could mean that we
520                    // got an error while trying to display and error. We better stop here.
521                    return Err(error);
522                }
523
524                block.set_error(self.fullscreen_block == Some(block.id), error.error);
525                block.notify_intervals(&self.widget_updates_sender);
526
527                self.render_block(error.block_id)?;
528                self.render();
529            }
530        }
531    }
532}