hyprshell_exec_lib/
run.rs1use core_lib::{Warn, TERMINALS};
2use std::os::unix::prelude::CommandExt;
3use std::path::Path;
4use std::process::{Command, Stdio};
5use std::{env, io, thread};
6use tracing::{debug, error, info, trace};
7
8pub fn run_program(
9 run: &str,
10 path: Option<Box<Path>>,
11 terminal: bool,
12 default_terminal: &Option<Box<str>>,
13) {
14 debug!("Running: {run}");
15 if terminal {
16 if let Some(term) = default_terminal {
17 let command = format!("{term} -e {run}");
18 run_command(&command, &path).warn("Failed to run command");
19 } else {
20 let path_env = env::var_os("PATH").unwrap_or_default();
21 info!("No default terminal found, searching common terminals in PATH. (Set default_terminal in config to avoid this search)");
22 trace!("PATH: {}", path_env.to_string_lossy());
23 let paths: Vec<_> = env::split_paths(&path_env).collect();
24 let mut found_terminal = false;
25 for term in TERMINALS {
26 if paths.iter().any(|p| p.join(term).exists()) {
27 let command = format!("{term} -e {run}");
28 if run_command(&command, &path).is_ok() {
29 trace!("Found and launched terminal: {term}");
30 found_terminal = true;
31 break;
32 }
33 }
34 }
35 if !found_terminal {
36 error!("Failed to find a terminal to run the command");
37 }
38 }
39 } else {
40 run_command(run, &path).warn("Failed to run command");
41 }
42}
43
44fn get_command(command: &str) -> Command {
45 if env::var_os("INVOCATION_ID").is_some() {
47 let mut cmd = Command::new("systemd-run");
48 cmd.args(["--user", "--scope", "--collect", "sh", "-c", command]);
49 cmd
50 } else {
51 let mut cmd = Command::new("sh");
52 cmd.args(["-c", command]);
53 cmd
54 }
55}
56
57fn run_command(run: &str, path: &Option<Box<Path>>) -> io::Result<()> {
58 trace!("Original command: {:?}", run);
59 let mut cmd = get_command(run);
60 cmd.process_group(0);
61 if let Some(path) = path {
62 cmd.current_dir(path.as_ref());
63 }
64
65 debug!("Running command: {:?}", cmd);
66 let _out = cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).spawn()?;
67
68 thread::spawn(move || {
69 let output = _out.wait_with_output();
70 if env::var_os("HYPRSHELL_SHOW_OUTPUT").is_some() {
71 if let Ok(output) = output {
72 if !output.stdout.is_empty() || !output.stderr.is_empty() {
73 debug!("Output: {:?}", output);
74 }
75 }
76 }
77 });
78 Ok(())
79}