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