notification.rs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. // Copyright 2019-2022 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. //! Types and functions related to desktop notifications.
  5. #[cfg(windows)]
  6. use std::path::MAIN_SEPARATOR as SEP;
  7. /// The desktop notification definition.
  8. ///
  9. /// Allows you to construct a Notification data and send it.
  10. ///
  11. /// # Examples
  12. /// ```rust,no_run
  13. /// use tauri::api::notification::Notification;
  14. /// // first we build the application to access the Tauri configuration
  15. /// let app = tauri::Builder::default()
  16. /// // on an actual app, remove the string argument
  17. /// .build(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
  18. /// .expect("error while building tauri application");
  19. ///
  20. /// // shows a notification with the given title and body
  21. /// Notification::new(&app.config().tauri.bundle.identifier)
  22. /// .title("New message")
  23. /// .body("You've got a new message.")
  24. /// .show();
  25. ///
  26. /// // run the app
  27. /// app.run(|_app_handle, _event| {});
  28. /// ```
  29. #[allow(dead_code)]
  30. #[derive(Debug, Default)]
  31. pub struct Notification {
  32. /// The notification body.
  33. body: Option<String>,
  34. /// The notification title.
  35. title: Option<String>,
  36. /// The notification icon.
  37. icon: Option<String>,
  38. /// The notification identifier
  39. identifier: String,
  40. }
  41. impl Notification {
  42. /// Initializes a instance of a Notification.
  43. pub fn new(identifier: impl Into<String>) -> Self {
  44. Self {
  45. identifier: identifier.into(),
  46. ..Default::default()
  47. }
  48. }
  49. /// Sets the notification body.
  50. #[must_use]
  51. pub fn body(mut self, body: impl Into<String>) -> Self {
  52. self.body = Some(body.into());
  53. self
  54. }
  55. /// Sets the notification title.
  56. #[must_use]
  57. pub fn title(mut self, title: impl Into<String>) -> Self {
  58. self.title = Some(title.into());
  59. self
  60. }
  61. /// Sets the notification icon.
  62. #[must_use]
  63. pub fn icon(mut self, icon: impl Into<String>) -> Self {
  64. self.icon = Some(icon.into());
  65. self
  66. }
  67. /// Shows the notification.
  68. ///
  69. /// # Examples
  70. ///
  71. /// ```no_run
  72. /// use tauri::api::notification::Notification;
  73. ///
  74. /// // on an actual app, remove the string argument
  75. /// let context = tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json");
  76. /// Notification::new(&context.config().tauri.bundle.identifier)
  77. /// .title("Tauri")
  78. /// .body("Tauri is awesome!")
  79. /// .show()
  80. /// .unwrap();
  81. /// ```
  82. ///
  83. /// ## Platform-specific
  84. ///
  85. /// - **Windows**: Not supported on Windows 7. If your app targets it, enable the `windows7-compat` feature and use [`Self::notify`].
  86. #[cfg_attr(
  87. all(not(doc_cfg), feature = "windows7-compat"),
  88. deprecated = "This function does not work on Windows 7. Use `Self::notify` instead."
  89. )]
  90. pub fn show(self) -> crate::api::Result<()> {
  91. let mut notification = notify_rust::Notification::new();
  92. if let Some(body) = self.body {
  93. notification.body(&body);
  94. }
  95. if let Some(title) = self.title {
  96. notification.summary(&title);
  97. }
  98. if let Some(icon) = self.icon {
  99. notification.icon(&icon);
  100. } else {
  101. notification.auto_icon();
  102. }
  103. #[cfg(windows)]
  104. {
  105. let exe = tauri_utils::platform::current_exe()?;
  106. let exe_dir = exe.parent().expect("failed to get exe directory");
  107. let curr_dir = exe_dir.display().to_string();
  108. // set the notification's System.AppUserModel.ID only when running the installed app
  109. if !(curr_dir.ends_with(format!("{SEP}target{SEP}debug").as_str())
  110. || curr_dir.ends_with(format!("{SEP}target{SEP}release").as_str()))
  111. {
  112. notification.app_id(&self.identifier);
  113. }
  114. }
  115. #[cfg(target_os = "macos")]
  116. {
  117. let _ = notify_rust::set_application(if cfg!(feature = "custom-protocol") {
  118. &self.identifier
  119. } else {
  120. "com.apple.Terminal"
  121. });
  122. }
  123. crate::async_runtime::spawn(async move {
  124. let _ = notification.show();
  125. });
  126. Ok(())
  127. }
  128. /// Shows the notification. This API is similar to [`Self::show`], but it also works on Windows 7.
  129. ///
  130. /// # Examples
  131. ///
  132. /// ```no_run
  133. /// use tauri::api::notification::Notification;
  134. ///
  135. /// // on an actual app, remove the string argument
  136. /// let context = tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json");
  137. /// let identifier = context.config().tauri.bundle.identifier.clone();
  138. ///
  139. /// tauri::Builder::default()
  140. /// .setup(move |app| {
  141. /// Notification::new(&identifier)
  142. /// .title("Tauri")
  143. /// .body("Tauri is awesome!")
  144. /// .notify(&app.handle())
  145. /// .unwrap();
  146. /// Ok(())
  147. /// })
  148. /// .run(context)
  149. /// .expect("error while running tauri application");
  150. /// ```
  151. #[cfg(feature = "windows7-compat")]
  152. #[cfg_attr(doc_cfg, doc(cfg(feature = "windows7-compat")))]
  153. #[allow(unused_variables)]
  154. pub fn notify<R: crate::Runtime>(self, app: &crate::AppHandle<R>) -> crate::api::Result<()> {
  155. #[cfg(windows)]
  156. {
  157. if crate::utils::platform::is_windows_7() {
  158. self.notify_win7(app)
  159. } else {
  160. #[allow(deprecated)]
  161. self.show()
  162. }
  163. }
  164. #[cfg(not(windows))]
  165. {
  166. #[allow(deprecated)]
  167. self.show()
  168. }
  169. }
  170. #[cfg(all(windows, feature = "windows7-compat"))]
  171. fn notify_win7<R: crate::Runtime>(self, app: &crate::AppHandle<R>) -> crate::api::Result<()> {
  172. let app = app.clone();
  173. let default_window_icon = app.manager.inner.default_window_icon.clone();
  174. let _ = app.run_on_main_thread(move || {
  175. let mut notification = win7_notifications::Notification::new();
  176. if let Some(body) = self.body {
  177. notification.body(&body);
  178. }
  179. if let Some(title) = self.title {
  180. notification.summary(&title);
  181. }
  182. if let Some(crate::Icon::Rgba {
  183. rgba,
  184. width,
  185. height,
  186. }) = default_window_icon
  187. {
  188. notification.icon(rgba, width, height);
  189. }
  190. let _ = notification.show();
  191. });
  192. Ok(())
  193. }
  194. }