tablero 0.4.3

A fast, native Wayland status bar for Hyprland
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! Native Hypridle process discovery, watching, and state control.
//!
//! Finding hypridle means scanning the process table, which is too much to do
//! every couple of seconds for a state that changes a few times a day. So the
//! scan only runs while hypridle is *not* running, at a slow cadence; once a
//! process is found the producer holds a pidfd on it and sleeps until the kernel
//! reports its exit.

use std::fs;
use std::io;
use std::os::fd::OwnedFd;
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::Duration;

use log::warn;
use nix::errno::Errno;
use nix::sys::signal::{Signal, kill};
use nix::unistd::Pid;
use rustix::process::{PidfdFlags, pidfd_open};
use tokio::io::unix::AsyncFd;
use tokio::process::Command as TokioCommand;
use tokio::time;

use crate::command::CommandReceiver;
use crate::producer::{MsgSender, Producer, ProducerFuture, ProducerResult};
use crate::widget::{Command, Hypridle, Msg};

const PROC_ROOT: &str = "/proc";
const HYPRIDLE_EXECUTABLE: &str = "hypridle";
/// How often the process table is scanned while hypridle is not running — the
/// longest an instance started outside the bar goes unnoticed. Configurable per
/// widget as `interval`.
pub const DEFAULT_INTERVAL: Duration = Duration::from_secs(10);
const STOP_TIMEOUT: Duration = Duration::from_secs(1);
const STOP_POLL_INTERVAL: Duration = Duration::from_millis(50);

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum HypridleAction {
    None,
    Start,
    Stop,
}

fn required_action(active: bool, desired: bool) -> HypridleAction {
    match (active, desired) {
        (false, true) => HypridleAction::Start,
        (true, false) => HypridleAction::Stop,
        _ => HypridleAction::None,
    }
}

/// Find same-user processes whose kernel command name is exactly `hypridle`.
///
/// Deliberately synchronous: `/proc` is memory-backed, so a walk takes a
/// millisecond or two, whereas `tokio::fs` would hand each of its hundreds of
/// reads to the blocking pool and wake two threads apiece.
fn discover_hypridle_processes(root: &Path) -> io::Result<Vec<i32>> {
    let current_uid = fs::metadata(root.join("self"))
        .or_else(|_| fs::metadata(root))?
        .uid();
    let mut pids = Vec::new();
    for entry in fs::read_dir(root)? {
        let entry = entry?;
        let Some(pid) = entry
            .file_name()
            .to_str()
            .and_then(|name| name.parse::<i32>().ok())
        else {
            continue;
        };
        if !is_hypridle(root, pid) {
            continue;
        }
        // Checked last: almost no process gets this far, so almost none is stat'ed.
        if entry
            .metadata()
            .is_ok_and(|metadata| metadata.uid() == current_uid)
        {
            pids.push(pid);
        }
    }
    pids.sort_unstable();
    Ok(pids)
}

fn active(root: &Path) -> io::Result<bool> {
    Ok(!discover_hypridle_processes(root)?.is_empty())
}

/// Remembers the hypridle process last seen, so that confirming it is still
/// there costs one small read instead of a walk over every process.
#[derive(Debug, Default)]
struct Tracker {
    pid: Option<i32>,
    /// A process seen to exit but still listed: a zombie awaiting its parent. It
    /// is not running, and its pidfd would report the same exit forever.
    exited: Option<i32>,
}

impl Tracker {
    fn active(&mut self, root: &Path) -> io::Result<bool> {
        if let Some(pid) = self.pid
            && is_hypridle(root, pid)
        {
            return Ok(true);
        }
        let pids = discover_hypridle_processes(root)?;
        self.exited = self.exited.filter(|exited| pids.contains(exited));
        self.pid = pids.into_iter().find(|pid| Some(*pid) != self.exited);
        Ok(self.pid.is_some())
    }

    /// Wait until the state may have changed: for the tracked process to exit,
    /// or, with none to track, for the next scan to be due.
    async fn changed(&mut self, interval: Duration) {
        match self.pid.map(ProcessExit::watch) {
            Some(Ok(exit)) => {
                exit.wait().await;
                self.exited = self.pid.take();
            }
            Some(Err(error)) => {
                // Already gone is the ordinary case and worth a prompt rescan;
                // anything else (no pidfd support) falls back to polling.
                if error.kind() != io::ErrorKind::NotFound {
                    time::sleep(interval).await;
                }
            }
            None => time::sleep(interval).await,
        }
    }
}

fn is_hypridle(root: &Path, pid: i32) -> bool {
    fs::read_to_string(root.join(pid.to_string()).join("comm"))
        .is_ok_and(|comm| comm.trim_end() == HYPRIDLE_EXECUTABLE)
}

/// A process's exit as an awaitable event: a pidfd becomes readable when the
/// process terminates, so nothing runs until then.
struct ProcessExit(AsyncFd<OwnedFd>);

impl ProcessExit {
    fn watch(pid: i32) -> io::Result<Self> {
        let pid = rustix::process::Pid::from_raw(pid)
            .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput))?;
        let fd = pidfd_open(pid, PidfdFlags::NONBLOCK).map_err(|errno| match errno {
            rustix::io::Errno::SRCH => io::Error::from(io::ErrorKind::NotFound),
            errno => io::Error::from(errno),
        })?;
        AsyncFd::new(fd).map(Self)
    }

    async fn wait(self) {
        // An error here means the reactor is going away; either way stop waiting.
        let _ = self.0.readable().await;
    }
}

/// Lightweight process watcher used only when the Hypridle widget is configured.
pub struct HypridleProducer {
    root: PathBuf,
    interval: Duration,
}

impl HypridleProducer {
    /// Watch the session's process table, scanning at the default cadence.
    pub fn new() -> Self {
        Self::with_interval(DEFAULT_INTERVAL)
    }

    /// Scan for a not-yet-running hypridle every `interval`.
    pub fn with_interval(interval: Duration) -> Self {
        Self {
            root: PathBuf::from(PROC_ROOT),
            interval,
        }
    }
}

impl Default for HypridleProducer {
    fn default() -> Self {
        Self::new()
    }
}

impl Producer for HypridleProducer {
    fn name(&self) -> String {
        "hypridle".to_string()
    }

    fn run(self: Box<Self>, tx: MsgSender) -> ProducerFuture {
        Box::pin(run_producer(self.root, self.interval, tx))
    }
}

async fn run_producer(root: PathBuf, interval: Duration, tx: MsgSender) -> ProducerResult {
    let mut previous = None;
    let mut tracker = Tracker::default();
    loop {
        let next = match tracker.active(&root) {
            Ok(active) => active,
            Err(error) => {
                warn!("hypridle: reading process state failed: {error}");
                time::sleep(interval).await;
                continue;
            }
        };
        if previous != Some(next) {
            previous = Some(next);
            if tx.send(Msg::Hypridle(Hypridle::new(next))).is_err() {
                return Ok(());
            }
        }
        tracker.changed(interval).await;
    }
}

fn signal_stop(pids: &[i32]) -> io::Result<()> {
    for &pid in pids {
        if let Err(error) = kill(Pid::from_raw(pid), Signal::SIGTERM)
            && error != Errno::ESRCH
        {
            return Err(io::Error::from_raw_os_error(error as i32));
        }
    }
    Ok(())
}

async fn wait_until_stopped(root: &Path) -> io::Result<bool> {
    let deadline = time::Instant::now() + STOP_TIMEOUT;
    loop {
        if !active(root)? {
            return Ok(false);
        }
        if time::Instant::now() >= deadline {
            return Ok(true);
        }
        time::sleep(STOP_POLL_INTERVAL).await;
    }
}

async fn set_state(root: &Path, executable: &Path, desired: bool) -> io::Result<bool> {
    let pids = discover_hypridle_processes(root)?;
    match required_action(!pids.is_empty(), desired) {
        HypridleAction::None => Ok(desired),
        HypridleAction::Start => {
            TokioCommand::new(executable)
                .stdin(Stdio::null())
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .spawn()?;
            Ok(true)
        }
        HypridleAction::Stop => {
            signal_stop(&pids)?;
            wait_until_stopped(root).await
        }
    }
}

/// Execute typed Hypridle state requests and immediately report the result.
pub async fn run_commands(mut commands: CommandReceiver, updates: MsgSender) -> ProducerResult {
    while let Some(command) = commands.recv().await {
        let Command::SetHypridle(desired) = command else {
            continue;
        };
        let state = match set_state(
            Path::new(PROC_ROOT),
            Path::new(HYPRIDLE_EXECUTABLE),
            desired,
        )
        .await
        {
            Ok(state) => state,
            Err(error) => {
                warn!("hypridle: setting active={desired} failed: {error}");
                match active(Path::new(PROC_ROOT)) {
                    Ok(state) => state,
                    Err(refresh_error) => {
                        warn!("hypridle: refreshing after command failed: {refresh_error}");
                        continue;
                    }
                }
            }
        };
        if updates.send(Msg::Hypridle(Hypridle::new(state))).is_err() {
            return Ok(());
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::fs;

    use std::time::{Duration, Instant};

    use super::{
        HypridleAction, ProcessExit, Tracker, discover_hypridle_processes, required_action,
    };

    fn process(root: &std::path::Path, pid: i32, name: &str) {
        let path = root.join(pid.to_string());
        fs::create_dir(&path).unwrap();
        fs::write(path.join("comm"), format!("{name}\n")).unwrap();
    }

    #[test]
    fn discovery_matches_exact_same_user_process_names() {
        let root = tempfile::tempdir().unwrap();
        fs::create_dir(root.path().join("self")).unwrap();
        process(root.path(), 42, "hypridle");
        process(root.path(), 43, "hypridle-helper");
        process(root.path(), 44, "Hypridle");

        let pids = discover_hypridle_processes(root.path()).unwrap();
        assert_eq!(pids, vec![42]);
    }

    #[test]
    fn discovery_ignores_non_process_entries_and_missing_comm_files() {
        let root = tempfile::tempdir().unwrap();
        fs::create_dir(root.path().join("self")).unwrap();
        fs::create_dir(root.path().join("51")).unwrap();
        process(root.path(), 52, "hypridle");

        let pids = discover_hypridle_processes(root.path()).unwrap();
        assert_eq!(pids, vec![52]);
    }

    #[test]
    fn desired_state_is_idempotent() {
        assert_eq!(required_action(false, false), HypridleAction::None);
        assert_eq!(required_action(true, true), HypridleAction::None);
        assert_eq!(required_action(false, true), HypridleAction::Start);
        assert_eq!(required_action(true, false), HypridleAction::Stop);
    }

    #[test]
    fn a_tracked_process_is_confirmed_without_rescanning() {
        let root = tempfile::tempdir().unwrap();
        fs::create_dir(root.path().join("self")).unwrap();
        process(root.path(), 42, "hypridle");
        let mut tracker = Tracker::default();
        assert!(tracker.active(root.path()).unwrap());
        assert_eq!(tracker.pid, Some(42));

        // A scan would now fail outright; only the remembered pid is consulted.
        fs::remove_dir(root.path().join("self")).unwrap();
        process(root.path(), 7, "hypridle");
        assert!(tracker.active(root.path()).unwrap());
        assert_eq!(tracker.pid, Some(42));
    }

    #[test]
    fn a_vanished_or_recycled_pid_falls_back_to_a_scan() {
        let root = tempfile::tempdir().unwrap();
        fs::create_dir(root.path().join("self")).unwrap();
        process(root.path(), 42, "hypridle");
        let mut tracker = Tracker::default();
        assert!(tracker.active(root.path()).unwrap());

        // The pid now belongs to something else, and hypridle runs elsewhere.
        fs::write(root.path().join("42/comm"), "bash\n").unwrap();
        process(root.path(), 99, "hypridle");
        assert!(tracker.active(root.path()).unwrap());
        assert_eq!(tracker.pid, Some(99));

        fs::remove_dir_all(root.path().join("99")).unwrap();
        assert!(!tracker.active(root.path()).unwrap());
        assert_eq!(tracker.pid, None);
    }

    #[test]
    fn an_exited_process_still_listed_as_a_zombie_is_not_running() {
        let root = tempfile::tempdir().unwrap();
        fs::create_dir(root.path().join("self")).unwrap();
        process(root.path(), 42, "hypridle");
        let mut tracker = Tracker {
            pid: None,
            exited: Some(42),
        };
        assert!(!tracker.active(root.path()).unwrap());

        // Once reaped it is forgotten, so a later reuse of the pid counts.
        fs::remove_dir_all(root.path().join("42")).unwrap();
        assert!(!tracker.active(root.path()).unwrap());
        process(root.path(), 42, "hypridle");
        assert!(tracker.active(root.path()).unwrap());
    }

    #[test]
    fn a_process_exit_ends_the_wait_without_polling() {
        let runtime = tokio::runtime::Runtime::new().unwrap();
        let mut child = std::process::Command::new("sleep")
            .arg("60")
            .spawn()
            .unwrap();
        let pid = child.id() as i32;

        runtime.block_on(async {
            let exit = ProcessExit::watch(pid).unwrap();
            let waiting = tokio::spawn(exit.wait());
            tokio::time::sleep(Duration::from_millis(50)).await;
            assert!(!waiting.is_finished(), "still running");

            let killed = Instant::now();
            child.kill().unwrap();
            tokio::time::timeout(Duration::from_secs(5), waiting)
                .await
                .expect("exit observed")
                .unwrap();
            assert!(killed.elapsed() < Duration::from_secs(1));
        });
        child.wait().unwrap();
    }

    #[test]
    fn watching_a_process_that_is_already_gone_reports_not_found() {
        let runtime = tokio::runtime::Runtime::new().unwrap();
        let mut child = std::process::Command::new("true").spawn().unwrap();
        let pid = child.id() as i32;
        child.wait().unwrap();
        let error = runtime
            .block_on(async { ProcessExit::watch(pid).map(|_| ()) })
            .unwrap_err();
        assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
    }
}