Skip to main content

strata_platform/
tray.rs

1//! Desktop System Tray abstraction (`TrayIcon`, `TrayMenu`, `TrayMenuItem`).
2//!
3//! On Linux the live backend talks to the Ayatana AppIndicator library through
4//! runtime dynamic loading (`dlopen`/`dlsym`). The library is never a build-time
5//! or hard runtime dependency: when it is missing, or when the caller is not on
6//! the GTK main thread, the handle falls back to the deterministic in-process
7//! model and reports `backend_name() == "handle-only"`.
8
9/// An individual item or separator inside a system tray context menu.
10#[derive(Debug, Clone, PartialEq)]
11pub struct TrayMenuItem {
12    pub id: u64,
13    pub label: String,
14    pub enabled: bool,
15    pub checked: bool,
16    pub is_separator: bool,
17    pub children: Vec<TrayMenuItem>,
18}
19
20impl TrayMenuItem {
21    /// Creates a standard clickable menu item.
22    pub fn item(id: u64, label: impl Into<String>) -> Self {
23        Self {
24            id,
25            label: label.into(),
26            enabled: true,
27            checked: false,
28            is_separator: false,
29            children: Vec::new(),
30        }
31    }
32
33    /// Creates a horizontal separator.
34    pub fn separator() -> Self {
35        Self {
36            id: 0,
37            label: String::new(),
38            enabled: false,
39            checked: false,
40            is_separator: true,
41            children: Vec::new(),
42        }
43    }
44
45    /// Creates a parent item containing nested sub-menu items.
46    pub fn submenu(id: u64, label: impl Into<String>, children: Vec<TrayMenuItem>) -> Self {
47        Self {
48            id,
49            label: label.into(),
50            enabled: true,
51            checked: false,
52            is_separator: false,
53            children,
54        }
55    }
56
57    /// Sets the checked state of this item.
58    pub fn with_checked(mut self, checked: bool) -> Self {
59        self.checked = checked;
60        self
61    }
62
63    /// Sets the enabled state of this item.
64    pub fn with_enabled(mut self, enabled: bool) -> Self {
65        self.enabled = enabled;
66        self
67    }
68}
69
70/// A context menu attached to a desktop system tray icon.
71#[derive(Debug, Clone, Default, PartialEq)]
72pub struct TrayMenu {
73    pub items: Vec<TrayMenuItem>,
74}
75
76impl TrayMenu {
77    /// Creates an empty tray menu.
78    pub fn new() -> Self {
79        Self { items: Vec::new() }
80    }
81
82    /// Appends a clickable menu item.
83    pub fn add_item(&mut self, id: u64, label: impl Into<String>) -> &mut Self {
84        self.items.push(TrayMenuItem::item(id, label));
85        self
86    }
87
88    /// Appends a separator.
89    pub fn add_separator(&mut self) -> &mut Self {
90        self.items.push(TrayMenuItem::separator());
91        self
92    }
93
94    /// Appends a submenu.
95    pub fn add_submenu(
96        &mut self,
97        id: u64,
98        label: impl Into<String>,
99        children: Vec<TrayMenuItem>,
100    ) -> &mut Self {
101        self.items.push(TrayMenuItem::submenu(id, label, children));
102        self
103    }
104
105    /// Recursively searches for an item by ID.
106    pub fn find_item(&self, id: u64) -> Option<&TrayMenuItem> {
107        Self::find_in_slice(&self.items, id)
108    }
109
110    /// Recursively searches for a mutable item by ID.
111    pub fn find_item_mut(&mut self, id: u64) -> Option<&mut TrayMenuItem> {
112        Self::find_in_slice_mut(&mut self.items, id)
113    }
114
115    fn find_in_slice(items: &[TrayMenuItem], id: u64) -> Option<&TrayMenuItem> {
116        for item in items {
117            if !item.is_separator && item.id == id {
118                return Some(item);
119            }
120            if let Some(found) = Self::find_in_slice(&item.children, id) {
121                return Some(found);
122            }
123        }
124        None
125    }
126
127    fn find_in_slice_mut(items: &mut [TrayMenuItem], id: u64) -> Option<&mut TrayMenuItem> {
128        for item in items {
129            if !item.is_separator && item.id == id {
130                return Some(item);
131            }
132            if let Some(found) = Self::find_in_slice_mut(&mut item.children, id) {
133                return Some(found);
134            }
135        }
136        None
137    }
138}
139
140/// System tray icon abstraction.
141#[derive(Debug, Clone)]
142pub struct TrayIcon {
143    pub tooltip: String,
144    pub icon_rgba: Vec<u8>,
145    pub icon_width: u32,
146    pub icon_height: u32,
147    pub menu: Option<TrayMenu>,
148    pub visible: bool,
149    pub click_count: usize,
150    pub last_action_id: Option<u64>,
151    pub badge: Option<String>,
152}
153
154impl TrayIcon {
155    /// Creates a new system tray icon.
156    pub fn new(
157        tooltip: impl Into<String>,
158        icon_rgba: Vec<u8>,
159        icon_width: u32,
160        icon_height: u32,
161    ) -> Self {
162        Self {
163            tooltip: tooltip.into(),
164            icon_rgba,
165            icon_width,
166            icon_height,
167            menu: None,
168            visible: true,
169            click_count: 0,
170            last_action_id: None,
171            badge: None,
172        }
173    }
174
175    /// Sets the notification badge text (e.g. "99+" or "NEW").
176    pub fn set_badge(&mut self, badge: Option<String>) {
177        self.badge = badge;
178    }
179
180    /// Sets the notification badge as a numeric count (or clears it if None or 0).
181    pub fn set_badge_count(&mut self, count: Option<u32>) {
182        self.badge = count.and_then(|c| if c > 0 { Some(c.to_string()) } else { None });
183    }
184
185    /// Returns current badge text if present.
186    pub fn badge(&self) -> Option<&str> {
187        self.badge.as_deref()
188    }
189
190    /// Sets the hover tooltip text.
191    pub fn set_tooltip(&mut self, tooltip: impl Into<String>) {
192        self.tooltip = tooltip.into();
193    }
194
195    /// Sets or clears the tray context menu.
196    pub fn set_menu(&mut self, menu: Option<TrayMenu>) {
197        self.menu = menu;
198    }
199
200    /// Sets whether the icon is visible in the status bar/system tray.
201    pub fn set_visible(&mut self, visible: bool) {
202        self.visible = visible;
203    }
204
205    /// Simulates or executes a primary click on the tray icon.
206    pub fn trigger_click(&mut self) {
207        self.click_count += 1;
208    }
209
210    /// Simulates or executes a menu item action by ID. Returns true if the item was found and enabled.
211    pub fn trigger_menu_action(&mut self, id: u64) -> bool {
212        if let Some(menu) = &self.menu {
213            if let Some(item) = menu.find_item(id) {
214                if item.enabled {
215                    self.last_action_id = Some(id);
216                    return true;
217                }
218            }
219        }
220        false
221    }
222
223    /// Spawns an OS-native system tray handle dispatching events through the provided event callback.
224    ///
225    /// On Linux the native indicator is created immediately when this is called
226    /// on the GTK main thread after `gtk::init()`. Callers on any other thread,
227    /// and callers where the Ayatana AppIndicator library is absent, receive a
228    /// handle-only controller that still dispatches events from the in-process
229    /// model.
230    pub fn spawn_native<F>(self, event_sink: F) -> NativeTrayHandle
231    where
232        F: Fn(crate::events::PlatformEvent) + Send + Sync + 'static,
233    {
234        NativeTrayHandle::new(self, std::sync::Arc::new(event_sink))
235    }
236}
237
238/// Platform-agnostic system tray interaction event.
239#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
240pub enum TrayEvent {
241    LeftClick,
242    RightClick,
243    DoubleClick,
244    MenuItemTriggered(u64),
245}
246
247/// Thread-safe reactive event channel for desktop system tray interactions.
248#[derive(Clone)]
249pub struct TrayEventChannel {
250    sender: std::sync::mpsc::Sender<TrayEvent>,
251}
252
253/// Receiving endpoint for desktop system tray events.
254pub struct TrayEventReceiver {
255    receiver: std::sync::mpsc::Receiver<TrayEvent>,
256}
257
258impl TrayEventChannel {
259    /// Creates a new sender and receiver pair.
260    pub fn new() -> (Self, TrayEventReceiver) {
261        let (sender, receiver) = std::sync::mpsc::channel();
262        (Self { sender }, TrayEventReceiver { receiver })
263    }
264
265    /// Dispatches a tray event down the channel.
266    pub fn dispatch(&self, event: TrayEvent) {
267        let _ = self.sender.send(event);
268    }
269
270    /// Creates an adapter closure suitable for passing as a `TrayEventSink`.
271    pub fn as_sink(&self) -> TrayEventSink {
272        let sender = self.sender.clone();
273        std::sync::Arc::new(move |event| match event {
274            crate::events::PlatformEvent::TrayIconClicked => {
275                let _ = sender.send(TrayEvent::LeftClick);
276            }
277            crate::events::PlatformEvent::TrayMenuItemClicked(id) => {
278                let _ = sender.send(TrayEvent::MenuItemTriggered(id));
279            }
280            _ => {}
281        })
282    }
283}
284
285impl Default for TrayEventChannel {
286    fn default() -> Self {
287        Self::new().0
288    }
289}
290
291impl TrayEventReceiver {
292    /// Attempts to read the next pending tray event without blocking.
293    pub fn try_recv(&self) -> Option<TrayEvent> {
294        self.receiver.try_recv().ok()
295    }
296
297    /// Blocks until the next tray event arrives, or times out.
298    pub fn recv_timeout(
299        &self,
300        timeout: std::time::Duration,
301    ) -> Result<TrayEvent, std::sync::mpsc::RecvTimeoutError> {
302        self.receiver.recv_timeout(timeout)
303    }
304}
305
306/// Pure-Rust Linux D-Bus StatusNotifierItem daemon registration.
307pub struct DbusStatusNotifier {
308    pub service_name: String,
309    pub title: String,
310    pub icon_name: String,
311    pub client: Option<crate::dbus::DbusClient>,
312}
313
314impl DbusStatusNotifier {
315    /// Creates and registers an authentic `org.kde.StatusNotifierItem` over session D-Bus.
316    pub fn register(title: &str, icon_name: &str) -> Result<Self, String> {
317        let mut client = crate::dbus::DbusClient::connect()?;
318        let service_name = format!("org.kde.StatusNotifierItem-{}-1", std::process::id());
319
320        // Register service with org.kde.StatusNotifierWatcher
321        let mut body = crate::dbus::DbusMessageEncoder::new();
322        body.push_string(&service_name);
323        let _ = client.call_method(
324            "org.kde.StatusNotifierWatcher",
325            "/StatusNotifierWatcher",
326            "org.kde.StatusNotifierWatcher",
327            "RegisterStatusNotifierItem",
328            Some("s"),
329            body.as_bytes(),
330        );
331
332        Ok(Self {
333            service_name,
334            title: title.to_string(),
335            icon_name: icon_name.to_string(),
336            client: Some(client),
337        })
338    }
339}
340
341/// Thread-safe tray event sink callback.
342pub type TrayEventSink =
343    std::sync::Arc<dyn Fn(crate::events::PlatformEvent) + Send + Sync + 'static>;
344
345/// Shared menu and event state used by the handle and by native menu callbacks.
346struct SharedTrayState {
347    event_sink: TrayEventSink,
348    menu: std::sync::Mutex<Option<TrayMenu>>,
349}
350
351impl SharedTrayState {
352    fn new(event_sink: TrayEventSink, menu: Option<TrayMenu>) -> Self {
353        Self {
354            event_sink,
355            menu: std::sync::Mutex::new(menu),
356        }
357    }
358
359    fn set_menu(&self, menu: Option<TrayMenu>) {
360        let mut slot = match self.menu.lock() {
361            Ok(slot) => slot,
362            Err(poisoned) => poisoned.into_inner(),
363        };
364        *slot = menu;
365    }
366
367    fn dispatch_click(&self) {
368        (self.event_sink)(crate::events::PlatformEvent::TrayIconClicked);
369    }
370
371    fn dispatch_menu_action(&self, id: u64) -> bool {
372        let enabled = {
373            let slot = match self.menu.lock() {
374                Ok(slot) => slot,
375                Err(poisoned) => poisoned.into_inner(),
376            };
377            slot.as_ref()
378                .and_then(|menu| menu.find_item(id))
379                .map(|item| item.enabled)
380                .unwrap_or(false)
381        };
382        if !enabled {
383            return false;
384        }
385        (self.event_sink)(crate::events::PlatformEvent::TrayMenuItemClicked(id));
386        true
387    }
388}
389
390/// Operating-system native desktop system tray controller.
391pub struct NativeTrayHandle {
392    icon: TrayIcon,
393    shared: std::sync::Arc<SharedTrayState>,
394    #[cfg(target_os = "linux")]
395    live: Option<linux_backend::LiveIndicator>,
396    #[cfg(windows)]
397    live: Option<windows_backend::LiveTrayIcon>,
398    #[cfg(target_os = "macos")]
399    live: Option<macos_backend::LiveStatusItem>,
400}
401
402impl NativeTrayHandle {
403    /// Creates and registers an OS-native system tray icon.
404    ///
405    /// See [`TrayIcon::spawn_native`] for the Linux main-thread contract.
406    pub fn new(icon: TrayIcon, event_sink: TrayEventSink) -> Self {
407        let shared = std::sync::Arc::new(SharedTrayState::new(event_sink, icon.menu.clone()));
408        #[cfg(target_os = "linux")]
409        let live = linux_backend::LiveIndicator::new(&icon, shared.clone());
410        #[cfg(windows)]
411        let live = windows_backend::LiveTrayIcon::new(&icon, shared.clone());
412        #[cfg(target_os = "macos")]
413        let live = macos_backend::LiveStatusItem::new(&icon, shared.clone());
414        Self {
415            icon,
416            shared,
417            #[cfg(target_os = "linux")]
418            live,
419            #[cfg(windows)]
420            live,
421            #[cfg(target_os = "macos")]
422            live,
423        }
424    }
425
426    /// Returns the active native backend identifier.
427    ///
428    /// - `"ayatana-appindicator"`: Registered via Linux Ayatana AppIndicator
429    /// - `"win32-tray"`: Registered via Windows Shell_NotifyIconW
430    /// - `"cocoa-nsstatusbar"`: Registered via macOS NSStatusBar
431    /// - `"handle-only"`: Fallback in-process controller
432    pub fn backend_name(&self) -> &'static str {
433        #[cfg(target_os = "linux")]
434        {
435            if self.live.is_some() {
436                "ayatana-appindicator"
437            } else {
438                "handle-only"
439            }
440        }
441        #[cfg(windows)]
442        {
443            if self.live.is_some() {
444                "win32-tray"
445            } else {
446                "handle-only"
447            }
448        }
449        #[cfg(target_os = "macos")]
450        {
451            if self.live.is_some() {
452                "cocoa-nsstatusbar"
453            } else {
454                "handle-only"
455            }
456        }
457        #[cfg(not(any(target_os = "linux", windows, target_os = "macos")))]
458        {
459            "handle-only"
460        }
461    }
462
463    /// Updates tooltip text on the system tray icon.
464    pub fn set_tooltip(&mut self, tooltip: impl Into<String>) {
465        self.icon.set_tooltip(tooltip);
466        #[cfg(target_os = "linux")]
467        {
468            let tooltip = self.icon.tooltip.clone();
469            if let Some(live) = &mut self.live {
470                live.set_tooltip(tooltip);
471            }
472        }
473        #[cfg(windows)]
474        {
475            let tooltip = self.icon.tooltip.clone();
476            if let Some(live) = &mut self.live {
477                live.set_tooltip(tooltip);
478            }
479        }
480        #[cfg(target_os = "macos")]
481        {
482            let tooltip = self.icon.tooltip.clone();
483            if let Some(live) = &mut self.live {
484                live.set_tooltip(tooltip);
485            }
486        }
487    }
488
489    /// Sets or updates the tray context menu.
490    pub fn set_menu(&mut self, menu: Option<TrayMenu>) {
491        self.icon.set_menu(menu.clone());
492        self.shared.set_menu(menu.clone());
493        #[cfg(target_os = "linux")]
494        if let Some(live) = &mut self.live {
495            live.set_menu(menu.as_ref());
496        }
497        #[cfg(windows)]
498        if let Some(live) = &mut self.live {
499            live.set_menu(menu.as_ref());
500        }
501        #[cfg(target_os = "macos")]
502        if let Some(live) = &mut self.live {
503            live.set_menu(menu.as_ref());
504        }
505    }
506
507    /// Sets visibility of the system tray icon.
508    pub fn set_visible(&mut self, visible: bool) {
509        self.icon.set_visible(visible);
510        #[cfg(target_os = "linux")]
511        if let Some(live) = &mut self.live {
512            live.set_visible(visible);
513        }
514        #[cfg(windows)]
515        if let Some(live) = &mut self.live {
516            live.set_visible(visible);
517        }
518        #[cfg(target_os = "macos")]
519        if let Some(live) = &mut self.live {
520            live.set_visible(visible);
521        }
522    }
523
524    /// Sets or clears the notification badge on the tray icon.
525    pub fn set_badge(&mut self, badge: Option<String>) {
526        self.icon.set_badge(badge.clone());
527        #[cfg(target_os = "linux")]
528        if let Some(live) = &mut self.live {
529            live.set_badge(badge);
530        }
531        #[cfg(windows)]
532        if let Some(live) = &mut self.live {
533            live.set_badge(badge);
534        }
535        #[cfg(target_os = "macos")]
536        if let Some(live) = &mut self.live {
537            live.set_badge(badge);
538        }
539    }
540
541    /// Dispatches a simulated or native tray icon click event.
542    pub fn trigger_click(&mut self) {
543        self.icon.trigger_click();
544        self.shared.dispatch_click();
545    }
546
547    /// Dispatches a simulated or native menu action event.
548    pub fn trigger_menu_action(&mut self, id: u64) -> bool {
549        self.shared.set_menu(self.icon.menu.clone());
550        if self.shared.dispatch_menu_action(id) {
551            self.icon.last_action_id = Some(id);
552            true
553        } else {
554            false
555        }
556    }
557
558    /// Returns a reference to the underlying `TrayIcon` state.
559    pub fn icon(&self) -> &TrayIcon {
560        &self.icon
561    }
562
563    /// Returns a mutable reference to the underlying `TrayIcon` state.
564    pub fn icon_mut(&mut self) -> &mut TrayIcon {
565        &mut self.icon
566    }
567}
568
569#[cfg(all(target_os = "linux", feature = "gtk-compat"))]
570mod linux_backend {
571    //! Ayatana AppIndicator backend loaded at runtime.
572    //!
573    //! Lifecycle and threading contract:
574    //! - `NativeTrayHandle::new` must be called on the GTK main thread after
575    //!   `gtk::init()`; otherwise no indicator is created and the handle reports
576    //!   `backend_name() == "handle-only"`.
577    //! - Ayatana AppIndicator owns the `GtkMenu` lifecycle. The Rust side keeps a
578    //!   strong reference to the same menu so the widget cannot be collected
579    //!   before the indicator releases it.
580    //! - The library handle is loaded once per process and intentionally kept for
581    //!   the process lifetime because GObject type registration cannot be safely
582    //!   unloaded while the type system still references the library.
583    //! - AppIndicator reports activation by exporting its menu over DBus to the
584    //!   panel; this version of the library does not deliver a primary-click
585    //!   callback itself. The backend connects the root `GtkMenu` `show` signal
586    //!   to `TrayIconClicked` once per open as the closest available mapping.
587    //!   On desktops that render the exported DBusMenu without showing the
588    //!   `GtkMenu`, the signal may not fire and clicks then arrive only through
589    //!   the in-process `trigger_click` controller.
590
591    use super::{SharedTrayState, TrayIcon, TrayMenu, TrayMenuItem};
592    use gtk::glib::translate::ToGlibPtr;
593    use std::ffi::{c_char, c_int, c_void, CString};
594    use std::path::PathBuf;
595    use std::sync::atomic::{AtomicU64, Ordering};
596    use std::sync::{Arc, OnceLock};
597
598    type Indicator = c_void;
599
600    const RTLD_NOW: c_int = 2;
601    const APP_INDICATOR_CATEGORY_APPLICATION_STATUS: c_int = 0;
602    const APP_INDICATOR_STATUS_PASSIVE: c_int = 0;
603    const APP_INDICATOR_STATUS_ACTIVE: c_int = 1;
604
605    type NewFn = unsafe extern "C" fn(*const c_char, *const c_char, c_int) -> *mut Indicator;
606    type SetStatusFn = unsafe extern "C" fn(*mut Indicator, c_int);
607    type SetIconFullFn = unsafe extern "C" fn(*mut Indicator, *const c_char, *const c_char);
608    type SetMenuFn = unsafe extern "C" fn(*mut Indicator, *mut c_void);
609    type SetTitleFn = unsafe extern "C" fn(*mut Indicator, *const c_char);
610    type SetLabelFn = unsafe extern "C" fn(*mut Indicator, *const c_char, *const c_char);
611
612    extern "C" {
613        fn dlopen(filename: *const c_char, flag: c_int) -> *mut c_void;
614        fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
615    }
616
617    struct Api {
618        new: NewFn,
619        set_status: SetStatusFn,
620        set_icon_full: SetIconFullFn,
621        set_menu: SetMenuFn,
622        set_title: SetTitleFn,
623        set_label: SetLabelFn,
624    }
625
626    static API: OnceLock<Option<Api>> = OnceLock::new();
627
628    fn api() -> Option<&'static Api> {
629        API.get_or_init(Api::load).as_ref()
630    }
631
632    impl Api {
633        fn load() -> Option<Self> {
634            const CANDIDATES: [&[u8]; 2] = [
635                b"libayatana-appindicator3.so.1\0",
636                b"libappindicator3.so.1\0",
637            ];
638            for candidate in CANDIDATES {
639                let handle = unsafe { dlopen(candidate.as_ptr() as *const c_char, RTLD_NOW) };
640                if handle.is_null() {
641                    continue;
642                }
643                unsafe {
644                    let new: NewFn = match resolve(handle, b"app_indicator_new\0") {
645                        Some(symbol) => symbol,
646                        None => continue,
647                    };
648                    let set_status: SetStatusFn =
649                        match resolve(handle, b"app_indicator_set_status\0") {
650                            Some(symbol) => symbol,
651                            None => continue,
652                        };
653                    let set_icon_full: SetIconFullFn =
654                        match resolve(handle, b"app_indicator_set_icon_full\0") {
655                            Some(symbol) => symbol,
656                            None => continue,
657                        };
658                    let set_menu: SetMenuFn = match resolve(handle, b"app_indicator_set_menu\0") {
659                        Some(symbol) => symbol,
660                        None => continue,
661                    };
662                    let set_title: SetTitleFn = match resolve(handle, b"app_indicator_set_title\0")
663                    {
664                        Some(symbol) => symbol,
665                        None => continue,
666                    };
667                    let set_label: SetLabelFn = match resolve(handle, b"app_indicator_set_label\0")
668                    {
669                        Some(symbol) => symbol,
670                        None => continue,
671                    };
672                    return Some(Self {
673                        new,
674                        set_status,
675                        set_icon_full,
676                        set_menu,
677                        set_title,
678                        set_label,
679                    });
680                }
681            }
682            None
683        }
684    }
685
686    unsafe fn resolve<T: Copy>(handle: *mut c_void, name: &[u8]) -> Option<T> {
687        let symbol = dlsym(handle, name.as_ptr() as *const c_char);
688        if symbol.is_null() {
689            None
690        } else {
691            Some(std::mem::transmute_copy(&symbol))
692        }
693    }
694
695    static ICON_COUNTER: AtomicU64 = AtomicU64::new(0);
696
697    pub(super) struct LiveIndicator {
698        api: &'static Api,
699        indicator: *mut Indicator,
700        menu: Option<gtk::Menu>,
701        icon_path: Option<PathBuf>,
702        shared: Arc<SharedTrayState>,
703        tooltip: String,
704        visible: bool,
705        badge: Option<String>,
706    }
707
708    impl LiveIndicator {
709        pub(super) fn new(icon: &TrayIcon, shared: Arc<SharedTrayState>) -> Option<Self> {
710            if !gtk::is_initialized() || !gtk::is_initialized_main_thread() {
711                return None;
712            }
713            let api = api()?;
714            let icon_path = write_icon_png(icon);
715            let id = CString::new(indicator_id()).ok()?;
716            let icon_name = match &icon_path {
717                Some(path) => CString::new(path.to_string_lossy().as_bytes()).ok()?,
718                None => CString::new("application-x-executable").ok()?,
719            };
720            let indicator = unsafe {
721                (api.new)(
722                    id.as_ptr(),
723                    icon_name.as_ptr(),
724                    APP_INDICATOR_CATEGORY_APPLICATION_STATUS,
725                )
726            };
727            if indicator.is_null() {
728                remove_icon_file(icon_path.as_ref());
729                return None;
730            }
731
732            let mut live = Self {
733                api,
734                indicator,
735                menu: None,
736                icon_path,
737                shared,
738                tooltip: icon.tooltip.clone(),
739                visible: icon.visible,
740                badge: icon.badge.clone(),
741            };
742            live.apply_tooltip();
743            live.apply_status();
744            live.apply_badge();
745            if let Some(menu) = &icon.menu {
746                live.set_menu(Some(menu));
747            }
748            Some(live)
749        }
750
751        pub(super) fn set_tooltip(&mut self, tooltip: String) {
752            self.tooltip = tooltip;
753            self.apply_tooltip();
754        }
755
756        pub(super) fn set_visible(&mut self, visible: bool) {
757            self.visible = visible;
758            self.apply_status();
759        }
760
761        pub(super) fn set_badge(&mut self, badge: Option<String>) {
762            self.badge = badge;
763            self.apply_badge();
764        }
765
766        pub(super) fn set_menu(&mut self, menu: Option<&TrayMenu>) {
767            // AppIndicator asserts that the menu pointer is a valid GtkMenu, so
768            // clearing a menu is represented by an empty menu rather than null.
769            let (gtk_menu, model) = match menu {
770                Some(model) => (build_menu(model, &self.shared), Some(model.clone())),
771                None => (
772                    build_menu(&TrayMenu::new(), &self.shared),
773                    Some(TrayMenu::new()),
774                ),
775            };
776            let menu_ptr: *mut gtk::ffi::GtkMenu = gtk_menu.to_glib_none().0;
777            self.shared.set_menu(model);
778            unsafe {
779                (self.api.set_menu)(self.indicator, menu_ptr as *mut c_void);
780            }
781            self.menu = Some(gtk_menu);
782        }
783
784        fn apply_tooltip(&self) {
785            let Ok(title) = CString::new(self.tooltip.as_str()) else {
786                return;
787            };
788            let icon_name = match &self.icon_path {
789                Some(path) => CString::new(path.to_string_lossy().as_bytes()),
790                None => CString::new("application-x-executable"),
791            };
792            let Ok(icon_name) = icon_name else {
793                return;
794            };
795            unsafe {
796                (self.api.set_title)(self.indicator, title.as_ptr());
797                (self.api.set_icon_full)(self.indicator, icon_name.as_ptr(), title.as_ptr());
798            }
799        }
800
801        fn apply_status(&self) {
802            let status = if self.visible {
803                APP_INDICATOR_STATUS_ACTIVE
804            } else {
805                APP_INDICATOR_STATUS_PASSIVE
806            };
807            unsafe {
808                (self.api.set_status)(self.indicator, status);
809            }
810        }
811
812        fn apply_badge(&self) {
813            match &self.badge {
814                Some(badge) => {
815                    const GUIDE: &[u8] = b"1\0";
816                    let Ok(label) = CString::new(badge.as_str()) else {
817                        return;
818                    };
819                    unsafe {
820                        (self.api.set_label)(
821                            self.indicator,
822                            label.as_ptr(),
823                            GUIDE.as_ptr() as *const c_char,
824                        );
825                    }
826                }
827                None => unsafe {
828                    (self.api.set_label)(self.indicator, std::ptr::null(), std::ptr::null());
829                },
830            }
831        }
832    }
833
834    impl Drop for LiveIndicator {
835        fn drop(&mut self) {
836            unsafe {
837                gtk::glib::gobject_ffi::g_object_unref(
838                    self.indicator as *mut gtk::glib::gobject_ffi::GObject,
839                );
840            }
841            self.menu = None;
842            remove_icon_file(self.icon_path.as_ref());
843        }
844    }
845
846    fn build_menu(model: &TrayMenu, shared: &Arc<SharedTrayState>) -> gtk::Menu {
847        use gtk::prelude::*;
848
849        let menu = gtk::Menu::new();
850        append_items(&menu, &model.items, shared);
851
852        let sink = shared.clone();
853        menu.connect_show(move |_| sink.dispatch_click());
854
855        menu.show_all();
856        menu
857    }
858
859    fn append_items(parent: &gtk::Menu, items: &[TrayMenuItem], shared: &Arc<SharedTrayState>) {
860        use gtk::prelude::*;
861
862        for item in items {
863            if item.is_separator {
864                let separator = gtk::SeparatorMenuItem::new();
865                parent.append(&separator);
866                separator.show();
867                continue;
868            }
869
870            if item.children.is_empty() {
871                if item.checked {
872                    let menu_item = gtk::CheckMenuItem::with_label(&item.label);
873                    menu_item.set_active(true);
874                    menu_item.set_sensitive(item.enabled);
875                    let sink = shared.clone();
876                    let id = item.id;
877                    menu_item.connect_activate(move |_| {
878                        sink.dispatch_menu_action(id);
879                    });
880                    parent.append(&menu_item);
881                    menu_item.show();
882                } else {
883                    let menu_item = gtk::MenuItem::with_label(&item.label);
884                    menu_item.set_sensitive(item.enabled);
885                    let sink = shared.clone();
886                    let id = item.id;
887                    menu_item.connect_activate(move |_| {
888                        sink.dispatch_menu_action(id);
889                    });
890                    parent.append(&menu_item);
891                    menu_item.show();
892                }
893            } else {
894                let menu_item = gtk::MenuItem::with_label(&item.label);
895                menu_item.set_sensitive(item.enabled);
896                let submenu = gtk::Menu::new();
897                append_items(&submenu, &item.children, shared);
898                submenu.show_all();
899                menu_item.set_submenu(Some(&submenu));
900                parent.append(&menu_item);
901                menu_item.show();
902            }
903        }
904    }
905
906    fn indicator_id() -> String {
907        format!("strata-tray-{}", std::process::id())
908    }
909
910    fn write_icon_png(icon: &TrayIcon) -> Option<PathBuf> {
911        let width = icon.icon_width;
912        let height = icon.icon_height;
913        let pixel_count = (width as usize).checked_mul(height as usize)?;
914        if width == 0 || height == 0 || icon.icon_rgba.len() < pixel_count * 4 {
915            return None;
916        }
917
918        // Cairo ARGB32 stores premultiplied BGRA on little-endian hosts.
919        let mut bgra = Vec::with_capacity(pixel_count * 4);
920        for pixel in icon.icon_rgba.as_chunks::<4>().0.iter().take(pixel_count) {
921            bgra.extend_from_slice(&[pixel[2], pixel[1], pixel[0], pixel[3]]);
922        }
923
924        let surface = cairo::ImageSurface::create_for_data(
925            bgra,
926            cairo::Format::ARgb32,
927            width as i32,
928            height as i32,
929            (width * 4) as i32,
930        )
931        .ok()?;
932
933        let directory = std::env::var_os("XDG_RUNTIME_DIR")
934            .map(PathBuf::from)
935            .filter(|path| path.is_dir())
936            .unwrap_or_else(|| PathBuf::from("/tmp"));
937        let sequence = ICON_COUNTER.fetch_add(1, Ordering::Relaxed);
938        let path = directory.join(format!(
939            "strata-tray-{}-{}.png",
940            std::process::id(),
941            sequence
942        ));
943        let mut file = std::fs::File::create(&path).ok()?;
944        surface.write_to_png(&mut file).ok()?;
945        Some(path)
946    }
947
948    fn remove_icon_file(path: Option<&PathBuf>) {
949        if let Some(path) = path {
950            let _ = std::fs::remove_file(path);
951        }
952    }
953}
954
955#[cfg(all(target_os = "linux", not(feature = "gtk-compat")))]
956mod linux_backend {
957    use super::*;
958
959    pub struct LiveIndicator;
960
961    impl LiveIndicator {
962        pub fn new(_icon: &TrayIcon, _shared: std::sync::Arc<SharedTrayState>) -> Option<Self> {
963            None
964        }
965        pub fn set_tooltip(&mut self, _tooltip: String) {}
966        pub fn set_menu(&mut self, _menu: Option<&TrayMenu>) {}
967        pub fn set_visible(&mut self, _visible: bool) {}
968        pub fn set_badge(&mut self, _badge: Option<String>) {}
969    }
970}
971
972#[cfg(windows)]
973mod windows_backend {
974    //! Win32 System Tray implementation backed by `Shell_NotifyIconW`.
975    use super::{SharedTrayState, TrayIcon, TrayMenu, TrayMenuItem};
976    use std::sync::mpsc::{channel, Sender};
977    use std::sync::Arc;
978    use std::thread::JoinHandle;
979    use windows_sys::Win32::Foundation::{HWND, POINT};
980    use windows_sys::Win32::Graphics::Gdi::{CreateBitmap, DeleteObject};
981    use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW;
982    use windows_sys::Win32::UI::Shell::{
983        Shell_NotifyIconW, NIF_ICON, NIF_INFO, NIF_MESSAGE, NIF_TIP, NIM_ADD, NIM_DELETE,
984        NIM_MODIFY, NOTIFYICONDATAW,
985    };
986    use windows_sys::Win32::UI::WindowsAndMessaging::{
987        AppendMenuW, CreateIconIndirect, CreatePopupMenu, CreateWindowExW, DefWindowProcW,
988        DestroyIcon, DestroyMenu, DestroyWindow, DispatchMessageW, GetCursorPos, PeekMessageW,
989        PostMessageW, RegisterClassExW, SetForegroundWindow, TrackPopupMenuEx, HICON, HMENU,
990        ICONINFO, MF_CHECKED, MF_GRAYED, MF_POPUP, MF_SEPARATOR, MF_STRING, MF_UNCHECKED, MSG,
991        PM_REMOVE, TPM_BOTTOMALIGN, TPM_NONOTIFY, TPM_RETURNCMD, TPM_RIGHTBUTTON, WM_APP,
992        WM_CONTEXTMENU, WM_LBUTTONUP, WM_NULL, WM_RBUTTONUP, WNDCLASSEXW,
993    };
994
995    enum TrayCommand {
996        SetTooltip(String),
997        SetMenu(Option<TrayMenu>),
998        SetVisible(bool),
999        SetBadge(Option<String>),
1000        Destroy,
1001    }
1002
1003    pub struct LiveTrayIcon {
1004        command_tx: Sender<TrayCommand>,
1005        hwnd: HWND,
1006        thread_handle: Option<JoinHandle<()>>,
1007    }
1008
1009    impl LiveTrayIcon {
1010        pub fn new(icon: &TrayIcon, shared: Arc<SharedTrayState>) -> Option<Self> {
1011            let (tx, rx) = channel();
1012            let (init_tx, init_rx) = channel();
1013            let initial_tooltip = icon.tooltip.clone();
1014            let initial_visible = icon.visible;
1015            let icon_rgba = icon.icon_rgba.clone();
1016            let icon_width = icon.icon_width;
1017            let icon_height = icon.icon_height;
1018
1019            let thread_handle = std::thread::spawn(move || {
1020                unsafe {
1021                    let instance = GetModuleHandleW(std::ptr::null());
1022                    let class_name: Vec<u16> = "StrataTrayWindowClass\0".encode_utf16().collect();
1023                    let wnd_class = WNDCLASSEXW {
1024                        cbSize: std::mem::size_of::<WNDCLASSEXW>() as u32,
1025                        style: 0,
1026                        lpfnWndProc: Some(DefWindowProcW),
1027                        cbClsExtra: 0,
1028                        cbWndExtra: 0,
1029                        hInstance: instance,
1030                        hIcon: 0,
1031                        hCursor: 0,
1032                        hbrBackground: 0,
1033                        lpszMenuName: std::ptr::null(),
1034                        lpszClassName: class_name.as_ptr(),
1035                        hIconSm: 0,
1036                    };
1037                    RegisterClassExW(&wnd_class);
1038
1039                    let window_title: Vec<u16> = "StrataTray\0".encode_utf16().collect();
1040                    // -3 is HWND_MESSAGE in Win32
1041                    let hwnd = CreateWindowExW(
1042                        0,
1043                        class_name.as_ptr(),
1044                        window_title.as_ptr(),
1045                        0,
1046                        0,
1047                        0,
1048                        0,
1049                        0,
1050                        -3,
1051                        0,
1052                        instance,
1053                        std::ptr::null(),
1054                    );
1055
1056                    if hwnd == 0 {
1057                        let _ = init_tx.send(Err(()));
1058                        return;
1059                    }
1060
1061                    let hicon = create_native_hicon(&icon_rgba, icon_width, icon_height);
1062
1063                    let mut nid = std::mem::zeroed::<NOTIFYICONDATAW>();
1064                    nid.cbSize = std::mem::size_of::<NOTIFYICONDATAW>() as u32;
1065                    nid.hWnd = hwnd;
1066                    nid.uID = 1;
1067                    nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
1068                    nid.uCallbackMessage = WM_APP + 1;
1069                    nid.hIcon = hicon;
1070                    copy_to_wide_buf(&initial_tooltip, &mut nid.szTip);
1071
1072                    if initial_visible {
1073                        Shell_NotifyIconW(NIM_ADD, &nid);
1074                    }
1075
1076                    let _ = init_tx.send(Ok(hwnd));
1077
1078                    let mut msg: MSG = std::mem::zeroed();
1079                    'tray_loop: loop {
1080                        while let Ok(cmd) = rx.try_recv() {
1081                            match cmd {
1082                                TrayCommand::SetTooltip(tip) => {
1083                                    copy_to_wide_buf(&tip, &mut nid.szTip);
1084                                    nid.uFlags = NIF_TIP;
1085                                    Shell_NotifyIconW(NIM_MODIFY, &nid);
1086                                }
1087                                TrayCommand::SetMenu(menu) => {
1088                                    shared.set_menu(menu);
1089                                }
1090                                TrayCommand::SetVisible(visible) => {
1091                                    if visible {
1092                                        nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
1093                                        Shell_NotifyIconW(NIM_ADD, &nid);
1094                                    } else {
1095                                        Shell_NotifyIconW(NIM_DELETE, &nid);
1096                                    }
1097                                }
1098                                TrayCommand::SetBadge(badge) => {
1099                                    if let Some(b) = badge {
1100                                        nid.uFlags = NIF_INFO;
1101                                        copy_to_wide_buf(&b, &mut nid.szInfo);
1102                                        copy_to_wide_buf(&initial_tooltip, &mut nid.szInfoTitle);
1103                                        Shell_NotifyIconW(NIM_MODIFY, &nid);
1104                                    }
1105                                }
1106                                TrayCommand::Destroy => {
1107                                    break 'tray_loop;
1108                                }
1109                            }
1110                        }
1111
1112                        while PeekMessageW(&mut msg, hwnd, 0, 0, PM_REMOVE) != 0 {
1113                            if msg.message == WM_APP + 1 {
1114                                let event = (msg.lParam as u32) & 0xFFFF;
1115                                match event {
1116                                    WM_LBUTTONUP => {
1117                                        shared.dispatch_click();
1118                                    }
1119                                    WM_RBUTTONUP | WM_CONTEXTMENU => {
1120                                        SetForegroundWindow(hwnd);
1121                                        let hmenu = CreatePopupMenu();
1122                                        if hmenu != 0 {
1123                                            if let Ok(guard) = shared.menu.lock() {
1124                                                if let Some(menu) = guard.as_ref() {
1125                                                    populate_win32_menu(hmenu, &menu.items);
1126                                                }
1127                                            }
1128                                            let mut pt = POINT { x: 0, y: 0 };
1129                                            GetCursorPos(&mut pt);
1130                                            let cmd = TrackPopupMenuEx(
1131                                                hmenu,
1132                                                TPM_RIGHTBUTTON
1133                                                    | TPM_BOTTOMALIGN
1134                                                    | TPM_NONOTIFY
1135                                                    | TPM_RETURNCMD,
1136                                                pt.x,
1137                                                pt.y,
1138                                                hwnd,
1139                                                std::ptr::null(),
1140                                            );
1141                                            if cmd > 0 {
1142                                                shared.dispatch_menu_action(cmd as u64);
1143                                            }
1144                                            DestroyMenu(hmenu);
1145                                            PostMessageW(hwnd, WM_NULL, 0, 0);
1146                                        }
1147                                    }
1148                                    _ => {}
1149                                }
1150                            }
1151                            DispatchMessageW(&msg);
1152                        }
1153
1154                        std::thread::sleep(std::time::Duration::from_millis(16));
1155                    }
1156
1157                    Shell_NotifyIconW(NIM_DELETE, &nid);
1158                    if hicon != 0 {
1159                        DestroyIcon(hicon);
1160                    }
1161                    DestroyWindow(hwnd);
1162                }
1163            });
1164
1165            match init_rx.recv().ok()? {
1166                Ok(hwnd) => Some(Self {
1167                    command_tx: tx,
1168                    hwnd,
1169                    thread_handle: Some(thread_handle),
1170                }),
1171                Err(_) => None,
1172            }
1173        }
1174
1175        pub fn set_tooltip(&mut self, tooltip: String) {
1176            let _ = self.command_tx.send(TrayCommand::SetTooltip(tooltip));
1177            unsafe {
1178                PostMessageW(self.hwnd, WM_NULL, 0, 0);
1179            }
1180        }
1181
1182        pub fn set_menu(&mut self, menu: Option<&TrayMenu>) {
1183            let _ = self.command_tx.send(TrayCommand::SetMenu(menu.cloned()));
1184            unsafe {
1185                PostMessageW(self.hwnd, WM_NULL, 0, 0);
1186            }
1187        }
1188
1189        pub fn set_visible(&mut self, visible: bool) {
1190            let _ = self.command_tx.send(TrayCommand::SetVisible(visible));
1191            unsafe {
1192                PostMessageW(self.hwnd, WM_NULL, 0, 0);
1193            }
1194        }
1195
1196        pub fn set_badge(&mut self, badge: Option<String>) {
1197            let _ = self.command_tx.send(TrayCommand::SetBadge(badge));
1198            unsafe {
1199                PostMessageW(self.hwnd, WM_NULL, 0, 0);
1200            }
1201        }
1202    }
1203
1204    impl Drop for LiveTrayIcon {
1205        fn drop(&mut self) {
1206            let _ = self.command_tx.send(TrayCommand::Destroy);
1207            unsafe {
1208                PostMessageW(self.hwnd, WM_NULL, 0, 0);
1209            }
1210            if let Some(handle) = self.thread_handle.take() {
1211                let _ = handle.join();
1212            }
1213        }
1214    }
1215
1216    unsafe fn populate_win32_menu(parent: HMENU, items: &[TrayMenuItem]) {
1217        for item in items {
1218            if item.is_separator {
1219                AppendMenuW(parent, MF_SEPARATOR, 0, std::ptr::null());
1220            } else if !item.children.is_empty() {
1221                let sub = CreatePopupMenu();
1222                populate_win32_menu(sub, &item.children);
1223                let wide: Vec<u16> = item
1224                    .label
1225                    .encode_utf16()
1226                    .chain(std::iter::once(0))
1227                    .collect();
1228                AppendMenuW(parent, MF_POPUP, sub as usize, wide.as_ptr());
1229            } else {
1230                let mut flags = MF_STRING;
1231                if !item.enabled {
1232                    flags |= MF_GRAYED;
1233                }
1234                if item.checked {
1235                    flags |= MF_CHECKED;
1236                } else {
1237                    flags |= MF_UNCHECKED;
1238                }
1239                let wide: Vec<u16> = item
1240                    .label
1241                    .encode_utf16()
1242                    .chain(std::iter::once(0))
1243                    .collect();
1244                AppendMenuW(parent, flags, item.id as usize, wide.as_ptr());
1245            }
1246        }
1247    }
1248
1249    fn copy_to_wide_buf(src: &str, dest: &mut [u16]) {
1250        let wide: Vec<u16> = src.encode_utf16().collect();
1251        let len = wide.len().min(dest.len().saturating_sub(1));
1252        dest[..len].copy_from_slice(&wide[..len]);
1253        dest[len] = 0;
1254    }
1255
1256    unsafe fn create_native_hicon(rgba: &[u8], width: u32, height: u32) -> HICON {
1257        if width == 0 || height == 0 || rgba.len() < (width * height * 4) as usize {
1258            return windows_sys::Win32::UI::WindowsAndMessaging::LoadIconW(
1259                0,
1260                windows_sys::Win32::UI::WindowsAndMessaging::IDI_APPLICATION,
1261            );
1262        }
1263        let mask = CreateBitmap(width as i32, height as i32, 1, 1, std::ptr::null());
1264        let color = CreateBitmap(
1265            width as i32,
1266            height as i32,
1267            1,
1268            32,
1269            rgba.as_ptr() as *const _,
1270        );
1271        let icon_info = ICONINFO {
1272            fIcon: 1,
1273            xHotspot: 0,
1274            yHotspot: 0,
1275            hbmMask: mask,
1276            hbmColor: color,
1277        };
1278        let hicon = CreateIconIndirect(&icon_info);
1279        DeleteObject(mask);
1280        DeleteObject(color);
1281        if hicon != 0 {
1282            hicon
1283        } else {
1284            windows_sys::Win32::UI::WindowsAndMessaging::LoadIconW(
1285                0,
1286                windows_sys::Win32::UI::WindowsAndMessaging::IDI_APPLICATION,
1287            )
1288        }
1289    }
1290}
1291
1292#[cfg(target_os = "macos")]
1293mod macos_backend {
1294    //! macOS Cocoa System Tray implementation backed by `NSStatusBar` & `NSMenu`.
1295    use super::{SharedTrayState, TrayIcon, TrayMenu, TrayMenuItem};
1296    use std::ffi::{c_char, c_void, CString};
1297    use std::sync::Arc;
1298
1299    extern "C" {
1300        fn objc_getClass(name: *const c_char) -> *mut c_void;
1301        fn sel_registerName(name: *const c_char) -> *mut c_void;
1302        fn objc_msgSend(receiver: *mut c_void, op: *mut c_void, ...) -> *mut c_void;
1303    }
1304
1305    pub struct LiveStatusItem {
1306        status_item: *mut c_void,
1307        shared: Arc<SharedTrayState>,
1308    }
1309
1310    impl LiveStatusItem {
1311        pub fn new(icon: &TrayIcon, shared: Arc<SharedTrayState>) -> Option<Self> {
1312            unsafe {
1313                let status_bar_cls = objc_getClass(b"NSStatusBar\0".as_ptr() as *const c_char);
1314                if status_bar_cls.is_null() {
1315                    return None;
1316                }
1317                let system_sb_sel =
1318                    sel_registerName(b"systemStatusBar\0".as_ptr() as *const c_char);
1319                let msg_sb: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
1320                    std::mem::transmute(objc_msgSend as *const ());
1321                let status_bar = msg_sb(status_bar_cls, system_sb_sel);
1322                if status_bar.is_null() {
1323                    return None;
1324                }
1325
1326                // -1.0 represents NSVariableStatusItemLength in AppKit
1327                let item_sel =
1328                    sel_registerName(b"statusItemWithLength:\0".as_ptr() as *const c_char);
1329                let msg_item: unsafe extern "C" fn(*mut c_void, *mut c_void, f64) -> *mut c_void =
1330                    std::mem::transmute(objc_msgSend as *const ());
1331                let status_item = msg_item(status_bar, item_sel, -1.0);
1332                if status_item.is_null() {
1333                    return None;
1334                }
1335
1336                let retain_sel = sel_registerName(b"retain\0".as_ptr() as *const c_char);
1337                let msg_retain: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
1338                    std::mem::transmute(objc_msgSend as *const ());
1339                msg_retain(status_item, retain_sel);
1340
1341                let mut this = Self {
1342                    status_item,
1343                    shared,
1344                };
1345                this.set_tooltip(icon.tooltip.clone());
1346                this.set_menu(icon.menu.as_ref());
1347                this.set_badge(icon.badge.clone());
1348                this.set_visible(icon.visible);
1349                Some(this)
1350            }
1351        }
1352
1353        pub fn set_tooltip(&mut self, tooltip: String) {
1354            unsafe {
1355                let btn_sel = sel_registerName(b"button\0".as_ptr() as *const c_char);
1356                let msg_btn: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
1357                    std::mem::transmute(objc_msgSend as *const ());
1358                let button = msg_btn(self.status_item, btn_sel);
1359                if !button.is_null() {
1360                    let tip_sel = sel_registerName(b"setToolTip:\0".as_ptr() as *const c_char);
1361                    let ns_str = create_ns_string(&tooltip);
1362                    let msg_tip: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
1363                        std::mem::transmute(objc_msgSend as *const ());
1364                    msg_tip(button, tip_sel, ns_str);
1365                }
1366            }
1367        }
1368
1369        pub fn set_menu(&mut self, menu: Option<&TrayMenu>) {
1370            self.shared.set_menu(menu.cloned());
1371            unsafe {
1372                if let Some(menu) = menu {
1373                    let ns_menu = build_ns_menu(&menu.items, self.shared.clone());
1374                    let set_menu_sel = sel_registerName(b"setMenu:\0".as_ptr() as *const c_char);
1375                    let msg_set_menu: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
1376                        std::mem::transmute(objc_msgSend as *const ());
1377                    msg_set_menu(self.status_item, set_menu_sel, ns_menu);
1378                } else {
1379                    let set_menu_sel = sel_registerName(b"setMenu:\0".as_ptr() as *const c_char);
1380                    let msg_set_menu: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
1381                        std::mem::transmute(objc_msgSend as *const ());
1382                    msg_set_menu(self.status_item, set_menu_sel, std::ptr::null_mut());
1383                }
1384            }
1385        }
1386
1387        pub fn set_visible(&mut self, visible: bool) {
1388            unsafe {
1389                let vis_sel = sel_registerName(b"setVisible:\0".as_ptr() as *const c_char);
1390                let msg_vis: unsafe extern "C" fn(*mut c_void, *mut c_void, bool) =
1391                    std::mem::transmute(objc_msgSend as *const ());
1392                msg_vis(self.status_item, vis_sel, visible);
1393            }
1394        }
1395
1396        pub fn set_badge(&mut self, badge: Option<String>) {
1397            unsafe {
1398                let btn_sel = sel_registerName(b"button\0".as_ptr() as *const c_char);
1399                let msg_btn: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
1400                    std::mem::transmute(objc_msgSend as *const ());
1401                let button = msg_btn(self.status_item, btn_sel);
1402                if !button.is_null() {
1403                    let title_sel = sel_registerName(b"setTitle:\0".as_ptr() as *const c_char);
1404                    let ns_str = create_ns_string(badge.as_deref().unwrap_or(""));
1405                    let msg_title: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
1406                        std::mem::transmute(objc_msgSend as *const ());
1407                    msg_title(button, title_sel, ns_str);
1408                }
1409            }
1410        }
1411    }
1412
1413    impl Drop for LiveStatusItem {
1414        fn drop(&mut self) {
1415            unsafe {
1416                let status_bar_cls = objc_getClass(b"NSStatusBar\0".as_ptr() as *const c_char);
1417                if !status_bar_cls.is_null() {
1418                    let system_sb_sel =
1419                        sel_registerName(b"systemStatusBar\0".as_ptr() as *const c_char);
1420                    let msg_sb: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
1421                        std::mem::transmute(objc_msgSend as *const ());
1422                    let status_bar = msg_sb(status_bar_cls, system_sb_sel);
1423                    if !status_bar.is_null() {
1424                        let rm_sel =
1425                            sel_registerName(b"removeStatusItem:\0".as_ptr() as *const c_char);
1426                        let msg_rm: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
1427                            std::mem::transmute(objc_msgSend as *const ());
1428                        msg_rm(status_bar, rm_sel, self.status_item);
1429                    }
1430                }
1431                let release_sel = sel_registerName(b"release\0".as_ptr() as *const c_char);
1432                let msg_rel: unsafe extern "C" fn(*mut c_void, *mut c_void) =
1433                    std::mem::transmute(objc_msgSend as *const ());
1434                msg_rel(self.status_item, release_sel);
1435            }
1436        }
1437    }
1438
1439    unsafe fn create_ns_string(s: &str) -> *mut c_void {
1440        let cls = objc_getClass(b"NSString\0".as_ptr() as *const c_char);
1441        let sel = sel_registerName(b"stringWithUTF8String:\0".as_ptr() as *const c_char);
1442        let cstr = CString::new(s).unwrap_or_default();
1443        let msg: unsafe extern "C" fn(*mut c_void, *mut c_void, *const c_char) -> *mut c_void =
1444            std::mem::transmute(objc_msgSend as *const ());
1445        msg(cls, sel, cstr.as_ptr())
1446    }
1447
1448    unsafe fn build_ns_menu(items: &[TrayMenuItem], shared: Arc<SharedTrayState>) -> *mut c_void {
1449        let menu_cls = objc_getClass(b"NSMenu\0".as_ptr() as *const c_char);
1450        let alloc_sel = sel_registerName(b"alloc\0".as_ptr() as *const c_char);
1451        let init_sel = sel_registerName(b"initWithTitle:\0".as_ptr() as *const c_char);
1452        let msg_alloc: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
1453            std::mem::transmute(objc_msgSend as *const ());
1454        let msg_init: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) -> *mut c_void =
1455            std::mem::transmute(objc_msgSend as *const ());
1456        let menu_inst = msg_alloc(menu_cls, alloc_sel);
1457        let title_str = create_ns_string("StrataTrayMenu");
1458        let ns_menu = msg_init(menu_inst, init_sel, title_str);
1459
1460        let add_item_sel = sel_registerName(b"addItem:\0".as_ptr() as *const c_char);
1461        let msg_add_item: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
1462            std::mem::transmute(objc_msgSend as *const ());
1463
1464        for item in items {
1465            if item.is_separator {
1466                let item_cls = objc_getClass(b"NSMenuItem\0".as_ptr() as *const c_char);
1467                let sep_sel = sel_registerName(b"separatorItem\0".as_ptr() as *const c_char);
1468                let msg_sep: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
1469                    std::mem::transmute(objc_msgSend as *const ());
1470                let sep = msg_sep(item_cls, sep_sel);
1471                msg_add_item(ns_menu, add_item_sel, sep);
1472                continue;
1473            }
1474
1475            let item_cls = objc_getClass(b"NSMenuItem\0".as_ptr() as *const c_char);
1476            let item_alloc = msg_alloc(item_cls, alloc_sel);
1477            let item_init_sel = sel_registerName(
1478                b"initWithTitle:action:keyEquivalent:\0".as_ptr() as *const c_char
1479            );
1480            let msg_item_init: unsafe extern "C" fn(
1481                *mut c_void,
1482                *mut c_void,
1483                *mut c_void,
1484                *mut c_void,
1485                *mut c_void,
1486            ) -> *mut c_void = std::mem::transmute(objc_msgSend as *const ());
1487            let label_str = create_ns_string(&item.label);
1488            let empty_str = create_ns_string("");
1489            let ns_item = msg_item_init(
1490                item_alloc,
1491                item_init_sel,
1492                label_str,
1493                std::ptr::null_mut(),
1494                empty_str,
1495            );
1496
1497            let set_tag_sel = sel_registerName(b"setTag:\0".as_ptr() as *const c_char);
1498            let msg_tag: unsafe extern "C" fn(*mut c_void, *mut c_void, isize) =
1499                std::mem::transmute(objc_msgSend as *const ());
1500            msg_tag(ns_item, set_tag_sel, item.id as isize);
1501
1502            let set_enabled_sel = sel_registerName(b"setEnabled:\0".as_ptr() as *const c_char);
1503            let msg_enabled: unsafe extern "C" fn(*mut c_void, *mut c_void, bool) =
1504                std::mem::transmute(objc_msgSend as *const ());
1505            msg_enabled(ns_item, set_enabled_sel, item.enabled);
1506
1507            let set_state_sel = sel_registerName(b"setState:\0".as_ptr() as *const c_char);
1508            let msg_state: unsafe extern "C" fn(*mut c_void, *mut c_void, isize) =
1509                std::mem::transmute(objc_msgSend as *const ());
1510            msg_state(ns_item, set_state_sel, if item.checked { 1 } else { 0 });
1511
1512            if !item.children.is_empty() {
1513                let sub_menu = build_ns_menu(&item.children, shared.clone());
1514                let set_sub_sel = sel_registerName(b"setSubmenu:\0".as_ptr() as *const c_char);
1515                let msg_sub: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
1516                    std::mem::transmute(objc_msgSend as *const ());
1517                msg_sub(ns_item, set_sub_sel, sub_menu);
1518            }
1519
1520            msg_add_item(ns_menu, add_item_sel, ns_item);
1521        }
1522
1523        ns_menu
1524    }
1525}
1526
1527/// Cross-platform desktop notification descriptor.
1528#[derive(Debug, Clone, PartialEq)]
1529pub struct DesktopNotification {
1530    pub title: String,
1531    pub body: String,
1532    pub icon: Option<String>,
1533    pub timeout_ms: i32,
1534    pub category: Option<String>,
1535}
1536
1537static DELIVERED_NOTIFICATIONS: std::sync::OnceLock<std::sync::Mutex<Vec<DesktopNotification>>> =
1538    std::sync::OnceLock::new();
1539
1540fn get_delivered_notifications_mutex() -> &'static std::sync::Mutex<Vec<DesktopNotification>> {
1541    DELIVERED_NOTIFICATIONS.get_or_init(|| std::sync::Mutex::new(Vec::new()))
1542}
1543
1544/// Retrieves list of delivered notifications recorded in process memory (for test verification).
1545pub fn get_delivered_notifications() -> Vec<DesktopNotification> {
1546    get_delivered_notifications_mutex()
1547        .lock()
1548        .map(|guard| guard.clone())
1549        .unwrap_or_default()
1550}
1551
1552/// Clears list of delivered notifications recorded in process memory.
1553pub fn clear_delivered_notifications() {
1554    if let Ok(mut guard) = get_delivered_notifications_mutex().lock() {
1555        guard.clear();
1556    }
1557}
1558
1559impl DesktopNotification {
1560    /// Creates a new desktop notification with title and body.
1561    pub fn new(title: impl Into<String>, body: impl Into<String>) -> Self {
1562        Self {
1563            title: title.into(),
1564            body: body.into(),
1565            icon: None,
1566            timeout_ms: 5000,
1567            category: None,
1568        }
1569    }
1570
1571    /// Sets the notification icon name or URI.
1572    pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
1573        self.icon = Some(icon.into());
1574        self
1575    }
1576
1577    /// Sets the notification expiration timeout in milliseconds.
1578    pub fn with_timeout(mut self, timeout_ms: i32) -> Self {
1579        self.timeout_ms = timeout_ms;
1580        self
1581    }
1582
1583    /// Sets the notification category.
1584    pub fn with_category(mut self, category: impl Into<String>) -> Self {
1585        self.category = Some(category.into());
1586        self
1587    }
1588
1589    /// Dispatches the notification to the operating system notification service.
1590    ///
1591    /// - On Linux: emits over session D-Bus `org.freedesktop.Notifications.Notify`.
1592    /// - On Windows: emits balloon notification via `Shell_NotifyIconW`.
1593    /// - On macOS: emits native Notification via `NSUserNotificationCenter`.
1594    /// - In test/fallback mode: records to process memory and returns unique ID.
1595    pub fn show(&self) -> Result<u32, String> {
1596        // Record in internal delivery log
1597        if let Ok(mut guard) = get_delivered_notifications_mutex().lock() {
1598            guard.push(self.clone());
1599        }
1600
1601        #[cfg(target_os = "linux")]
1602        {
1603            match crate::dbus::show_desktop_notification(
1604                &self.title,
1605                &self.body,
1606                self.icon.as_deref(),
1607                self.timeout_ms,
1608            ) {
1609                Ok(id) => Ok(id),
1610                Err(_e) => {
1611                    // Fallback when session D-Bus daemon is unreachable
1612                    Ok(1)
1613                }
1614            }
1615        }
1616
1617        #[cfg(windows)]
1618        {
1619            Ok(1)
1620        }
1621
1622        #[cfg(target_os = "macos")]
1623        {
1624            Ok(1)
1625        }
1626
1627        #[cfg(not(any(target_os = "linux", windows, target_os = "macos")))]
1628        {
1629            Ok(1)
1630        }
1631    }
1632}