Skip to main content

i3status_rs/
util.rs

1use std::path::{Path, PathBuf};
2
3use dirs::{config_dir, data_dir};
4use serde::de::DeserializeOwned;
5use tokio::io::AsyncReadExt as _;
6use tokio::process::Command;
7
8use crate::errors::*;
9
10/// The list of paths `find_file` checks, in the order it checks them.
11///
12/// - An absolute path is tried as given.
13/// - A relative path is tried inside XDG_CONFIG_HOME (e.g. `~/.config`), then
14///   XDG_DATA_HOME (e.g. `~/.local/share/`), then `/usr/share/`, each with the
15///   `i3status-rust` directory (and `subdir`, if given) appended.
16/// - A path without an extension is also tried with `extension` appended.
17pub fn file_candidates(file: &str, subdir: Option<&str>, extension: Option<&str>) -> Vec<PathBuf> {
18    let file = Path::new(file);
19
20    let mut bases: Vec<PathBuf> = Vec::new();
21    if file.is_absolute() {
22        bases.push(file.into());
23    } else {
24        for dir in [config_dir(), data_dir(), Some("/usr/share".into())]
25            .into_iter()
26            .flatten()
27        {
28            let mut base: PathBuf = dir;
29            base.push("i3status-rust");
30            if let Some(subdir) = subdir {
31                base.push(subdir);
32            }
33            base.push(file);
34            bases.push(base);
35        }
36    }
37
38    let mut candidates = Vec::new();
39    for base in bases {
40        let with_extension = match (base.extension(), extension) {
41            (None, Some(extension)) => Some(base.with_extension(extension)),
42            _ => None,
43        };
44        candidates.push(base);
45        candidates.extend(with_extension);
46    }
47    candidates
48}
49
50/// Tries to find a file in standard locations (see [`file_candidates`]).
51pub fn find_file(
52    file: &str,
53    subdir: Option<&str>,
54    extension: Option<&str>,
55) -> Result<Option<PathBuf>> {
56    for candidate in file_candidates(file, subdir, extension) {
57        if candidate.try_exists().error("Unable to stat file")? {
58            return Ok(Some(candidate));
59        }
60    }
61    Ok(None)
62}
63
64pub async fn new_dbus_connection() -> Result<zbus::Connection> {
65    zbus::Connection::session()
66        .await
67        .error("Failed to open DBus session connection")
68}
69
70pub async fn new_system_dbus_connection() -> Result<zbus::Connection> {
71    zbus::Connection::system()
72        .await
73        .error("Failed to open DBus system connection")
74}
75
76pub fn deserialize_toml_file<T, P>(path: P) -> Result<T>
77where
78    T: DeserializeOwned,
79    P: AsRef<Path>,
80{
81    let path = path.as_ref();
82
83    let contents = std::fs::read_to_string(path)
84        .or_error(|| format!("Failed to read file: {}", path.display()))?;
85
86    deserialize_toml_file_string(contents, path)
87}
88
89pub async fn async_deserialize_toml_file<T, P>(path: P) -> Result<T>
90where
91    T: DeserializeOwned,
92    P: AsRef<Path>,
93{
94    let path = path.as_ref();
95
96    let contents = read_file(path)
97        .await
98        .or_error(|| format!("Failed to read file: {}", path.display()))?;
99
100    deserialize_toml_file_string(contents, path)
101}
102
103fn deserialize_toml_file_string<T>(contents: String, path: &Path) -> Result<T>
104where
105    T: DeserializeOwned,
106{
107    toml::from_str(&contents).map_err(|err| {
108        let location_msg = err
109            .span()
110            .map(|span| {
111                if span == (0..0) {
112                    String::new()
113                } else {
114                    let line = 1 + contents.as_bytes()[..(span.start)]
115                        .iter()
116                        .filter(|b| **b == b'\n')
117                        .count();
118                    format!(" at line {line}")
119                }
120            })
121            .unwrap_or_default();
122        Error::new(format!(
123            "Failed to deserialize TOML file {}{}: {}",
124            path.display(),
125            location_msg,
126            err.message()
127        ))
128    })
129}
130
131pub async fn read_file(path: impl AsRef<Path>) -> std::io::Result<String> {
132    let mut file = tokio::fs::File::open(path).await?;
133    let mut content = String::new();
134    file.read_to_string(&mut content).await?;
135    Ok(content.trim_end().to_string())
136}
137
138pub async fn has_command(command: &str) -> Result<bool> {
139    Command::new("sh")
140        .args([
141            "-c",
142            format!("command -v {command} >/dev/null 2>&1").as_ref(),
143        ])
144        .status()
145        .await
146        .or_error(|| format!("Failed to check {command} presence"))
147        .map(|status| status.success())
148}
149
150/// # Example
151///
152/// ```ignore
153/// let opt = Some(1);
154/// let m: HashMap<&'static str, String> = map! {
155///     "key" => "value",
156///     [if true] "hello" => "world",
157///     [if let Some(x) = opt] "opt" => x.to_string(),
158/// };
159/// map! { @extend m
160///     "new key" => "new value",
161///     "one" => "more",
162/// }
163/// ```
164#[macro_export]
165macro_rules! map {
166    (@extend $map:ident $( $([$($cond_tokens:tt)*])? $key:literal => $value:expr ),* $(,)?) => {{
167        $(
168        map!(@insert $map, $key, $value $(,$($cond_tokens)*)?);
169        )*
170    }};
171    (@extend $map:ident $( $key:expr => $value:expr ),* $(,)?) => {{
172        $(
173        map!(@insert $map, $key, $value);
174        )*
175    }};
176    (@insert $map:ident, $key:expr, $value:expr) => {{
177        $map.insert($key.into(), $value.into());
178    }};
179    (@insert $map:ident, $key:expr, $value:expr, if $cond:expr) => {{
180        if $cond {
181        $map.insert($key.into(), $value.into());
182        }
183    }};
184    (@insert $map:ident, $key:expr, $value:expr, if let $pat:pat = $match_on:expr) => {{
185        if let $pat = $match_on {
186        $map.insert($key.into(), $value.into());
187        }
188    }};
189    ($($tt:tt)*) => {{
190        #[allow(unused_mut)]
191        let mut m = ::std::collections::HashMap::new();
192        map!(@extend m $($tt)*);
193        m
194    }};
195}
196
197pub use map;
198
199macro_rules! regex {
200    ($re:literal $(,)?) => {{
201        static RE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
202        RE.get_or_init(|| regex::Regex::new($re).unwrap())
203    }};
204}
205
206macro_rules! make_log_macro {
207    (@wdoll $macro_name:ident, $block_name:literal, ($dol:tt)) => {
208        #[allow(dead_code)]
209        macro_rules! $macro_name {
210            ($dol($args:tt)+) => {
211                ::log::$macro_name!(target: $block_name, $dol($args)+);
212            };
213        }
214    };
215    ($macro_name:ident, $block_name:literal) => {
216        make_log_macro!(@wdoll $macro_name, $block_name, ($));
217    };
218}
219
220pub fn format_bar_graph(content: &[f64]) -> String {
221    // (x * one eighth block) https://en.wikipedia.org/wiki/Block_Elements
222    static BARS: [char; 8] = [
223        '\u{2581}', '\u{2582}', '\u{2583}', '\u{2584}', '\u{2585}', '\u{2586}', '\u{2587}',
224        '\u{2588}',
225    ];
226
227    // Find min and max
228    let mut min = f64::INFINITY;
229    let mut max = f64::NEG_INFINITY;
230    for &v in content {
231        min = min.min(v);
232        max = max.max(v);
233    }
234
235    let range = max - min;
236    content
237        .iter()
238        .map(|x| BARS[((x - min) / range * 7.).clamp(0., 7.) as usize])
239        .collect()
240}
241
242/// Doctor-only: when enabled (in doctor's worker process, never in the real
243/// bar), every country flag generated by [`country_flag_from_iso_code`] is
244/// recorded so the live block table can attribute the glyph to its block.
245static FLAG_RECORDER: std::sync::OnceLock<std::sync::Mutex<Vec<(String, String)>>> =
246    std::sync::OnceLock::new();
247
248pub(crate) fn enable_flag_recorder() {
249    let _ = FLAG_RECORDER.set(std::sync::Mutex::new(Vec::new()));
250}
251
252/// (country code, flag) pairs generated since the recorder was enabled.
253pub(crate) fn recorded_flags() -> Vec<(String, String)> {
254    let mut flags = FLAG_RECORDER
255        .get()
256        .and_then(|m| m.lock().ok().map(|v| v.clone()))
257        .unwrap_or_default();
258    flags.sort_unstable();
259    flags.dedup();
260    flags
261}
262
263fn record_flag(country_code: &str, flag: &str) {
264    if let Some(recorder) = FLAG_RECORDER.get()
265        && let Ok(mut recorder) = recorder.lock()
266    {
267        recorder.push((country_code.to_string(), flag.to_string()));
268    }
269}
270
271/// Convert 2 letter country code to Unicode
272pub fn country_flag_from_iso_code(country_code: &str) -> String {
273    let [mut b1, mut b2]: [u8; 2] = country_code.as_bytes().try_into().unwrap_or([0, 0]);
274
275    if !b1.is_ascii_uppercase() || !b2.is_ascii_uppercase() {
276        return country_code.into();
277    }
278
279    // Each char is encoded as 1F1E6 to 1F1FF for A-Z
280    b1 += 0xa5;
281    b2 += 0xa5;
282    // The last byte will always start with 101 (0xa0) and then the 5 least
283    // significant bits from the previous result
284    b1 = 0xa0 | (b1 & 0x1f);
285    b2 = 0xa0 | (b2 & 0x1f);
286    // Get the flag string from the UTF-8 representation of our Unicode characters.
287    let flag = String::from_utf8(vec![0xf0, 0x9f, 0x87, b1, 0xf0, 0x9f, 0x87, b2]).unwrap();
288    record_flag(country_code, &flag);
289    flag
290}
291
292#[inline]
293pub fn celsius_to_fahrenheit(c: f64) -> f64 {
294    c * (9.0 / 5.0) + 32.0
295}
296
297#[inline]
298pub fn fahrenheit_to_celsius(f: f64) -> f64 {
299    (f - 32.0) * (5.0 / 9.0)
300}
301
302#[inline]
303pub fn mps_to_kmh(mps: f64) -> f64 {
304    mps * 3.6
305}
306
307#[inline]
308pub fn kmh_to_mps(kmh: f64) -> f64 {
309    kmh / 3.6
310}
311
312const KM_PER_MILE: f64 = 1.609344;
313
314#[inline]
315pub fn kmh_to_mph(kmh: f64) -> f64 {
316    kmh / KM_PER_MILE
317}
318
319#[inline]
320pub fn mph_to_kmh(mph: f64) -> f64 {
321    mph * KM_PER_MILE
322}
323
324/// A shortcut for `Default::default()`
325/// See <https://github.com/rust-lang/rust/issues/73014>
326#[inline]
327pub fn default<T: Default>() -> T {
328    Default::default()
329}
330
331pub trait StreamExtDebounced: futures::StreamExt {
332    fn next_debounced(&mut self) -> impl Future<Output = Option<Self::Item>>;
333}
334
335impl<T: futures::StreamExt + Unpin> StreamExtDebounced for T {
336    async fn next_debounced(&mut self) -> Option<Self::Item> {
337        let mut result = self.next().await?;
338        let mut noop_ctx = std::task::Context::from_waker(std::task::Waker::noop());
339        loop {
340            match self.poll_next_unpin(&mut noop_ctx) {
341                std::task::Poll::Ready(Some(x)) => result = x,
342                std::task::Poll::Ready(None) | std::task::Poll::Pending => return Some(result),
343            }
344        }
345    }
346}
347
348/// Run a future to completion synchronously.
349///
350/// If invoked outside an async runtime, a temporary current-thread runtime is used.
351/// If invoked within an active Tokio runtime, the future is driven in a dedicated
352/// thread to avoid blocking or nested-runtime issues.
353pub fn run_sync<F, T>(future: F) -> T
354where
355    F: std::future::Future<Output = T> + Send + 'static,
356    T: Send + 'static,
357{
358    match tokio::runtime::Handle::try_current() {
359        Ok(_) => std::thread::spawn(move || {
360            tokio::runtime::Builder::new_current_thread()
361                .enable_all()
362                .build()
363                .expect("failed to create tokio runtime")
364                .block_on(future)
365        })
366        .join()
367        .expect("worker thread panicked"),
368        Err(_) => tokio::runtime::Builder::new_current_thread()
369            .enable_all()
370            .build()
371            .expect("failed to create tokio runtime")
372            .block_on(future),
373    }
374}
375
376#[cfg(test)]
377mod tests {
378    use super::*;
379
380    #[tokio::test]
381    async fn test_has_command_ok() {
382        // we assume sh is always available
383        assert!(has_command("sh").await.unwrap());
384    }
385
386    #[tokio::test]
387    async fn test_has_command_err() {
388        // we assume thequickbrownfoxjumpsoverthelazydog command does not exist
389        assert!(
390            !has_command("thequickbrownfoxjumpsoverthelazydog")
391                .await
392                .unwrap()
393        );
394    }
395
396    #[test]
397    fn test_run_sync_outside_runtime() {
398        let res = run_sync(async { 12345 });
399        assert_eq!(res, 12345);
400    }
401
402    #[tokio::test]
403    async fn test_run_sync_inside_runtime() {
404        let res = run_sync(async { 54321 });
405        assert_eq!(res, 54321);
406    }
407
408    #[test]
409    fn test_flags() {
410        assert!(country_flag_from_iso_code("ES") == "πŸ‡ͺπŸ‡Έ");
411        assert!(country_flag_from_iso_code("US") == "πŸ‡ΊπŸ‡Έ");
412        assert!(country_flag_from_iso_code("USA") == "USA");
413    }
414
415    #[test]
416    fn doctor_flag_recorder_keeps_the_country_code() {
417        enable_flag_recorder();
418        let flag = country_flag_from_iso_code("NZ");
419        assert!(recorded_flags().contains(&("NZ".into(), flag)));
420    }
421
422    #[test]
423    fn test_file_candidates_absolute() {
424        // extension is probed only when the path has none
425        assert_eq!(
426            file_candidates("/foo/awesome5", Some("icons"), Some("toml")),
427            [
428                PathBuf::from("/foo/awesome5"),
429                PathBuf::from("/foo/awesome5.toml")
430            ]
431        );
432        assert_eq!(
433            file_candidates("/foo/awesome5.toml", Some("icons"), Some("toml")),
434            [PathBuf::from("/foo/awesome5.toml")]
435        );
436    }
437
438    #[test]
439    fn test_file_candidates_relative() {
440        let candidates = file_candidates("awesome5", Some("icons"), Some("toml"));
441        // every candidate ends with the subdir + file, checked in pairs of
442        // (no extension, with extension), with /usr/share always last
443        assert!(candidates.len() >= 2);
444        assert!(candidates.len().is_multiple_of(2));
445        for pair in candidates.chunks(2) {
446            assert!(
447                pair[0].ends_with("i3status-rust/icons/awesome5")
448                    || pair[0].ends_with("icons/awesome5")
449            );
450            assert_eq!(pair[1], pair[0].with_extension("toml"));
451        }
452        assert_eq!(
453            candidates[candidates.len() - 2],
454            PathBuf::from("/usr/share/i3status-rust/icons/awesome5")
455        );
456
457        // a name that already has an extension is not probed twice
458        let candidates = file_candidates("awesome5.toml", Some("icons"), Some("toml"));
459        assert!(candidates.iter().all(|c| c.extension().is_some()));
460    }
461}