소스 검색

feat(windows): implement `with_tooltip` (#5938)

Co-authored-by: Amr Bashir <amr.bashir2015@gmail.com>
Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
luofei 2 년 전
부모
커밋
2265e09718

+ 6 - 0
.changes/tray-tooltip-runtime.md

@@ -0,0 +1,6 @@
+---
+"tauri-runtime": minor
+"tauri-runtime-wry": minor
+---
+
+Added `TrayHandle::set_tooltip` and `SystemTray::with_tooltip`.

+ 5 - 0
.changes/tray-tooltip.md

@@ -0,0 +1,5 @@
+---
+"tauri": patch
+---
+
+Implement `SystemTray::with_tooltip` and `SystemTrayHandle::set_tooltip` for Windows and macOS.

+ 6 - 0
core/tauri-runtime-wry/src/lib.rs

@@ -1124,6 +1124,7 @@ pub enum TrayMessage {
   UpdateIconAsTemplate(bool),
   #[cfg(target_os = "macos")]
   UpdateTitle(String),
+  UpdateTooltip(String),
   Create(SystemTray, Sender<Result<()>>),
   Destroy(Sender<Result<()>>),
 }
@@ -2636,6 +2637,11 @@ fn handle_user_message<T: UserEvent>(
               tray.set_title(&title);
             }
           }
+          TrayMessage::UpdateTooltip(tooltip) => {
+            if let Some(tray) = &mut *tray_context.tray.lock().unwrap() {
+              tray.set_tooltip(&tooltip);
+            }
+          }
           TrayMessage::Create(_tray, _tx) => {
             // already handled
           }

+ 14 - 0
core/tauri-runtime-wry/src/system_tray.rs

@@ -114,6 +114,10 @@ pub fn create_tray<T>(
     }
   }
 
+  if let Some(tooltip) = system_tray.tooltip {
+    builder = builder.with_tooltip(&tooltip);
+  }
+
   let tray = builder
     .build(event_loop)
     .map_err(|e| Error::SystemTray(Box::new(e)))?;
@@ -172,6 +176,16 @@ impl<T: UserEvent> TrayHandle for SystemTrayHandle<T> {
       .map_err(|_| Error::FailedToSendMessage)
   }
 
+  fn set_tooltip(&self, tooltip: &str) -> Result<()> {
+    self
+      .proxy
+      .send_event(Message::Tray(
+        self.id,
+        TrayMessage::UpdateTooltip(tooltip.to_owned()),
+      ))
+      .map_err(|_| Error::FailedToSendMessage)
+  }
+
   fn destroy(&self) -> Result<()> {
     let (tx, rx) = std::sync::mpsc::channel();
     send_user_message(

+ 14 - 0
core/tauri-runtime/src/lib.rs

@@ -54,6 +54,7 @@ pub struct SystemTray {
   #[cfg(target_os = "macos")]
   pub title: Option<String>,
   pub on_event: Option<Box<TrayEventHandler>>,
+  pub tooltip: Option<String>,
 }
 
 #[cfg(all(desktop, feature = "system-tray"))]
@@ -87,6 +88,7 @@ impl Clone for SystemTray {
       menu_on_left_click: self.menu_on_left_click,
       #[cfg(target_os = "macos")]
       title: self.title.clone(),
+      tooltip: self.tooltip.clone(),
     }
   }
 }
@@ -105,6 +107,7 @@ impl Default for SystemTray {
       #[cfg(target_os = "macos")]
       title: None,
       on_event: None,
+      tooltip: None,
     }
   }
 }
@@ -157,6 +160,17 @@ impl SystemTray {
     self
   }
 
+  /// Sets the tray icon tooltip.
+  ///
+  /// ## Platform-specific:
+  ///
+  /// - **Linux:** Unsupported
+  #[must_use]
+  pub fn with_tooltip(mut self, tooltip: &str) -> Self {
+    self.tooltip = Some(tooltip.to_owned());
+    self
+  }
+
   /// Sets the menu to show when the system tray is right clicked.
   #[must_use]
   pub fn with_menu(mut self, menu: menu::SystemTrayMenu) -> Self {

+ 1 - 0
core/tauri-runtime/src/menu.rs

@@ -154,6 +154,7 @@ pub trait TrayHandle: fmt::Debug + Clone + Send + Sync {
   fn set_icon_as_template(&self, is_template: bool) -> crate::Result<()>;
   #[cfg(target_os = "macos")]
   fn set_title(&self, title: &str) -> crate::Result<()>;
+  fn set_tooltip(&self, tooltip: &str) -> crate::Result<()>;
   fn destroy(&self) -> crate::Result<()>;
 }
 

+ 38 - 0
core/tauri/src/app/tray.rs

@@ -64,6 +64,7 @@ pub struct SystemTray {
   icon_as_template_set: bool,
   #[cfg(target_os = "macos")]
   title: Option<String>,
+  tooltip: Option<String>,
 }
 
 impl fmt::Debug for SystemTray {
@@ -98,6 +99,7 @@ impl Default for SystemTray {
       menu_on_left_click_set: false,
       #[cfg(target_os = "macos")]
       title: None,
+      tooltip: None,
     }
   }
 }
@@ -257,6 +259,29 @@ impl SystemTray {
     self
   }
 
+  /// Sets the tray icon tooltip.
+  ///
+  /// ## Platform-specific:
+  ///
+  /// - **Linux:** Unsupported
+  ///
+  /// # Examples
+  ///
+  /// ```
+  /// use tauri::SystemTray;
+  ///
+  /// tauri::Builder::default()
+  ///   .setup(|app| {
+  ///     let tray_handle = SystemTray::new().with_tooltip("My App").build(app)?;
+  ///     Ok(())
+  ///   });
+  /// ```
+  #[must_use]
+  pub fn with_tooltip(mut self, tooltip: &str) -> Self {
+    self.tooltip = Some(tooltip.to_owned());
+    self
+  }
+
   /// Sets the event listener for this system tray.
   ///
   /// # Examples
@@ -414,6 +439,10 @@ impl SystemTray {
       }
     }
 
+    if let Some(tooltip) = self.tooltip {
+      runtime_tray = runtime_tray.with_tooltip(&tooltip);
+    }
+
     let id = runtime_tray.id;
     let tray_handler = match manager.runtime() {
       RuntimeOrDispatch::Runtime(r) => r.system_tray(runtime_tray),
@@ -610,6 +639,15 @@ impl<R: Runtime> SystemTrayHandle<R> {
     self.inner.set_title(title).map_err(Into::into)
   }
 
+  /// Set the tooltip for this tray icon.
+  ///
+  /// ## Platform-specific:
+  ///
+  /// - **Linux:** Unsupported
+  pub fn set_tooltip(&self, tooltip: &str) -> crate::Result<()> {
+    self.inner.set_tooltip(tooltip).map_err(Into::into)
+  }
+
   /// Destroys this system tray.
   pub fn destroy(&self) -> crate::Result<()> {
     self.inner.destroy().map_err(Into::into)

+ 4 - 0
core/tauri/src/test/mock_runtime.rs

@@ -593,6 +593,10 @@ impl TrayHandle for MockTrayHandler {
     Ok(())
   }
 
+  fn set_tooltip(&self, tooltip: &str) -> Result<()> {
+    Ok(())
+  }
+
   fn destroy(&self) -> Result<()> {
     Ok(())
   }

+ 8 - 7
examples/api/src-tauri/src/desktop.rs

@@ -93,6 +93,7 @@ fn create_tray(app: &tauri::App) -> tauri::Result<()> {
   SystemTray::new()
     .with_id(&tray_id)
     .with_menu(tray_menu1.clone())
+    .with_tooltip("Tauri")
     .on_event(move |event| {
       let tray_handle = handle.tray_handle_by_id(&tray_id).unwrap();
       match event {
@@ -158,13 +159,13 @@ fn create_tray(app: &tauri::App) -> tauri::Result<()> {
             }
             "switch_menu" => {
               let flag = is_menu1.load(Ordering::Relaxed);
-              tray_handle
-                .set_menu(if flag {
-                  tray_menu2.clone()
-                } else {
-                  tray_menu1.clone()
-                })
-                .unwrap();
+              let (menu, tooltip) = if flag {
+                (tray_menu2.clone(), "Menu 2")
+              } else {
+                (tray_menu1.clone(), "Tauri")
+              };
+              tray_handle.set_menu(menu).unwrap();
+              tray_handle.set_tooltip(tooltip).unwrap();
               is_menu1.store(!flag, Ordering::Relaxed);
             }
             "about" => {