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
#![doc = include_str!("../README.md")]
#![warn(missing_docs)]

use std::{io, process::Command};

use arci::{Speaker, WaitFuture};

/// A [`Speaker`] implementation using a local command.
///
/// Currently, this uses the following command:
///
/// - On macOS, use `say` command.
/// - On Windows, call [SAPI] via PowerShell.
/// - On others, use `espeak` command.
///
/// **Disclaimer**: These commands might change over time.
///
/// [SAPI]: https://en.wikipedia.org/wiki/Microsoft_Speech_API
#[derive(Debug, Default)]
#[non_exhaustive]
pub struct LocalCommand {}

impl LocalCommand {
    /// Creates a new `LocalCommand`.
    pub fn new() -> Self {
        Self::default()
    }
}

impl Speaker for LocalCommand {
    fn speak(&self, message: &str) -> Result<WaitFuture, arci::Error> {
        let (sender, receiver) = tokio::sync::oneshot::channel();
        let message = message.to_string();

        std::thread::spawn(move || {
            let res = run_local_command(&message).map_err(|e| arci::Error::Other(e.into()));
            let _ = sender.send(res);
        });

        Ok(WaitFuture::new(async move {
            receiver.await.map_err(|e| arci::Error::Other(e.into()))?
        }))
    }
}

#[cfg(not(windows))]
fn run_local_command(message: &str) -> io::Result<()> {
    #[cfg(not(target_os = "macos"))]
    const CMD_NAME: &str = "espeak";
    #[cfg(target_os = "macos")]
    const CMD_NAME: &str = "say";

    let mut cmd = Command::new(CMD_NAME);
    let status = cmd.arg(message).status()?;

    if status.success() {
        Ok(())
    } else {
        Err(io::Error::new(
            io::ErrorKind::Other,
            format!("failed to run `{CMD_NAME}` with message {message:?}"),
        ))
    }
}

#[cfg(windows)]
fn run_local_command(message: &str) -> io::Result<()> {
    // TODO: Ideally, it would be more efficient to use SAPI directly via winapi or something.
    // https://stackoverflow.com/questions/1040655/ms-speech-from-command-line
    let cmd = format!("PowerShell -Command \"Add-Type –AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak('{message}');\"");
    let status = Command::new("powershell").arg(cmd).status()?;

    if status.success() {
        Ok(())
    } else {
        Err(io::Error::new(
            io::ErrorKind::Other,
            format!("failed to run `powershell` with message {message:?}"),
        ))
    }
}

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

    #[test]
    fn test_local_command() {
        let local_command = LocalCommand::new();

        let wait = local_command.speak("message");

        assert!(wait.is_ok());
    }
}