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
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
//! An incomplete wrapper over the WinRT toast api
//!
//! Tested in windows 10. Untested in Windows 8 and 8.1, might work.
//!
//! Todo:
//!
//! * Add support for Adaptive Content
//! * Add support for Actions
//!
//! Known Issues:
//!
//! * Will not work for Windows 7.
//! * Will not build when targeting the 32-bit gnu toolchain (i686-pc-windows-gnu).

/// for xml schema details check out:
///
/// * https://docs.microsoft.com/en-us/uwp/schemas/tiles/toastschema/root-elements
/// * https://docs.microsoft.com/en-us/windows/uwp/controls-and-patterns/tiles-and-notifications-toast-xml-schema
/// * https://docs.microsoft.com/en-us/windows/uwp/controls-and-patterns/tiles-and-notifications-adaptive-interactive-toasts
/// * https://msdn.microsoft.com/library/14a07fce-d631-4bad-ab99-305b703713e6#Sending_toast_notifications_from_desktop_apps

/// for Windows 7 and older support look into Shell_NotifyIcon
/// https://msdn.microsoft.com/en-us/library/windows/desktop/ee330740(v=vs.85).aspx
/// https://softwareengineering.stackexchange.com/questions/222339/using-the-system-tray-notification-area-app-in-windows-7


extern crate winrt;
extern crate xml;

use winrt::{FastHString, RuntimeContext};
use winrt::windows::data::xml::dom::IXmlDocumentIO;
use winrt::windows::ui::notifications::{ToastNotification, ToastNotificationManager,
                                        ToastTemplateType_ToastText01};


use std::fmt;
use std::path::Path;

use xml::escape::escape_str_attribute;

pub struct Toast {
    duration: String,
    title: String,
    line1: String,
    line2: String,
    images: String,
    audio: String,
    app_id: String,
}

pub enum Duration {
    /// 7 seconds
    Short,

    /// 25 seconds
    Long,
}

#[derive(Debug)]
pub enum Sound {
    Default,
    IM,
    Mail,
    Reminder,
    SMS,
    /// Play the loopable sound only once
    Single(LoopableSound),
    /// Loop the loopable sound for the entire duration of the toast
    Loop(LoopableSound),
}

/// Sounds suitable for Looping
#[derive(Debug)]
#[allow(dead_code)]
pub enum LoopableSound {
    Alarm,
    Alarm2,
    Alarm3,
    Alarm4,
    Alarm5,
    Alarm6,
    Alarm7,
    Alarm8,
    Alarm9,
    Alarm10,
    Call,
    Call2,
    Call3,
    Call4,
    Call5,
    Call6,
    Call7,
    Call8,
    Call9,
    Call10,
}

#[allow(dead_code)]
pub enum IconCrop {
    Square,
    Circular,
}

#[doc(hidden)]
impl fmt::Display for Sound {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

#[doc(hidden)]
impl fmt::Display for LoopableSound {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

impl Toast {
    /// Constructor for the toast builder
    ///
    /// app_id is used in the toast to inform the user where it came from.
    #[allow(dead_code)]
    pub fn new(app_id: &str) -> Toast {
        Toast {
            duration: String::new(),
            title: format!("<text>{}</text>", escape_str_attribute(app_id)),
            line1: String::new(),
            line2: String::new(),
            images: String::new(),
            audio: String::new(),
            app_id: app_id.to_string(),
        }
    }

    /// Sets the title of the toast.
    ///
    /// Will be white.
    /// Supports Unicode ✓
    pub fn title(mut self, content: &str) -> Toast {
        self.title = format!("<text>{}</text>", escape_str_attribute(content));
        self
    }

    /// Add/Sets the first line of text below title.
    ///
    /// Will be grey.
    /// Supports Unicode ✓
    pub fn text1(mut self, content: &str) -> Toast {
        self.line1 = format!("<text>{}</text>", escape_str_attribute(content));
        self
    }

    /// Add/Sets the second line of text below title.
    ///
    /// Will be grey.
    /// Supports Unicode ✓
    pub fn text2(mut self, content: &str) -> Toast {
        self.line2 = format!("<text>{}</text>", escape_str_attribute(content));
        self
    }

    /// Set the length of time to show the toast
    pub fn duration(mut self, duration: Duration) -> Toast {
        self.duration = match duration {
            Duration::Long => "duration=\"long\"",
            Duration::Short => "duration=\"short\"",
        }.to_owned();
        self
    }

    /// Set the icon shown in the upper left of the toast
    ///
    /// The default is supposed to be determined by your app id.
    /// In practice it will be blank.
    pub fn icon(mut self, source: &Path, crop: IconCrop, alt_text: &str) -> Toast {
        let crop_type_attr = match crop {
            IconCrop::Square => "".to_string(),
            IconCrop::Circular => "hint-crop=\"circle\"".to_string(),
        };

        self.images = format!(
            "{}<image placement=\"appLogoOverride\" {} src=\"file:///{}\" alt=\"{}\" />",
            self.images,
            crop_type_attr,
            escape_str_attribute(&source.display().to_string()),
            escape_str_attribute(alt_text)
        );
        self
    }

    /// Add/Set a Hero image for the toast.
    ///
    /// This will be above the toast text and the icon.
    pub fn hero(mut self, source: &Path, alt_text: &str) -> Toast {
        self.images = format!(
            "{}<image placement=\"Hero\" src=\"file:///{}\" alt=\"{}\" />",
            self.images,
            escape_str_attribute(&source.display().to_string()),
            escape_str_attribute(alt_text)
        );
        self
    }

    /// Add an image to the toast
    ///
    /// May be done many times.
    /// Will appear below text.
    pub fn image(mut self, source: &Path, alt_text: &str) -> Toast {
        self.images = format!(
            "{}<image src=\"file:///{}\" alt=\"{}\" />",
            self.images,
            escape_str_attribute(&source.display().to_string()),
            escape_str_attribute(alt_text)
        );
        self
    }

    /// Set the sound for the toast or silence it
    ///
    /// Default is [Sound::IM](enum.Sound.html)
    pub fn sound(mut self, src: Option<Sound>) -> Toast {
        self.audio = match src {
            None => "<audio silent=\"true\" />".to_owned(),
            Some(Sound::Default) => "".to_owned(),
            Some(Sound::Loop(sound)) => format!(
                "<audio loop=\"true\" src=\"ms-winsoundevent:Notification.Looping.{}\" />",
                sound
            ),
            Some(Sound::Single(sound)) => format!(
                "<audio src=\"ms-winsoundevent:Notification.Looping.{}\" />",
                sound
            ),
            Some(sound) => format!("<audio src=\"ms-winsoundevent:Notification.{}\" />", sound),
        };

        self
    }

    /// Display the toast on the screen
    pub fn show(&self) -> Result<(), winrt::Error> {
        let _rt = RuntimeContext::init();

        //using this to get an instance of XmlDocument
        let toast_xml =
            ToastNotificationManager::get_template_content(ToastTemplateType_ToastText01).unwrap();

        //XmlDocument implements IXmlDocumentIO so this is safe
        let toast_xml_as_xml_io = toast_xml.query_interface::<IXmlDocumentIO>().unwrap();

        unsafe {
            (*toast_xml_as_xml_io).load_xml(&FastHString::new(&format!(
                "<toast {}>
                        <visual>
                            <binding template=\"ToastGeneric\">
                            {}
                            {}{}{}
                            </binding>
                        </visual>
                        {}
                    </toast>",
                self.duration,
                self.images,
                self.title,
                self.line1,
                self.line2,
                self.audio,
            )))?
        };

        // Create the toast and attach event listeners
        let toast_template = ToastNotification::create_toast_notification(&*toast_xml)?;

        // Show the toast.
        unsafe {
            let toast_notifier = ToastNotificationManager::create_toast_notifier_with_id(
                &FastHString::new(&self.app_id),
            )?;
            toast_notifier.show(&*toast_template)
        }
    }
}


#[cfg(test)]
mod tests {
    use ::*;
    use std::path::Path;

    #[test]
    fn simple_toast() {
        let toast = Toast::new("winrt-simple-notify");
        toast
            .hero(
                &Path::new(env!("CARGO_MANIFEST_DIR")).join("resources/test/flower.jpeg"),
                "flower",
            )
            .icon(
                &Path::new(env!("CARGO_MANIFEST_DIR")).join("resources/test/chick.jpeg"),
                IconCrop::Circular,
                "chicken",
            )
            .title("title")
            .text1("line1")
            .text2("line2")
            .duration(Duration::Short)
            //.sound(Some(Sound::Loop(LoopableSound::Call)))
            //.sound(Some(Sound::SMS))
            .sound(None)
            .show()
            // silently consume errors
            .expect("notification failed");
    }
}