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
use arci::Speaker;
use log::error;
use std::{io, process::Command};

/// 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()
    }

    /// Similar to `Speaker::speak`, but returns an error when the command failed.
    pub fn try_speak(&self, message: &str) -> io::Result<()> {
        run_local_command(message)
    }
}

impl Speaker for LocalCommand {
    fn speak(&self, message: &str) {
        if let Err(e) = self.try_speak(message) {
            // TODO: Speaker trait seems to assume that speak method will always succeed.
            error!("{}", e);
        }
    }
}

#[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 `{}` with message {:?}", CMD_NAME, 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),
        ))
    }
}