tauri 2.0.0

Make tiny, secure apps for all desktop platforms with Tauri
Documentation
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

//! Tray icon types and utilities.

pub(crate) mod plugin;

use crate::app::{GlobalMenuEventListener, GlobalTrayIconEventListener};
use crate::menu::ContextMenu;
use crate::menu::MenuEvent;
use crate::resources::Resource;
use crate::{
  image::Image, menu::run_item_main_thread, AppHandle, Manager, PhysicalPosition, Rect, Runtime,
};
use serde::Serialize;
use std::path::Path;
pub use tray_icon::TrayIconId;

/// Describes the mouse button state.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize)]
pub enum MouseButtonState {
  /// Mouse button pressed.
  Up,
  /// Mouse button released.
  Down,
}

impl Default for MouseButtonState {
  fn default() -> Self {
    Self::Up
  }
}

impl From<tray_icon::MouseButtonState> for MouseButtonState {
  fn from(value: tray_icon::MouseButtonState) -> Self {
    match value {
      tray_icon::MouseButtonState::Up => MouseButtonState::Up,
      tray_icon::MouseButtonState::Down => MouseButtonState::Down,
    }
  }
}

/// Describes which mouse button triggered the event..
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize)]
pub enum MouseButton {
  /// Left mouse button.
  Left,
  /// Right mouse button.
  Right,
  /// Middle mouse button.
  Middle,
}

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

impl From<tray_icon::MouseButton> for MouseButton {
  fn from(value: tray_icon::MouseButton) -> Self {
    match value {
      tray_icon::MouseButton::Left => MouseButton::Left,
      tray_icon::MouseButton::Right => MouseButton::Right,
      tray_icon::MouseButton::Middle => MouseButton::Middle,
    }
  }
}

/// Describes a tray icon event.
///
/// ## Platform-specific:
///
/// - **Linux**: Unsupported. The event is not emmited even though the icon is shown
///   and will still show a context menu on right click.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type")]
#[non_exhaustive]
pub enum TrayIconEvent {
  /// A click happened on the tray icon.
  #[serde(rename_all = "camelCase")]
  Click {
    /// Id of the tray icon which triggered this event.
    id: TrayIconId,
    /// Physical Position of this event.
    position: PhysicalPosition<f64>,
    /// Position and size of the tray icon.
    rect: Rect,
    /// Mouse button that triggered this event.
    button: MouseButton,
    /// Mouse button state when this event was triggered.
    button_state: MouseButtonState,
  },
  /// A double click happened on the tray icon. **Windows Only**
  DoubleClick {
    /// Id of the tray icon which triggered this event.
    id: TrayIconId,
    /// Physical Position of this event.
    position: PhysicalPosition<f64>,
    /// Position and size of the tray icon.
    rect: Rect,
    /// Mouse button that triggered this event.
    button: MouseButton,
  },
  /// The mouse entered the tray icon region.
  Enter {
    /// Id of the tray icon which triggered this event.
    id: TrayIconId,
    /// Physical Position of this event.
    position: PhysicalPosition<f64>,
    /// Position and size of the tray icon.
    rect: Rect,
  },
  /// The mouse moved over the tray icon region.
  Move {
    /// Id of the tray icon which triggered this event.
    id: TrayIconId,
    /// Physical Position of this event.
    position: PhysicalPosition<f64>,
    /// Position and size of the tray icon.
    rect: Rect,
  },
  /// The mouse left the tray icon region.
  Leave {
    /// Id of the tray icon which triggered this event.
    id: TrayIconId,
    /// Physical Position of this event.
    position: PhysicalPosition<f64>,
    /// Position and size of the tray icon.
    rect: Rect,
  },
}

impl TrayIconEvent {
  /// Get the id of the tray icon that triggered this event.
  pub fn id(&self) -> &TrayIconId {
    match self {
      TrayIconEvent::Click { id, .. } => id,
      TrayIconEvent::DoubleClick { id, .. } => id,
      TrayIconEvent::Enter { id, .. } => id,
      TrayIconEvent::Move { id, .. } => id,
      TrayIconEvent::Leave { id, .. } => id,
    }
  }
}

impl From<tray_icon::TrayIconEvent> for TrayIconEvent {
  fn from(value: tray_icon::TrayIconEvent) -> Self {
    match value {
      tray_icon::TrayIconEvent::Click {
        id,
        position,
        rect,
        button,
        button_state,
      } => TrayIconEvent::Click {
        id,
        position,
        rect: Rect {
          position: rect.position.into(),
          size: rect.size.into(),
        },
        button: button.into(),
        button_state: button_state.into(),
      },
      tray_icon::TrayIconEvent::DoubleClick {
        id,
        position,
        rect,
        button,
      } => TrayIconEvent::DoubleClick {
        id,
        position,
        rect: Rect {
          position: rect.position.into(),
          size: rect.size.into(),
        },
        button: button.into(),
      },
      tray_icon::TrayIconEvent::Enter { id, position, rect } => TrayIconEvent::Enter {
        id,
        position,
        rect: Rect {
          position: rect.position.into(),
          size: rect.size.into(),
        },
      },
      tray_icon::TrayIconEvent::Move { id, position, rect } => TrayIconEvent::Move {
        id,
        position,
        rect: Rect {
          position: rect.position.into(),
          size: rect.size.into(),
        },
      },
      tray_icon::TrayIconEvent::Leave { id, position, rect } => TrayIconEvent::Leave {
        id,
        position,
        rect: Rect {
          position: rect.position.into(),
          size: rect.size.into(),
        },
      },
      _ => todo!(),
    }
  }
}

/// [`TrayIcon`] builder struct and associated methods.
#[derive(Default)]
pub struct TrayIconBuilder<R: Runtime> {
  on_menu_event: Option<GlobalMenuEventListener<AppHandle<R>>>,
  on_tray_icon_event: Option<GlobalTrayIconEventListener<TrayIcon<R>>>,
  inner: tray_icon::TrayIconBuilder,
}

impl<R: Runtime> TrayIconBuilder<R> {
  /// Creates a new tray icon builder.
  ///
  /// ## 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() -> Self {
    Self {
      inner: tray_icon::TrayIconBuilder::new(),
      on_menu_event: None,
      on_tray_icon_event: None,
    }
  }

  /// Creates a new tray icon builder with the specified id.
  ///
  /// ## 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_id<I: Into<TrayIconId>>(id: I) -> Self {
    let mut builder = Self::new();
    builder.inner = builder.inner.with_id(id);
    builder
  }

  /// 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 menu<M: ContextMenu>(mut self, menu: &M) -> Self {
    self.inner = self.inner.with_menu(menu.inner_context_owned());
    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 icon(mut self, icon: Image<'_>) -> Self {
    let icon = icon.try_into().ok();
    if let Some(icon) = icon {
      self.inner = self.inner.with_icon(icon);
    }
    self
  }

  /// Set a tooltip for this tray icon.
  ///
  /// ## Platform-specific:
  ///
  /// - **Linux:** Unsupported.
  pub fn tooltip<S: AsRef<str>>(mut self, s: S) -> Self {
    self.inner = self.inner.with_tooltip(s);
    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 title<S: AsRef<str>>(mut self, title: S) -> Self {
    self.inner = self.inner.with_title(title);
    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 temp_dir_path<P: AsRef<Path>>(mut self, s: P) -> Self {
    self.inner = self.inner.with_temp_dir_path(s);
    self
  }

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

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

  /// Set a handler for menu events.
  ///
  /// Note that this handler is called for any menu event,
  /// whether it is coming from this window, another window or from the tray icon menu.
  pub fn on_menu_event<F: Fn(&AppHandle<R>, MenuEvent) + Sync + Send + 'static>(
    mut self,
    f: F,
  ) -> Self {
    self.on_menu_event.replace(Box::new(f));
    self
  }

  /// Set a handler for this tray icon events.
  pub fn on_tray_icon_event<F: Fn(&TrayIcon<R>, TrayIconEvent) + Sync + Send + 'static>(
    mut self,
    f: F,
  ) -> Self {
    self.on_tray_icon_event.replace(Box::new(f));
    self
  }

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

  /// Builds and adds a new [`TrayIcon`] to the system tray.
  pub fn build<M: Manager<R>>(self, manager: &M) -> crate::Result<TrayIcon<R>> {
    let id = self.id().clone();
    let inner = self.inner.build()?;
    let icon = TrayIcon {
      id,
      inner,
      app_handle: manager.app_handle().clone(),
    };

    icon.register(
      &icon.app_handle,
      self.on_menu_event,
      self.on_tray_icon_event,
    );

    Ok(icon)
  }
}

/// Tray icon struct and associated methods.
///
/// This type is reference-counted and the icon is removed when the last instance is dropped.
///
/// See [TrayIconBuilder] to construct this type.
#[tauri_macros::default_runtime(crate::Wry, wry)]
pub struct TrayIcon<R: Runtime> {
  id: TrayIconId,
  inner: tray_icon::TrayIcon,
  app_handle: AppHandle<R>,
}

impl<R: Runtime> Clone for TrayIcon<R> {
  fn clone(&self) -> Self {
    Self {
      id: self.id.clone(),
      inner: self.inner.clone(),
      app_handle: self.app_handle.clone(),
    }
  }
}

/// # Safety
///
/// We make sure it always runs on the main thread.
unsafe impl<R: Runtime> Sync for TrayIcon<R> {}
unsafe impl<R: Runtime> Send for TrayIcon<R> {}

impl<R: Runtime> TrayIcon<R> {
  fn register(
    &self,
    app_handle: &AppHandle<R>,
    on_menu_event: Option<GlobalMenuEventListener<AppHandle<R>>>,
    on_tray_icon_event: Option<GlobalTrayIconEventListener<TrayIcon<R>>>,
  ) {
    if let Some(handler) = on_menu_event {
      app_handle
        .manager
        .menu
        .global_event_listeners
        .lock()
        .unwrap()
        .push(handler);
    }

    if let Some(handler) = on_tray_icon_event {
      app_handle
        .manager
        .tray
        .event_listeners
        .lock()
        .unwrap()
        .insert(self.id.clone(), handler);
    }

    app_handle
      .manager
      .tray
      .icons
      .lock()
      .unwrap()
      .push(self.clone());
  }

  /// The application handle associated with this type.
  pub fn app_handle(&self) -> &AppHandle<R> {
    &self.app_handle
  }

  /// Register a handler for menu events.
  ///
  /// Note that this handler is called for any menu event,
  /// whether it is coming from this window, another window or from the tray icon menu.
  pub fn on_menu_event<F: Fn(&AppHandle<R>, MenuEvent) + Sync + Send + 'static>(&self, f: F) {
    self
      .app_handle
      .manager
      .menu
      .global_event_listeners
      .lock()
      .unwrap()
      .push(Box::new(f));
  }

  /// Register a handler for this tray icon events.
  pub fn on_tray_icon_event<F: Fn(&TrayIcon<R>, TrayIconEvent) + Sync + Send + 'static>(
    &self,
    f: F,
  ) {
    self
      .app_handle
      .manager
      .tray
      .event_listeners
      .lock()
      .unwrap()
      .insert(self.id.clone(), Box::new(f));
  }

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

  /// Sets a new tray icon. If `None` is provided, it will remove the icon.
  pub fn set_icon(&self, icon: Option<Image<'_>>) -> crate::Result<()> {
    let icon = match icon {
      Some(i) => Some(i.try_into()?),
      None => None,
    };
    run_item_main_thread!(self, |self_: Self| self_.inner.set_icon(icon))?.map_err(Into::into)
  }

  /// Sets a new tray menu.
  ///
  /// ## Platform-specific:
  ///
  /// - **Linux**: once a menu is set it cannot be removed so `None` has no effect
  pub fn set_menu<M: ContextMenu + 'static>(&self, menu: Option<M>) -> crate::Result<()> {
    run_item_main_thread!(self, |self_: Self| self_
      .inner
      .set_menu(menu.map(|m| m.inner_context_owned())))
  }

  /// Sets the tooltip for this tray icon.
  ///
  /// ## Platform-specific:
  ///
  /// - **Linux:** Unsupported
  pub fn set_tooltip<S: AsRef<str>>(&self, tooltip: Option<S>) -> crate::Result<()> {
    let s = tooltip.map(|s| s.as_ref().to_string());
    run_item_main_thread!(self, |self_: Self| self_.inner.set_tooltip(s))?.map_err(Into::into)
  }

  /// Sets the title 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>) -> crate::Result<()> {
    let s = title.map(|s| s.as_ref().to_string());
    run_item_main_thread!(self, |self_: Self| self_.inner.set_title(s))
  }

  /// Show or hide this tray icon.
  pub fn set_visible(&self, visible: bool) -> crate::Result<()> {
    run_item_main_thread!(self, |self_: Self| self_.inner.set_visible(visible))?.map_err(Into::into)
  }

  /// 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>) -> crate::Result<()> {
    #[allow(unused)]
    let p = path.map(|p| p.as_ref().to_path_buf());
    #[cfg(target_os = "linux")]
    run_item_main_thread!(self, |self_: Self| self_.inner.set_temp_dir_path(p))?;
    Ok(())
  }

  /// Sets 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, #[allow(unused)] is_template: bool) -> crate::Result<()> {
    #[cfg(target_os = "macos")]
    run_item_main_thread!(self, |self_: Self| self_
      .inner
      .set_icon_as_template(is_template))?;
    Ok(())
  }

  /// Disable or enable showing the tray menu on left click. **macOS only**.
  pub fn set_show_menu_on_left_click(&self, #[allow(unused)] enable: bool) -> crate::Result<()> {
    #[cfg(target_os = "macos")]
    run_item_main_thread!(self, |self_: Self| self_
      .inner
      .set_show_menu_on_left_click(enable))?;
    Ok(())
  }

  /// Get tray icon rect.
  ///
  /// ## Platform-specific:
  ///
  /// - **Linux**: Unsupported, always returns `None`.
  pub fn rect(&self) -> crate::Result<Option<crate::Rect>> {
    run_item_main_thread!(self, |self_: Self| self_.inner.rect().map(|rect| {
      Rect {
        position: rect.position.into(),
        size: rect.size.into(),
      }
    }))
  }
}

impl<R: Runtime> Resource for TrayIcon<R> {
  fn close(self: std::sync::Arc<Self>) {
    self.app_handle.remove_tray_by_id(&self.id);
  }
}

#[cfg(test)]
mod tests {
  #[test]
  fn tray_event_json_serialization() {
    // NOTE: if this test is ever changed, you probably need to change `TrayIconEvent` in JS as well

    use super::*;
    let event = TrayIconEvent::Click {
      button: MouseButton::Left,
      button_state: MouseButtonState::Down,
      id: TrayIconId::new("id"),
      position: crate::PhysicalPosition::default(),
      rect: crate::Rect {
        position: tray_icon::Rect::default().position.into(),
        size: tray_icon::Rect::default().size.into(),
      },
    };

    let value = serde_json::to_value(&event).unwrap();
    assert_eq!(
      value,
      serde_json::json!({
          "type": "Click",
          "button": "Left",
          "buttonState": "Down",
          "id": "id",
          "position": {
              "x": 0.0,
              "y": 0.0,
          },
          "rect": {
              "size": {
                  "Physical": {
                      "width": 0,
                      "height": 0,
                  }
              },
              "position": {
                  "Physical": {
                      "x": 0,
                      "y": 0,
                  }
              },
          }
      })
    );
  }
}