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
#![warn(clippy::match_same_arms)]
#![warn(clippy::semicolon_if_nothing_returned)]
#![warn(clippy::unnecessary_wraps)]
#![cfg_attr(docsrs, feature(doc_cfg))]

#[macro_use]
mod util;
mod config;
mod consts;
mod device;
mod errors;
#[cfg(feature = "watch")]
mod watcher;

use std::collections::HashMap;
use std::ffi::OsString;

use futures::future::join_all;
use regex::Regex;
use tokio::fs::read_dir;

pub use crate::config::{CalibrightConfig, DeviceConfig};
use crate::consts::*;
use crate::device::Device;
pub use crate::errors::CalibrightError;
use crate::errors::*;
use crate::util::*;
#[cfg(feature = "watch")]
use crate::watcher::*;

make_log_macro!(debug, "calibright");

/// Used to construct [`Calibright`]
pub struct CalibrightBuilder<'a> {
    device_regex: &'a str,
    config: Option<CalibrightConfig>,
    #[cfg(feature = "watch")]
    poll_interval: Duration,
}

impl<'a> Default for CalibrightBuilder<'a> {
    fn default() -> Self {
        Self {
            device_regex: ".",
            config: None,
            #[cfg(feature = "watch")]
            poll_interval: Duration::from_secs(2),
        }
    }
}

impl<'a> CalibrightBuilder<'a> {
    /// Create a new [`CalibrightBuilder`].
    pub fn new() -> Self {
        CalibrightBuilder::default()
    }

    /// Defaults to `"."` (matches all devices).
    pub fn with_device_regex(mut self, device_regex: &'a str) -> Self {
        self.device_regex = device_regex;
        self
    }

    /// Defaults to [`CalibrightConfig::new()`].
    pub fn with_config(mut self, config: CalibrightConfig) -> Self {
        self.config = Some(config);
        self
    }

    #[cfg(feature = "watch")]
    #[cfg_attr(docsrs, doc(cfg(feature = "watch")))]
    /// Default poll_interval is 2 seconds.
    pub fn with_poll_interval(mut self, poll_interval: Duration) -> Self {
        self.poll_interval = poll_interval;
        self
    }

    /// Returns the constructed [`Calibright`] instance.
    pub async fn build(self) -> Result<Calibright> {
        let config = match self.config {
            Some(config) => config,
            None => CalibrightConfig::new().await?,
        };

        Calibright::new(
            Regex::new(self.device_regex)?,
            config,
            #[cfg(feature = "watch")]
            self.poll_interval,
        )
        .await
    }
}

#[cfg(not(feature = "watch"))]
pub struct Calibright {
    devices: HashMap<OsString, Device>,
}

#[cfg(feature = "watch")]
pub struct Calibright {
    devices: HashMap<OsString, Device>,
    device_regex: Regex,
    config: CalibrightConfig,
    _poll_watcher: PollWatcher,
    inotify_watcher: INotifyWatcher,
    rx: Receiver<notify::Result<notify::Event>>,
    poll_interval: Duration,
}

impl Calibright {
    pub(crate) async fn new(
        device_regex: Regex,
        config: CalibrightConfig,
        #[cfg(feature = "watch")] poll_interval: Duration,
    ) -> Result<Self> {
        let mut sysfs_paths = read_dir(DEVICES_PATH).await?;

        let mut device_names = Vec::new();
        while let Some(sysfs_path) = sysfs_paths.next_entry().await? {
            let device_name = sysfs_path.file_name();
            if device_regex.is_match(&device_name.to_string_lossy()) {
                debug!(
                    "{:?} matched {}",
                    device_name.to_string_lossy().to_string(),
                    device_regex.as_str()
                );

                device_names.push(device_name.to_string_lossy().to_string());
            }
        }

        let mut device_map = HashMap::new();
        let device_list =
            join_all(device_names.iter().map(|device_name| {
                Device::new(device_name, config.get_device_config(device_name))
            }))
            .await;
        let device_list = device_list.iter().filter_map(|device| match device {
            Ok(device) => Some(device.to_owned()),
            Err(e) => {
                debug!("{e}");
                None
            }
        });

        #[cfg(not(feature = "watch"))]
        {
            for device in device_list {
                device_map.insert(device.device_name.clone(), device);
            }

            Ok(Calibright {
                devices: device_map,
            })
        }

        #[cfg(feature = "watch")]
        {
            let (_poll_watcher, mut inotify_watcher, rx) =
                pseudo_fs_watcher(DEVICES_PATH, poll_interval)?;

            for device in device_list {
                let watch_path = device.read_brightness_file.to_path_buf();
                inotify_watcher.watch(&watch_path, notify::RecursiveMode::NonRecursive)?;
                device_map.insert(device.device_name.clone(), device);
            }

            Ok(Calibright {
                devices: device_map,
                device_regex,
                config,
                _poll_watcher,
                inotify_watcher,
                rx,
                poll_interval,
            })
        }
    }

    #[cfg(feature = "watch")]
    #[cfg_attr(docsrs, doc(cfg(feature = "watch")))]
    /// Wait for a device to be added/removed or for brightness to be changed.
    pub async fn next(&mut self) -> Result<()> {
        use futures::StreamExt;
        use std::path::{Path, PathBuf};

        while let Some(res) = self.rx.next().await {
            let mut change_occurred = false;
            let event = res?;
            debug!("{:?}", event);
            let depth1_paths: Vec<&PathBuf> = event
                .paths
                .iter()
                .filter(|&p| p.parent() == Some(Path::new(DEVICES_PATH)))
                .collect();
            let brightness_paths: Vec<&PathBuf> = event
                .paths
                .iter()
                .filter(|&p| p.ends_with(FILE_BRIGHTNESS) || p.ends_with(FILE_BRIGHTNESS_AMD))
                .collect();
            if event.kind.is_create() && !depth1_paths.is_empty() {
                for path in depth1_paths {
                    if let Some(file_name) = path.file_name() {
                        let device_name = file_name.to_string_lossy().to_string();
                        debug!("New device {:?}", device_name);
                        if self.devices.contains_key(file_name) {
                            // We already know about this device, so no need to create a new `Device`
                            debug!("New device {:?}, already known", path);
                            continue;
                        }
                        if self.device_regex.is_match(&device_name) {
                            debug!("{:?} matched {}", device_name, self.device_regex.as_str());
                            let new_device = Device::new(
                                &device_name,
                                self.config.get_device_config(&device_name),
                            )
                            .await?;
                            let watch_path = new_device.read_brightness_file.clone();
                            self.inotify_watcher
                                .watch(&watch_path, notify::RecursiveMode::NonRecursive)?;
                            self.devices
                                .insert(new_device.device_name.clone(), new_device);
                            change_occurred = true;
                        }
                    }
                }
            } else if event.kind.is_remove() && !depth1_paths.is_empty() {
                for path in depth1_paths {
                    if let Some(file_name) = path.file_name() {
                        debug!("Remove {}", path.display());
                        if let Some(old_device) = self.devices.remove(file_name) {
                            debug!("Removed {}", old_device.read_brightness_file.display());
                            self.inotify_watcher
                                .unwatch(&old_device.read_brightness_file)?;
                            change_occurred = true;
                        }
                    }
                }
            } else if event.kind.is_modify() && !brightness_paths.is_empty() {
                for brightness_path in brightness_paths {
                    if let Some(path) = brightness_path.parent() {
                        if let Some(file_name) = path.file_name() {
                            if let Some(device) = self.devices.get(file_name) {
                                if device.get_last_set_ago() > self.poll_interval {
                                    change_occurred = true;
                                }
                            }
                        }
                    }
                }
            }
            if change_occurred {
                return Ok(());
            }
        }
        Err(CalibrightError::Other("Nothing to watch".into()))
    }

    /// Get the average screen brightness based on the calibration settings.
    /// Brightness is in range 0.0 to 1.0 (inclusive).
    pub async fn get_brightness(&mut self) -> Result<f64> {
        let brightnesses = join_all_accept_single_ok(
            self.devices
                .iter_mut()
                .map(|(_, device)| device.get_brightness()),
        )
        .await?;

        Ok(brightnesses.iter().sum::<f64>() / (brightnesses.len() as f64))
    }

    /// Set the screen brightness based on the calibration settings.
    /// Brightness is in range 0.0 to 1.0 (inclusive).
    pub async fn set_brightness(&mut self, brightness: f64) -> Result<()> {
        join_all_accept_single_ok(
            self.devices
                .iter_mut()
                .map(|(_, device)| device.set_brightness(brightness)),
        )
        .await?;

        Ok(())
    }
}