Skip to main content

sk_desktop/
tray.rs

1//! Application-owned notification icons. OS callbacks never run inside JS: on Windows they run on the
2//! tray's own thread, on macOS on the main thread (the VM's), from AppKit's event dispatch.
3
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::sync::{Arc, Mutex, OnceLock, Weak};
6
7pub type Callback = Arc<dyn Fn() + Send + Sync + 'static>;
8
9#[derive(Clone, Debug, PartialEq, Eq)]
10pub struct Icon {
11    pub width: u32,
12    pub height: u32,
13    pub rgba: Arc<[u8]>,
14    pub template: bool,
15}
16
17impl Icon {
18    pub fn rgba(width: u32, height: u32, pixels: impl Into<Arc<[u8]>>) -> Result<Self, Error> {
19        let icon = Self {
20            width,
21            height,
22            rgba: pixels.into(),
23            template: false,
24        };
25        icon.validate()?;
26        Ok(icon)
27    }
28    fn validate(&self) -> Result<(), Error> {
29        if self.width == 0
30            || self.height == 0
31            || self.width > 512
32            || self.height > 512
33            || self
34                .width
35                .checked_mul(self.height)
36                .and_then(|n| n.checked_mul(4))
37                .map(|n| n as usize)
38                != Some(self.rgba.len())
39        {
40            return Err(Error::Invalid(
41                "tray icon must contain exact RGBA pixels, at most 512 × 512".into(),
42            ));
43        }
44        Ok(())
45    }
46}
47
48#[derive(Clone)]
49pub enum MenuItem {
50    Action {
51        label: String,
52        disabled: bool,
53        checked: Option<bool>,
54        default: bool,
55        on_select: Option<Callback>,
56    },
57    Separator,
58    Submenu {
59        label: String,
60        disabled: bool,
61        items: Vec<MenuItem>,
62    },
63    Quit {
64        label: Option<String>,
65        disabled: bool,
66    },
67}
68impl MenuItem {
69    pub fn action(label: impl Into<String>, on_select: impl Fn() + Send + Sync + 'static) -> Self {
70        Self::Action {
71            label: label.into(),
72            disabled: false,
73            checked: None,
74            default: false,
75            on_select: Some(Arc::new(on_select)),
76        }
77    }
78    pub fn submenu(label: impl Into<String>, items: Vec<MenuItem>) -> Self {
79        Self::Submenu {
80            label: label.into(),
81            disabled: false,
82            items,
83        }
84    }
85    pub fn quit() -> Self {
86        Self::Quit {
87            label: None,
88            disabled: false,
89        }
90    }
91}
92
93#[derive(Clone, Default)]
94pub struct Options {
95    pub icon: Option<Icon>,
96    pub tooltip: String,
97    pub menu: Vec<MenuItem>,
98    pub on_click: Option<Callback>,
99    pub on_quit: Option<Callback>,
100}
101impl Options {
102    pub fn validate(&self) -> Result<(), Error> {
103        if self.tooltip.contains('\0') || self.tooltip.encode_utf16().count() > 127 {
104            return Err(Error::Invalid(
105                "tray tooltip must be NUL-free and at most 127 UTF-16 units".into(),
106            ));
107        }
108        if let Some(icon) = &self.icon {
109            icon.validate()?;
110        }
111        let mut count = 0;
112        validate_menu(&self.menu, 0, &mut count, self.on_quit.is_some())
113    }
114}
115fn validate_menu(
116    items: &[MenuItem],
117    depth: usize,
118    count: &mut usize,
119    can_quit: bool,
120) -> Result<(), Error> {
121    if depth > 8 {
122        return Err(Error::Invalid("tray menu nesting exceeds 8".into()));
123    }
124    for item in items {
125        *count += 1;
126        if *count > 512 {
127            return Err(Error::Invalid("tray menu exceeds 512 items".into()));
128        }
129        let label = match item {
130            MenuItem::Action { label, .. } | MenuItem::Submenu { label, .. } => {
131                Some(label.as_str())
132            }
133            MenuItem::Quit { label, .. } => {
134                if !can_quit {
135                    return Err(Error::Invalid(
136                        "a quit menu item requires Options::on_quit".into(),
137                    ));
138                }
139                label.as_deref()
140            }
141            MenuItem::Separator => None,
142        };
143        if label.is_some_and(|label| {
144            label.is_empty() || label.contains('\0') || label.encode_utf16().count() > 512
145        }) {
146            return Err(Error::Invalid(
147                "tray menu labels must be nonempty, NUL-free and at most 512 UTF-16 units".into(),
148            ));
149        }
150        if let MenuItem::Submenu { items, .. } = item {
151            validate_menu(items, depth + 1, count, can_quit)?;
152        }
153    }
154    Ok(())
155}
156
157#[derive(Clone, Debug, PartialEq, Eq)]
158pub enum Error {
159    Unsupported,
160    Closed,
161    Invalid(String),
162    Platform(String),
163}
164impl std::fmt::Display for Error {
165    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
166        match self {
167            Self::Unsupported => f.write_str("native tray is not implemented on this platform"),
168            Self::Closed => f.write_str("native tray has stopped"),
169            Self::Invalid(message) | Self::Platform(message) => f.write_str(message),
170        }
171    }
172}
173impl std::error::Error for Error {}
174
175#[cfg(windows)]
176mod windows;
177#[cfg(windows)]
178use windows::Controller;
179#[cfg(target_os = "macos")]
180mod macos;
181#[cfg(target_os = "macos")]
182use macos::Controller;
183#[cfg(any(target_os = "macos", test))]
184mod mac_plan;
185#[cfg(not(any(windows, target_os = "macos")))]
186struct Controller;
187#[cfg(not(any(windows, target_os = "macos")))]
188impl Controller {
189    fn start() -> Result<Arc<Self>, Error> {
190        Err(Error::Unsupported)
191    }
192    fn set(&self, _: Option<Options>) -> Result<u64, Error> {
193        Err(Error::Unsupported)
194    }
195    fn revision(&self) -> u64 {
196        0
197    }
198    fn stop(&self) {}
199}
200struct Owner(Arc<Controller>);
201impl Drop for Owner {
202    fn drop(&mut self) {
203        self.0.stop();
204    }
205}
206
207#[derive(Clone)]
208pub struct Tray {
209    owner: Arc<Owner>,
210}
211static APP: OnceLock<Mutex<Weak<Owner>>> = OnceLock::new();
212static APP_SHOWN: AtomicBool = AtomicBool::new(false);
213impl Tray {
214    pub const fn is_available() -> bool {
215        cfg!(any(windows, target_os = "macos"))
216    }
217    pub fn new() -> Result<Self, Error> {
218        Ok(Self {
219            owner: Arc::new(Owner(Controller::start()?)),
220        })
221    }
222    pub fn app() -> Result<Self, Error> {
223        let mut slot = APP
224            .get_or_init(|| Mutex::new(Weak::new()))
225            .lock()
226            .map_err(|_| Error::Closed)?;
227        if let Some(owner) = slot.upgrade() {
228            return Ok(Self { owner });
229        }
230        let tray = Self::new()?;
231        *slot = Arc::downgrade(&tray.owner);
232        Ok(tray)
233    }
234    pub fn existing_app() -> Option<Self> {
235        let owner = APP.get()?.lock().ok()?.upgrade()?;
236        Some(Self { owner })
237    }
238    /// Queues a complete replacement; None removes the icon. The returned revision fences events from a replaced menu.
239    pub fn set(&self, options: Option<Options>) -> Result<u64, Error> {
240        if let Some(options) = &options {
241            options.validate()?;
242        }
243        let shown = options.is_some();
244        let revision = self.owner.0.set(options)?;
245        if self.is_app() {
246            APP_SHOWN.store(shown, Ordering::Release);
247        }
248        Ok(revision)
249    }
250    fn is_app(&self) -> bool {
251        APP.get()
252            .and_then(|slot| slot.lock().ok()?.upgrade())
253            .is_some_and(|owner| Arc::ptr_eq(&owner, &self.owner))
254    }
255    pub fn app_shown() -> bool {
256        APP_SHOWN.load(Ordering::Acquire) && Self::existing_app().is_some()
257    }
258    pub fn revision(&self) -> u64 {
259        self.owner.0.revision()
260    }
261    pub fn stop(&self) {
262        self.owner.0.stop();
263    }
264    pub fn downgrade(&self) -> WeakTray {
265        WeakTray(Arc::downgrade(&self.owner))
266    }
267}
268#[derive(Clone)]
269pub struct WeakTray(Weak<Owner>);
270impl WeakTray {
271    pub fn upgrade(&self) -> Option<Tray> {
272        self.0.upgrade().map(|owner| Tray { owner })
273    }
274}
275
276pub(super) fn invoke(callback: &Callback) {
277    if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| callback())).is_err() {
278        crate::log_later("error", "native tray callback panicked".into());
279    }
280}
281
282#[cfg(test)]
283mod tests {
284    use super::*;
285    #[test]
286    fn menu_validation_bounds_state_without_opening_the_desktop() {
287        let mut options = Options {
288            menu: vec![
289                MenuItem::action("Open", || {}),
290                MenuItem::Separator,
291                MenuItem::submenu(
292                    "Status",
293                    vec![MenuItem::Action {
294                        label: "Muted".into(),
295                        disabled: true,
296                        checked: Some(true),
297                        default: false,
298                        on_select: None,
299                    }],
300                ),
301                MenuItem::quit(),
302            ],
303            on_quit: Some(Arc::new(|| {})),
304            ..Default::default()
305        };
306        assert!(options.validate().is_ok());
307        options.on_quit = None;
308        assert!(options.validate().is_err());
309        options.menu.clear();
310        options.tooltip = "😀".repeat(64);
311        assert!(options.validate().is_err());
312        options.tooltip.clear();
313        options.menu = vec![MenuItem::Separator; 513];
314        assert!(options.validate().is_err());
315        options.menu = vec![MenuItem::action("", || {})];
316        assert!(options.validate().is_err());
317    }
318    #[test]
319    fn icon_validation_checks_exact_lengths_before_platform_calls() {
320        assert!(Icon::rgba(2, 2, vec![0; 16]).is_ok());
321        assert!(Icon::rgba(2, 2, vec![0; 15]).is_err());
322        assert!(Icon::rgba(0, 2, vec![]).is_err());
323        assert!(Icon::rgba(u32::MAX, u32::MAX, vec![]).is_err());
324    }
325}