leftwm_core/utils/
child_process.rs

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
//! Starts programs in autostart, runs global 'up' script, and boots theme. Provides function to
//! boot other desktop files also.
use std::cmp::Reverse;
use std::collections::BinaryHeap;
use std::collections::HashMap;
use std::ffi::OsStr;
use std::fs;
use std::iter::{Extend, FromIterator};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::sync::{atomic::AtomicBool, Arc};

use xdg::BaseDirectories;

use crate::errors::Result;

pub type ChildID = u32;

#[derive(Default)]
pub struct Nanny {}

impl Nanny {
    /// Retrieve the path to the config directory. Tries to create it if it does not exist.
    ///
    /// # Errors
    ///
    /// Will error if unable to open or create the config directory.
    /// Could be caused by inadequate permissions.
    fn get_config_dir() -> Result<PathBuf> {
        BaseDirectories::with_prefix("leftwm")?
            .create_config_directory("")
            .map_err(Into::into)
    }

    /// Runs a script if it exits
    fn run_script(path: &Path) -> Result<Child> {
        Command::new(path)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .map_err(Into::into)
    }

    /// Runs the 'up' script in the config directory, if there is one.
    ///
    /// # Errors
    ///
    /// Will error if unable to open current config directory.
    /// Could be caused by inadequate permissions.
    pub fn run_global_up_script() -> Result<Child> {
        let mut path = Self::get_config_dir()?;
        let mut scripts = Self::get_files_in_path_with_ext(&path, "up")?;

        while let Some(Reverse(script)) = scripts.pop() {
            if let Err(e) = Self::run_script(&script) {
                tracing::error!("Unable to run script {script:?}, error: {e}");
            }
        }

        path.push("up");
        Self::run_script(&path)
    }

    /// Returns a min-heap of files with the specified extension.
    ///
    /// # Errors
    ///
    /// Comes from `std::fs::read_dir()`.
    fn get_files_in_path_with_ext(
        path: impl AsRef<Path>,
        ext: impl AsRef<OsStr>,
    ) -> Result<BinaryHeap<Reverse<PathBuf>>> {
        let dir = fs::read_dir(&path)?;

        let mut files = BinaryHeap::new();

        for entry in dir.flatten() {
            let file = entry.path();

            if let Some(extension) = file.extension() {
                if extension == ext.as_ref() {
                    files.push(Reverse(file));
                }
            }
        }

        Ok(files)
    }

    /// Runs the 'up' script of the current theme, if there is one.
    ///
    /// # Errors
    ///
    /// Will error if unable to open current theme directory.
    /// Could be caused by inadequate permissions.
    pub fn boot_current_theme() -> Result<Child> {
        let mut path = Self::get_config_dir()?;
        path.push("themes");
        path.push("current");
        path.push("up");
        Self::run_script(&path)
    }
}

/// A struct managing children processes.
#[derive(Debug, Default)]
pub struct Children {
    inner: HashMap<ChildID, Child>,
}

impl Children {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }
    #[must_use]
    pub fn len(&self) -> usize {
        self.inner.len()
    }
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }
    /// Insert a `Child` in the `Children`.
    ///
    /// # Returns
    /// - `true` if `child` is a new child-process
    /// - `false` if `child` is already known
    pub fn insert(&mut self, child: Child) -> bool {
        self.inner.insert(child.id(), child).is_none()
    }

    /// Merge another `Children` into this `Children`.
    pub fn merge(&mut self, reaper: Self) {
        self.inner.extend(reaper.inner);
    }

    /// Remove all children precosses which finished
    pub fn remove_finished_children(&mut self) {
        self.inner
            .retain(|_, child| child.try_wait().map_or(true, |ret| ret.is_none()));
    }
}

impl FromIterator<Child> for Children {
    fn from_iter<T: IntoIterator<Item = Child>>(iter: T) -> Self {
        Self {
            inner: iter.into_iter().map(|child| (child.id(), child)).collect(),
        }
    }
}

impl Extend<Child> for Children {
    fn extend<T: IntoIterator<Item = Child>>(&mut self, iter: T) {
        self.inner
            .extend(iter.into_iter().map(|child| (child.id(), child)));
    }
}

/// Register the `SIGCHLD` signal handler. Once the signal is received,
/// the flag will be set true. User needs to manually clear the flag.
pub fn register_child_hook(flag: Arc<AtomicBool>) {
    _ = signal_hook::flag::register(signal_hook::consts::signal::SIGCHLD, flag)
        .map_err(|err| tracing::error!("Cannot register SIGCHLD signal handler: {:?}", err));
}

/// Sends command to shell for execution
/// Assumes STDIN/STDERR/STDOUT unwanted.
pub fn exec_shell(command: &str, children: &mut Children) -> Option<ChildID> {
    exec_shell_with_args(command, Vec::new(), children)
}

/// Sends command to shell for execution including arguments.
/// Assumes STDIN/STDERR/STDOUT unwanted.
pub fn exec_shell_with_args(
    command: &str,
    args: Vec<String>,
    children: &mut Children,
) -> Option<ChildID> {
    let child = Command::new(command)
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .ok()?;
    let pid = child.id();
    children.insert(child);
    Some(pid)
}