1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
// Copyright 2022-2022 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

#![allow(clippy::uninlined_format_args)]

//! tray-icon lets you create tray icons for desktop applications.
//!
//! # Platforms supported:
//!
//! - Windows
//! - macOS
//! - Linux (gtk Only)
//!
//! # Platform-specific notes:
//!
//! - On Windows and Linux, an event loop must be running on the thread, on Windows, a win32 event loop and on Linux, a gtk event loop. It doesn't need to be the main thread but you have to create the tray icon on the same thread as the event loop.
//! - On macOS, an event loop must be running on the main thread so you also need to create the tray icon on the main thread.
//!
//! # Dependencies (Linux Only)
//!
//! On Linux, `gtk`, `libxdo` is used to make the predfined `Copy`, `Cut`, `Paste` and `SelectAll` menu items work and `libappindicator` or `libayatnat-appindicator` are used to create the tray icon, so make sure to install them on your system.
//!
//! #### Arch Linux / Manjaro:
//!
//! ```sh
//! pacman -S gtk3 xdotool libappindicator-gtk3 #or libayatana-appindicator
//! ```
//!
//! #### Debian / Ubuntu:
//!
//! ```sh
//! sudo apt install libgtk-3-dev libxdo-dev libappindicator3-dev #or libayatana-appindicator3-dev
//! ```
//!
//! # Examples
//!
//! #### Create a tray icon without a menu.
//!
//! ```no_run
//! use tray_icon_ex::{TrayIconBuilder, Icon};
//!
//! # let icon = Icon::from_rgba(Vec::new(), 0, 0).unwrap();
//! let tray_icon = TrayIconBuilder::new()
//!     .with_tooltip("system-tray - tray icon library!")
//!     .with_icon(icon)
//!     .build()
//!     .unwrap();
//! ```
//!
//! #### Create a tray icon with a menu.
//!
//! ```no_run
//! use tray_icon_ex::{TrayIconBuilder, menu::Menu,Icon};
//!
//! # let icon = Icon::from_rgba(Vec::new(), 0, 0).unwrap();
//! let tray_menu = Menu::new();
//! let tray_icon = TrayIconBuilder::new()
//!     .with_menu(Box::new(tray_menu))
//!     .with_tooltip("system-tray - tray icon library!")
//!     .with_icon(icon)
//!     .build()
//!     .unwrap();
//! ```
//!
//! # Processing tray events
//!
//! You can use [`TrayIconEvent::receiver`] to get a reference to the [`TrayIconEventReceiver`]
//! which you can use to listen to events when a click happens on the tray icon
//! ```no_run
//! use tray_icon_ex::TrayIconEvent;
//!
//! if let Ok(event) = TrayIconEvent::receiver().try_recv() {
//!     println!("{:?}", event);
//! }
//! ```
//!
//! You can also listen for the menu events using [`MenuEvent::receiver`](crate::menu::MenuEvent::receiver) to get events for the tray context menu.
//!
//! ```no_run
//! use tray_icon_ex::{TrayIconEvent, menu::MenuEvent};
//!
//! if let Ok(event) = TrayIconEvent::receiver().try_recv() {
//!     println!("tray event: {:?}", event);
//! }
//!
//! if let Ok(event) = MenuEvent::receiver().try_recv() {
//!     println!("menu event: {:?}", event);
//! }
//! ```

use std::{
    cell::RefCell,
    path::{Path, PathBuf},
    rc::Rc,
};

use counter::Counter;
use crossbeam_channel::{unbounded, Receiver, Sender};
use once_cell::sync::{Lazy, OnceCell};

mod counter;
mod error;
mod icon;
mod platform_impl;
mod tray_icon_id;

pub use self::error::*;
pub use self::icon::{BadIcon, Icon};
pub use self::tray_icon_id::TrayIconId;

/// Re-export of [muda](::muda) crate and used for tray context menu.
pub mod menu {
    pub use muda::*;
}

static COUNTER: Counter = Counter::new();

/// Attributes to use when creating a tray icon.
pub struct TrayIconAttributes {
    /// Tray icon tooltip
    ///
    /// ## Platform-specific:
    ///
    /// - **Linux:** Unsupported.
    pub tooltip: Option<String>,

    /// Tray menu
    ///
    /// ## Platform-specific:
    ///
    /// - **Linux**: once a menu is set, it cannot be removed.
    pub menu: Option<Box<dyn menu::ContextMenu>>,

    /// Tray icon
    ///
    /// ## Platform-specific:
    ///
    /// - **Linux:** Sometimes the icon won't be visible unless a menu is set.
    ///     Setting an empty [`Menu`](crate::menu::Menu) is enough.
    pub icon: Option<Icon>,

    /// Tray icon temp dir path. **Linux only**.
    pub temp_dir_path: Option<PathBuf>,

    /// Use the icon as a [template](https://developer.apple.com/documentation/appkit/nsimage/1520017-template?language=objc). **macOS only**.
    pub icon_is_template: bool,

    /// Whether to show the tray menu on left click or not, default is `true`. **macOS only**.
    pub menu_on_left_click: bool,

    /// Tray icon title.
    ///
    /// ## Platform-specific
    ///
    /// - **Linux:** The title will not be shown unless there is an icon
    /// as well.  The title is useful for numerical and other frequently
    /// updated information.  In general, it shouldn't be shown unless a
    /// user requests it as it can take up a significant amount of space
    /// on the user's panel.  This may not be shown in all visualizations.
    /// - **Windows:** Unsupported.
    pub title: Option<String>,
}

impl Default for TrayIconAttributes {
    fn default() -> Self {
        Self {
            tooltip: None,
            menu: None,
            icon: None,
            temp_dir_path: None,
            icon_is_template: false,
            menu_on_left_click: true,
            title: None,
        }
    }
}

/// [`TrayIcon`] builder struct and associated methods.
#[derive(Default)]
pub struct TrayIconBuilder {
    id: TrayIconId,
    attrs: TrayIconAttributes,
}

impl TrayIconBuilder {
    /// Creates a new [`TrayIconBuilder`] with default [`TrayIconAttributes`].
    ///
    /// See [`TrayIcon::new`] for more info.
    pub fn new() -> Self {
        Self {
            id: TrayIconId(COUNTER.next().to_string()),
            attrs: TrayIconAttributes::default(),
        }
    }

    /// Sets the unique id to build the tray icon with.
    pub fn with_id<I: Into<TrayIconId>>(mut self, id: I) -> Self {
        self.id = id.into();
        self
    }

    /// Set the a menu for this tray icon.
    ///
    /// ## Platform-specific:
    ///
    /// - **Linux**: once a menu is set, it cannot be removed or replaced but you can change its content.
    pub fn with_menu(mut self, menu: Box<dyn menu::ContextMenu>) -> Self {
        self.attrs.menu = Some(menu);
        self
    }

    /// Set an icon for this tray icon.
    ///
    /// ## Platform-specific:
    ///
    /// - **Linux:** Sometimes the icon won't be visible unless a menu is set.
    /// Setting an empty [`Menu`](crate::menu::Menu) is enough.
    pub fn with_icon(mut self, icon: Icon) -> Self {
        self.attrs.icon = Some(icon);
        self
    }

    /// Set a tooltip for this tray icon.
    ///
    /// ## Platform-specific:
    ///
    /// - **Linux:** Unsupported.
    pub fn with_tooltip<S: AsRef<str>>(mut self, s: S) -> Self {
        self.attrs.tooltip = Some(s.as_ref().to_string());
        self
    }

    /// Set the tray icon title.
    ///
    /// ## Platform-specific
    ///
    /// - **Linux:** The title will not be shown unless there is an icon
    /// as well.  The title is useful for numerical and other frequently
    /// updated information.  In general, it shouldn't be shown unless a
    /// user requests it as it can take up a significant amount of space
    /// on the user's panel.  This may not be shown in all visualizations.
    /// - **Windows:** Unsupported.
    pub fn with_title<S: AsRef<str>>(mut self, title: S) -> Self {
        self.attrs.title.replace(title.as_ref().to_string());
        self
    }

    /// Set tray icon temp dir path. **Linux only**.
    ///
    /// On Linux, we need to write the icon to the disk and usually it will
    /// be `$XDG_RUNTIME_DIR/tray-icon` or `$TEMP/tray-icon`.
    pub fn with_temp_dir_path<P: AsRef<Path>>(mut self, s: P) -> Self {
        self.attrs.temp_dir_path = Some(s.as_ref().to_path_buf());
        self
    }

    /// Use the icon as a [template](https://developer.apple.com/documentation/appkit/nsimage/1520017-template?language=objc). **macOS only**.
    pub fn with_icon_as_template(mut self, is_template: bool) -> Self {
        self.attrs.icon_is_template = is_template;
        self
    }

    /// Whether to show the tray menu on left click or not, default is `true`. **macOS only**.
    pub fn with_menu_on_left_click(mut self, enable: bool) -> Self {
        self.attrs.menu_on_left_click = enable;
        self
    }

    /// Access the unique id that will be assigned to the tray icon
    /// this builder will create.
    pub fn id(&self) -> &TrayIconId {
        &self.id
    }

    /// Builds and adds a new [`TrayIcon`] to the system tray.
    pub fn build(self) -> Result<TrayIcon> {
        TrayIcon::with_id(self.id, self.attrs)
    }
}

/// Tray icon struct and associated methods.
///
/// This type is reference-counted and the icon is removed when the last instance is dropped.
#[derive(Clone)]
pub struct TrayIcon {
    id: TrayIconId,
    tray: Rc<RefCell<platform_impl::TrayIcon>>,
}

impl TrayIcon {
    /// Builds and adds a new tray icon to the system tray.
    ///
    /// ## Platform-specific:
    ///
    /// - **Linux:** Sometimes the icon won't be visible unless a menu is set.
    /// Setting an empty [`Menu`](crate::menu::Menu) is enough.
    pub fn new(attrs: TrayIconAttributes) -> Result<Self> {
        let id = TrayIconId(COUNTER.next().to_string());
        Ok(Self {
            tray: Rc::new(RefCell::new(platform_impl::TrayIcon::new(
                id.clone(),
                attrs,
            )?)),
            id,
        })
    }

    /// Builds and adds a new tray icon to the system tray with the specified Id.
    ///
    /// See [`TrayIcon::new`] for more info.
    pub fn with_id<I: Into<TrayIconId>>(id: I, attrs: TrayIconAttributes) -> Result<Self> {
        let id = id.into();
        Ok(Self {
            tray: Rc::new(RefCell::new(platform_impl::TrayIcon::new(
                id.clone(),
                attrs,
            )?)),
            id,
        })
    }

    /// Returns the id associated with this tray icon.
    pub fn id(&self) -> &TrayIconId {
        &self.id
    }

    /// Set new tray icon. If `None` is provided, it will remove the icon.
    pub fn set_icon(&self, icon: Option<Icon>) -> Result<()> {
        self.tray.borrow_mut().set_icon(icon)
    }

    /// Set new tray menu.
    ///
    /// ## Platform-specific:
    ///
    /// - **Linux**: once a menu is set it cannot be removed so `None` has no effect
    pub fn set_menu(&self, menu: Option<Box<dyn menu::ContextMenu>>) {
        self.tray.borrow_mut().set_menu(menu)
    }

    /// Sets the tooltip for this tray icon.
    ///
    /// ## Platform-specific:
    ///
    /// - **Linux:** Unsupported
    pub fn set_tooltip<S: AsRef<str>>(&self, tooltip: Option<S>) -> Result<()> {
        self.tray.borrow_mut().set_tooltip(tooltip)
    }

    /// Sets the tooltip for this tray icon.
    ///
    /// ## Platform-specific:
    ///
    /// - **Linux:** The title will not be shown unless there is an icon
    /// as well.  The title is useful for numerical and other frequently
    /// updated information.  In general, it shouldn't be shown unless a
    /// user requests it as it can take up a significant amount of space
    /// on the user's panel.  This may not be shown in all visualizations.
    /// - **Windows:** Unsupported
    pub fn set_title<S: AsRef<str>>(&self, title: Option<S>) {
        self.tray.borrow_mut().set_title(title)
    }

    /// Show or hide this tray icon
    pub fn set_visible(&self, visible: bool) -> Result<()> {
        self.tray.borrow_mut().set_visible(visible)
    }

    /// Sets the tray icon temp dir path. **Linux only**.
    ///
    /// On Linux, we need to write the icon to the disk and usually it will
    /// be `$XDG_RUNTIME_DIR/tray-icon` or `$TEMP/tray-icon`.
    pub fn set_temp_dir_path<P: AsRef<Path>>(&self, path: Option<P>) {
        #[cfg(target_os = "linux")]
        self.tray.borrow_mut().set_temp_dir_path(path);
        #[cfg(not(target_os = "linux"))]
        let _ = path;
    }

    /// Set the current icon as a [template](https://developer.apple.com/documentation/appkit/nsimage/1520017-template?language=objc). **macOS only**.
    pub fn set_icon_as_template(&self, is_template: bool) {
        #[cfg(target_os = "macos")]
        self.tray.borrow_mut().set_icon_as_template(is_template);
        #[cfg(not(target_os = "macos"))]
        let _ = is_template;
    }

    /// Disable or enable showing the tray menu on left click. **macOS only**.
    pub fn set_show_menu_on_left_click(&self, enable: bool) {
        #[cfg(target_os = "macos")]
        self.tray.borrow_mut().set_show_menu_on_left_click(enable);
        #[cfg(not(target_os = "macos"))]
        let _ = enable;
    }

    pub fn is_dark_mode(&self) -> bool {
        #[cfg(target_os = "macos")]
        return self.tray.borrow_mut().is_dark_mode();

        #[cfg(not(target_os = "macos"))]
        return false;
    }
}

/// Describes a tray event emitted when a tray icon is clicked
///
/// ## Platform-specific:
///
/// - **Linux**: Unsupported. The event is not emmited even though the icon is shown,
/// the icon will still show a context menu on right click.
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TrayIconEvent {
    /// Id of the tray icon which triggered this event.
    pub id: TrayIconId,
    /// Physical X Position of the click the triggered this event.
    pub x: f64,
    /// Physical Y Position of the click the triggered this event.
    pub y: f64,
    /// Position and size of the tray icon
    pub icon_rect: Rectangle,
    /// The click type that triggered this event.
    pub click_type: ClickType,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ClickType {
    Left,
    Right,
    Double,
}

impl Default for ClickType {
    fn default() -> Self {
        Self::Left
    }
}

/// Describes a rectangle including position (x - y axis) and size.
#[derive(Debug, PartialEq, Clone, Copy, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Rectangle {
    pub left: f64,
    pub right: f64,
    pub top: f64,
    pub bottom: f64,
}

/// A reciever that could be used to listen to tray events.
pub type TrayIconEventReceiver = Receiver<TrayIconEvent>;
type TrayIconEventHandler = Box<dyn Fn(TrayIconEvent) + Send + Sync + 'static>;

static TRAY_CHANNEL: Lazy<(Sender<TrayIconEvent>, TrayIconEventReceiver)> = Lazy::new(unbounded);
static TRAY_EVENT_HANDLER: OnceCell<Option<TrayIconEventHandler>> = OnceCell::new();

impl TrayIconEvent {
    /// Returns the id of the tray icon which triggered this event.
    pub fn id(&self) -> &TrayIconId {
        &self.id
    }

    /// Gets a reference to the event channel's [`TrayIconEventReceiver`]
    /// which can be used to listen for tray events.
    ///
    /// ## Note
    ///
    /// This will not receive any events if [`TrayIconEvent::set_event_handler`] has been called with a `Some` value.
    pub fn receiver<'a>() -> &'a TrayIconEventReceiver {
        &TRAY_CHANNEL.1
    }

    /// Set a handler to be called for new events. Useful for implementing custom event sender.
    ///
    /// ## Note
    ///
    /// Calling this function with a `Some` value,
    /// will not send new events to the channel associated with [`TrayIconEvent::receiver`]
    pub fn set_event_handler<F: Fn(TrayIconEvent) + Send + Sync + 'static>(f: Option<F>) {
        if let Some(f) = f {
            let _ = TRAY_EVENT_HANDLER.set(Some(Box::new(f)));
        } else {
            let _ = TRAY_EVENT_HANDLER.set(None);
        }
    }

    #[allow(unused)]
    pub(crate) fn send(event: TrayIconEvent) {
        if let Some(handler) = TRAY_EVENT_HANDLER.get_or_init(|| None) {
            handler(event);
        } else {
            let _ = TRAY_CHANNEL.0.send(event);
        }
    }
}