Skip to main content

i3status_rs/
widget.rs

1use crate::block_plan::{CONTRACT_BUG, OutputHandle, OutputKind};
2use crate::config::SharedConfig;
3use crate::errors::*;
4use crate::formatting::{Format, Fragment, Values};
5use crate::protocol::i3bar_block::I3BarBlock;
6use serde::Deserialize;
7use smart_default::SmartDefault;
8
9#[derive(Debug, Clone, Default)]
10pub struct Widget {
11    pub state: State,
12    source: Source,
13    values: Values,
14    /// The declared output variant this widget renders, when the block has
15    /// been migrated to a prepared [`crate::block_plan::BlockPlan`].
16    contract: Option<OutputHandle>,
17}
18
19impl Widget {
20    pub fn new() -> Self {
21        Self::default()
22    }
23
24    /*
25     * Builders
26     */
27
28    pub fn with_text(mut self, text: String) -> Self {
29        self.set_text(text);
30        self
31    }
32
33    pub fn with_state(mut self, state: State) -> Self {
34        self.state = state;
35        self
36    }
37
38    pub fn with_format(mut self, format: Format) -> Self {
39        self.set_format(format);
40        self
41    }
42
43    /*
44     * Setters
45     */
46
47    pub fn set_text(&mut self, text: String) {
48        if text.is_empty() {
49            self.source = Source::None;
50        } else {
51            self.source = Source::Text(text);
52        }
53        // Same reasoning as `set_format`: raw text is not what the output
54        // handle promised, so the contract no longer describes this widget.
55        // Text output is declared and rendered via `new_text_widget`.
56        self.contract = None;
57    }
58
59    pub fn set_format(&mut self, format: Format) {
60        self.source = Source::Format(format);
61        // A raw format replacement invalidates whatever output contract the
62        // widget carried: the plan no longer describes what will render.
63        // Contracted widgets must switch outputs via `set_output` instead;
64        // publishing this widget now fails the contract check.
65        self.contract = None;
66    }
67
68    pub(crate) fn values(&self) -> &Values {
69        &self.values
70    }
71
72    pub fn set_values(&mut self, new_values: Values) {
73        self.values = new_values;
74    }
75
76    /// A widget rendering `output`'s declared format. Source and contract are
77    /// set together and only here: there is deliberately no way to attach a
78    /// handle to a widget whose source did not come from it, which would let
79    /// an arbitrary format pass validation under a valid output's name.
80    pub(crate) fn from_output(output: &OutputHandle) -> Self {
81        let mut widget = Self::new();
82        widget.set_output(output);
83        widget
84    }
85
86    /// A widget rendering `text` as `output`, which must be a text output.
87    /// See [`Self::from_output`] for why this is a constructor.
88    pub(crate) fn text_from_output(output: &OutputHandle, text: String) -> Self {
89        let mut widget = Self::new();
90        widget.set_text(text);
91        widget.contract = Some(output.clone());
92        widget
93    }
94
95    /// Switch this widget to another declared output: installs that output's
96    /// effective format and contract together.
97    pub(crate) fn set_output(&mut self, output: &OutputHandle) {
98        self.set_format(output.format().clone());
99        self.contract = Some(output.clone());
100    }
101
102    #[cfg(test)]
103    pub(crate) fn contract(&self) -> Option<&OutputHandle> {
104        self.contract.as_ref()
105    }
106
107    /// Enforce the prepared contract at the point a block publishes this
108    /// widget: everything that renders — a format or plain text alike — must
109    /// come from an output handle of the matching kind, and every icon value
110    /// must be declared. A failure here is an i3status-rs bug (the bar shows
111    /// it as a block error), never a configuration problem.
112    pub(crate) fn check_contract(&self) -> Result<()> {
113        // A widget with no source renders nothing at all, so there is no
114        // output to hold it to.
115        if matches!(self.source, Source::None) {
116            return Ok(());
117        }
118        let Some(handle) = &self.contract else {
119            let kind = match self.source {
120                Source::Format(_) => "format",
121                _ => "text",
122            };
123            return Err(Error::new(format!(
124                "{CONTRACT_BUG}: a {kind} widget was published without a \
125                 prepared output handle"
126            )));
127        };
128        let declared = handle.output().kind();
129        let matches_source = match self.source {
130            Source::Format(_) => declared == OutputKind::Format,
131            Source::Text(_) => declared == OutputKind::Text,
132            Source::None => true,
133        };
134        if !matches_source {
135            return Err(Error::new(format!(
136                "{CONTRACT_BUG}: output '{}' is declared as {declared:?} but \
137                 the published widget renders {}",
138                handle.id(),
139                match self.source {
140                    Source::Format(_) => "a format",
141                    _ => "text",
142                }
143            )));
144        }
145        if let Some(violation) = self.contract_violations().into_iter().next() {
146            return Err(Error::new(violation));
147        }
148        Ok(())
149    }
150
151    /// Icon values not declared by this widget's output contract.
152    pub(crate) fn contract_violations(&self) -> Vec<String> {
153        match &self.contract {
154            Some(handle) => handle.icon_violations(&self.values),
155            None => Vec::new(),
156        }
157    }
158
159    pub fn intervals(&self) -> Vec<u64> {
160        match &self.source {
161            Source::Format(f) => f.intervals(),
162            _ => Vec::new(),
163        }
164    }
165
166    /// Construct `I3BarBlock` from this widget
167    pub fn get_data(&self, shared_config: &SharedConfig, id: usize) -> Result<Vec<I3BarBlock>> {
168        // Create a "template" block
169        let (key_bg, key_fg) = shared_config.theme.get_colors(self.state);
170        let (full, short) = self.source.render(shared_config, &self.values)?;
171        let mut template = I3BarBlock {
172            instance: format!("{id}:"),
173            background: key_bg,
174            color: key_fg,
175            ..I3BarBlock::default()
176        };
177
178        // Collect all the pieces into "parts"
179        let mut parts = Vec::new();
180
181        if full.is_empty() {
182            return Ok(parts);
183        }
184
185        // If short text is available, it's necessary to hide all full blocks. `swaybar`/`i3bar`
186        // will switch a block to "short mode" only if it's "short_text" is set to a non-empty
187        // string "<span/>" is a non-empty string and it doesn't display anything. It's kinda hacky,
188        // but it works.
189        if !short.is_empty() {
190            template.short_text = "<span/>".into();
191        }
192
193        parts.extend(full.into_iter().map(|w| {
194            let mut data = template.clone();
195            data.full_text = w.formatted_text();
196            if let Some(i) = &w.metadata.instance {
197                data.instance.push_str(i);
198            }
199            data
200        }));
201
202        template.full_text = "<span/>".into();
203        parts.extend(short.into_iter().map(|w| {
204            let mut data = template.clone();
205            data.short_text = w.formatted_text();
206            if let Some(i) = &w.metadata.instance {
207                data.instance.push_str(i);
208            }
209            data
210        }));
211
212        Ok(parts)
213    }
214}
215
216/// State of the widget. Affects the theming.
217#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq, SmartDefault)]
218pub enum State {
219    #[default]
220    #[serde(alias = "idle")]
221    Idle,
222    #[serde(alias = "info")]
223    Info,
224    #[serde(alias = "good")]
225    Good,
226    #[serde(alias = "warning")]
227    Warning,
228    #[serde(alias = "critical")]
229    Critical,
230}
231
232/// The source of text for widget
233#[derive(Debug, Clone, SmartDefault)]
234enum Source {
235    /// Collapsed widget (only icon will be displayed)
236    #[default]
237    None,
238    /// Simple text
239    Text(String),
240    /// A format template
241    Format(Format),
242}
243
244impl Source {
245    fn render(
246        &self,
247        config: &SharedConfig,
248        values: &Values,
249    ) -> Result<(Vec<Fragment>, Vec<Fragment>)> {
250        match self {
251            Self::Text(text) => Ok((vec![text.clone().into()], vec![])),
252            Self::Format(format) => format.render(values, config),
253            Self::None => Ok((vec![], vec![])),
254        }
255    }
256}