ソースを参照

feat(core): expose `run_on_main_thread` API (#2711)

Lucas Fernandes Nogueira 3 年 前
コミット
53fdfe52bb

+ 5 - 0
.changes/run-on-main-thread.md

@@ -0,0 +1,5 @@
+---
+"tauri": patch
+---
+
+Expose `run_on_main_thread` APIs on `Window` and `AppHandle`.

+ 6 - 0
.changes/runtime-handle-run-on-main-thread.md

@@ -0,0 +1,6 @@
+---
+"tauri-runtime": "patch"
+"tauri-runtime-wry": patch
+---
+
+Added `run_on_main_thread` API on `RuntimeHandle`.

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

@@ -1528,6 +1528,10 @@ impl RuntimeHandle for WryHandle {
     Ok(DetachedWindow { label, dispatcher })
   }
 
+  fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> Result<()> {
+    send_user_message(&self.context, Message::Task(Box::new(f)))
+  }
+
   #[cfg(all(windows, feature = "system-tray"))]
   /// Deprecated. (not needed anymore)
   fn remove_system_tray(&self) -> Result<()> {

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

@@ -255,6 +255,9 @@ pub trait RuntimeHandle: Debug + Send + Sized + Clone + 'static {
     pending: PendingWindow<Self::Runtime>,
   ) -> crate::Result<DetachedWindow<Self::Runtime>>;
 
+  /// Run a task on the main thread.
+  fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> crate::Result<()>;
+
   #[cfg(all(windows, feature = "system-tray"))]
   #[cfg_attr(doc_cfg, doc(cfg(all(windows, feature = "system-tray"))))]
   fn remove_system_tray(&self) -> crate::Result<()>;

+ 8 - 1
core/tauri/src/app.rs

@@ -33,7 +33,6 @@ use std::{
 
 use crate::runtime::menu::{Menu, MenuId, MenuIdRef};
 
-#[cfg(all(windows, feature = "system-tray"))]
 use crate::runtime::RuntimeHandle;
 #[cfg(feature = "system-tray")]
 use crate::runtime::{Icon, SystemTrayEvent as RuntimeSystemTrayEvent};
@@ -225,6 +224,14 @@ impl<'de, R: Runtime> CommandArg<'de, R> for AppHandle<R> {
 }
 
 impl<R: Runtime> AppHandle<R> {
+  /// Runs the given closure on the main thread.
+  pub fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> crate::Result<()> {
+    self
+      .runtime_handle
+      .run_on_main_thread(f)
+      .map_err(Into::into)
+  }
+
   /// Removes the system tray.
   #[cfg(all(windows, feature = "system-tray"))]
   #[cfg_attr(doc_cfg, doc(cfg(all(windows, feature = "system-tray"))))]

+ 2 - 2
core/tauri/src/window.rs

@@ -206,8 +206,8 @@ impl<R: Runtime> Window<R> {
     self.window.dispatcher.clone()
   }
 
-  #[allow(dead_code)]
-  pub(crate) fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> crate::Result<()> {
+  /// Runs the given closure on the main thread.
+  pub fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> crate::Result<()> {
     self
       .window
       .dispatcher