Skip to main content

rust_voice_assistant/execution/
system.rs

1//! System subprocess execution with timeout constraints.
2
3use crate::error::{Error, Result};
4use std::process::Stdio;
5use std::time::Duration;
6use tokio::io::AsyncReadExt;
7use tokio::process::Command;
8use tokio::time::timeout;
9
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub struct SystemCommandResult {
12    pub stdout: String,
13    pub stderr: String,
14    pub exit_code: Option<i32>,
15    pub timed_out: bool,
16}
17
18pub struct SystemExecutor;
19
20impl SystemExecutor {
21    pub async fn run_command(
22        cmd: &str,
23        args: &[&str],
24        duration: Duration,
25    ) -> Result<SystemCommandResult> {
26        let mut child = Command::new(cmd)
27            .args(args)
28            .stdout(Stdio::piped())
29            .stderr(Stdio::piped())
30            .spawn()
31            .map_err(Error::Io)?;
32
33        let mut stdout_pipe = child.stdout.take().expect("stdout is piped");
34        let mut stderr_pipe = child.stderr.take().expect("stderr is piped");
35        let stdout_task = tokio::spawn(async move {
36            let mut buf = Vec::new();
37            let _ = stdout_pipe.read_to_end(&mut buf).await;
38            buf
39        });
40        let stderr_task = tokio::spawn(async move {
41            let mut buf = Vec::new();
42            let _ = stderr_pipe.read_to_end(&mut buf).await;
43            buf
44        });
45
46        match timeout(duration, child.wait()).await {
47            Ok(Ok(status)) => {
48                let stdout = stdout_task.await.unwrap_or_default();
49                let stderr = stderr_task.await.unwrap_or_default();
50                Ok(SystemCommandResult {
51                    stdout: String::from_utf8_lossy(&stdout).trim().to_string(),
52                    stderr: String::from_utf8_lossy(&stderr).trim().to_string(),
53                    exit_code: status.code(),
54                    timed_out: false,
55                })
56            }
57            Ok(Err(e)) => {
58                stdout_task.abort();
59                stderr_task.abort();
60                Err(Error::Io(e))
61            }
62            Err(_) => {
63                let _ = child.kill().await;
64                let _ = stdout_task.await;
65                let _ = stderr_task.await;
66                Ok(SystemCommandResult {
67                    stdout: String::new(),
68                    stderr: "Process timed out".to_string(),
69                    exit_code: None,
70                    timed_out: true,
71                })
72            }
73        }
74    }
75
76    async fn pipewire_volume(args: &[&str]) -> Result<()> {
77        let res = Self::run_command("wpctl", args, Duration::from_secs(5)).await;
78        match res {
79            Ok(r) if !r.timed_out && r.exit_code == Some(0) => Ok(()),
80            _ => {
81                // Fallback for systems without WirePlumber (PulseAudio only).
82                let mut pactl_args = vec!["set-sink-volume", "@DEFAULT_SINK@"];
83                pactl_args.extend_from_slice(&args[2..]);
84                if args[0] == "set-mute" {
85                    pactl_args = vec!["set-sink-mute", "@DEFAULT_SINK@", args[2]];
86                }
87                let res = Self::run_command("pactl", &pactl_args, Duration::from_secs(5)).await?;
88                if res.timed_out || res.exit_code != Some(0) {
89                    return Err(Error::Audio(format!(
90                        "volume control failed (wpctl/pactl): {}",
91                        res.stderr
92                    )));
93                }
94                Ok(())
95            }
96        }
97    }
98
99    /// Raises the default output volume by `percent` points via wpctl/pactl.
100    pub async fn volume_up(percent: u32) -> Result<()> {
101        Self::pipewire_volume(&[
102            "set-volume",
103            "@DEFAULT_AUDIO_SINK@",
104            &format!("{}%+", percent),
105        ])
106        .await
107    }
108
109    /// Lowers the default output volume by `percent` points via wpctl/pactl.
110    pub async fn volume_down(percent: u32) -> Result<()> {
111        Self::pipewire_volume(&[
112            "set-volume",
113            "@DEFAULT_AUDIO_SINK@",
114            &format!("{}%-", percent),
115        ])
116        .await
117    }
118
119    /// Toggles mute on the default output sink.
120    pub async fn toggle_mute() -> Result<()> {
121        Self::pipewire_volume(&["set-mute", "@DEFAULT_AUDIO_SINK@", "toggle"]).await
122    }
123
124    /// Sets mute explicitly — "unmute" must not toggle a live sink off.
125    /// Returns the resulting audible state (`true` = now muted).
126    pub async fn set_mute(muted: bool) -> Result<bool> {
127        if Self::is_muted().await.unwrap_or(false) == muted {
128            return Ok(muted);
129        }
130        Self::pipewire_volume(&[
131            "set-mute",
132            "@DEFAULT_AUDIO_SINK@",
133            if muted { "1" } else { "0" },
134        ])
135        .await?;
136        Ok(muted)
137    }
138
139    /// Sets the default output volume to an absolute percentage.
140    pub async fn volume_set(percent: u32) -> Result<()> {
141        Self::pipewire_volume(&[
142            "set-volume",
143            "@DEFAULT_AUDIO_SINK@",
144            &format!("{}%", percent.min(150)),
145        ])
146        .await
147    }
148
149    /// Current mute state of the default sink (wpctl or pactl).
150    pub async fn is_muted() -> Result<bool> {
151        let res = Self::run_command(
152            "wpctl",
153            &["get-volume", "@DEFAULT_AUDIO_SINK@"],
154            Duration::from_secs(5),
155        )
156        .await?;
157        if !res.timed_out && res.exit_code == Some(0) {
158            return Ok(res.stdout.contains("[MUTED]"));
159        }
160        let res = Self::run_command(
161            "pactl",
162            &["get-sink-mute", "@DEFAULT_SINK@"],
163            Duration::from_secs(5),
164        )
165        .await?;
166        Ok(res.stdout.to_lowercase().contains("yes"))
167    }
168
169    /// Launches a detached application process. A reaper task awaits the
170    /// child so exited apps don't linger as zombies under the daemon.
171    pub async fn launch(program: &str) -> Result<()> {
172        let mut child = Command::new(program)
173            .stdin(Stdio::null())
174            .stdout(Stdio::null())
175            .stderr(Stdio::null())
176            .spawn()
177            .map_err(|e| Error::Audio(format!("failed to launch '{}': {}", program, e)))?;
178        tokio::spawn(async move {
179            let _ = child.wait().await;
180        });
181        Ok(())
182    }
183}