Przeglądaj źródła

fix(core): trigger `tauri://*` events to Rust listeners, closes #2901 (#2902)

Lucas Fernandes Nogueira 3 lat temu
rodzic
commit
4c4ab1eb8b

+ 5 - 0
.changes/emit-and-trigger-tauri-events.md

@@ -0,0 +1,5 @@
+---
+"tauri": patch
+---
+
+Emit `tauri://*` events to Rust listeners.

+ 15 - 13
core/tauri/src/manager.rs

@@ -493,9 +493,11 @@ impl<R: Runtime> WindowManager<R> {
       crate::async_runtime::block_on(async move {
         let window = Window::new(manager.clone(), window, app_handle);
         let _ = match event {
-          FileDropEvent::Hovered(paths) => window.emit("tauri://file-drop-hover", Some(paths)),
-          FileDropEvent::Dropped(paths) => window.emit("tauri://file-drop", Some(paths)),
-          FileDropEvent::Cancelled => window.emit("tauri://file-drop-cancelled", Some(())),
+          FileDropEvent::Hovered(paths) => {
+            window.emit_and_trigger("tauri://file-drop-hover", paths)
+          }
+          FileDropEvent::Dropped(paths) => window.emit_and_trigger("tauri://file-drop", paths),
+          FileDropEvent::Cancelled => window.emit_and_trigger("tauri://file-drop-cancelled", ()),
           _ => unimplemented!(),
         };
       });
@@ -796,13 +798,13 @@ fn on_window_event<R: Runtime>(
   event: &WindowEvent,
 ) -> crate::Result<()> {
   match event {
-    WindowEvent::Resized(size) => window.emit(WINDOW_RESIZED_EVENT, Some(size))?,
-    WindowEvent::Moved(position) => window.emit(WINDOW_MOVED_EVENT, Some(position))?,
+    WindowEvent::Resized(size) => window.emit_and_trigger(WINDOW_RESIZED_EVENT, size)?,
+    WindowEvent::Moved(position) => window.emit_and_trigger(WINDOW_MOVED_EVENT, position)?,
     WindowEvent::CloseRequested => {
-      window.emit(WINDOW_CLOSE_REQUESTED_EVENT, Some(()))?;
+      window.emit_and_trigger(WINDOW_CLOSE_REQUESTED_EVENT, ())?;
     }
     WindowEvent::Destroyed => {
-      window.emit(WINDOW_DESTROYED_EVENT, Some(()))?;
+      window.emit_and_trigger(WINDOW_DESTROYED_EVENT, ())?;
       let label = window.label();
       for window in manager.inner.windows.lock().unwrap().values() {
         window.eval(&format!(
@@ -811,24 +813,24 @@ fn on_window_event<R: Runtime>(
         ))?;
       }
     }
-    WindowEvent::Focused(focused) => window.emit(
+    WindowEvent::Focused(focused) => window.emit_and_trigger(
       if *focused {
         WINDOW_FOCUS_EVENT
       } else {
         WINDOW_BLUR_EVENT
       },
-      Some(()),
+      (),
     )?,
     WindowEvent::ScaleFactorChanged {
       scale_factor,
       new_inner_size,
       ..
-    } => window.emit(
+    } => window.emit_and_trigger(
       WINDOW_SCALE_FACTOR_CHANGED_EVENT,
-      Some(ScaleFactorChanged {
+      ScaleFactorChanged {
         scale_factor: *scale_factor,
         size: *new_inner_size,
-      }),
+      },
     )?,
     _ => unimplemented!(),
   }
@@ -843,5 +845,5 @@ struct ScaleFactorChanged {
 }
 
 fn on_menu_event<R: Runtime>(window: &Window<R>, event: &MenuEvent) -> crate::Result<()> {
-  window.emit(MENU_EVENT, Some(event.menu_item_id.clone()))
+  window.emit_and_trigger(MENU_EVENT, event.menu_item_id.clone())
 }

+ 6 - 6
core/tauri/src/updater/mod.rs

@@ -461,13 +461,13 @@ pub(crate) fn listener<R: Runtime>(
             let body = updater.body.clone().unwrap_or_else(|| String::from(""));
 
             // Emit `tauri://update-available`
-            let _ = window.emit(
+            let _ = window.emit_and_trigger(
               EVENT_UPDATE_AVAILABLE,
-              Some(UpdateManifest {
+              UpdateManifest {
                 body,
                 date: updater.date.clone(),
                 version: updater.version.clone(),
-              }),
+              },
             );
 
             // Listen for `tauri://update-install`
@@ -510,12 +510,12 @@ pub(crate) fn listener<R: Runtime>(
 
 // Send a status update via `tauri://update-status` event.
 fn send_status_update<R: Runtime>(window: Window<R>, status: &str, error: Option<String>) {
-  let _ = window.emit(
+  let _ = window.emit_and_trigger(
     EVENT_STATUS_UPDATE,
-    Some(StatusEvent {
+    StatusEvent {
       error,
       status: String::from(status),
-    }),
+    },
   );
 }
 

+ 20 - 5
core/tauri/src/window.rs

@@ -266,7 +266,15 @@ impl<R: Runtime> Window<R> {
     &self.window.label
   }
 
-  /// Emits an event to the current window.
+  /// Emits an event to both the JavaScript and the Rust listeners.
+  pub fn emit_and_trigger<S: Serialize>(&self, event: &str, payload: S) -> crate::Result<()> {
+    self.trigger(event, Some(serde_json::to_string(&payload)?));
+    self.emit(event, payload)
+  }
+
+  /// Emits an event to the JavaScript listeners on the current window.
+  ///
+  /// The event is only delivered to listeners that used the `appWindow.listen` method on the @tauri-apps/api `window` module.
   pub fn emit<S: Serialize>(&self, event: &str, payload: S) -> crate::Result<()> {
     self.eval(&format!(
       "window['{}']({{event: {}, payload: {}}})",
@@ -274,16 +282,21 @@ impl<R: Runtime> Window<R> {
       serde_json::to_string(event)?,
       serde_json::to_value(payload)?,
     ))?;
-
     Ok(())
   }
 
-  /// Emits an event on all windows except this one.
+  /// Emits an event to the JavaScript listeners on all windows except this one.
+  ///
+  /// The event is only delivered to listeners that used the `appWindow.listen` function from the `@tauri-apps/api `window` module.
   pub fn emit_others<S: Serialize + Clone>(&self, event: &str, payload: S) -> crate::Result<()> {
     self.manager.emit_filter(event, payload, |w| w != self)
   }
 
   /// Listen to an event on this window.
+  ///
+  /// This listener only receives events that are triggered using the
+  /// [`trigger`](Window#method.trigger) and [`emit_and_trigger`](Window#method.emit_and_trigger) methods or
+  /// the `appWindow.emit` function from the @tauri-apps/api `window` module.
   pub fn listen<F>(&self, event: impl Into<String>, handler: F) -> EventHandler
   where
     F: Fn(Event) + Send + 'static,
@@ -297,7 +310,7 @@ impl<R: Runtime> Window<R> {
     self.manager.unlisten(handler_id)
   }
 
-  /// Listen to a an event on this window a single time.
+  /// Listen to an event on this window a single time.
   pub fn once<F>(&self, event: impl Into<String>, handler: F) -> EventHandler
   where
     F: Fn(Event) + Send + 'static,
@@ -306,7 +319,9 @@ impl<R: Runtime> Window<R> {
     self.manager.once(event.into(), Some(label), handler)
   }
 
-  /// Triggers an event on this window.
+  /// Triggers an event to the Rust listeners on this window.
+  ///
+  /// The event is only delivered to listeners that used the [`listen`](Window#method.listen) method.
   pub fn trigger(&self, event: &str, data: Option<String>) {
     let label = self.window.label.clone();
     self.manager.trigger(event, Some(label), data)