use std::io::Read;
#[cfg(unix)]
use std::os::unix::process::CommandExt;
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
use std::sync::mpsc::Sender;
use std::sync::{Arc, Mutex};
use std::thread;
use crate::lsp::log_file;
const BINARY: &str = "termux-dialog";
const SPEECH_WIDGET: &str = "speech";
const DIALOG_TITLE: &str = "croft voice input";
const JSON_TEXT: &str = "text";
const JSON_ERROR: &str = "error";
const ERR_NO_MIC_PERMISSION: &str = "ERROR_INSUFFICIENT_PERMISSIONS";
const TERMUX_INSTALL_PKG: &str = "pkg install -y termux-api";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Availability {
Ready,
NeedsTermux,
NeedsApi,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VoiceMsg {
Transcript(String),
Empty,
Failed(String),
}
static LISTENING: AtomicBool = AtomicBool::new(false);
pub fn is_listening() -> bool {
LISTENING.load(Ordering::Relaxed)
}
fn set_listening(on: bool) {
LISTENING.store(on, Ordering::Relaxed);
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InstallState {
Idle = 0,
Running = 1,
Done = 2,
Failed = 3,
}
static INSTALL_STATE: AtomicU8 = AtomicU8::new(0);
fn set_install_state(state: InstallState) {
INSTALL_STATE.store(state as u8, Ordering::Relaxed);
}
pub fn install_state() -> InstallState {
match INSTALL_STATE.load(Ordering::Relaxed) {
1 => InstallState::Running,
2 => InstallState::Done,
3 => InstallState::Failed,
_ => InstallState::Idle,
}
}
fn binary_present() -> bool {
if let Some(prefix) = std::env::var_os("PREFIX")
&& PathBuf::from(prefix).join("bin").join(BINARY).exists()
{
return true;
}
Command::new("sh")
.arg("-c")
.arg(format!("command -v {BINARY}"))
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.map(|s| s.success())
.unwrap_or(false)
}
pub fn availability() -> Availability {
if !crate::iterm2_inline::detect_termux() {
Availability::NeedsTermux
} else if binary_present() {
Availability::Ready
} else {
Availability::NeedsApi
}
}
pub fn ensure_api_installed_in_background() {
if matches!(install_state(), InstallState::Running) {
return;
}
set_install_state(InstallState::Running);
thread::spawn(|| {
match Command::new("sh")
.arg("-c")
.arg(TERMUX_INSTALL_PKG)
.output()
{
Ok(out) if out.status.success() => {
log_file::log(&format!("voice: `{TERMUX_INSTALL_PKG}` succeeded"))
}
Ok(out) => log_file::log(&format!(
"voice: `{TERMUX_INSTALL_PKG}` exited {}: {}",
out.status,
String::from_utf8_lossy(&out.stderr).trim()
)),
Err(e) => log_file::log(&format!(
"voice: `{TERMUX_INSTALL_PKG}` could not start: {e}"
)),
}
if binary_present() {
set_install_state(InstallState::Done);
} else {
set_install_state(InstallState::Failed);
}
});
}
pub struct VoiceHandle {
child: Arc<Mutex<Option<Child>>>,
}
impl VoiceHandle {
pub fn stop(&self) {
if let Ok(mut guard) = self.child.lock()
&& let Some(child) = guard.as_mut()
{
#[cfg(unix)]
unsafe {
libc::kill(-(child.id() as i32), libc::SIGKILL);
}
let _ = child.kill();
}
}
}
pub fn start(tx: Sender<VoiceMsg>) -> VoiceHandle {
set_listening(true);
let mut cmd = Command::new(BINARY);
cmd.arg(SPEECH_WIDGET)
.arg("-t")
.arg(DIALOG_TITLE)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
#[cfg(unix)]
unsafe {
cmd.pre_exec(|| {
libc::setsid();
Ok(())
});
}
let mut child = match cmd.spawn() {
Ok(c) => c,
Err(e) => {
set_listening(false);
log_file::log(&format!("voice: could not start `{BINARY}`: {e}"));
let _ = tx.send(VoiceMsg::Failed(format!("voice input unavailable: {e}")));
return VoiceHandle {
child: Arc::new(Mutex::new(None)),
};
}
};
let mut stdout = child.stdout.take();
let mut stderr = child.stderr.take();
let shared: Arc<Mutex<Option<Child>>> = Arc::new(Mutex::new(Some(child)));
let reader_shared = Arc::clone(&shared);
thread::spawn(move || {
let mut json = String::new();
if let Some(stdout) = stdout.as_mut() {
let _ = stdout.read_to_string(&mut json);
}
let mut err = String::new();
if let Some(stderr) = stderr.as_mut() {
let _ = stderr.read_to_string(&mut err);
}
let status = if let Ok(mut guard) = reader_shared.lock()
&& let Some(child) = guard.as_mut()
{
child.wait().ok()
} else {
None
};
set_listening(false);
let parsed = serde_json::from_str::<serde_json::Value>(json.trim()).ok();
let field = |key: &str| -> String {
parsed
.as_ref()
.and_then(|v| v.get(key))
.and_then(|v| v.as_str())
.unwrap_or("")
.trim()
.to_string()
};
let text = field(JSON_TEXT);
let rec_err = field(JSON_ERROR);
log_file::log(&format!(
"voice: dialog ended status={status:?} text_chars={} error={rec_err:?} stderr={:?}",
text.chars().count(),
err.trim()
));
let msg = if !text.is_empty() {
VoiceMsg::Transcript(text)
} else if rec_err == ERR_NO_MIC_PERMISSION {
VoiceMsg::Failed(String::from(
"Grant Termux:API microphone permission, then tap the mic again",
))
} else if !rec_err.is_empty() {
VoiceMsg::Failed(format!("Voice input error: {rec_err}"))
} else {
VoiceMsg::Empty
};
let _ = tx.send(msg);
});
VoiceHandle { child: shared }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn install_state_round_trips_through_the_atomic() {
set_install_state(InstallState::Running);
assert_eq!(install_state(), InstallState::Running);
set_install_state(InstallState::Done);
assert_eq!(install_state(), InstallState::Done);
set_install_state(InstallState::Idle);
assert_eq!(install_state(), InstallState::Idle);
}
#[test]
fn listening_flag_round_trips() {
set_listening(true);
assert!(is_listening());
set_listening(false);
assert!(!is_listening());
}
}