app.rs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425
  1. // Copyright 2019-2021 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. #[cfg(feature = "system-tray")]
  5. pub(crate) mod tray;
  6. use crate::{
  7. api::ipc::CallbackFn,
  8. command::{CommandArg, CommandItem},
  9. hooks::{
  10. window_invoke_responder, InvokeHandler, InvokeResponder, OnPageLoad, PageLoadPayload, SetupHook,
  11. },
  12. manager::{Asset, CustomProtocol, WindowManager},
  13. plugin::{Plugin, PluginStore},
  14. runtime::{
  15. http::{Request as HttpRequest, Response as HttpResponse},
  16. webview::{WebviewAttributes, WindowBuilder as _},
  17. window::{PendingWindow, WindowEvent},
  18. Dispatch, ExitRequestedEventAction, RunEvent as RuntimeRunEvent,
  19. },
  20. scope::FsScope,
  21. sealed::{ManagerBase, RuntimeOrDispatch},
  22. utils::config::{Config, WindowUrl},
  23. utils::{assets::Assets, Env},
  24. window::WindowBuilder,
  25. Context, EventLoopMessage, Invoke, InvokeError, InvokeResponse, Manager, Runtime, Scopes,
  26. StateManager, Window,
  27. };
  28. #[cfg(shell_scope)]
  29. use crate::scope::ShellScope;
  30. use tauri_macros::default_runtime;
  31. use tauri_utils::PackageInfo;
  32. use std::{
  33. collections::HashMap,
  34. path::PathBuf,
  35. sync::{mpsc::Sender, Arc, Weak},
  36. };
  37. use crate::runtime::menu::{Menu, MenuId, MenuIdRef};
  38. use crate::runtime::RuntimeHandle;
  39. #[cfg(feature = "system-tray")]
  40. use crate::runtime::{SystemTrayEvent as RuntimeSystemTrayEvent, TrayIcon};
  41. #[cfg(feature = "updater")]
  42. use crate::updater;
  43. #[cfg(target_os = "macos")]
  44. use crate::ActivationPolicy;
  45. pub(crate) type GlobalMenuEventListener<R> = Box<dyn Fn(WindowMenuEvent<R>) + Send + Sync>;
  46. pub(crate) type GlobalWindowEventListener<R> = Box<dyn Fn(GlobalWindowEvent<R>) + Send + Sync>;
  47. #[cfg(feature = "system-tray")]
  48. type SystemTrayEventListener<R> = Box<dyn Fn(&AppHandle<R>, tray::SystemTrayEvent) + Send + Sync>;
  49. /// Api exposed on the `ExitRequested` event.
  50. #[derive(Debug)]
  51. pub struct ExitRequestApi(Sender<ExitRequestedEventAction>);
  52. impl ExitRequestApi {
  53. /// Prevents the app from exiting
  54. pub fn prevent_exit(&self) {
  55. self.0.send(ExitRequestedEventAction::Prevent).unwrap();
  56. }
  57. }
  58. /// Api exposed on the `CloseRequested` event.
  59. #[derive(Debug)]
  60. pub struct CloseRequestApi(Sender<bool>);
  61. impl CloseRequestApi {
  62. /// Prevents the window from being closed.
  63. pub fn prevent_close(&self) {
  64. self.0.send(true).unwrap();
  65. }
  66. }
  67. /// An application event, triggered from the event loop.
  68. #[derive(Debug)]
  69. #[non_exhaustive]
  70. pub enum RunEvent {
  71. /// Event loop is exiting.
  72. Exit,
  73. /// The app is about to exit
  74. #[non_exhaustive]
  75. ExitRequested {
  76. /// The label of the window that requested the exit.
  77. /// It is the last window managed by tauri.
  78. window_label: String,
  79. /// Event API
  80. api: ExitRequestApi,
  81. },
  82. /// Window close was requested by the user.
  83. #[non_exhaustive]
  84. CloseRequested {
  85. /// The window label.
  86. label: String,
  87. /// Event API.
  88. api: CloseRequestApi,
  89. },
  90. /// Window closed.
  91. WindowClosed(String),
  92. /// Application ready.
  93. Ready,
  94. /// Sent if the event loop is being resumed.
  95. Resumed,
  96. /// Emitted when all of the event loop’s input events have been processed and redraw processing is about to begin.
  97. ///
  98. /// This event is useful as a place to put your code that should be run after all state-changing events have been handled and you want to do stuff (updating state, performing calculations, etc) that happens as the “main body” of your event loop.
  99. MainEventsCleared,
  100. /// Updater event.
  101. #[cfg(feature = "updater")]
  102. #[cfg_attr(doc_cfg, doc(cfg(feature = "updater")))]
  103. Updater(crate::UpdaterEvent),
  104. }
  105. impl From<EventLoopMessage> for RunEvent {
  106. fn from(event: EventLoopMessage) -> Self {
  107. match event {
  108. #[cfg(feature = "updater")]
  109. EventLoopMessage::Updater(event) => RunEvent::Updater(event),
  110. }
  111. }
  112. }
  113. /// A menu event that was triggered on a window.
  114. #[default_runtime(crate::Wry, wry)]
  115. #[derive(Debug)]
  116. pub struct WindowMenuEvent<R: Runtime> {
  117. pub(crate) menu_item_id: MenuId,
  118. pub(crate) window: Window<R>,
  119. }
  120. impl<R: Runtime> WindowMenuEvent<R> {
  121. /// The menu item id.
  122. pub fn menu_item_id(&self) -> MenuIdRef<'_> {
  123. &self.menu_item_id
  124. }
  125. /// The window that the menu belongs to.
  126. pub fn window(&self) -> &Window<R> {
  127. &self.window
  128. }
  129. }
  130. /// A window event that was triggered on the specified window.
  131. #[default_runtime(crate::Wry, wry)]
  132. #[derive(Debug)]
  133. pub struct GlobalWindowEvent<R: Runtime> {
  134. pub(crate) event: WindowEvent,
  135. pub(crate) window: Window<R>,
  136. }
  137. impl<R: Runtime> GlobalWindowEvent<R> {
  138. /// The event payload.
  139. pub fn event(&self) -> &WindowEvent {
  140. &self.event
  141. }
  142. /// The window that the menu belongs to.
  143. pub fn window(&self) -> &Window<R> {
  144. &self.window
  145. }
  146. }
  147. /// The path resolver is a helper for the application-specific [`crate::api::path`] APIs.
  148. #[derive(Debug, Clone)]
  149. pub struct PathResolver {
  150. env: Env,
  151. config: Arc<Config>,
  152. package_info: PackageInfo,
  153. }
  154. impl PathResolver {
  155. /// Returns the path to the resource directory of this app.
  156. pub fn resource_dir(&self) -> Option<PathBuf> {
  157. crate::api::path::resource_dir(&self.package_info, &self.env)
  158. }
  159. /// Returns the path to the suggested directory for your app config files.
  160. pub fn app_dir(&self) -> Option<PathBuf> {
  161. crate::api::path::app_dir(&self.config)
  162. }
  163. /// Returns the path to the suggested log directory.
  164. pub fn log_dir(&self) -> Option<PathBuf> {
  165. crate::api::path::log_dir(&self.config)
  166. }
  167. }
  168. /// The asset resolver is a helper to access the [`tauri_utils::assets::Assets`] interface.
  169. #[derive(Debug, Clone)]
  170. pub struct AssetResolver<R: Runtime> {
  171. manager: WindowManager<R>,
  172. }
  173. impl<R: Runtime> AssetResolver<R> {
  174. /// Gets the app asset associated with the given path.
  175. pub fn get(&self, path: String) -> Option<Asset> {
  176. self.manager.get_asset(path).ok()
  177. }
  178. }
  179. /// A handle to the currently running application.
  180. ///
  181. /// This type implements [`Manager`] which allows for manipulation of global application items.
  182. #[default_runtime(crate::Wry, wry)]
  183. #[derive(Debug)]
  184. pub struct AppHandle<R: Runtime> {
  185. runtime_handle: R::Handle,
  186. manager: WindowManager<R>,
  187. global_shortcut_manager: R::GlobalShortcutManager,
  188. clipboard_manager: R::ClipboardManager,
  189. #[cfg(feature = "system-tray")]
  190. tray_handle: Option<tray::SystemTrayHandle<R>>,
  191. }
  192. impl<R: Runtime> AppHandle<R> {
  193. // currently only used on the updater
  194. #[allow(dead_code)]
  195. pub(crate) fn create_proxy(&self) -> R::EventLoopProxy {
  196. self.runtime_handle.create_proxy()
  197. }
  198. }
  199. #[cfg(feature = "wry")]
  200. impl AppHandle<crate::Wry> {
  201. /// Create a new tao window using a callback. The event loop must be running at this point.
  202. pub fn create_tao_window<
  203. F: FnOnce() -> (String, tauri_runtime_wry::WryWindowBuilder) + Send + 'static,
  204. >(
  205. &self,
  206. f: F,
  207. ) -> crate::Result<Weak<tauri_runtime_wry::Window>> {
  208. self.runtime_handle.create_tao_window(f).map_err(Into::into)
  209. }
  210. /// Sends a window message to the event loop.
  211. pub fn send_tao_window_event(
  212. &self,
  213. window_id: tauri_runtime_wry::WindowId,
  214. message: tauri_runtime_wry::WindowMessage,
  215. ) -> crate::Result<()> {
  216. self
  217. .runtime_handle
  218. .send_event(tauri_runtime_wry::Message::Window(
  219. self.runtime_handle.window_id(window_id),
  220. message,
  221. ))
  222. .map_err(Into::into)
  223. }
  224. }
  225. impl<R: Runtime> Clone for AppHandle<R> {
  226. fn clone(&self) -> Self {
  227. Self {
  228. runtime_handle: self.runtime_handle.clone(),
  229. manager: self.manager.clone(),
  230. global_shortcut_manager: self.global_shortcut_manager.clone(),
  231. clipboard_manager: self.clipboard_manager.clone(),
  232. #[cfg(feature = "system-tray")]
  233. tray_handle: self.tray_handle.clone(),
  234. }
  235. }
  236. }
  237. impl<'de, R: Runtime> CommandArg<'de, R> for AppHandle<R> {
  238. /// Grabs the [`Window`] from the [`CommandItem`] and returns the associated [`AppHandle`]. This will never fail.
  239. fn from_command(command: CommandItem<'de, R>) -> Result<Self, InvokeError> {
  240. Ok(command.message.window().app_handle)
  241. }
  242. }
  243. impl<R: Runtime> AppHandle<R> {
  244. /// Runs the given closure on the main thread.
  245. pub fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> crate::Result<()> {
  246. self
  247. .runtime_handle
  248. .run_on_main_thread(f)
  249. .map_err(Into::into)
  250. }
  251. /// Removes the system tray.
  252. #[cfg(all(windows, feature = "system-tray"))]
  253. #[cfg_attr(doc_cfg, doc(cfg(all(windows, feature = "system-tray"))))]
  254. fn remove_system_tray(&self) -> crate::Result<()> {
  255. self.runtime_handle.remove_system_tray().map_err(Into::into)
  256. }
  257. /// Adds a plugin to the runtime.
  258. pub fn plugin<P: Plugin<R> + 'static>(&self, mut plugin: P) -> crate::Result<()> {
  259. plugin
  260. .initialize(
  261. self,
  262. self
  263. .config()
  264. .plugins
  265. .0
  266. .get(plugin.name())
  267. .cloned()
  268. .unwrap_or_default(),
  269. )
  270. .map_err(|e| crate::Error::PluginInitialization(plugin.name().to_string(), e.to_string()))?;
  271. self
  272. .manager()
  273. .inner
  274. .plugins
  275. .lock()
  276. .unwrap()
  277. .register(plugin);
  278. Ok(())
  279. }
  280. /// Exits the app. This is the same as [`std::process::exit`], but it performs cleanup on this application.
  281. pub fn exit(&self, exit_code: i32) {
  282. self.cleanup_before_exit();
  283. std::process::exit(exit_code);
  284. }
  285. /// Restarts the app. This is the same as [`crate::api::process::restart`], but it performs cleanup on this application.
  286. pub fn restart(&self) {
  287. self.cleanup_before_exit();
  288. crate::api::process::restart(&self.env());
  289. }
  290. /// Runs necessary cleanup tasks before exiting the process
  291. fn cleanup_before_exit(&self) {
  292. #[cfg(shell_execute)]
  293. {
  294. crate::api::process::kill_children();
  295. }
  296. #[cfg(all(windows, feature = "system-tray"))]
  297. {
  298. let _ = self.remove_system_tray();
  299. }
  300. }
  301. }
  302. impl<R: Runtime> Manager<R> for AppHandle<R> {}
  303. impl<R: Runtime> ManagerBase<R> for AppHandle<R> {
  304. fn manager(&self) -> &WindowManager<R> {
  305. &self.manager
  306. }
  307. fn runtime(&self) -> RuntimeOrDispatch<'_, R> {
  308. RuntimeOrDispatch::RuntimeHandle(self.runtime_handle.clone())
  309. }
  310. fn managed_app_handle(&self) -> AppHandle<R> {
  311. self.clone()
  312. }
  313. }
  314. /// The instance of the currently running application.
  315. ///
  316. /// This type implements [`Manager`] which allows for manipulation of global application items.
  317. #[default_runtime(crate::Wry, wry)]
  318. #[derive(Debug)]
  319. pub struct App<R: Runtime> {
  320. runtime: Option<R>,
  321. manager: WindowManager<R>,
  322. global_shortcut_manager: R::GlobalShortcutManager,
  323. clipboard_manager: R::ClipboardManager,
  324. #[cfg(feature = "system-tray")]
  325. tray_handle: Option<tray::SystemTrayHandle<R>>,
  326. handle: AppHandle<R>,
  327. }
  328. impl<R: Runtime> Manager<R> for App<R> {}
  329. impl<R: Runtime> ManagerBase<R> for App<R> {
  330. fn manager(&self) -> &WindowManager<R> {
  331. &self.manager
  332. }
  333. fn runtime(&self) -> RuntimeOrDispatch<'_, R> {
  334. RuntimeOrDispatch::Runtime(self.runtime.as_ref().unwrap())
  335. }
  336. fn managed_app_handle(&self) -> AppHandle<R> {
  337. self.handle()
  338. }
  339. }
  340. macro_rules! shared_app_impl {
  341. ($app: ty) => {
  342. impl<R: Runtime> $app {
  343. /// Creates a new webview window.
  344. ///
  345. /// Data URLs are only supported with the `window-data-url` feature flag.
  346. ///
  347. /// See [`crate::window::WindowBuilder::new`] for an API with extended functionality.
  348. #[deprecated(
  349. since = "1.0.0-rc.4",
  350. note = "The `window_builder` function offers an easier API with extended functionality"
  351. )]
  352. pub fn create_window<F>(
  353. &self,
  354. label: impl Into<String>,
  355. url: WindowUrl,
  356. setup: F,
  357. ) -> crate::Result<Window<R>>
  358. where
  359. F: FnOnce(
  360. <R::Dispatcher as Dispatch<EventLoopMessage>>::WindowBuilder,
  361. WebviewAttributes,
  362. ) -> (
  363. <R::Dispatcher as Dispatch<EventLoopMessage>>::WindowBuilder,
  364. WebviewAttributes,
  365. ),
  366. {
  367. let mut builder = WindowBuilder::<R>::new(self, label, url);
  368. let (window_builder, webview_attributes) =
  369. setup(builder.window_builder, builder.webview_attributes);
  370. builder.window_builder = window_builder;
  371. builder.webview_attributes = webview_attributes;
  372. builder.build()
  373. }
  374. #[cfg(feature = "system-tray")]
  375. #[cfg_attr(doc_cfg, doc(cfg(feature = "system-tray")))]
  376. /// Gets a handle handle to the system tray.
  377. pub fn tray_handle(&self) -> tray::SystemTrayHandle<R> {
  378. self
  379. .tray_handle
  380. .clone()
  381. .expect("tray not configured; use the `Builder#system_tray` API first.")
  382. }
  383. /// The path resolver for the application.
  384. pub fn path_resolver(&self) -> PathResolver {
  385. PathResolver {
  386. env: self.state::<Env>().inner().clone(),
  387. config: self.manager.config(),
  388. package_info: self.manager.package_info().clone(),
  389. }
  390. }
  391. /// Gets a copy of the global shortcut manager instance.
  392. pub fn global_shortcut_manager(&self) -> R::GlobalShortcutManager {
  393. self.global_shortcut_manager.clone()
  394. }
  395. /// Gets a copy of the clipboard manager instance.
  396. pub fn clipboard_manager(&self) -> R::ClipboardManager {
  397. self.clipboard_manager.clone()
  398. }
  399. /// Gets the app's configuration, defined on the `tauri.conf.json` file.
  400. pub fn config(&self) -> Arc<Config> {
  401. self.manager.config()
  402. }
  403. /// Gets the app's package information.
  404. pub fn package_info(&self) -> &PackageInfo {
  405. self.manager.package_info()
  406. }
  407. /// The application's asset resolver.
  408. pub fn asset_resolver(&self) -> AssetResolver<R> {
  409. AssetResolver {
  410. manager: self.manager.clone(),
  411. }
  412. }
  413. }
  414. };
  415. }
  416. shared_app_impl!(App<R>);
  417. shared_app_impl!(AppHandle<R>);
  418. impl<R: Runtime> App<R> {
  419. /// Gets a handle to the application instance.
  420. pub fn handle(&self) -> AppHandle<R> {
  421. self.handle.clone()
  422. }
  423. /// Sets the activation policy for the application. It is set to `NSApplicationActivationPolicyRegular` by default.
  424. ///
  425. /// # Examples
  426. /// ```rust,no_run
  427. /// let mut app = tauri::Builder::default()
  428. /// // on an actual app, remove the string argument
  429. /// .build(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
  430. /// .expect("error while building tauri application");
  431. /// #[cfg(target_os = "macos")]
  432. /// app.set_activation_policy(tauri::ActivationPolicy::Accessory);
  433. /// app.run(|_app_handle, _event| {});
  434. /// ```
  435. #[cfg(target_os = "macos")]
  436. #[cfg_attr(doc_cfg, doc(cfg(target_os = "macos")))]
  437. pub fn set_activation_policy(&mut self, activation_policy: ActivationPolicy) {
  438. self
  439. .runtime
  440. .as_mut()
  441. .unwrap()
  442. .set_activation_policy(activation_policy);
  443. }
  444. /// Runs the application.
  445. ///
  446. /// # Examples
  447. /// ```rust,no_run
  448. /// let app = tauri::Builder::default()
  449. /// // on an actual app, remove the string argument
  450. /// .build(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
  451. /// .expect("error while building tauri application");
  452. /// app.run(|_app_handle, event| match event {
  453. /// tauri::RunEvent::ExitRequested { api, .. } => {
  454. /// api.prevent_exit();
  455. /// }
  456. /// _ => {}
  457. /// });
  458. /// ```
  459. pub fn run<F: FnMut(&AppHandle<R>, RunEvent) + 'static>(mut self, mut callback: F) {
  460. let app_handle = self.handle();
  461. let manager = self.manager.clone();
  462. self.runtime.take().unwrap().run(move |event| match event {
  463. RuntimeRunEvent::Exit => {
  464. app_handle.cleanup_before_exit();
  465. on_event_loop_event(
  466. &app_handle,
  467. RuntimeRunEvent::Exit,
  468. &manager,
  469. Some(&mut callback),
  470. );
  471. }
  472. _ => {
  473. on_event_loop_event(&app_handle, event, &manager, Some(&mut callback));
  474. }
  475. });
  476. }
  477. /// Runs a iteration of the runtime event loop and immediately return.
  478. ///
  479. /// Note that when using this API, app cleanup is not automatically done.
  480. /// The cleanup calls [`crate::api::process::kill_children`] so you may want to call that function before exiting the application.
  481. /// Additionally, the cleanup calls [AppHandle#remove_system_tray](`AppHandle#method.remove_system_tray`) (Windows only).
  482. ///
  483. /// # Examples
  484. /// ```rust,no_run
  485. /// let mut app = tauri::Builder::default()
  486. /// // on an actual app, remove the string argument
  487. /// .build(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
  488. /// .expect("error while building tauri application");
  489. /// loop {
  490. /// let iteration = app.run_iteration();
  491. /// if iteration.window_count == 0 {
  492. /// break;
  493. /// }
  494. /// }
  495. /// ```
  496. pub fn run_iteration(&mut self) -> crate::runtime::RunIteration {
  497. let manager = self.manager.clone();
  498. let app_handle = self.handle();
  499. self.runtime.as_mut().unwrap().run_iteration(move |event| {
  500. on_event_loop_event(
  501. &app_handle,
  502. event,
  503. &manager,
  504. Option::<&mut Box<dyn FnMut(&AppHandle<R>, RunEvent)>>::None,
  505. )
  506. })
  507. }
  508. }
  509. #[cfg(feature = "updater")]
  510. impl<R: Runtime> App<R> {
  511. /// Runs the updater hook with built-in dialog.
  512. fn run_updater_dialog(&self) {
  513. let updater_config = self.manager.config().tauri.updater.clone();
  514. let package_info = self.manager.package_info().clone();
  515. let handle = self.handle();
  516. crate::async_runtime::spawn(async move {
  517. updater::check_update_with_dialog(updater_config, package_info, handle).await
  518. });
  519. }
  520. /// Listen updater events when dialog are disabled.
  521. fn listen_updater_events(&self, handle: AppHandle<R>) {
  522. let updater_config = self.manager.config().tauri.updater.clone();
  523. updater::listener(updater_config, self.manager.package_info().clone(), &handle);
  524. }
  525. fn run_updater(&self) {
  526. let handle = self.handle();
  527. let handle_ = handle.clone();
  528. let updater_config = self.manager.config().tauri.updater.clone();
  529. // check if updater is active or not
  530. if updater_config.dialog && updater_config.active {
  531. // if updater dialog is enabled spawn a new task
  532. self.run_updater_dialog();
  533. let config = self.manager.config().tauri.updater.clone();
  534. let package_info = self.manager.package_info().clone();
  535. // When dialog is enabled, if user want to recheck
  536. // if an update is available after first start
  537. // invoke the Event `tauri://update` from JS or rust side.
  538. handle.listen_global(updater::EVENT_CHECK_UPDATE, move |_msg| {
  539. let handle = handle_.clone();
  540. let package_info = package_info.clone();
  541. let config = config.clone();
  542. // re-spawn task inside tokyo to launch the download
  543. // we don't need to emit anything as everything is handled
  544. // by the process (user is asked to restart at the end)
  545. // and it's handled by the updater
  546. crate::async_runtime::spawn(async move {
  547. updater::check_update_with_dialog(config, package_info, handle).await
  548. });
  549. });
  550. } else if updater_config.active {
  551. // we only listen for `tauri://update`
  552. // once we receive the call, we check if an update is available or not
  553. // if there is a new update we emit `tauri://update-available` with details
  554. // this is the user responsabilities to display dialog and ask if user want to install
  555. // to install the update you need to invoke the Event `tauri://update-install`
  556. self.listen_updater_events(handle);
  557. }
  558. }
  559. }
  560. /// Builds a Tauri application.
  561. ///
  562. /// # Examples
  563. /// ```rust,no_run
  564. /// tauri::Builder::default()
  565. /// // on an actual app, remove the string argument
  566. /// .run(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
  567. /// .expect("error while running tauri application");
  568. /// ```
  569. #[allow(clippy::type_complexity)]
  570. pub struct Builder<R: Runtime> {
  571. /// A flag indicating that the runtime must be started on an environment that supports the event loop not on the main thread.
  572. #[cfg(any(windows, target_os = "linux"))]
  573. #[cfg_attr(doc_cfg, doc(any(windows, target_os = "linux")))]
  574. runtime_any_thread: bool,
  575. /// The JS message handler.
  576. invoke_handler: Box<InvokeHandler<R>>,
  577. /// The JS message responder.
  578. invoke_responder: Arc<InvokeResponder<R>>,
  579. /// The script that initializes the `window.__TAURI_POST_MESSAGE__` function.
  580. invoke_initialization_script: String,
  581. /// The setup hook.
  582. setup: SetupHook<R>,
  583. /// Page load hook.
  584. on_page_load: Box<OnPageLoad<R>>,
  585. /// windows to create when starting up.
  586. pending_windows: Vec<PendingWindow<EventLoopMessage, R>>,
  587. /// All passed plugins
  588. plugins: PluginStore<R>,
  589. /// The webview protocols available to all windows.
  590. uri_scheme_protocols: HashMap<String, Arc<CustomProtocol<R>>>,
  591. /// App state.
  592. state: StateManager,
  593. /// The menu set to all windows.
  594. menu: Option<Menu>,
  595. /// Menu event handlers that listens to all windows.
  596. menu_event_listeners: Vec<GlobalMenuEventListener<R>>,
  597. /// Window event handlers that listens to all windows.
  598. window_event_listeners: Vec<GlobalWindowEventListener<R>>,
  599. /// The app system tray.
  600. #[cfg(feature = "system-tray")]
  601. system_tray: Option<tray::SystemTray>,
  602. /// System tray event handlers.
  603. #[cfg(feature = "system-tray")]
  604. system_tray_event_listeners: Vec<SystemTrayEventListener<R>>,
  605. }
  606. impl<R: Runtime> Builder<R> {
  607. /// Creates a new App builder.
  608. pub fn new() -> Self {
  609. Self {
  610. #[cfg(any(windows, target_os = "linux"))]
  611. runtime_any_thread: false,
  612. setup: Box::new(|_| Ok(())),
  613. invoke_handler: Box::new(|_| ()),
  614. invoke_responder: Arc::new(window_invoke_responder),
  615. invoke_initialization_script:
  616. "Object.defineProperty(window, '__TAURI_POST_MESSAGE__', { value: (message) => window.ipc.postMessage(JSON.stringify(message)) })".into(),
  617. on_page_load: Box::new(|_, _| ()),
  618. pending_windows: Default::default(),
  619. plugins: PluginStore::default(),
  620. uri_scheme_protocols: Default::default(),
  621. state: StateManager::new(),
  622. menu: None,
  623. menu_event_listeners: Vec::new(),
  624. window_event_listeners: Vec::new(),
  625. #[cfg(feature = "system-tray")]
  626. system_tray: None,
  627. #[cfg(feature = "system-tray")]
  628. system_tray_event_listeners: Vec::new(),
  629. }
  630. }
  631. /// Builds a new Tauri application running on any thread, bypassing the main thread requirement.
  632. ///
  633. /// ## Platform-specific
  634. ///
  635. /// - **macOS**: on macOS the application *must* be executed on the main thread, so this function is not exposed.
  636. #[cfg(any(windows, target_os = "linux"))]
  637. #[cfg_attr(doc_cfg, doc(any(windows, target_os = "linux")))]
  638. #[must_use]
  639. pub fn any_thread(mut self) -> Self {
  640. self.runtime_any_thread = true;
  641. self
  642. }
  643. /// Defines the JS message handler callback.
  644. ///
  645. /// # Examples
  646. /// ```rust,no_run
  647. /// #[tauri::command]
  648. /// fn command_1() -> String {
  649. /// return "hello world".to_string();
  650. /// }
  651. /// tauri::Builder::default()
  652. /// .invoke_handler(tauri::generate_handler![
  653. /// command_1,
  654. /// // etc...
  655. /// ]);
  656. /// ```
  657. #[must_use]
  658. pub fn invoke_handler<F>(mut self, invoke_handler: F) -> Self
  659. where
  660. F: Fn(Invoke<R>) + Send + Sync + 'static,
  661. {
  662. self.invoke_handler = Box::new(invoke_handler);
  663. self
  664. }
  665. /// Defines a custom JS message system.
  666. ///
  667. /// The `responder` is a function that will be called when a command has been executed and must send a response to the JS layer.
  668. ///
  669. /// The `initialization_script` is a script that initializes `window.__TAURI_POST_MESSAGE__`.
  670. /// That function must take the `message: object` argument and send it to the backend.
  671. #[must_use]
  672. pub fn invoke_system<F>(mut self, initialization_script: String, responder: F) -> Self
  673. where
  674. F: Fn(Window<R>, InvokeResponse, CallbackFn, CallbackFn) + Send + Sync + 'static,
  675. {
  676. self.invoke_initialization_script = initialization_script;
  677. self.invoke_responder = Arc::new(responder);
  678. self
  679. }
  680. /// Defines the setup hook.
  681. ///
  682. /// # Examples
  683. /// ```rust,no_run
  684. /// use tauri::Manager;
  685. /// tauri::Builder::default()
  686. /// .setup(|app| {
  687. /// let main_window = app.get_window("main").unwrap();
  688. #[cfg_attr(
  689. feature = "dialog",
  690. doc = r#" tauri::api::dialog::blocking::message(Some(&main_window), "Hello", "Welcome back!");"#
  691. )]
  692. /// Ok(())
  693. /// });
  694. /// ```
  695. #[must_use]
  696. pub fn setup<F>(mut self, setup: F) -> Self
  697. where
  698. F: FnOnce(&mut App<R>) -> Result<(), Box<dyn std::error::Error + Send>> + Send + 'static,
  699. {
  700. self.setup = Box::new(setup);
  701. self
  702. }
  703. /// Defines the page load hook.
  704. #[must_use]
  705. pub fn on_page_load<F>(mut self, on_page_load: F) -> Self
  706. where
  707. F: Fn(Window<R>, PageLoadPayload) + Send + Sync + 'static,
  708. {
  709. self.on_page_load = Box::new(on_page_load);
  710. self
  711. }
  712. /// Adds a plugin to the runtime.
  713. #[must_use]
  714. pub fn plugin<P: Plugin<R> + 'static>(mut self, plugin: P) -> Self {
  715. self.plugins.register(plugin);
  716. self
  717. }
  718. /// Add `state` to the state managed by the application.
  719. ///
  720. /// This method can be called any number of times as long as each call
  721. /// refers to a different `T`.
  722. ///
  723. /// Managed state can be retrieved by any command handler via the
  724. /// [`State`](crate::State) guard. In particular, if a value of type `T`
  725. /// is managed by Tauri, adding `State<T>` to the list of arguments in a
  726. /// command handler instructs Tauri to retrieve the managed value.
  727. ///
  728. /// # Panics
  729. ///
  730. /// Panics if state of type `T` is already being managed.
  731. ///
  732. /// # Mutability
  733. ///
  734. /// Since the managed state is global and must be [`Send`] + [`Sync`], mutations can only happen through interior mutability:
  735. ///
  736. /// ```rust,no_run
  737. /// use std::{collections::HashMap, sync::Mutex};
  738. /// use tauri::State;
  739. /// // here we use Mutex to achieve interior mutability
  740. /// struct Storage {
  741. /// store: Mutex<HashMap<u64, String>>,
  742. /// }
  743. /// struct Connection;
  744. /// struct DbConnection {
  745. /// db: Mutex<Option<Connection>>,
  746. /// }
  747. ///
  748. /// #[tauri::command]
  749. /// fn connect(connection: State<DbConnection>) {
  750. /// // initialize the connection, mutating the state with interior mutability
  751. /// *connection.db.lock().unwrap() = Some(Connection {});
  752. /// }
  753. ///
  754. /// #[tauri::command]
  755. /// fn storage_insert(key: u64, value: String, storage: State<Storage>) {
  756. /// // mutate the storage behind the Mutex
  757. /// storage.store.lock().unwrap().insert(key, value);
  758. /// }
  759. ///
  760. /// tauri::Builder::default()
  761. /// .manage(Storage { store: Default::default() })
  762. /// .manage(DbConnection { db: Default::default() })
  763. /// .invoke_handler(tauri::generate_handler![connect, storage_insert])
  764. /// // on an actual app, remove the string argument
  765. /// .run(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
  766. /// .expect("error while running tauri application");
  767. /// ```
  768. ///
  769. /// # Examples
  770. ///
  771. /// ```rust,no_run
  772. /// use tauri::State;
  773. ///
  774. /// struct MyInt(isize);
  775. /// struct MyString(String);
  776. ///
  777. /// #[tauri::command]
  778. /// fn int_command(state: State<MyInt>) -> String {
  779. /// format!("The stateful int is: {}", state.0)
  780. /// }
  781. ///
  782. /// #[tauri::command]
  783. /// fn string_command<'r>(state: State<'r, MyString>) {
  784. /// println!("state: {}", state.inner().0);
  785. /// }
  786. ///
  787. /// tauri::Builder::default()
  788. /// .manage(MyInt(10))
  789. /// .manage(MyString("Hello, managed state!".to_string()))
  790. /// .invoke_handler(tauri::generate_handler![int_command, string_command])
  791. /// // on an actual app, remove the string argument
  792. /// .run(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
  793. /// .expect("error while running tauri application");
  794. /// ```
  795. #[must_use]
  796. pub fn manage<T>(self, state: T) -> Self
  797. where
  798. T: Send + Sync + 'static,
  799. {
  800. let type_name = std::any::type_name::<T>();
  801. assert!(
  802. self.state.set(state),
  803. "state for type '{}' is already being managed",
  804. type_name
  805. );
  806. self
  807. }
  808. /// Creates a new webview window.
  809. ///
  810. /// # Examples
  811. /// ```rust,no_run
  812. /// use tauri::WindowBuilder;
  813. /// tauri::Builder::default()
  814. /// .create_window("main", tauri::WindowUrl::default(), |win, webview| {
  815. /// let win = win
  816. /// .title("My Main Window")
  817. /// .resizable(true)
  818. /// .inner_size(800.0, 550.0)
  819. /// .min_inner_size(400.0, 200.0);
  820. /// return (win, webview);
  821. /// });
  822. /// ```
  823. pub fn create_window<F>(
  824. mut self,
  825. label: impl Into<String>,
  826. url: WindowUrl,
  827. setup: F,
  828. ) -> crate::Result<Self>
  829. where
  830. F: FnOnce(
  831. <R::Dispatcher as Dispatch<EventLoopMessage>>::WindowBuilder,
  832. WebviewAttributes,
  833. ) -> (
  834. <R::Dispatcher as Dispatch<EventLoopMessage>>::WindowBuilder,
  835. WebviewAttributes,
  836. ),
  837. {
  838. let (window_builder, webview_attributes) = setup(
  839. <R::Dispatcher as Dispatch<EventLoopMessage>>::WindowBuilder::new(),
  840. WebviewAttributes::new(url),
  841. );
  842. self.pending_windows.push(PendingWindow::new(
  843. window_builder,
  844. webview_attributes,
  845. label,
  846. )?);
  847. Ok(self)
  848. }
  849. /// Adds the icon configured on `tauri.conf.json` to the system tray with the specified menu items.
  850. #[cfg(feature = "system-tray")]
  851. #[cfg_attr(doc_cfg, doc(cfg(feature = "system-tray")))]
  852. #[must_use]
  853. pub fn system_tray(mut self, system_tray: tray::SystemTray) -> Self {
  854. self.system_tray.replace(system_tray);
  855. self
  856. }
  857. /// Sets the menu to use on all windows.
  858. ///
  859. /// # Examples
  860. /// ```rust,no_run
  861. /// use tauri::{MenuEntry, Submenu, MenuItem, Menu, CustomMenuItem};
  862. ///
  863. /// tauri::Builder::default()
  864. /// .menu(Menu::with_items([
  865. /// MenuEntry::Submenu(Submenu::new(
  866. /// "File",
  867. /// Menu::with_items([
  868. /// MenuItem::CloseWindow.into(),
  869. /// #[cfg(target_os = "macos")]
  870. /// CustomMenuItem::new("hello", "Hello").into(),
  871. /// ]),
  872. /// )),
  873. /// ]));
  874. /// ```
  875. #[must_use]
  876. pub fn menu(mut self, menu: Menu) -> Self {
  877. self.menu.replace(menu);
  878. self
  879. }
  880. /// Registers a menu event handler for all windows.
  881. ///
  882. /// # Examples
  883. /// ```rust,no_run
  884. /// use tauri::{Menu, MenuEntry, Submenu, CustomMenuItem, api, Manager};
  885. /// tauri::Builder::default()
  886. /// .menu(Menu::with_items([
  887. /// MenuEntry::Submenu(Submenu::new(
  888. /// "File",
  889. /// Menu::with_items([
  890. /// CustomMenuItem::new("New", "New").into(),
  891. /// CustomMenuItem::new("Learn More", "Learn More").into(),
  892. /// ]),
  893. /// )),
  894. /// ]))
  895. /// .on_menu_event(|event| {
  896. /// match event.menu_item_id() {
  897. /// "Learn More" => {
  898. /// // open in browser (requires the `shell-open-api` feature)
  899. #[cfg_attr(
  900. feature = "shell-open-api",
  901. doc = r#" api::shell::open(&event.window().shell_scope(), "https://github.com/tauri-apps/tauri".to_string(), None).unwrap();"#
  902. )]
  903. /// }
  904. /// id => {
  905. /// // do something with other events
  906. /// println!("got menu event: {}", id);
  907. /// }
  908. /// }
  909. /// });
  910. /// ```
  911. #[must_use]
  912. pub fn on_menu_event<F: Fn(WindowMenuEvent<R>) + Send + Sync + 'static>(
  913. mut self,
  914. handler: F,
  915. ) -> Self {
  916. self.menu_event_listeners.push(Box::new(handler));
  917. self
  918. }
  919. /// Registers a window event handler for all windows.
  920. ///
  921. /// # Examples
  922. /// ```rust,no_run
  923. /// tauri::Builder::default()
  924. /// .on_window_event(|event| match event.event() {
  925. /// tauri::WindowEvent::Focused(focused) => {
  926. /// // hide window whenever it loses focus
  927. /// if !focused {
  928. /// event.window().hide().unwrap();
  929. /// }
  930. /// }
  931. /// _ => {}
  932. /// });
  933. /// ```
  934. #[must_use]
  935. pub fn on_window_event<F: Fn(GlobalWindowEvent<R>) + Send + Sync + 'static>(
  936. mut self,
  937. handler: F,
  938. ) -> Self {
  939. self.window_event_listeners.push(Box::new(handler));
  940. self
  941. }
  942. /// Registers a system tray event handler.
  943. ///
  944. /// # Examples
  945. /// ```rust,no_run
  946. /// use tauri::Manager;
  947. /// tauri::Builder::default()
  948. /// .on_system_tray_event(|app, event| match event {
  949. /// // show window with id "main" when the tray is left clicked
  950. /// tauri::SystemTrayEvent::LeftClick { .. } => {
  951. /// let window = app.get_window("main").unwrap();
  952. /// window.show().unwrap();
  953. /// window.set_focus().unwrap();
  954. /// }
  955. /// _ => {}
  956. /// });
  957. /// ```
  958. #[cfg(feature = "system-tray")]
  959. #[cfg_attr(doc_cfg, doc(cfg(feature = "system-tray")))]
  960. #[must_use]
  961. pub fn on_system_tray_event<
  962. F: Fn(&AppHandle<R>, tray::SystemTrayEvent) + Send + Sync + 'static,
  963. >(
  964. mut self,
  965. handler: F,
  966. ) -> Self {
  967. self.system_tray_event_listeners.push(Box::new(handler));
  968. self
  969. }
  970. /// Registers a URI scheme protocol available to all webviews.
  971. /// Leverages [setURLSchemeHandler](https://developer.apple.com/documentation/webkit/wkwebviewconfiguration/2875766-seturlschemehandler) on macOS,
  972. /// [AddWebResourceRequestedFilter](https://docs.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2.addwebresourcerequestedfilter?view=webview2-dotnet-1.0.774.44) on Windows
  973. /// and [webkit-web-context-register-uri-scheme](https://webkitgtk.org/reference/webkit2gtk/stable/WebKitWebContext.html#webkit-web-context-register-uri-scheme) on Linux.
  974. ///
  975. /// # Arguments
  976. ///
  977. /// * `uri_scheme` The URI scheme to register, such as `example`.
  978. /// * `protocol` the protocol associated with the given URI scheme. It's a function that takes an URL such as `example://localhost/asset.css`.
  979. #[must_use]
  980. pub fn register_uri_scheme_protocol<
  981. N: Into<String>,
  982. H: Fn(&AppHandle<R>, &HttpRequest) -> Result<HttpResponse, Box<dyn std::error::Error>>
  983. + Send
  984. + Sync
  985. + 'static,
  986. >(
  987. mut self,
  988. uri_scheme: N,
  989. protocol: H,
  990. ) -> Self {
  991. self.uri_scheme_protocols.insert(
  992. uri_scheme.into(),
  993. Arc::new(CustomProtocol {
  994. protocol: Box::new(protocol),
  995. }),
  996. );
  997. self
  998. }
  999. /// Builds the application.
  1000. #[allow(clippy::type_complexity)]
  1001. pub fn build<A: Assets>(mut self, context: Context<A>) -> crate::Result<App<R>> {
  1002. #[cfg(feature = "system-tray")]
  1003. let system_tray_icon = {
  1004. let icon = context.system_tray_icon.clone();
  1005. // check the icon format if the system tray is configured
  1006. if self.system_tray.is_some() {
  1007. use std::io::{Error, ErrorKind};
  1008. #[cfg(target_os = "linux")]
  1009. if let Some(TrayIcon::Raw(..)) = icon {
  1010. return Err(crate::Error::InvalidIcon(Box::new(Error::new(
  1011. ErrorKind::InvalidInput,
  1012. "system tray icons on linux must be a file path",
  1013. ))));
  1014. }
  1015. #[cfg(not(target_os = "linux"))]
  1016. if let Some(TrayIcon::File(_)) = icon {
  1017. return Err(crate::Error::InvalidIcon(Box::new(Error::new(
  1018. ErrorKind::InvalidInput,
  1019. "system tray icons on non-linux platforms must be the raw bytes",
  1020. ))));
  1021. }
  1022. }
  1023. icon
  1024. };
  1025. #[cfg(all(feature = "system-tray", target_os = "macos"))]
  1026. let system_tray_icon_as_template = context
  1027. .config
  1028. .tauri
  1029. .system_tray
  1030. .as_ref()
  1031. .map(|t| t.icon_as_template)
  1032. .unwrap_or_default();
  1033. #[cfg(shell_scope)]
  1034. let shell_scope = context.shell_scope.clone();
  1035. let manager = WindowManager::with_handlers(
  1036. context,
  1037. self.plugins,
  1038. self.invoke_handler,
  1039. self.on_page_load,
  1040. self.uri_scheme_protocols,
  1041. self.state,
  1042. self.window_event_listeners,
  1043. (self.menu, self.menu_event_listeners),
  1044. (self.invoke_responder, self.invoke_initialization_script),
  1045. );
  1046. // set up all the windows defined in the config
  1047. for config in manager.config().tauri.windows.clone() {
  1048. let url = config.url.clone();
  1049. let label = config.label.clone();
  1050. let file_drop_enabled = config.file_drop_enabled;
  1051. let mut webview_attributes = WebviewAttributes::new(url);
  1052. if !file_drop_enabled {
  1053. webview_attributes = webview_attributes.disable_file_drop_handler();
  1054. }
  1055. self.pending_windows.push(PendingWindow::with_config(
  1056. config,
  1057. webview_attributes,
  1058. label,
  1059. )?);
  1060. }
  1061. #[cfg(any(windows, target_os = "linux"))]
  1062. let runtime = if self.runtime_any_thread {
  1063. R::new_any_thread()?
  1064. } else {
  1065. R::new()?
  1066. };
  1067. #[cfg(not(any(windows, target_os = "linux")))]
  1068. let runtime = R::new()?;
  1069. let runtime_handle = runtime.handle();
  1070. let global_shortcut_manager = runtime.global_shortcut_manager();
  1071. let clipboard_manager = runtime.clipboard_manager();
  1072. let mut app = App {
  1073. runtime: Some(runtime),
  1074. manager: manager.clone(),
  1075. global_shortcut_manager: global_shortcut_manager.clone(),
  1076. clipboard_manager: clipboard_manager.clone(),
  1077. #[cfg(feature = "system-tray")]
  1078. tray_handle: None,
  1079. handle: AppHandle {
  1080. runtime_handle,
  1081. manager,
  1082. global_shortcut_manager,
  1083. clipboard_manager,
  1084. #[cfg(feature = "system-tray")]
  1085. tray_handle: None,
  1086. },
  1087. };
  1088. let env = Env::default();
  1089. app.manage(Scopes {
  1090. fs: FsScope::for_fs_api(
  1091. &app.manager.config(),
  1092. app.package_info(),
  1093. &env,
  1094. &app.config().tauri.allowlist.fs.scope,
  1095. )?,
  1096. #[cfg(protocol_asset)]
  1097. asset_protocol: FsScope::for_fs_api(
  1098. &app.manager.config(),
  1099. app.package_info(),
  1100. &env,
  1101. &app.config().tauri.allowlist.protocol.asset_scope,
  1102. )?,
  1103. #[cfg(http_request)]
  1104. http: crate::scope::HttpScope::for_http_api(&app.config().tauri.allowlist.http.scope),
  1105. #[cfg(shell_scope)]
  1106. shell: ShellScope::new(shell_scope),
  1107. });
  1108. app.manage(env);
  1109. #[cfg(windows)]
  1110. {
  1111. if let Some(w) = &app
  1112. .manager
  1113. .config()
  1114. .tauri
  1115. .bundle
  1116. .windows
  1117. .webview_fixed_runtime_path
  1118. {
  1119. if let Some(resource_dir) = app.path_resolver().resource_dir() {
  1120. std::env::set_var("WEBVIEW2_BROWSER_EXECUTABLE_FOLDER", resource_dir.join(w));
  1121. } else {
  1122. #[cfg(debug_assertions)]
  1123. eprintln!(
  1124. "failed to resolve resource directory; fallback to the installed Webview2 runtime."
  1125. );
  1126. }
  1127. }
  1128. }
  1129. #[cfg(feature = "system-tray")]
  1130. if let Some(system_tray) = self.system_tray {
  1131. let mut ids = HashMap::new();
  1132. if let Some(menu) = system_tray.menu() {
  1133. tray::get_menu_ids(&mut ids, menu);
  1134. }
  1135. let mut tray = tray::SystemTray::new();
  1136. if let Some(menu) = system_tray.menu {
  1137. tray = tray.with_menu(menu);
  1138. }
  1139. #[cfg(not(target_os = "macos"))]
  1140. let tray_handler = app
  1141. .runtime
  1142. .as_ref()
  1143. .unwrap()
  1144. .system_tray(
  1145. tray.with_icon(
  1146. system_tray
  1147. .icon
  1148. .or(system_tray_icon)
  1149. .expect("tray icon not found; please configure it on tauri.conf.json"),
  1150. ),
  1151. )
  1152. .expect("failed to run tray");
  1153. #[cfg(target_os = "macos")]
  1154. let tray_handler = app
  1155. .runtime
  1156. .as_ref()
  1157. .unwrap()
  1158. .system_tray(
  1159. tray
  1160. .with_icon(
  1161. system_tray
  1162. .icon
  1163. .or(system_tray_icon)
  1164. .expect("tray icon not found; please configure it on tauri.conf.json"),
  1165. )
  1166. .with_icon_as_template(system_tray_icon_as_template),
  1167. )
  1168. .expect("failed to run tray");
  1169. let tray_handle = tray::SystemTrayHandle {
  1170. ids: Arc::new(std::sync::Mutex::new(ids)),
  1171. inner: tray_handler,
  1172. };
  1173. let ids = tray_handle.ids.clone();
  1174. app.tray_handle.replace(tray_handle.clone());
  1175. app.handle.tray_handle.replace(tray_handle);
  1176. for listener in self.system_tray_event_listeners {
  1177. let app_handle = app.handle();
  1178. let ids = ids.clone();
  1179. let listener = Arc::new(std::sync::Mutex::new(listener));
  1180. app
  1181. .runtime
  1182. .as_mut()
  1183. .unwrap()
  1184. .on_system_tray_event(move |event| {
  1185. let app_handle = app_handle.clone();
  1186. let event = match event {
  1187. RuntimeSystemTrayEvent::MenuItemClick(id) => tray::SystemTrayEvent::MenuItemClick {
  1188. id: ids.lock().unwrap().get(id).unwrap().clone(),
  1189. },
  1190. RuntimeSystemTrayEvent::LeftClick { position, size } => {
  1191. tray::SystemTrayEvent::LeftClick {
  1192. position: *position,
  1193. size: *size,
  1194. }
  1195. }
  1196. RuntimeSystemTrayEvent::RightClick { position, size } => {
  1197. tray::SystemTrayEvent::RightClick {
  1198. position: *position,
  1199. size: *size,
  1200. }
  1201. }
  1202. RuntimeSystemTrayEvent::DoubleClick { position, size } => {
  1203. tray::SystemTrayEvent::DoubleClick {
  1204. position: *position,
  1205. size: *size,
  1206. }
  1207. }
  1208. };
  1209. let listener = listener.clone();
  1210. listener.lock().unwrap()(&app_handle, event);
  1211. });
  1212. }
  1213. }
  1214. app.manager.initialize_plugins(&app.handle())?;
  1215. let window_labels = self
  1216. .pending_windows
  1217. .iter()
  1218. .map(|p| p.label.clone())
  1219. .collect::<Vec<_>>();
  1220. for pending in self.pending_windows {
  1221. let pending =
  1222. app
  1223. .manager
  1224. .prepare_window(app.handle.clone(), pending, &window_labels, None)?;
  1225. let detached = app.runtime.as_ref().unwrap().create_window(pending)?;
  1226. let _window = app.manager.attach_window(app.handle(), detached);
  1227. }
  1228. (self.setup)(&mut app).map_err(|e| crate::Error::Setup(e))?;
  1229. #[cfg(feature = "updater")]
  1230. app.run_updater();
  1231. Ok(app)
  1232. }
  1233. /// Runs the configured Tauri application.
  1234. pub fn run<A: Assets>(self, context: Context<A>) -> crate::Result<()> {
  1235. self.build(context)?.run(|_, _| {});
  1236. Ok(())
  1237. }
  1238. }
  1239. fn on_event_loop_event<R: Runtime, F: FnMut(&AppHandle<R>, RunEvent) + 'static>(
  1240. app_handle: &AppHandle<R>,
  1241. event: RuntimeRunEvent<EventLoopMessage>,
  1242. manager: &WindowManager<R>,
  1243. callback: Option<&mut F>,
  1244. ) {
  1245. if let RuntimeRunEvent::WindowClose(label) = &event {
  1246. manager.on_window_close(label);
  1247. }
  1248. let event = match event {
  1249. RuntimeRunEvent::Exit => RunEvent::Exit,
  1250. RuntimeRunEvent::ExitRequested { window_label, tx } => RunEvent::ExitRequested {
  1251. window_label,
  1252. api: ExitRequestApi(tx),
  1253. },
  1254. RuntimeRunEvent::CloseRequested { label, signal_tx } => RunEvent::CloseRequested {
  1255. label,
  1256. api: CloseRequestApi(signal_tx),
  1257. },
  1258. RuntimeRunEvent::WindowClose(label) => RunEvent::WindowClosed(label),
  1259. RuntimeRunEvent::Ready => RunEvent::Ready,
  1260. RuntimeRunEvent::Resumed => RunEvent::Resumed,
  1261. RuntimeRunEvent::MainEventsCleared => RunEvent::MainEventsCleared,
  1262. RuntimeRunEvent::UserEvent(t) => t.into(),
  1263. _ => unimplemented!(),
  1264. };
  1265. manager
  1266. .inner
  1267. .plugins
  1268. .lock()
  1269. .expect("poisoned plugin store")
  1270. .on_event(app_handle, &event);
  1271. if let Some(c) = callback {
  1272. c(app_handle, event);
  1273. }
  1274. }
  1275. /// Make `Wry` the default `Runtime` for `Builder`
  1276. #[cfg(feature = "wry")]
  1277. #[cfg_attr(doc_cfg, doc(cfg(feature = "wry")))]
  1278. impl Default for Builder<crate::Wry> {
  1279. fn default() -> Self {
  1280. Self::new()
  1281. }
  1282. }
  1283. #[cfg(test)]
  1284. mod tests {
  1285. #[test]
  1286. fn is_send_sync() {
  1287. crate::test_utils::assert_send::<super::AppHandle>();
  1288. crate::test_utils::assert_sync::<super::AppHandle>();
  1289. #[cfg(feature = "wry")]
  1290. {
  1291. crate::test_utils::assert_send::<super::AssetResolver<crate::Wry>>();
  1292. crate::test_utils::assert_sync::<super::AssetResolver<crate::Wry>>();
  1293. }
  1294. crate::test_utils::assert_send::<super::PathResolver>();
  1295. crate::test_utils::assert_sync::<super::PathResolver>();
  1296. }
  1297. }