Эх сурвалжийг харах

refactor(tauri): remove app runner, use builder (#1429)

Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
chip 4 жил өмнө
parent
commit
94038b5e71

+ 2 - 3
cli/core/templates/src-tauri/src/main.rs

@@ -4,8 +4,7 @@
 )]
 
 fn main() {
-  tauri::AppBuilder::default()
-    .build(tauri::generate_context!())
-    .run()
+  tauri::Builder::default()
+    .run(tauri::generate_context!())
     .expect("error while running tauri application");
 }

+ 3 - 3
cli/tauri.js/test/jest/fixtures/app/src-tauri/src/main.rs

@@ -1,7 +1,7 @@
 use tauri::ApplicationDispatcherExt;
 
 fn main() {
-  tauri::AppBuilder::default()
+  tauri::Builder::default()
     .setup(|webview_manager| async move {
       let mut webview_manager_ = webview_manager.clone();
       tauri::event::listen(String::from("hello"), move |_| {
@@ -21,6 +21,6 @@ fn main() {
         webview_manager.close().unwrap();
       }
     })
-    .build(tauri::generate_context!())
-    .run();
+    .run(tauri::generate_context!())
+    .expect("error encountered while running tauri application");
 }

+ 2 - 3
examples/api/src-tauri/src/main.rs

@@ -13,7 +13,7 @@ struct Reply {
 }
 
 fn main() {
-  tauri::AppBuilder::default()
+  tauri::Builder::default()
     .on_page_load(|window, _| {
       let window_ = window.clone();
       window.listen("js-event".into(), move |event| {
@@ -31,7 +31,6 @@ fn main() {
       cmd::log_operation,
       cmd::perform_request
     ])
-    .build(tauri::generate_context!())
-    .run()
+    .run(tauri::generate_context!())
     .expect("error while running tauri application");
 }

+ 2 - 3
examples/helloworld/src-tauri/src/main.rs

@@ -9,9 +9,8 @@ fn my_custom_command(argument: String) {
 }
 
 fn main() {
-  tauri::AppBuilder::default()
+  tauri::Builder::default()
     .invoke_handler(tauri::generate_handler![my_custom_command])
-    .build(tauri::generate_context!())
-    .run()
+    .run(tauri::generate_context!())
     .expect("error while running tauri application");
 }

+ 2 - 3
examples/multiwindow/src-tauri/src/main.rs

@@ -6,7 +6,7 @@
 use tauri::Attributes;
 
 fn main() {
-  tauri::AppBuilder::default()
+  tauri::Builder::default()
     .on_page_load(|window, _payload| {
       let label = window.label().to_string();
       window.listen("clicked".to_string(), move |_payload| {
@@ -18,7 +18,6 @@ fn main() {
       tauri::WindowUrl::App("index.html".into()),
       |attributes| attributes.title("Tauri - Rust"),
     )
-    .build(tauri::generate_context!())
-    .run()
+    .run(tauri::generate_context!())
     .expect("failed to run tauri application");
 }

+ 2 - 3
examples/updater/src-tauri/src/main.rs

@@ -9,9 +9,8 @@ fn my_custom_command(argument: String) {
 }
 
 fn main() {
-  tauri::AppBuilder::default()
+  tauri::Builder::default()
     .invoke_handler(tauri::generate_handler![my_custom_command])
-    .build(tauri::generate_context!())
-    .run()
+    .run(tauri::generate_context!())
     .expect("error while running tauri application");
 }

+ 1 - 1
tauri/src/lib.rs

@@ -35,7 +35,7 @@ pub type SyncTask = Box<dyn FnOnce() + Send>;
 pub use {
   api::config::WindowUrl,
   hooks::InvokeMessage,
-  runtime::app::AppBuilder,
+  runtime::app::Builder,
   runtime::webview::Attributes,
   runtime::window::Window,
   runtime::{Context, Manager, Params},

+ 72 - 83
tauri/src/runtime/app.rs

@@ -5,7 +5,7 @@ use crate::{
   runtime::{
     flavor::wry::Wry,
     manager::WindowManager,
-    sealed::ManagerPrivate,
+    sealed::{ManagerPrivate, ParamsPrivate},
     tag::Tag,
     updater,
     webview::{Attributes, WindowConfig},
@@ -15,9 +15,20 @@ use crate::{
 };
 
 /// A handle to the currently running application.
-pub struct App<M: Params> {
-  runtime: M::Runtime,
-  manager: M,
+pub struct App<P: Params> {
+  runtime: P::Runtime,
+  manager: P,
+}
+
+impl<P: Params> Manager<P> for App<P> {}
+impl<P: Params> ManagerPrivate<P> for App<P> {
+  fn manager(&self) -> &P {
+    &self.manager
+  }
+
+  fn runtime(&mut self) -> RuntimeOrDispatch<'_, P> {
+    RuntimeOrDispatch::Runtime(&mut self.runtime)
+  }
 }
 
 #[cfg(feature = "updater")]
@@ -79,77 +90,8 @@ impl<M: Params> App<M> {
   }
 }
 
-impl<M: Params> Manager<M> for App<M> {}
-impl<M: Params> ManagerPrivate<M> for App<M> {
-  fn manager(&self) -> &M {
-    &self.manager
-  }
-
-  fn runtime(&mut self) -> RuntimeOrDispatch<'_, M> {
-    RuntimeOrDispatch::Runtime(&mut self.runtime)
-  }
-}
-
-#[allow(missing_docs)]
-pub struct Runner<M: Params> {
-  pending_windows: Vec<PendingWindow<M>>,
-  manager: M,
-  setup: SetupHook<M>,
-}
-
-impl<M: Params> Runner<M> {
-  /// Consume and run the [`Application`] until it is finished.
-  pub fn run(mut self) -> crate::Result<()> {
-    // set up all the windows defined in the config
-    for config in self.manager.config().tauri.windows.clone() {
-      let url = config.url.clone();
-      let label = config
-        .label
-        .parse()
-        .unwrap_or_else(|_| panic!("bad label: {}", config.label));
-
-      self
-        .pending_windows
-        .push(PendingWindow::new(WindowConfig(config), label, url));
-    }
-
-    self.manager.initialize_plugins()?;
-    let labels = self
-      .pending_windows
-      .iter()
-      .map(|p| p.label.clone())
-      .collect::<Vec<_>>();
-
-    let mut app = App {
-      runtime: M::Runtime::new()?,
-      manager: self.manager,
-    };
-
-    let pending_windows = self.pending_windows;
-    #[cfg(feature = "updater")]
-    let mut main_window = None;
-
-    for pending in pending_windows {
-      let pending = app.manager.prepare_window(pending, &labels)?;
-      let detached = app.runtime.create_window(pending)?;
-      let window = app.manager.attach_window(detached);
-      #[cfg(feature = "updater")]
-      if main_window.is_none() {
-        main_window = Some(window);
-      }
-    }
-
-    #[cfg(feature = "updater")]
-    app.run_updater(main_window);
-
-    (self.setup)(&mut app)?;
-    app.runtime.run();
-    Ok(())
-  }
-}
-
 /// The App builder.
-pub struct AppBuilder<E, L, A, R>
+pub struct Builder<E, L, A, R>
 where
   E: Tag,
   L: Tag,
@@ -172,7 +114,7 @@ where
   plugins: PluginStore<WindowManager<E, L, A, R>>,
 }
 
-impl<E, L, A, R> AppBuilder<E, L, A, R>
+impl<E, L, A, R> Builder<E, L, A, R>
 where
   E: Tag,
   L: Tag,
@@ -237,18 +179,65 @@ where
     self
   }
 
-  /// Builds the [`App`] and the underlying [`Runtime`].
-  pub fn build(self, context: Context<A>) -> Runner<WindowManager<E, L, A, R>> {
-    Runner {
-      pending_windows: self.pending_windows,
-      setup: self.setup,
-      manager: WindowManager::with_handlers(context, self.invoke_handler, self.on_page_load),
+  /// Runs the configured Tauri application.
+  pub fn run(mut self, context: Context<A>) -> crate::Result<()> {
+    let manager = WindowManager::with_handlers(
+      context,
+      self.plugins,
+      self.invoke_handler,
+      self.on_page_load,
+    );
+
+    // set up all the windows defined in the config
+    for config in manager.config().tauri.windows.clone() {
+      let url = config.url.clone();
+      let label = config
+        .label
+        .parse()
+        .unwrap_or_else(|_| panic!("bad label found in config: {}", config.label));
+
+      self
+        .pending_windows
+        .push(PendingWindow::new(WindowConfig(config), label, url));
+    }
+
+    manager.initialize_plugins()?;
+
+    let mut app = App {
+      runtime: R::new()?,
+      manager,
+    };
+
+    let pending_labels = self
+      .pending_windows
+      .iter()
+      .map(|p| p.label.clone())
+      .collect::<Vec<_>>();
+
+    #[cfg(feature = "updater")]
+    let mut main_window = None;
+
+    for pending in self.pending_windows {
+      let pending = app.manager.prepare_window(pending, &pending_labels)?;
+      let detached = app.runtime.create_window(pending)?;
+      let _window = app.manager.attach_window(detached);
+      #[cfg(feature = "updater")]
+      if main_window.is_none() {
+        main_window = Some(_window);
+      }
     }
+
+    #[cfg(feature = "updater")]
+    app.run_updater(main_window);
+
+    (self.setup)(&mut app)?;
+    app.runtime.run();
+    Ok(())
   }
 }
 
-/// Make `Wry` the default `ApplicationExt` for `AppBuilder`
-impl<A: Assets> Default for AppBuilder<String, String, A, Wry> {
+/// Make `Wry` the default `Runtime` for `Builder`
+impl<A: Assets> Default for Builder<String, String, A, Wry> {
   fn default() -> Self {
     Self::new()
   }

+ 9 - 5
tauri/src/runtime/manager.rs

@@ -81,13 +81,14 @@ where
 {
   pub(crate) fn with_handlers(
     context: Context<A>,
+    plugins: PluginStore<Self>,
     invoke_handler: Box<InvokeHandler<Self>>,
     on_page_load: Box<OnPageLoad<Self>>,
   ) -> Self {
     Self {
       inner: Arc::new(InnerWindowManager {
         windows: Mutex::default(),
-        plugins: Mutex::default(),
+        plugins: Mutex::new(plugins),
         listeners: Listeners::default(),
         invoke_handler,
         on_page_load,
@@ -333,15 +334,18 @@ where
 
 #[cfg(test)]
 mod test {
-  use crate::{generate_context, runtime::flavor::wry::Wry};
-
   use super::WindowManager;
+  use crate::{generate_context, plugin::PluginStore, runtime::flavor::wry::Wry};
 
   #[test]
   fn check_get_url() {
     let context = generate_context!("test/fixture/src-tauri/tauri.conf.json", crate::Context);
-    let manager: WindowManager<String, String, _, Wry> =
-      WindowManager::with_handlers(context, Box::new(|_| ()), Box::new(|_, _| ()));
+    let manager: WindowManager<String, String, _, Wry> = WindowManager::with_handlers(
+      context,
+      PluginStore::default(),
+      Box::new(|_| ()),
+      Box::new(|_, _| ()),
+    );
 
     #[cfg(custom_protocol)]
     assert_eq!(manager.get_url(), "tauri://studio.tauri.example");