forked from h4llow3En/mac-notification-sys
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnotification.rs
More file actions
390 lines (356 loc) · 12.9 KB
/
notification.rs
File metadata and controls
390 lines (356 loc) · 12.9 KB
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
//! Custom structs and enums for mac-notification-sys.
use objc2_foundation::{NSDictionary, NSString};
use std::default::Default;
use std::ops::Deref;
use objc2::rc::Retained;
use crate::error::{NotificationError, NotificationResult};
use crate::{ensure, ensure_application_set, sys};
/// Possible actions accessible through the main button of the notification
#[derive(Clone, Debug)]
pub enum MainButton<'a> {
/// Display a single action with the given name
///
/// # Example:
///
/// ```no_run
/// # use mac_notification_sys::*;
/// let _ = MainButton::SingleAction("Action name");
/// ```
SingleAction(&'a str),
/// Display a dropdown with the given title, with a list of actions with given names
///
/// # Example:
///
/// ```no_run
/// # use mac_notification_sys::*;
/// let _ = MainButton::DropdownActions("Dropdown name", &["Action 1", "Action 2"]);
/// ```
DropdownActions(&'a str, &'a [&'a str]),
/// Display a text input field with the given placeholder
///
/// # Example:
///
/// ```no_run
/// # use mac_notification_sys::*;
/// let _ = MainButton::Response("Enter some text...");
/// ```
Response(&'a str),
}
/// Helper to determine whether you want to play the default sound or custom one
#[derive(Clone)]
pub enum Sound {
/// notification plays the sound [`NSUserNotificationDefaultSoundName`](https://developer.apple.com/documentation/foundation/nsusernotification/nsusernotificationdefaultsoundname)
Default,
/// notification plays your custom sound
Custom(String),
}
impl<I> From<I> for Sound
where
I: ToString,
{
fn from(value: I) -> Self {
Sound::Custom(value.to_string())
}
}
/// Options to further customize the notification
#[derive(Clone, Default)]
pub struct Notification<'a> {
pub(crate) title: &'a str,
pub(crate) subtitle: Option<&'a str>,
pub(crate) message: &'a str,
pub(crate) main_button: Option<MainButton<'a>>,
pub(crate) close_button: Option<&'a str>,
pub(crate) app_icon: Option<&'a str>,
pub(crate) content_image: Option<&'a str>,
pub(crate) delivery_date: Option<f64>,
pub(crate) sound: Option<Sound>,
pub(crate) asynchronous: Option<bool>,
pub(crate) wait_for_click: Option<bool>,
}
impl<'a> Notification<'a> {
/// Create a Notification to further customize the notification
pub fn new() -> Self {
Default::default()
}
/// Set `title` field
pub fn title(&mut self, title: &'a str) -> &mut Self {
self.title = title;
self
}
/// Set `subtitle` field
pub fn subtitle(&mut self, subtitle: &'a str) -> &mut Self {
self.subtitle = Some(subtitle);
self
}
/// Set `subtitle` field
pub fn maybe_subtitle(&mut self, subtitle: Option<&'a str>) -> &mut Self {
self.subtitle = subtitle;
self
}
/// Set `message` field
pub fn message(&mut self, message: &'a str) -> &mut Self {
self.message = message;
self
}
/// Allow actions through a main button
///
/// # Example:
///
/// ```no_run
/// # use mac_notification_sys::*;
/// let _ = Notification::new().main_button(MainButton::SingleAction("Main button"));
/// ```
pub fn main_button(&mut self, main_button: MainButton<'a>) -> &mut Self {
self.main_button = Some(main_button);
self
}
/// Display a close button with the given name
///
/// # Example:
///
/// ```no_run
/// # use mac_notification_sys::*;
/// let _ = Notification::new().close_button("Close");
/// ```
pub fn close_button(&mut self, close_button: &'a str) -> &mut Self {
self.close_button = Some(close_button);
self
}
/// Display an icon on the left side of the notification
///
/// NOTE: The icon of the app associated to the bundle will be displayed next to the notification title
///
/// # Example:
///
/// ```no_run
/// # use mac_notification_sys::*;
/// let _ = Notification::new().app_icon("/path/to/icon.icns");
/// ```
pub fn app_icon(&mut self, app_icon: &'a str) -> &mut Self {
self.app_icon = Some(app_icon);
self
}
/// Display an image on the right side of the notification
///
/// # Example:
///
/// ```no_run
/// # use mac_notification_sys::*;
/// let _ = Notification::new().content_image("/path/to/image.png");
/// ```
pub fn content_image(&mut self, content_image: &'a str) -> &mut Self {
self.content_image = Some(content_image);
self
}
/// Schedule the notification to be delivered at a later time
///
/// # Example:
///
/// ```no_run
/// # use mac_notification_sys::*;
/// let stamp = time::OffsetDateTime::now_utc().unix_timestamp() as f64 + 5.;
/// let _ = Notification::new().delivery_date(stamp);
/// ```
pub fn delivery_date(&mut self, delivery_date: f64) -> &mut Self {
self.delivery_date = Some(delivery_date);
self
}
/// Play the default sound `"NSUserNotificationDefaultSoundName"` system sound when the notification is delivered.
/// # Example:
///
/// ```no_run
/// # use mac_notification_sys::*;
/// let _ = Notification::new().default_sound();
/// ```
pub fn default_sound(&mut self) -> &mut Self {
self.sound = Some(Sound::Default);
self
}
/// Play a system sound when the notification is delivered. Use [`Sound::Default`] to play the default sound.
/// # Example:
///
/// ```no_run
/// # use mac_notification_sys::*;
/// let _ = Notification::new().sound("Blow");
/// ```
pub fn sound<S>(&mut self, sound: S) -> &mut Self
where
S: Into<Sound>,
{
self.sound = Some(sound.into());
self
}
/// Play a system sound when the notification is delivered. Use [`Sound::Default`] to play the default sound.
///
/// # Example:
///
/// ```no_run
/// # use mac_notification_sys::*;
/// let _ = Notification::new().sound("Blow");
/// ```
pub fn maybe_sound<S>(&mut self, sound: Option<S>) -> &mut Self
where
S: Into<Sound>,
{
self.sound = sound.map(Into::into);
self
}
/// Deliver the notification asynchronously (without waiting for an interaction).
///
/// Note: Setting this to true is equivalent to a fire-and-forget.
///
/// # Example:
///
/// ```no_run
/// # use mac_notification_sys::*;
/// let _ = Notification::new().asynchronous(true);
/// ```
pub fn asynchronous(&mut self, asynchronous: bool) -> &mut Self {
self.asynchronous = Some(asynchronous);
self
}
/// Allow waiting a response for notification click.
///
/// # Example:
///
/// ```no_run
/// # use mac_notification_sys::*;
/// let _ = Notification::new().wait_for_click(true);
/// ```
pub fn wait_for_click(&mut self, click: bool) -> &mut Self {
self.wait_for_click = Some(click);
self
}
/// Convert the Notification to an Objective C NSDictionary
pub(crate) fn to_dictionary(&self) -> Retained<NSDictionary<NSString, NSString>> {
// TODO: If possible, find a way to simplify this so I don't have to manually convert struct to NSDictionary
let keys = &[
&*NSString::from_str("mainButtonLabel"),
&*NSString::from_str("actions"),
&*NSString::from_str("closeButtonLabel"),
&*NSString::from_str("appIcon"),
&*NSString::from_str("contentImage"),
&*NSString::from_str("response"),
&*NSString::from_str("deliveryDate"),
&*NSString::from_str("asynchronous"),
&*NSString::from_str("sound"),
&*NSString::from_str("click"),
];
let (main_button_label, actions, is_response): (&str, &[&str], bool) =
match &self.main_button {
Some(main_button) => match main_button {
MainButton::SingleAction(main_button_label) => (main_button_label, &[], false),
MainButton::DropdownActions(main_button_label, actions) => {
(main_button_label, actions, false)
}
MainButton::Response(response) => (response, &[], true),
},
None => ("", &[], false),
};
let sound = match self.sound {
Some(Sound::Custom(ref name)) => name.as_str(),
Some(Sound::Default) => "NSUserNotificationDefaultSoundName",
None => "",
};
let vals = vec![
NSString::from_str(main_button_label),
// TODO: Find a way to support NSArray as a NSDictionary Value rather than JUST NSString so I don't have to convert array to string and back
NSString::from_str(&actions.join(",")),
NSString::from_str(self.close_button.unwrap_or("")),
NSString::from_str(self.app_icon.unwrap_or("")),
NSString::from_str(self.content_image.unwrap_or("")),
// TODO: Same as above, if NSDictionary could support multiple types, this could be a boolean
NSString::from_str(if is_response { "yes" } else { "" }),
NSString::from_str(&match self.delivery_date {
Some(delivery_date) => delivery_date.to_string(),
_ => String::new(),
}),
// TODO: Same as above, if NSDictionary could support multiple types, this could be a boolean
NSString::from_str(match self.asynchronous {
Some(true) => "yes",
_ => "no",
}),
// TODO: Same as above, if NSDictionary could support multiple types, this could be a boolean
NSString::from_str(match self.wait_for_click {
Some(true) => "yes",
_ => "no",
}),
NSString::from_str(sound),
];
NSDictionary::from_retained_objects(keys, &vals)
}
/// Delivers a new notification
///
/// Returns a `NotificationError` if a notification could not be delivered
///
pub fn send(&self) -> NotificationResult<NotificationResponse> {
if let Some(delivery_date) = self.delivery_date {
ensure!(
delivery_date >= time::OffsetDateTime::now_utc().unix_timestamp() as f64,
NotificationError::ScheduleInThePast
);
};
let options = self.to_dictionary();
ensure_application_set()?;
let dictionary_response = unsafe {
sys::sendNotification(
NSString::from_str(self.title).deref(),
NSString::from_str(self.subtitle.unwrap_or("")).deref(),
NSString::from_str(self.message).deref(),
options.deref(),
)
};
ensure!(
dictionary_response
.objectForKey(NSString::from_str("error").deref())
.is_none(),
NotificationError::UnableToDeliver
);
let response = NotificationResponse::from_dictionary(dictionary_response);
Ok(response)
}
}
/// Response from the Notification
#[derive(Debug)]
pub enum NotificationResponse {
/// No interaction has occured
None,
/// User clicked on an action button with the given name
ActionButton(String),
/// User clicked on the close button with the given name
CloseButton(String),
/// User clicked the notification directly
Click,
/// User submitted text to the input text field
Reply(String),
}
impl NotificationResponse {
/// Create a NotificationResponse from the given Objective C NSDictionary
pub(crate) fn from_dictionary(dictionary: Retained<NSDictionary<NSString, NSString>>) -> Self {
let activation_type = dictionary
.objectForKey(NSString::from_str("activationType").deref())
.map(|str| str.to_string());
match activation_type.as_deref() {
Some("actionClicked") => NotificationResponse::ActionButton(
match dictionary.objectForKey(NSString::from_str("activationValue").deref()) {
Some(str) => str.to_string(),
None => String::from(""),
},
),
Some("closeClicked") => NotificationResponse::CloseButton(
match dictionary.objectForKey(NSString::from_str("activationValue").deref()) {
Some(str) => str.to_string(),
None => String::from(""),
},
),
Some("replied") => NotificationResponse::Reply(
match dictionary.objectForKey(NSString::from_str("activationValue").deref()) {
Some(str) => str.to_string(),
None => String::from(""),
},
),
Some("contentsClicked") => NotificationResponse::Click,
_ => NotificationResponse::None,
}
}
}