tablero 0.3.2

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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
//! The command channel: render loop → producer runtime.
//!
//! The counterpart to the [producer bridge](crate::producer). Producers push
//! [`Msg`](crate::widget::Msg)s *into* the synchronous loop; commands flow
//! the other way — the loop turns a click into a [`Command`] and hands it to
//! async code that can execute it (the Hyprland command socket).
//!
//! ```text
//!   calloop loop (sync)                       Tokio runtime
//!   ┌────────────────────┐  CommandSender.send  ┌──────────────────┐
//!   │ pointer ─▶ on_click │ ───────────────────▶ │ command executor │
//!   └────────────────────┘   (cross-thread)     └──────────────────┘
//! ```
//!
//! The channel is an unbounded Tokio mpsc so the synchronous send never blocks
//! the render loop. The executor end is spawned on the producer bridge; see
//! [`hyprland::run_commands`](crate::hyprland::run_commands).

use std::env;
use std::error::Error;
use std::fmt;
use std::path::{Path, PathBuf};
use std::process::Stdio;

use log::{debug, info, warn};
use tokio::process::Command as TokioCommand;
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};

use crate::producer::ProducerResult;
use crate::widget::{Command, LaunchSpec};

/// The receiving end of the command channel, drained by the executor task.
pub type CommandReceiver = UnboundedReceiver<Command>;

/// The sending half held by the render loop: how synchronous input reaches the
/// async executor. Cloneable, and sending never blocks (the channel is
/// unbounded).
#[derive(Clone)]
pub struct CommandSender {
    inner: UnboundedSender<Command>,
}

impl CommandSender {
    /// Queue `command` for the executor.
    ///
    /// Fails only once the executor (and its runtime) has gone away and dropped
    /// the receiver; a caller seeing [`Closed`] should stop trying, since nothing
    /// will execute further commands.
    pub fn send(&self, command: Command) -> Result<(), Closed> {
        self.inner.send(command).map_err(|_| Closed)
    }
}

impl fmt::Debug for CommandSender {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CommandSender").finish_non_exhaustive()
    }
}

/// Build a command channel: the [`CommandSender`] for the loop and the
/// [`CommandReceiver`] for the executor task.
pub fn command_channel() -> (CommandSender, CommandReceiver) {
    let (inner, rx) = unbounded_channel();
    (CommandSender { inner }, rx)
}

/// The executor has been dropped; no further commands will be run.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Closed;

impl fmt::Display for Closed {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("command executor closed; channel receiver was dropped")
    }
}

impl Error for Closed {}

/// Expand a leading `~` in `path` to the user's home directory.
///
/// Only a single leading `~` (optionally followed by `/` or end-of-string) is
/// expanded; a `~` mid-path or a `~user` form is taken verbatim. The expansion
/// is a simple textual substitution — the caller has not checked the
/// resulting path's existence, and `tokio::process::Command::spawn` will
/// surface a clean error if the file is missing or not executable. Returning
/// the original `PathBuf` unchanged when `$HOME` is unset keeps the executor
/// deterministic in headless environments where the user still wants a
/// literal path to be tried as-is.
pub fn expand_tilde(path: &Path) -> PathBuf {
    let Some(s) = path.to_str() else {
        return path.to_path_buf();
    };
    let Some(rest) = s.strip_prefix('~') else {
        return path.to_path_buf();
    };
    if !rest.is_empty() && !rest.starts_with('/') {
        // A `~user` form is left verbatim — only `~` and `~/...` expand.
        return path.to_path_buf();
    }
    let Some(home) = std::env::var_os("HOME") else {
        return path.to_path_buf();
    };
    let mut expanded = PathBuf::from(home);
    if !rest.is_empty() {
        expanded.push(rest.trim_start_matches('/'));
    }
    expanded
}

/// Whether `path` is a single path component with no directory separators.
///
/// Bare names (`pavucontrol`) are looked up in `$PATH`. Paths with a slash
/// (`./script`, `bin/foo`) or after tilde expansion stay as-is.
pub fn is_bare_name(path: &Path) -> bool {
    path.components().count() == 1 && path.file_name().is_some_and(|name| Path::new(name) == path)
}

/// Search `$PATH` for an executable named `name` (a single file name).
pub fn find_in_path(name: &Path) -> Option<PathBuf> {
    let name = name.as_os_str();
    let path_var = env::var_os("PATH")?;
    for dir in env::split_paths(&path_var) {
        let candidate = dir.join(name);
        if is_executable_file(&candidate) {
            return Some(candidate);
        }
    }
    None
}

fn is_executable_file(path: &Path) -> bool {
    let Ok(meta) = std::fs::metadata(path) else {
        return false;
    };
    if !meta.is_file() {
        return false;
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        meta.permissions().mode() & 0o111 != 0
    }
    #[cfg(not(unix))]
    {
        true
    }
}

/// Expand `~`, then resolve a bare program name via `$PATH` when possible.
///
/// Absolute and multi-component relative paths are only tilde-expanded.
/// Unresolved bare names are returned unchanged so the caller can report a
/// clear "not found in PATH" error.
pub fn resolve_program(program: &Path) -> PathBuf {
    let expanded = expand_tilde(program);
    if expanded.is_absolute() || !is_bare_name(&expanded) {
        return expanded;
    }
    find_in_path(&expanded).unwrap_or(expanded)
}

/// True when `path` contains a `..` component (path traversal).
pub fn path_has_parent_component(path: &Path) -> bool {
    path.components()
        .any(|c| matches!(c, std::path::Component::ParentDir))
}

/// Soft preflight for on-click program paths before spawn.
///
/// Rejects `..` components, then for absolute paths checks existence and the
/// execute bit. Bare names that were not resolved should be rejected by the
/// caller before this runs.
pub fn preflight_on_click(path: &Path) -> Result<(), String> {
    if path_has_parent_component(path) {
        return Err(format!(
            "{} must not contain '..' path components",
            path.display()
        ));
    }
    if !path.is_absolute() {
        // Relative multi-component paths still go through spawn; the kernel
        // reports the failure. Absolute-only preflight keeps bare-name PATH
        // resolution as the dedicated failure path above.
        return Ok(());
    }
    match std::fs::metadata(path) {
        Ok(meta) => {
            if meta.is_dir() {
                return Err(format!("{} is a directory", path.display()));
            }
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                // Any execute bit is enough; the kernel still enforces the real
                // check at exec time for the running uid.
                if meta.permissions().mode() & 0o111 == 0 {
                    return Err(format!("{} is not executable (chmod +x)", path.display()));
                }
            }
            Ok(())
        }
        Err(error) => Err(format!("{}: {error}", path.display())),
    }
}

/// Format a finished child for logs: exit code or signal termination.
pub fn format_exit_status(status: std::process::ExitStatus) -> String {
    if let Some(code) = status.code() {
        format!("exit status {code}")
    } else {
        format!("terminated by signal ({status})")
    }
}

/// Spawn one on-click program: expand `~`, resolve bare names via `$PATH`,
/// preflight absolute paths, pass args, detach stdio, and wait for exit on a
/// background task so failures surface in logs.
///
/// Returns `Ok(())` when the process was started (the waiter owns the rest).
/// Returns `Err` with a user-facing reason when spawn never starts.
pub async fn spawn_run_program(spec: LaunchSpec) -> Result<(), String> {
    let program = resolve_program(spec.program());
    if is_bare_name(spec.program()) && !program.is_absolute() {
        return Err(format!(
            "{:?} not found in PATH (use an absolute path or fix PATH)",
            spec.program()
        ));
    }
    preflight_on_click(&program)?;

    let display = if spec.args().is_empty() {
        program.display().to_string()
    } else {
        // Log the resolved program with the original args for diagnosis.
        let mut out = program.display().to_string();
        for arg in spec.args() {
            out.push(' ');
            out.push_str(arg);
        }
        out
    };

    // Desktop-launcher hygiene: no stdin (scripts never hang on a closed tty),
    // discarded stdout (GUI noise), inherited stderr so short-lived script
    // errors land next to tablero's own logs when the bar is journaled or run
    // from a terminal. kill_on_drop is off so dropping a waiter handle never
    // kills a long-lived mixer or calendar.
    let mut command = TokioCommand::new(&program);
    command
        .args(spec.args())
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::inherit())
        .kill_on_drop(false);

    let mut child = command
        .spawn()
        .map_err(|error| format!("failed to spawn {display:?}: {error}"))?;

    info!("spawned on-click program: {display}");

    // Reap the child and log non-success exits. GUI apps that stay up for the
    // whole session only emit a debug line when they finally quit; scripts that
    // die immediately with a non-zero status are the flaky-click case we care
    // about and land at warn.
    tokio::spawn(async move {
        match child.wait().await {
            Ok(status) if status.success() => {
                debug!("on-click program {display:?} finished successfully");
            }
            Ok(status) => {
                warn!(
                    "on-click program {display:?} failed: {}",
                    format_exit_status(status)
                );
            }
            Err(error) => {
                warn!("on-click program {display:?}: wait failed: {error}");
            }
        }
    });

    Ok(())
}

/// Drain a [`CommandReceiver`] for as long as the render loop sends.
///
/// Each [`Command::RunProgram`] is spawned directly via
/// `tokio::process::Command` — no shell, no argument expansion beyond the
/// leading-`~` home expansion and bare-name `PATH` lookup. Other command
/// variants are silently ignored: those have their own executors, and every
/// [`CommandSender`] is fanned out to every executor, so the routing is by
/// `match` arm here. A spawn failure (missing file, non-executable, …) is
/// logged at warn level and does not end the loop — a bad click should never
/// take the bar down.
pub async fn run_commands(mut rx: CommandReceiver) -> ProducerResult {
    while let Some(command) = rx.recv().await {
        if let Command::RunProgram(spec) = command
            && let Err(reason) = spawn_run_program(spec).await
        {
            warn!("on-click: {reason}");
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn test_runtime() -> tokio::runtime::Runtime {
        // Multi-thread so `tokio::spawn` waiters inside `spawn_run_program` are
        // actually polled after the executor returns.
        tokio::runtime::Builder::new_multi_thread()
            .worker_threads(1)
            .enable_all()
            .build()
            .unwrap()
    }

    #[test]
    fn send_delivers_a_command_to_the_receiver() {
        let (tx, mut rx) = command_channel();
        tx.send(Command::SwitchWorkspace(3))
            .expect("receiver alive");
        assert_eq!(rx.try_recv().ok(), Some(Command::SwitchWorkspace(3)));
    }

    #[test]
    fn send_after_receiver_dropped_reports_closed() {
        let (tx, rx) = command_channel();
        drop(rx);
        assert_eq!(tx.send(Command::SwitchWorkspace(1)), Err(Closed));
    }

    #[test]
    fn expand_tilde_replaces_a_leading_tilde_with_home() {
        let home = std::env::var_os("HOME")
            .map(PathBuf::from)
            .expect("HOME is set in this test environment");
        let mut expected = home.clone();
        expected.push("scripts/bluetooth.sh");
        assert_eq!(
            expand_tilde(std::path::Path::new("~/scripts/bluetooth.sh")),
            expected
        );
    }

    #[test]
    fn expand_tilde_with_a_bare_tilde_replaces_with_home() {
        let home = std::env::var_os("HOME")
            .map(PathBuf::from)
            .expect("HOME is set in this test environment");
        assert_eq!(expand_tilde(std::path::Path::new("~")), home);
    }

    #[test]
    fn expand_tilde_leaves_an_absolute_path_unchanged() {
        assert_eq!(
            expand_tilde(std::path::Path::new("/usr/bin/blueman-manager")),
            PathBuf::from("/usr/bin/blueman-manager")
        );
    }

    #[test]
    fn expand_tilde_leaves_a_mid_path_tilde_unchanged() {
        // Only a leading `~` expands. A `~user` form (tilde followed by
        // something other than `/`) is taken verbatim, and a tilde inside the
        // path is left alone.
        assert_eq!(
            expand_tilde(std::path::Path::new("/tmp/~snapshot")),
            PathBuf::from("/tmp/~snapshot")
        );
        assert_eq!(
            expand_tilde(std::path::Path::new("~user/path")),
            PathBuf::from("~user/path")
        );
    }

    #[test]
    fn preflight_allows_bare_path_names() {
        // Bare names are rejected before preflight after PATH resolution fails;
        // preflight itself still skips non-absolute paths.
        assert!(preflight_on_click(Path::new("pavucontrol")).is_ok());
        assert!(preflight_on_click(Path::new("gnome-calendar")).is_ok());
    }

    #[test]
    fn is_bare_name_detects_single_components() {
        assert!(is_bare_name(Path::new("pavucontrol")));
        assert!(!is_bare_name(Path::new("/usr/bin/pavucontrol")));
        assert!(!is_bare_name(Path::new("bin/pavucontrol")));
        assert!(!is_bare_name(Path::new("./pavucontrol")));
    }

    #[test]
    fn find_in_path_locates_true() {
        // `true` is on PATH on every Linux/CI host we care about.
        let found = find_in_path(Path::new("true")).expect("true in PATH");
        assert!(found.is_absolute());
        assert!(found.ends_with("true") || found.file_name() == Some("true".as_ref()));
    }

    #[test]
    fn resolve_program_leaves_absolute_paths() {
        assert_eq!(
            resolve_program(Path::new("/usr/bin/pavucontrol")),
            PathBuf::from("/usr/bin/pavucontrol")
        );
    }

    #[test]
    fn preflight_rejects_missing_absolute_paths() {
        let err = preflight_on_click(Path::new("/this/path/definitely/does/not/exist"))
            .expect_err("missing file");
        assert!(err.contains("does/not/exist"), "{err}");
    }

    #[test]
    fn preflight_rejects_parent_dir_components() {
        let err = preflight_on_click(Path::new("/tmp/../etc/passwd")).expect_err("parent");
        assert!(err.contains(".."), "{err}");
        let err = preflight_on_click(Path::new("../bin/evil")).expect_err("relative parent");
        assert!(err.contains(".."), "{err}");
    }

    #[test]
    fn preflight_rejects_non_executable_scripts() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().expect("tempdir");
        let script = dir.path().join("no-exec.sh");
        std::fs::write(&script, "#!/bin/sh\n").expect("write");
        let mut perms = std::fs::metadata(&script).expect("stat").permissions();
        perms.set_mode(0o644);
        std::fs::set_permissions(&script, perms).expect("chmod");

        let err = preflight_on_click(&script).expect_err("not executable");
        assert!(err.contains("not executable"), "{err}");
    }

    #[test]
    fn format_exit_status_reports_codes() {
        // We cannot synthesize a signal status portably; codes are enough for
        // the log path unit test.
        let status = std::process::Command::new("true").status().expect("true");
        assert_eq!(format_exit_status(status), "exit status 0");

        let status = std::process::Command::new("false").status().expect("false");
        assert_eq!(format_exit_status(status), "exit status 1");
    }

    #[test]
    fn run_commands_ignores_non_run_program_commands() {
        // Commands with dedicated executors are filtered; this one only acts on
        // RunProgram.
        let rt = test_runtime();
        let (tx, rx) = command_channel();
        tx.send(Command::SwitchWorkspace(1)).unwrap();
        tx.send(Command::ActivateTrayItem {
            key: "foo".to_string(),
            x: 0,
            y: 0,
        })
        .unwrap();
        drop(tx);
        rt.block_on(run_commands(rx)).unwrap();
        // No assertion needed: if `run_commands` panicked or returned an
        // error, the `unwrap` above would fire. The fact that this test
        // passes means the executor drained both messages without trying
        // to spawn a process.
    }

    #[test]
    fn run_commands_spawns_a_run_program_path_directly() {
        // A real on-click flow: write a tiny script to a temp file, mark it
        // executable, fire `RunProgram(<path>)` through the executor, and
        // verify the script ran by waiting for its marker file to appear.
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().expect("tempdir");
        let marker = dir.path().join("clicked.marker");
        let script = dir.path().join("on-click.sh");
        std::fs::write(&script, format!("#!/bin/sh\ntouch {}\n", marker.display()))
            .expect("write script");
        let mut perms = std::fs::metadata(&script).expect("stat").permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&script, perms).expect("chmod");

        let rt = test_runtime();
        let (tx, rx) = command_channel();
        tx.send(Command::RunProgram(LaunchSpec::program_only(
            script.clone(),
        )))
        .unwrap();
        drop(tx);
        rt.block_on(run_commands(rx)).unwrap();

        // The script writes the marker unconditionally (the executor spawns
        // the path with no arguments). Wait briefly for the child to land;
        // a missing marker means the executor never spawned the process.
        let mut waited = std::time::Duration::ZERO;
        let step = std::time::Duration::from_millis(20);
        while !marker.exists() && waited < std::time::Duration::from_secs(2) {
            std::thread::sleep(step);
            waited += step;
        }
        assert!(
            marker.exists(),
            "executor spawned the script and the marker file appeared"
        );
    }

    #[test]
    fn run_commands_swallows_a_spawn_failure_without_ending_the_loop() {
        // A bogus path must not crash the executor: the warn is logged, the
        // loop continues, and a subsequent valid RunProgram is still
        // processed.
        let rt = test_runtime();
        let (tx, rx) = command_channel();
        tx.send(Command::RunProgram(LaunchSpec::program_only(
            PathBuf::from("/this/path/definitely/does/not/exist"),
        )))
        .unwrap();
        tx.send(Command::SwitchWorkspace(2)).unwrap();
        drop(tx);
        rt.block_on(run_commands(rx)).unwrap();
    }

    #[test]
    fn spawn_run_program_fails_preflight_for_missing_absolute_path() {
        let rt = test_runtime();
        let err = rt
            .block_on(spawn_run_program(LaunchSpec::program_only(PathBuf::from(
                "/this/path/definitely/does/not/exist",
            ))))
            .expect_err("preflight");
        assert!(err.contains("does/not/exist"), "{err}");
    }

    #[test]
    fn spawn_run_program_rejects_unknown_bare_names() {
        let rt = test_runtime();
        let err = rt
            .block_on(spawn_run_program(LaunchSpec::program_only(
                "tablero-definitely-not-on-path-xyz",
            )))
            .expect_err("missing bare name");
        assert!(err.contains("not found in PATH"), "{err}");
    }

    #[test]
    fn spawn_run_program_passes_arguments() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().expect("tempdir");
        let marker = dir.path().join("arg.marker");
        let script = dir.path().join("with-arg.sh");
        // argv[1] is written to the marker so we prove args reach the child.
        std::fs::write(
            &script,
            format!("#!/bin/sh\nprintf '%s' \"$1\" > {}\n", marker.display()),
        )
        .expect("write");
        let mut perms = std::fs::metadata(&script).expect("stat").permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&script, perms).expect("chmod");

        let rt = test_runtime();
        let spec = LaunchSpec::with_args(script, vec!["hello-arg".into()]);
        rt.block_on(spawn_run_program(spec)).expect("spawn");

        let mut waited = std::time::Duration::ZERO;
        let step = std::time::Duration::from_millis(20);
        while !marker.exists() && waited < std::time::Duration::from_secs(2) {
            std::thread::sleep(step);
            waited += step;
        }
        assert_eq!(std::fs::read_to_string(&marker).expect("read"), "hello-arg");
    }

    #[test]
    fn spawn_run_program_reaps_a_failing_script() {
        // A script that exits non-zero must still be waitable (no hang) and
        // report Ok from spawn — the failure is the child's exit, logged by
        // the background waiter.
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().expect("tempdir");
        let script = dir.path().join("fail.sh");
        std::fs::write(&script, "#!/bin/sh\nexit 42\n").expect("write");
        let mut perms = std::fs::metadata(&script).expect("stat").permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&script, perms).expect("chmod");

        let rt = test_runtime();
        rt.block_on(spawn_run_program(LaunchSpec::program_only(script)))
            .expect("spawn starts");
        // Give the waiter task time to reap the child.
        std::thread::sleep(std::time::Duration::from_millis(100));
    }

    #[test]
    fn spawn_run_program_expands_tilde_before_preflight() {
        use std::os::unix::fs::PermissionsExt;

        let home = std::env::var_os("HOME").expect("HOME");
        let dir = tempfile::tempdir_in(&home).expect("tempdir in home");
        // Build a ~/… relative path from the tempdir under $HOME.
        let rel = dir
            .path()
            .strip_prefix(&home)
            .expect("tempdir under HOME")
            .join("tilde.sh");
        let tilde_path = PathBuf::from(format!("~/{}", rel.display()));
        let absolute = expand_tilde(&tilde_path);
        std::fs::write(&absolute, "#!/bin/sh\nexit 0\n").expect("write");
        let mut perms = std::fs::metadata(&absolute).expect("stat").permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&absolute, perms).expect("chmod");

        let rt = test_runtime();
        rt.block_on(spawn_run_program(LaunchSpec::program_only(tilde_path)))
            .expect("tilde path resolves and spawns");
        std::thread::sleep(std::time::Duration::from_millis(100));
    }

    #[test]
    fn launch_spec_parse_splits_whitespace() {
        let spec = LaunchSpec::parse("gtk-launch org.gnome.Calendar").unwrap();
        assert_eq!(spec.program(), Path::new("gtk-launch"));
        assert_eq!(spec.args(), &["org.gnome.Calendar".to_string()]);
    }
}