@decaf-ts/for-os 0.0.0-stage → 0.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/LICENSE.md +21 -0
  2. package/README.md +380 -2
  3. package/lib/cjs/errors.cjs +73 -0
  4. package/lib/cjs/errors.cjs.map +1 -0
  5. package/lib/cjs/index.cjs +46 -0
  6. package/lib/cjs/index.cjs.map +1 -0
  7. package/lib/cjs/native/icons.cjs +123 -0
  8. package/lib/cjs/native/icons.cjs.map +1 -0
  9. package/lib/cjs/native/loader.cjs +123 -0
  10. package/lib/cjs/native/loader.cjs.map +1 -0
  11. package/lib/cjs/native/types.cjs +4 -0
  12. package/lib/cjs/native/types.cjs.map +1 -0
  13. package/lib/cjs/notifications/NotificationCenter.cjs +328 -0
  14. package/lib/cjs/notifications/NotificationCenter.cjs.map +1 -0
  15. package/lib/cjs/tray/TrayIcon.cjs +367 -0
  16. package/lib/cjs/tray/TrayIcon.cjs.map +1 -0
  17. package/lib/cjs/tray/assets.cjs +31 -0
  18. package/lib/cjs/tray/assets.cjs.map +1 -0
  19. package/lib/esm/errors.js +65 -0
  20. package/lib/esm/errors.js.map +1 -0
  21. package/lib/esm/index.js +28 -0
  22. package/lib/esm/index.js.map +1 -0
  23. package/lib/esm/native/icons.js +117 -0
  24. package/lib/esm/native/icons.js.map +1 -0
  25. package/lib/esm/native/loader.js +116 -0
  26. package/lib/esm/native/loader.js.map +1 -0
  27. package/lib/esm/native/types.js +8 -0
  28. package/lib/esm/native/types.js.map +1 -0
  29. package/lib/esm/notifications/NotificationCenter.js +322 -0
  30. package/lib/esm/notifications/NotificationCenter.js.map +1 -0
  31. package/lib/esm/tray/TrayIcon.js +362 -0
  32. package/lib/esm/tray/TrayIcon.js.map +1 -0
  33. package/lib/esm/tray/assets.js +26 -0
  34. package/lib/esm/tray/assets.js.map +1 -0
  35. package/lib/types/errors.d.cts +56 -0
  36. package/lib/types/errors.d.mts +56 -0
  37. package/lib/types/index.d.cts +27 -0
  38. package/lib/types/index.d.mts +27 -0
  39. package/lib/types/native/icons.d.cts +71 -0
  40. package/lib/types/native/icons.d.mts +71 -0
  41. package/lib/types/native/loader.d.cts +37 -0
  42. package/lib/types/native/loader.d.mts +37 -0
  43. package/lib/types/native/types.d.cts +104 -0
  44. package/lib/types/native/types.d.mts +104 -0
  45. package/lib/types/notifications/NotificationCenter.d.cts +163 -0
  46. package/lib/types/notifications/NotificationCenter.d.mts +163 -0
  47. package/lib/types/tray/TrayIcon.d.cts +174 -0
  48. package/lib/types/tray/TrayIcon.d.mts +174 -0
  49. package/lib/types/tray/assets.d.cts +25 -0
  50. package/lib/types/tray/assets.d.mts +25 -0
  51. package/native/tray-icon-node/Cargo.lock +1511 -0
  52. package/native/tray-icon-node/Cargo.toml +45 -0
  53. package/native/tray-icon-node/Cross.toml +10 -0
  54. package/native/tray-icon-node/LICENSE +21 -0
  55. package/native/tray-icon-node/UPSTREAM-README.md +281 -0
  56. package/native/tray-icon-node/UPSTREAM.md +213 -0
  57. package/native/tray-icon-node/build-manifest.json +16 -0
  58. package/native/tray-icon-node/build.rs +5 -0
  59. package/native/tray-icon-node/index.d.ts +368 -0
  60. package/native/tray-icon-node/index.js +609 -0
  61. package/native/tray-icon-node/package.json +55 -0
  62. package/native/tray-icon-node/rustfmt.toml +31 -0
  63. package/native/tray-icon-node/source-manifest.json +30 -0
  64. package/native/tray-icon-node/src/common.rs +101 -0
  65. package/native/tray-icon-node/src/icon.rs +255 -0
  66. package/native/tray-icon-node/src/lib.rs +449 -0
  67. package/native/tray-icon-node/src/menu.rs +849 -0
  68. package/native/tray-icon-node/src/tray.rs +251 -0
  69. package/native/tray-icon-node/tray-icon-node.linux-x64-gnu.node +0 -0
  70. package/package.json +131 -4
  71. package/scripts/for-os-build.mjs +60 -0
  72. package/scripts/for-os-init.mjs +327 -0
  73. package/scripts/for-os-install.mjs +47 -0
  74. package/scripts/for-os-integration.mjs +137 -0
  75. package/scripts/for-os-integrity.mjs +51 -0
  76. package/scripts/for-os-package.mjs +49 -0
  77. package/scripts/lib/native.mjs +591 -0
@@ -0,0 +1,449 @@
1
+ use napi::bindgen_prelude::*;
2
+ use napi_derive::napi;
3
+ use std::collections::VecDeque;
4
+ use std::process::{Command, Stdio};
5
+ use std::sync::Mutex;
6
+
7
+ static NOTIFICATION_ACTIONS: Mutex<VecDeque<String>> = Mutex::new(VecDeque::new());
8
+
9
+ pub mod common;
10
+ pub mod icon;
11
+ pub mod menu;
12
+ pub mod tray;
13
+
14
+ pub use common::*;
15
+ pub use icon::*;
16
+ pub use menu::*;
17
+ pub use tray::*;
18
+
19
+ /// Initializes the native tray subsystem.
20
+ ///
21
+ /// On Linux, this initializes GTK. On macOS and Windows, this is a no-op
22
+ /// as those platforms handle initialization automatically.
23
+ ///
24
+ /// # Errors
25
+ ///
26
+ /// Returns an error if GTK initialization fails (Linux only).
27
+ #[napi]
28
+ pub fn initialize() -> Result<()> {
29
+ #[cfg(target_os = "linux")]
30
+ {
31
+ if gtk::init().is_err() {
32
+ return Err(Error::from_reason("Failed to initialize GTK"));
33
+ }
34
+ }
35
+ Ok(())
36
+ }
37
+
38
+ /// Processes pending UI events for the tray subsystem.
39
+ ///
40
+ /// On Linux, this iterates pending GTK events.
41
+ /// On Windows, this processes the thread's message queue via `PeekMessageW`.
42
+ /// On macOS, this is a no-op as `NSApplication` handles its own event loop.
43
+ ///
44
+ /// Call this in your event loop to ensure tray interactions are processed.
45
+ #[napi]
46
+ pub fn update() {
47
+ #[cfg(target_os = "linux")]
48
+ {
49
+ while gtk::events_pending() {
50
+ gtk::main_iteration_do(false);
51
+ }
52
+ }
53
+
54
+ #[cfg(target_os = "windows")]
55
+ {
56
+ use windows_sys::Win32::UI::WindowsAndMessaging::{
57
+ DispatchMessageW, PeekMessageW, TranslateMessage, MSG, PM_REMOVE,
58
+ };
59
+ unsafe {
60
+ let mut msg: MSG = std::mem::zeroed();
61
+ while PeekMessageW(&mut msg, 0, 0, 0, PM_REMOVE) != 0 {
62
+ TranslateMessage(&msg);
63
+ DispatchMessageW(&msg);
64
+ }
65
+ }
66
+ }
67
+
68
+ #[cfg(target_os = "macos")]
69
+ {
70
+ // No-op: macOS uses NSApplication's built-in run loop.
71
+ }
72
+ }
73
+
74
+ /// One action button attached to a desktop notification.
75
+ ///
76
+ /// `id` is the value returned by [`poll_notification_actions`] when the user
77
+ /// activates the button; `label` is the text rendered by the notification
78
+ /// service.
79
+ #[napi(object)]
80
+ #[derive(Debug, Clone)]
81
+ pub struct NotificationAction {
82
+ pub id: String,
83
+ pub label: String,
84
+ }
85
+
86
+ #[derive(Debug, Clone)]
87
+ struct NotificationRequest {
88
+ title: String,
89
+ body: String,
90
+ actions: Vec<NotificationAction>,
91
+ expire_ms: Option<u32>,
92
+ }
93
+
94
+ impl NotificationRequest {
95
+ fn new(title: String, body: String, actions: Vec<NotificationAction>) -> Self {
96
+ Self {
97
+ title,
98
+ body,
99
+ actions,
100
+ expire_ms: None,
101
+ }
102
+ }
103
+
104
+ fn with_timeout(mut self, timeout_ms: Option<u32>) -> Self {
105
+ self.expire_ms = timeout_ms;
106
+ self
107
+ }
108
+ }
109
+
110
+ /// Ensures a body click (`default` action) maps to the first caller action.
111
+ ///
112
+ /// The freedesktop notification protocol reserves `default` for activating the
113
+ /// notification body. Adding it lets the user click the popup itself while the
114
+ /// bridge still reports a stable caller-defined action id.
115
+ fn with_default_action(mut request: NotificationRequest) -> NotificationRequest {
116
+ if let Some(first) = request.actions.first() {
117
+ if !request.actions.iter().any(|action| action.id == "default") {
118
+ let label = first.label.clone();
119
+ request.actions.push(NotificationAction {
120
+ id: "default".to_owned(),
121
+ label,
122
+ });
123
+ }
124
+ }
125
+ request
126
+ }
127
+
128
+ /// Builds the `notify-send` argument vector for a notification.
129
+ ///
130
+ /// Kept pure so the argument contract (timer and action buttons) can be
131
+ /// verified by the Rust test target without a desktop notification service.
132
+ #[cfg(any(target_os = "linux", test))]
133
+ fn notification_command_args(
134
+ request: &NotificationRequest,
135
+ wait_for_action: bool,
136
+ ) -> Vec<String> {
137
+ let mut args = vec!["--app-name=decaf-ts for-os".to_owned()];
138
+ if let Some(expire_ms) = request.expire_ms {
139
+ args.push(format!("--expire-time={expire_ms}"));
140
+ }
141
+ if wait_for_action {
142
+ args.push("--wait".to_owned());
143
+ }
144
+ for action in &request.actions {
145
+ args.push(format!("--action={}={}", action.id, action.label));
146
+ }
147
+ args.push("--".to_owned());
148
+ args.push(request.title.clone());
149
+ args.push(request.body.clone());
150
+ args
151
+ }
152
+
153
+ /// Normalizes the notification-service action id and stores it for polling.
154
+ ///
155
+ /// `default` is the reserved id the service reports when the notification
156
+ /// body itself (rather than a named button) is activated.
157
+ fn push_notification_action(raw_action: &str, default_alias: Option<&str>) {
158
+ let trimmed = raw_action.trim();
159
+ if trimmed.is_empty() {
160
+ return;
161
+ }
162
+ let normalized = if trimmed == "default" {
163
+ default_alias.unwrap_or("default")
164
+ } else {
165
+ trimmed
166
+ };
167
+ if let Ok(mut actions) = NOTIFICATION_ACTIONS.lock() {
168
+ actions.push_back(normalized.to_owned());
169
+ }
170
+ }
171
+
172
+ /// Sends a best-effort operating-system desktop notification.
173
+ ///
174
+ /// `timeout_ms` controls how long the notification remains visible where the
175
+ /// host notification service supports an expiry (Linux `notify-send`, Windows
176
+ /// balloon tips). macOS uses the system default dismissal policy.
177
+ #[napi]
178
+ pub fn show_notification(title: String, body: String, timeout_ms: Option<u32>) -> Result<()> {
179
+ let request = NotificationRequest::new(title, body, Vec::new()).with_timeout(timeout_ms);
180
+ send_notification(request)
181
+ }
182
+
183
+ /// Sends a desktop notification with caller-defined action buttons.
184
+ ///
185
+ /// Action buttons are delivered on Linux through `notify-send --wait`; the
186
+ /// activated button id is returned by [`poll_notification_actions`]. macOS and
187
+ /// Windows show a normal notification without buttons (the system notification
188
+ /// APIs used by this crate do not expose per-notification actions), so map
189
+ /// those platforms to a tray menu action instead.
190
+ #[napi]
191
+ pub fn show_notification_with_actions(
192
+ title: String,
193
+ body: String,
194
+ actions: Vec<NotificationAction>,
195
+ timeout_ms: Option<u32>,
196
+ ) -> Result<()> {
197
+ let default_alias = actions.first().map(|action| action.id.clone());
198
+ let request = with_default_action(
199
+ NotificationRequest::new(title, body, actions).with_timeout(timeout_ms),
200
+ );
201
+ send_notification_with_alias(request, default_alias)
202
+ }
203
+
204
+ /// Sends an appointment notification with Accept and See actions where the
205
+ /// desktop notification service supports actions (currently Linux notify-send).
206
+ /// Other platforms receive a normal notification and use the tray menu actions.
207
+ #[napi]
208
+ pub fn show_appointment_notification(
209
+ title: String,
210
+ body: String,
211
+ timeout_ms: Option<u32>,
212
+ ) -> Result<()> {
213
+ let request = NotificationRequest::new(
214
+ title,
215
+ body,
216
+ vec![
217
+ NotificationAction {
218
+ id: "default".to_owned(),
219
+ label: "See appointment".to_owned(),
220
+ },
221
+ NotificationAction {
222
+ id: "accept".to_owned(),
223
+ label: "Accept appointment".to_owned(),
224
+ },
225
+ NotificationAction {
226
+ id: "see".to_owned(),
227
+ label: "See appointment".to_owned(),
228
+ },
229
+ ],
230
+ )
231
+ .with_timeout(timeout_ms);
232
+ send_notification_with_alias(request, Some("see".to_owned()))
233
+ }
234
+
235
+ /// Returns the next notification action selected by the user.
236
+ #[napi]
237
+ pub fn poll_notification_actions() -> Option<String> {
238
+ NOTIFICATION_ACTIONS
239
+ .lock()
240
+ .ok()
241
+ .and_then(|mut actions| actions.pop_front())
242
+ }
243
+
244
+ #[cfg(target_os = "linux")]
245
+ fn send_notification(request: NotificationRequest) -> Result<()> {
246
+ send_notification_with_alias(request, None)
247
+ }
248
+
249
+ #[cfg(target_os = "linux")]
250
+ fn send_notification_with_alias(
251
+ request: NotificationRequest,
252
+ default_alias: Option<String>,
253
+ ) -> Result<()> {
254
+ let wait_for_action = !request.actions.is_empty();
255
+ let alias = default_alias;
256
+ std::thread::Builder::new()
257
+ .name("for-os-notification".to_owned())
258
+ .spawn(move || {
259
+ let args = notification_command_args(&request, wait_for_action);
260
+ let output = Command::new("notify-send")
261
+ .args(&args)
262
+ .stdin(Stdio::null())
263
+ .output();
264
+ if let Ok(output) = output {
265
+ let action = String::from_utf8_lossy(&output.stdout);
266
+ push_notification_action(&action, alias.as_deref());
267
+ }
268
+ })
269
+ .map_err(|error| {
270
+ Error::from_reason(format!("Failed to start desktop notification: {error}"))
271
+ })?;
272
+ Ok(())
273
+ }
274
+
275
+ #[cfg(not(target_os = "linux"))]
276
+ fn send_notification(request: NotificationRequest) -> Result<()> {
277
+ send_notification_with_alias(request, None)
278
+ }
279
+
280
+ #[cfg(not(target_os = "linux"))]
281
+ fn send_notification_with_alias(
282
+ request: NotificationRequest,
283
+ _default_alias: Option<String>,
284
+ ) -> Result<()> {
285
+ let NotificationRequest {
286
+ title,
287
+ body,
288
+ expire_ms,
289
+ ..
290
+ } = request;
291
+
292
+ #[cfg(target_os = "macos")]
293
+ let mut command = {
294
+ let script = format!(
295
+ "display notification \"{}\" with title \"{}\"",
296
+ escape_applescript(&body),
297
+ escape_applescript(&title)
298
+ );
299
+ let mut command = Command::new("osascript");
300
+ command.args(["-e", &script]);
301
+ command
302
+ };
303
+
304
+ #[cfg(target_os = "windows")]
305
+ let mut command = {
306
+ use std::os::windows::process::CommandExt;
307
+ const CREATE_NO_WINDOW: u32 = 0x0800_0000;
308
+ let timeout = expire_ms.unwrap_or(10_000);
309
+ let script = format!(
310
+ "Add-Type -AssemblyName System.Windows.Forms; Add-Type -AssemblyName System.Drawing; $n = New-Object System.Windows.Forms.NotifyIcon; $n.Icon = [System.Drawing.SystemIcons]::Information; $n.Visible = $true; $n.BalloonTipTitle = '{}'; $n.BalloonTipText = '{}'; $n.BalloonTipIcon = [System.Windows.Forms.ToolTipIcon]::Info; $n.ShowBalloonTip({timeout}); Start-Sleep -Seconds 2; $n.Dispose()",
311
+ escape_powershell_single_quote(&title),
312
+ escape_powershell_single_quote(&body)
313
+ );
314
+ let mut command = Command::new("powershell.exe");
315
+ command
316
+ .args(["-NoProfile", "-NonInteractive", "-Command", &script])
317
+ .creation_flags(CREATE_NO_WINDOW);
318
+ command
319
+ };
320
+
321
+ command
322
+ .stdin(Stdio::null())
323
+ .stdout(Stdio::null())
324
+ .stderr(Stdio::null())
325
+ .spawn()
326
+ .map(|_| ())
327
+ .map_err(|error| {
328
+ Error::from_reason(format!("Failed to send desktop notification: {error}"))
329
+ })
330
+ }
331
+
332
+ #[cfg(target_os = "macos")]
333
+ fn escape_applescript(value: &str) -> String {
334
+ value
335
+ .replace('\\', "\\\\")
336
+ .replace('"', "\\\"")
337
+ .replace('\r', " ")
338
+ .replace('\n', " ")
339
+ }
340
+
341
+ #[cfg(target_os = "windows")]
342
+ fn escape_powershell_single_quote(value: &str) -> String {
343
+ value
344
+ .replace('\'', "''")
345
+ .replace('\r', " ")
346
+ .replace('\n', " ")
347
+ }
348
+
349
+ #[cfg(test)]
350
+ mod notification_tests {
351
+ use super::{notification_command_args, NotificationAction, NotificationRequest};
352
+
353
+ fn request(actions: Vec<NotificationAction>) -> NotificationRequest {
354
+ NotificationRequest::new("title".to_owned(), "body".to_owned(), actions)
355
+ .with_timeout(Some(4_000))
356
+ }
357
+
358
+ #[test]
359
+ fn builds_timer_argument() {
360
+ let args = notification_command_args(&request(Vec::new()), false);
361
+ assert!(args.contains(&"--expire-time=4000".to_owned()));
362
+ assert!(!args.contains(&"--wait".to_owned()));
363
+ assert_eq!(args.last().map(String::as_str), Some("body"));
364
+ }
365
+
366
+ #[test]
367
+ fn builds_action_arguments_and_waits() {
368
+ let args = notification_command_args(
369
+ &request(vec![
370
+ NotificationAction {
371
+ id: "accept".to_owned(),
372
+ label: "Accept appointment".to_owned(),
373
+ },
374
+ NotificationAction {
375
+ id: "see".to_owned(),
376
+ label: "See appointment".to_owned(),
377
+ },
378
+ ]),
379
+ true,
380
+ );
381
+ assert!(args.contains(&"--wait".to_owned()));
382
+ assert!(args.contains(&"--action=accept=Accept appointment".to_owned()));
383
+ assert!(args.contains(&"--action=see=See appointment".to_owned()));
384
+ }
385
+
386
+ #[test]
387
+ fn adds_default_body_action_for_first_button() {
388
+ let request = super::with_default_action(request(vec![NotificationAction {
389
+ id: "accept".to_owned(),
390
+ label: "Accept".to_owned(),
391
+ }]));
392
+ let args = notification_command_args(&request, true);
393
+ assert!(args.contains(&"--action=accept=Accept".to_owned()));
394
+ assert!(args.contains(&"--action=default=Accept".to_owned()));
395
+ }
396
+
397
+ #[test]
398
+ fn omits_timer_when_not_configured() {
399
+ let args = notification_command_args(
400
+ &NotificationRequest::new("t".to_owned(), "b".to_owned(), Vec::new()),
401
+ false,
402
+ );
403
+ assert!(!args.iter().any(|arg| arg.starts_with("--expire-time=")));
404
+ }
405
+
406
+ #[test]
407
+ fn keeps_leading_dash_title_and_body_after_separator() {
408
+ let request = NotificationRequest::new(
409
+ "--expire-time=1".to_owned(),
410
+ "--urgency=critical".to_owned(),
411
+ Vec::new(),
412
+ );
413
+ let args = notification_command_args(&request, false);
414
+ let separator = args
415
+ .iter()
416
+ .position(|argument| argument == "--")
417
+ .expect("notification arguments must contain a -- separator");
418
+ let title = args
419
+ .iter()
420
+ .position(|argument| argument == "--expire-time=1")
421
+ .expect("title must be present in the argument vector");
422
+ let body = args
423
+ .iter()
424
+ .position(|argument| argument == "--urgency=critical")
425
+ .expect("body must be present in the argument vector");
426
+ assert!(
427
+ title > separator,
428
+ "a leading-dash title must be delivered after the -- separator"
429
+ );
430
+ assert!(
431
+ body > separator,
432
+ "a leading-dash body must be delivered after the -- separator"
433
+ );
434
+ assert_eq!(title, separator + 1);
435
+ assert_eq!(body, separator + 2);
436
+ }
437
+
438
+ #[cfg(target_os = "macos")]
439
+ #[test]
440
+ fn escapes_applescript_notification_text() {
441
+ assert_eq!(super::escape_applescript("a\\b\"c\nd"), "a\\\\b\\\"c d");
442
+ }
443
+
444
+ #[cfg(target_os = "windows")]
445
+ #[test]
446
+ fn escapes_powershell_notification_text() {
447
+ assert_eq!(super::escape_powershell_single_quote("a'b\nc"), "a''b c");
448
+ }
449
+ }