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 contract: Option<OutputHandle>,
17}
18
19impl Widget {
20 pub fn new() -> Self {
21 Self::default()
22 }
23
24 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 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 self.contract = None;
57 }
58
59 pub fn set_format(&mut self, format: Format) {
60 self.source = Source::Format(format);
61 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 pub(crate) fn from_output(output: &OutputHandle) -> Self {
81 let mut widget = Self::new();
82 widget.set_output(output);
83 widget
84 }
85
86 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 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 pub(crate) fn check_contract(&self) -> Result<()> {
113 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 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 pub fn get_data(&self, shared_config: &SharedConfig, id: usize) -> Result<Vec<I3BarBlock>> {
168 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 let mut parts = Vec::new();
180
181 if full.is_empty() {
182 return Ok(parts);
183 }
184
185 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#[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#[derive(Debug, Clone, SmartDefault)]
234enum Source {
235 #[default]
237 None,
238 Text(String),
240 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}