Skip to main content

i3status_rs/
config.rs

1use serde::{Deserialize, Deserializer};
2use smart_default::SmartDefault;
3use std::collections::HashMap;
4use std::sync::Arc;
5
6use crate::blocks::BlockConfig;
7use crate::click::ClickHandler;
8use crate::errors::*;
9use crate::formatting::config::Config as FormatConfig;
10use crate::geolocator::Geolocator;
11use crate::icons::{Icon, Icons};
12use crate::themes::{Theme, ThemeOverrides, ThemeUserConfig};
13
14#[derive(Deserialize, Debug)]
15#[serde(deny_unknown_fields)]
16pub struct Config {
17    #[serde(flatten)]
18    pub shared: SharedConfig,
19
20    /// Set to `true` to invert mouse wheel direction
21    #[serde(default)]
22    pub invert_scrolling: bool,
23
24    #[serde(default)]
25    pub geolocator: Arc<Geolocator>,
26
27    /// The maximum delay (ms) between two clicks that are considered as double click
28    #[serde(default)]
29    pub double_click_delay: u64,
30
31    #[serde(default = "default_error_format")]
32    pub error_format: FormatConfig,
33    #[serde(default = "default_error_fullscreen")]
34    pub error_fullscreen_format: FormatConfig,
35
36    #[serde(default)]
37    #[serde(rename = "block")]
38    pub blocks: Vec<BlockConfigEntry>,
39}
40
41#[derive(Deserialize, Debug, Clone)]
42pub struct SharedConfig {
43    #[serde(default)]
44    #[serde(deserialize_with = "deserialize_theme_config")]
45    pub theme: Arc<Theme>,
46    #[serde(default)]
47    pub icons: Arc<Icons>,
48    #[serde(default = "default_icons_format")]
49    pub icons_format: Arc<String>,
50}
51
52impl Default for SharedConfig {
53    fn default() -> Self {
54        Self {
55            theme: Default::default(),
56            icons: Default::default(),
57            icons_format: default_icons_format(),
58        }
59    }
60}
61
62fn default_error_format() -> FormatConfig {
63    " {$restart_block_icon |}{$short_error_message|X} "
64        .parse()
65        .unwrap()
66}
67
68fn default_error_fullscreen() -> FormatConfig {
69    " {$restart_block_icon |}$full_error_message.str(w:170,rot_interval:0.2) "
70        .parse()
71        .unwrap()
72}
73
74fn default_icons_format() -> Arc<String> {
75    Arc::new("{icon}".into())
76}
77
78/// Doctor-only: when enabled (inside a doctor worker process, never in the
79/// real bar), every icon that actually renders is recorded as (name,
80/// produced string). Only icons on the format branch that succeeded pass
81/// through `get_icon`, and the produced string tells the live-output
82/// analysis which characters came from an icon.
83///
84/// Worker-local by construction: a worker renders one block, so the
85/// recording belongs to that render.
86static ICON_RECORDER: std::sync::OnceLock<std::sync::Mutex<Vec<(String, String)>>> =
87    std::sync::OnceLock::new();
88
89pub(crate) fn enable_icon_recorder() {
90    let _ = ICON_RECORDER.set(std::sync::Mutex::new(Vec::new()));
91}
92
93/// The icons recorded so far, clearing the record.
94pub(crate) fn take_recorded_icons() -> Vec<(String, String)> {
95    ICON_RECORDER
96        .get()
97        .and_then(|recorder| recorder.lock().ok().map(|mut r| std::mem::take(&mut *r)))
98        .unwrap_or_default()
99}
100
101fn record_icon(icon: &str, produced: &str) {
102    if let Some(recorder) = ICON_RECORDER.get()
103        && let Ok(mut recorder) = recorder.lock()
104    {
105        recorder.push((icon.to_string(), produced.to_string()));
106    }
107}
108
109impl SharedConfig {
110    pub fn get_icon(&self, icon: &str, value: Option<f64>) -> Result<String> {
111        if icon.is_empty() {
112            return Ok(String::new());
113        }
114        let produced = self.icons_format.replace(
115            "{icon}",
116            self.icons
117                .get(icon, value)
118                .or_error(|| format!("Icon '{icon}' not found"))?,
119        );
120        record_icon(icon, &produced);
121        Ok(produced)
122    }
123}
124
125#[derive(Deserialize, Debug)]
126pub struct BlockConfigEntry {
127    #[serde(flatten)]
128    pub common: CommonBlockConfig,
129    #[serde(flatten)]
130    pub config: BlockConfig,
131}
132
133#[derive(Deserialize, Debug, SmartDefault)]
134#[serde(default)]
135pub struct CommonBlockConfig {
136    pub click: ClickHandler,
137    pub signal: Option<i32>,
138    pub icons_format: Option<String>,
139    pub theme_overrides: Option<ThemeOverrides>,
140    pub icons_overrides: Option<HashMap<String, Icon>>,
141    pub merge_with_next: bool,
142
143    #[default(5)]
144    pub error_interval: u64,
145    pub error_format: FormatConfig,
146    pub error_fullscreen_format: FormatConfig,
147    pub max_retries: Option<u8>,
148
149    pub if_command: Option<String>,
150}
151
152fn deserialize_theme_config<'de, D>(deserializer: D) -> Result<Arc<Theme>, D::Error>
153where
154    D: Deserializer<'de>,
155{
156    let theme_config = ThemeUserConfig::deserialize(deserializer)?;
157    let theme = Theme::try_from(theme_config).serde_error()?;
158    Ok(Arc::new(theme))
159}