1
//! System tray / status icon  -  platform-agnostic model.
2
//!
3
//! The actual OS plumbing lives in `azul-dll` (`desktop/tray/`). This module
4
//! only defines the data the three backends agree on.
5
//!
6
//! # Why the API has this shape
7
//!
8
//! The three platforms share almost nothing below the "icon + retained menu
9
//! tree" level, and two of their constraints leak into any honest API:
10
//!
11
//! 1. **On Linux the menu is not a popup  -  it is a remote model.** SNI's `Menu` property points
12
//!    at a `com.canonical.dbusmenu` object, and the *panel* draws the menu, calling back into us
13
//!    with `GetLayout` / `AboutToShow`. So the menu must be a RETAINED tree with stable ids and a
14
//!    revision counter. An API shaped as `show_context_menu_at(x, y)` cannot be implemented on
15
//!    Linux and would have to be redone  -  hence [`TrayIconData::menu`] is state, not a call.
16
//!
17
//! 2. **`ContextMenu` is a REQUEST, not a command.** On Linux the panel may open the menu itself
18
//!    and never tell us; on Windows and macOS we open it. Callers must not assume their handler is
19
//!    the only thing that runs.
20
//!
21
//! Two more platform truths that the API deliberately does NOT hide:
22
//!
23
//! * **A tray may genuinely not exist.** On a vanilla GNOME there is no
24
//!   `org.kde.StatusNotifierWatcher` at all: registration fails silently and no icon ever appears.
25
//!   [`TrayIconData`] is therefore accepted on a best-effort basis and the app must have a story
26
//!   for "no tray"  -  see `App::tray_available()` in azul-dll.
27
//! * **Click semantics differ.** The SNI spec does not say which gesture activates an item; some
28
//!   desktops use single left click, some double. Never document a precise gesture for
29
//!   [`TrayEventType::Activate`].
30

            
31
use alloc::{string::String, vec::Vec};
32

            
33
use azul_css::{corety::U8Vec, AzString, OptionString};
34

            
35
use crate::{
36
    menu::{Menu, OptionMenu},
37
    window::IconKey,
38
};
39

            
40
/// RGBA8 image for a tray icon, at one specific size.
41
///
42
/// Unlike [`crate::window::WindowIcon`], which is fixed at 16x16 / 32x32, a
43
/// tray icon needs arbitrary sizes: Windows wants
44
/// `GetSystemMetricsForDpi(SM_CXSMICON)` (16 / 20 / 24 / 32 px as the taskbar's
45
/// DPI changes), macOS wants an 18x18 *point* template image (so 36x36 px on a
46
/// 2x display), and SNI wants an array of whatever sizes we care to publish so
47
/// the panel can pick.
48
///
49
/// `rgba` is straight, non-premultiplied RGBA8, `width * height * 4` bytes, top
50
/// row first. Every backend converts from this one representation:
51
/// Windows builds a BGRA `HBITMAP` + mask, macOS an `NSBitmapImageRep`, and
52
/// Linux byte-swaps to the ARGB32-big-endian that `IconPixmap` requires.
53
#[derive(Debug, Clone)]
54
#[repr(C)]
55
pub struct TrayIconImage {
56
    /// Cache key  -  lets a backend skip re-uploading an unchanged icon.
57
    pub key: IconKey,
58
    pub width: u32,
59
    pub height: u32,
60
    pub rgba: U8Vec,
61
}
62

            
63
impl PartialEq for TrayIconImage {
64
    fn eq(&self, other: &Self) -> bool {
65
        self.key == other.key
66
    }
67
}
68
impl Eq for TrayIconImage {}
69

            
70
impl TrayIconImage {
71
    /// `rgba` must be exactly `width * height * 4` bytes; returns `None`
72
    /// otherwise.
73
    ///
74
    /// Returns `OptionTrayIconImage` rather than `Option<Self>` so the
75
    /// signature crosses the C ABI unchanged.
76
    #[must_use]
77
    #[allow(
78
        clippy::new_ret_no_self,
79
        reason = "C-ABI: must return OptionTrayIconImage"
80
    )]
81
9
    pub fn new(width: u32, height: u32, rgba: U8Vec) -> OptionTrayIconImage {
82
9
        if width == 0 || height == 0 {
83
2
            return OptionTrayIconImage::None;
84
7
        }
85
7
        let Some(expected) = (width as usize)
86
7
            .checked_mul(height as usize)
87
7
            .and_then(|n| n.checked_mul(4))
88
        else {
89
            return OptionTrayIconImage::None;
90
        };
91
7
        if rgba.as_ref().len() != expected {
92
2
            return OptionTrayIconImage::None;
93
5
        }
94
5
        OptionTrayIconImage::Some(Self {
95
5
            key: IconKey::new(),
96
5
            width,
97
5
            height,
98
5
            rgba,
99
5
        })
100
9
    }
101

            
102
    /// The icon's pixels as ARGB32 in **network (big-endian) byte order**, the
103
    /// wire format `org.kde.StatusNotifierItem`'s `IconPixmap` (`a(iiay)`)
104
    /// requires. Nothing else uses this layout, so it is computed on demand.
105
    #[must_use]
106
1
    pub fn to_argb32_be(&self) -> U8Vec {
107
1
        let src = self.rgba.as_ref();
108
1
        let mut out = Vec::with_capacity(src.len());
109
1
        for px in src.chunks_exact(4) {
110
1
            // RGBA -> ARGB, big-endian == [A, R, G, B] in memory order.
111
1
            out.extend_from_slice(&[px[3], px[0], px[1], px[2]]);
112
1
        }
113
1
        U8Vec::from_vec(out)
114
1
    }
115
}
116

            
117
impl_option!(
118
    TrayIconImage,
119
    OptionTrayIconImage,
120
    copy = false,
121
    [Debug, Clone, PartialEq, Eq]
122
);
123

            
124
impl_vec!(
125
    TrayIconImage,
126
    TrayIconImageVec,
127
    TrayIconImageVecDestructor,
128
    TrayIconImageVecDestructorType,
129
    TrayIconImageVecSlice,
130
    OptionTrayIconImage
131
);
132
impl_vec_debug!(TrayIconImage, TrayIconImageVec);
133
impl_vec_clone!(TrayIconImage, TrayIconImageVec, TrayIconImageVecDestructor);
134
impl_vec_partialeq!(TrayIconImage, TrayIconImageVec);
135

            
136
/// Where a tray icon's pixels come from.
137
#[derive(Debug, Clone, PartialEq)]
138
#[repr(C, u8)]
139
#[derive(Default)]
140
pub enum TrayIconSource {
141
    /// No icon. Most desktops render this as an invisible item, so it is
142
    /// almost never what you want.
143
    #[default]
144
    None,
145
    /// Explicit RGBA bitmaps, ideally at several sizes so each platform can
146
    /// pick  -  see [`TrayIconData::best_icon`].
147
    ///
148
    /// Only needed for an icon that genuinely is not in a pack  -  typically one
149
    /// generated at runtime, since the icon registry is frozen once the
150
    /// provider is shared (`App::run` consumes the handle).
151
    Rgba(TrayIconImageVec),
152
    /// An **icon spec**  -  exactly the string an `<icon>` node takes: a bare
153
    /// name (`"settings"`), a pack-qualified name (`"mypack:logo"`), or a
154
    /// comma-separated fallback list (`"mypack:logo, settings"`).
155
    ///
156
    /// This is the preferred form, for two reasons.
157
    ///
158
    /// It resolves through the SAME registry and resolver `<icon>` DOM nodes
159
    /// use, so anything registered there works with no tray-specific icon
160
    /// path: Material Icons (the default pack), an image pack loaded from a
161
    /// ZIP, or a custom resolver. Because resolution yields a `StyledDom`
162
    /// which is then
163
    /// rendered, an icon can be anything expressible as a DOM: a font glyph, a
164
    /// bitmap, later an SVG or an emoji.
165
    ///
166
    /// And a spec can be rendered at ANY size on demand, which a fixed bitmap
167
    /// cannot: a tray needs the same icon at several sizes and cannot know
168
    /// them up front (Windows re-asks at every taskbar DPI: 16/20/24/32; macOS
169
    /// wants 18pt, which is 36px on a 2x display; SNI publishes an array).
170
    Named(AzString),
171
}
172

            
173
/// Hint about what the tray item represents. Maps to SNI's `Category`; Windows
174
/// and macOS have no equivalent and ignore it.
175
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
176
#[repr(C)]
177
#[derive(Default)]
178
pub enum TrayCategory {
179
    #[default]
180
    ApplicationStatus,
181
    Communications,
182
    SystemServices,
183
    Hardware,
184
}
185

            
186
impl TrayCategory {
187
    /// The exact string the SNI `Category` property expects.
188
    #[must_use]
189
2
    pub const fn sni_name(self) -> &'static str {
190
2
        match self {
191
1
            Self::ApplicationStatus => "ApplicationStatus",
192
            Self::Communications => "Communications",
193
1
            Self::SystemServices => "SystemServices",
194
            Self::Hardware => "Hardware",
195
        }
196
2
    }
197
}
198

            
199
/// Attention state. Maps to SNI's `Status`.
200
///
201
/// On Windows and macOS only `Passive` is meaningful (it hides the icon);
202
/// `Active` and `NeedsAttention` both simply show it, because neither platform
203
/// has a "demanding attention" tray state.
204
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
205
#[repr(C)]
206
#[derive(Default)]
207
pub enum TrayStatus {
208
    /// The host MAY hide the item.
209
    Passive,
210
    #[default]
211
    Active,
212
    /// Draws attention; SNI hosts swap in `AttentionIcon`.
213
    NeedsAttention,
214
}
215

            
216
impl TrayStatus {
217
    #[must_use]
218
2
    pub const fn sni_name(self) -> &'static str {
219
2
        match self {
220
1
            Self::Passive => "Passive",
221
            Self::Active => "Active",
222
1
            Self::NeedsAttention => "NeedsAttention",
223
        }
224
2
    }
225
}
226

            
227
/// What the user did to the tray icon.
228
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
229
#[repr(C)]
230
pub enum TrayEventType {
231
    /// Primary activation. **Do not document a precise gesture**: it is left
232
    /// click or keyboard Enter on Windows, a click on macOS, and entirely
233
    /// desktop-dependent on Linux (the SNI spec does not specify it).
234
    Activate,
235
    /// Middle click on Windows/Linux; not emitted on macOS.
236
    SecondaryActivate,
237
    /// The user asked for the context menu. On Windows and macOS we then open
238
    /// it; **on Linux the panel already opened it itself** from the exported
239
    /// dbusmenu, so this is informational there.
240
    ContextMenu,
241
    /// Scroll wheel over the icon. Linux only (SNI `Scroll`); Windows and
242
    /// macOS never emit it.
243
    Scroll,
244
    /// A menu item was chosen. Carries the item's command id.
245
    MenuItem,
246
}
247

            
248
/// Scroll axis for [`TrayEventType::Scroll`].
249
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
250
#[repr(C)]
251
#[derive(Default)]
252
pub enum TrayScrollAxis {
253
    #[default]
254
    Vertical,
255
    Horizontal,
256
}
257

            
258
/// One thing that happened on the tray icon.
259
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
260
#[repr(C)]
261
pub struct TrayEvent {
262
    pub kind: TrayEventType,
263
    /// Set for [`TrayEventType::MenuItem`]; the chosen item's command id.
264
    pub menu_command: u32,
265
    /// Set for [`TrayEventType::Scroll`].
266
    pub scroll_delta: i32,
267
    pub scroll_axis: TrayScrollAxis,
268
}
269

            
270
impl TrayEvent {
271
    #[must_use]
272
    pub const fn simple(kind: TrayEventType) -> Self {
273
        Self {
274
            kind,
275
            menu_command: 0,
276
            scroll_delta: 0,
277
            scroll_axis: TrayScrollAxis::Vertical,
278
        }
279
    }
280
    #[must_use]
281
    pub const fn menu_item(command: u32) -> Self {
282
        Self {
283
            kind: TrayEventType::MenuItem,
284
            menu_command: command,
285
            scroll_delta: 0,
286
            scroll_axis: TrayScrollAxis::Vertical,
287
        }
288
    }
289
}
290

            
291
impl_option!(
292
    TrayEvent,
293
    OptionTrayEvent,
294
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
295
);
296

            
297
/// Everything a tray icon shows.
298
///
299
/// This is *state*: set it, mutate it, and the backend republishes. It is
300
/// deliberately not a set of imperative calls, because the Linux backend has
301
/// to be able to answer the panel's `GetLayout` at any moment.
302
#[derive(Debug, Clone, PartialEq)]
303
#[repr(C)]
304
pub struct TrayIconData {
305
    /// Stable identifier for this app's tray item. Used as SNI's `Id`, and as
306
    /// the seed for macOS's `NSStatusItem.autosaveName` (which is what makes
307
    /// the item keep its position in the menu bar across launches).
308
    ///
309
    /// Must be stable across runs and must NOT be derived from a path or pid.
310
    /// Reverse-DNS is the convention: `"org.example.myapp"`.
311
    pub id: AzString,
312
    /// Human-readable application name (SNI `Title`).
313
    pub title: AzString,
314
    /// Where the icon's pixels come from  -  a named icon-pack entry (preferred)
315
    /// or explicit RGBA bitmaps.
316
    pub icon: TrayIconSource,
317
    /// Shown when `status == NeedsAttention` on SNI hosts. Ignored elsewhere.
318
    pub attention_icon: TrayIconSource,
319
    pub tooltip: OptionString,
320
    pub category: TrayCategory,
321
    pub status: TrayStatus,
322
    /// The retained context menu. `None` means "no menu": on Windows and macOS
323
    /// a context-menu request then just reports [`TrayEventType::ContextMenu`],
324
    /// and on Linux the `Menu` property is left unset and hosts fall back to
325
    /// calling `ContextMenu()`.
326
    pub menu: OptionMenu,
327
}
328

            
329
impl Default for TrayIconData {
330
6
    fn default() -> Self {
331
6
        Self {
332
6
            id: AzString::from_const_str("azul.tray"),
333
6
            title: AzString::from_const_str(""),
334
6
            icon: TrayIconSource::None,
335
6
            attention_icon: TrayIconSource::None,
336
6
            tooltip: OptionString::None,
337
6
            category: TrayCategory::ApplicationStatus,
338
6
            status: TrayStatus::Active,
339
6
            menu: OptionMenu::None,
340
6
        }
341
6
    }
342
}
343

            
344
impl TrayIconData {
345
    #[must_use]
346
3
    pub fn new(id: AzString, title: AzString) -> Self {
347
3
        Self {
348
3
            id,
349
3
            title,
350
3
            ..Self::default()
351
3
        }
352
3
    }
353

            
354
    /// Use an icon from the icon registry, by the same spec an `<icon>` node
355
    /// takes  -  `"settings"`, `"mypack:logo"`, or a fallback list. Preferred:
356
    /// it renders at whatever size each platform asks for.
357
    #[must_use]
358
4
    pub fn with_named_icon(mut self, spec: AzString) -> Self {
359
4
        self.icon = TrayIconSource::Named(spec);
360
4
        self
361
4
    }
362

            
363
    /// Use an explicit RGBA bitmap. Prefer [`Self::with_named_icon`] unless the
364
    /// icon genuinely is not in a pack.
365
    #[must_use]
366
    pub fn with_icon(mut self, icon: TrayIconImage) -> Self {
367
        self.icon = TrayIconSource::Rgba(TrayIconImageVec::from_vec(alloc::vec![icon]));
368
        self
369
    }
370

            
371
    #[must_use]
372
    pub fn with_menu(mut self, menu: Menu) -> Self {
373
        self.menu = OptionMenu::Some(menu);
374
        self
375
    }
376

            
377
    #[must_use]
378
    pub fn with_tooltip(mut self, tooltip: AzString) -> Self {
379
        self.tooltip = OptionString::Some(tooltip);
380
        self
381
    }
382

            
383
    /// The icon closest to `target_px`, preferring the smallest one that is at
384
    /// least `target_px` (upscaling a small icon looks far worse than
385
    /// downscaling a large one  -  this is why Windows' own `LoadIconMetric`
386
    /// scales down from a larger frame rather than up).
387
    /// Only meaningful for [`TrayIconSource::Rgba`]; a `Named` icon is
388
    /// rasterized at the exact size instead, so it never needs picking.
389
    ///
390
    /// Returns an owned `OptionTrayIconImage` rather than `Option<&_>` because
391
    /// a borrow cannot cross the C ABI. The clone is one `U8Vec` bump.
392
    #[must_use]
393
5
    pub fn best_icon(&self, target_px: u32) -> OptionTrayIconImage {
394
5
        let TrayIconSource::Rgba(ref icons) = self.icon else {
395
2
            return OptionTrayIconImage::None;
396
        };
397
3
        let icons = icons.as_ref();
398
3
        icons
399
3
            .iter()
400
9
            .filter(|i| i.width >= target_px)
401
3
            .min_by_key(|i| i.width)
402
3
            .or_else(|| icons.iter().max_by_key(|i| i.width))
403
3
            .cloned()
404
3
            .into()
405
5
    }
406
}
407

            
408
#[cfg(test)]
409
#[path = "tray_test.rs"]
410
mod tray_test;