1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
use std::process::Command;
use std::str::FromStr;
use std::time::Duration;

use crossbeam_channel::Sender;
use regex::RegexSet;
use serde_derive::Deserialize;

use crate::blocks::{Block, ConfigBlock, Update};
use crate::config::{LogicalDirection, SharedConfig};
use crate::de::deserialize_duration;
use crate::errors::*;
use crate::formatting::value::Value;
use crate::formatting::FormatTemplate;
use crate::input::{I3BarEvent, MouseButton};
use crate::scheduler::Task;
use crate::subprocess::spawn_child_async;
use crate::widgets::text::TextWidget;
use crate::widgets::I3BarWidget;

struct Monitor {
    name: String,
    brightness: u32,
    resolution: String,
}

impl Monitor {
    fn new(name: &str, brightness: u32, resolution: &str) -> Self {
        Monitor {
            name: String::from(name),
            brightness,
            resolution: String::from(resolution),
        }
    }

    fn set_brightness(&mut self, step: i32) {
        spawn_child_async(
            "xrandr",
            &[
                "--output",
                &self.name,
                "--brightness",
                &format!("{}", (self.brightness as i32 + step) as f32 / 100.0),
            ],
        )
        .expect("Failed to set xrandr output.");
        self.brightness = (self.brightness as i32 + step) as u32;
    }
}

pub struct Xrandr {
    id: usize,
    text: TextWidget,
    update_interval: Duration,
    monitors: Vec<Monitor>,
    icons: bool,
    resolution: bool,
    step_width: u32,
    current_idx: usize,
    shared_config: SharedConfig,
}

// TODO add `format`
#[derive(Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields, default)]
pub struct XrandrConfig {
    /// Update interval in seconds
    #[serde(deserialize_with = "deserialize_duration")]
    pub interval: Duration,

    /// Show icons for brightness and resolution (needs awesome fonts support)
    pub icons: bool,

    /// Shows the screens resolution
    pub resolution: bool,

    /// The steps brightness is in/decreased for the selected screen (When greater than 50 it gets limited to 50)
    pub step_width: u32,
}

impl Default for XrandrConfig {
    fn default() -> Self {
        Self {
            interval: Duration::from_secs(5),
            icons: true,
            resolution: false,
            step_width: 5,
        }
    }
}

macro_rules! unwrap_or_continue {
    ($e: expr) => {
        match $e {
            Some(e) => e,
            None => continue,
        }
    };
}

impl Xrandr {
    fn get_active_monitors() -> Result<Option<Vec<String>>> {
        let active_monitors_cli = String::from_utf8(
            Command::new("xrandr")
                .args(&["--listactivemonitors"])
                .output()
                .block_error("xrandr", "couldn't collect active xrandr monitors")?
                .stdout,
        )
        .block_error("xrandr", "couldn't parse xrandr monitor list")?;

        let monitors: Vec<&str> = active_monitors_cli.split('\n').collect();
        let mut active_monitors: Vec<String> = Vec::new();
        for monitor in monitors {
            if let Some((name, _)) = monitor
                .split_whitespace()
                .collect::<Vec<&str>>()
                .split_last()
            {
                active_monitors.push(String::from(*name));
            }
        }
        if !active_monitors.is_empty() {
            Ok(Some(active_monitors))
        } else {
            Ok(None)
        }
    }

    fn get_monitor_metrics(monitor_names: &[String]) -> Result<Option<Vec<Monitor>>> {
        let mut monitor_metrics: Vec<Monitor> = Vec::new();
        let monitor_info_cli = String::from_utf8(
            Command::new("xrandr")
                .args(&["--verbose"])
                .output()
                .block_error("xrandr", "couldn't collect xrandr monitor info")?
                .stdout,
        )
        .block_error("xrandr", "couldn't parse xrandr monitor info")?;

        let regex_set = RegexSet::new(
            monitor_names
                .iter()
                .map(|x| format!("{} connected", x))
                .chain(std::iter::once("Brightness:".to_string())),
        )
        .block_error("xrandr", "invalid monitor name")?;

        let monitor_infos: Vec<&str> = monitor_info_cli
            .split('\n')
            .filter(|l| regex_set.is_match(l))
            .collect();
        for chunk in monitor_infos.chunks_exact(2) {
            let mut brightness = 0;
            let mut display: &str = "";
            let mi_line = unwrap_or_continue!(chunk.get(0));
            let b_line = unwrap_or_continue!(chunk.get(1));
            let mi_line_args: Vec<&str> = mi_line.split_whitespace().collect();
            if let Some(name) = mi_line_args.get(0) {
                display = name.trim();
                if let Some(brightness_raw) = b_line.split(':').collect::<Vec<&str>>().get(1) {
                    brightness = (f32::from_str(brightness_raw.trim())
                        .block_error("xrandr", "unable to parse brightness")?
                        * 100.0)
                        .floor() as u32;
                }
            }
            if let Some(mut res) = mi_line_args.get(2) {
                if res.find('+').is_none() {
                    res = unwrap_or_continue!(mi_line_args.get(3));
                }
                if let Some(resolution) = res.split('+').collect::<Vec<&str>>().get(0) {
                    monitor_metrics.push(Monitor::new(display, brightness, resolution.trim()));
                }
            }
        }
        if !monitor_metrics.is_empty() {
            Ok(Some(monitor_metrics))
        } else {
            Ok(None)
        }
    }

    fn display(&mut self) -> Result<()> {
        if let Some(m) = self.monitors.get(self.current_idx) {
            let values = map!(
                "display" => Value::from_string(m.name.clone()),
                "brightness" => Value::from_integer(m.brightness as i64).percents(),
                //TODO: change `brightness_icon` based on `brightness`
                "brightness_icon" => Value::from_string(self.shared_config.get_icon("backlight_full")?),
                "resolution" => Value::from_string(m.resolution.clone()),
                "res_icon" => Value::from_string(self.shared_config.get_icon("resolution")?),
            );

            self.text.set_icon("xrandr")?;
            //FIXME: allow user to set those strings
            let format_str = if self.resolution {
                if self.icons {
                    "{display} {brightness_icon} {brightness} {res_icon} {resolution}"
                } else {
                    "{display}: {brightness} [{resolution}]"
                }
            } else if self.icons {
                "{display} {brightness_icon} {brightness}"
            } else {
                "{display}: {brightness}"
            };

            if let Ok(fmt_template) = FormatTemplate::from_string(format_str) {
                self.text.set_text(fmt_template.render(&values)?);
            }
        }

        Ok(())
    }
}

impl ConfigBlock for Xrandr {
    type Config = XrandrConfig;

    fn new(
        id: usize,
        block_config: Self::Config,
        shared_config: SharedConfig,
        _tx_update_request: Sender<Task>,
    ) -> Result<Self> {
        let mut step_width = block_config.step_width;
        if step_width > 50 {
            step_width = 50;
        }
        Ok(Xrandr {
            id,
            text: TextWidget::new(id, 0, shared_config.clone()).with_icon("xrandr")?,
            update_interval: block_config.interval,
            current_idx: 0,
            icons: block_config.icons,
            resolution: block_config.resolution,
            step_width,
            monitors: Vec::new(),
            shared_config,
        })
    }
}

impl Block for Xrandr {
    fn update(&mut self) -> Result<Option<Update>> {
        if let Some(am) = Xrandr::get_active_monitors()? {
            if let Some(mm) = Xrandr::get_monitor_metrics(&am)? {
                self.monitors = mm;
                self.display()?;
            }
        }

        Ok(Some(self.update_interval.into()))
    }

    fn view(&self) -> Vec<&dyn I3BarWidget> {
        vec![&self.text]
    }

    fn click(&mut self, e: &I3BarEvent) -> Result<()> {
        match e.button {
            MouseButton::Left => {
                if self.current_idx < self.monitors.len() - 1 {
                    self.current_idx += 1;
                } else {
                    self.current_idx = 0;
                }
            }
            mb => {
                use LogicalDirection::*;
                match self.shared_config.scrolling.to_logical_direction(mb) {
                    Some(Up) => {
                        if let Some(monitor) = self.monitors.get_mut(self.current_idx) {
                            if monitor.brightness <= (100 - self.step_width) {
                                monitor.set_brightness(self.step_width as i32);
                            }
                        }
                    }
                    Some(Down) => {
                        if let Some(monitor) = self.monitors.get_mut(self.current_idx) {
                            if monitor.brightness >= self.step_width {
                                monitor.set_brightness(-(self.step_width as i32));
                            }
                        }
                    }
                    None => {}
                }
            }
        }
        self.display()?;

        Ok(())
    }

    fn id(&self) -> usize {
        self.id
    }
}