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
use crate::{Dialog, Error, MessageAlert, MessageConfirm, MessageType, Result};
use osascript::JavaScript;
use serde::de::DeserializeOwned;
use serde::Serialize;

impl Dialog for MessageAlert<'_> {
    type Output = ();

    fn show(self) -> Result<Self::Output> {
        display_alert(DisplayAlertParams {
            title: self.title,
            text: self.text,
            icon: &get_dialog_icon(self.typ),
            buttons: &["OK"],
        })
    }
}

impl Dialog for MessageConfirm<'_> {
    type Output = bool;

    fn show(self) -> Result<Self::Output> {
        let button = display_alert(DisplayAlertParams {
            title: self.title,
            text: self.text,
            icon: &get_dialog_icon(self.typ),
            buttons: &["No", "Yes"],
        })?;

        match button {
            Some(t) => Ok(String::eq(&t, "Yes")),
            None => Ok(false),
        }
    }
}

#[derive(Serialize)]
struct DisplayAlertParams<'a> {
    title: &'a str,
    text: &'a str,
    icon: &'a str,
    buttons: &'a [&'a str],
}

fn get_dialog_icon(typ: MessageType) -> String {
    match typ {
        MessageType::Info => "note".into(),
        MessageType::Warning => "caution".into(),
        MessageType::Error => "stop".into(),
    }
}

fn display_alert<T: DeserializeOwned>(params: DisplayAlertParams) -> Result<T> {
    let script = JavaScript::new(
        // language=js
        r"
        const app = Application.currentApplication();
        app.includeStandardAdditions = true;
        
        const options = {
            buttons: $params.buttons,
            withTitle: $params.title,
            withIcon: $params.icon,
        };
        
        try {
            return app.displayDialog($params.message, options).buttonReturned;
        } catch (e) {
            return null;
        }
        ",
    );

    script.execute_with_params(params).map_err(Error::from)
}