app.rs 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969
  1. // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. use crate::{
  5. image::Image,
  6. ipc::{
  7. channel::ChannelDataIpcQueue, CallbackFn, CommandArg, CommandItem, Invoke, InvokeError,
  8. InvokeHandler, InvokeResponder, InvokeResponse,
  9. },
  10. manager::{
  11. webview::{UriSchemeProtocol, WebviewLabelDef},
  12. AppManager, Asset,
  13. },
  14. plugin::{Plugin, PluginStore},
  15. resources::ResourceTable,
  16. runtime::{
  17. window::{WebviewEvent as RuntimeWebviewEvent, WindowEvent as RuntimeWindowEvent},
  18. ExitRequestedEventAction, RunEvent as RuntimeRunEvent,
  19. },
  20. sealed::{ManagerBase, RuntimeOrDispatch},
  21. utils::config::Config,
  22. utils::Env,
  23. webview::PageLoadPayload,
  24. Context, DeviceEventFilter, EventLoopMessage, Manager, Monitor, Runtime, Scopes, StateManager,
  25. Theme, Webview, WebviewWindowBuilder, Window,
  26. };
  27. #[cfg(desktop)]
  28. use crate::menu::{Menu, MenuEvent};
  29. #[cfg(all(desktop, feature = "tray-icon"))]
  30. use crate::tray::{TrayIcon, TrayIconBuilder, TrayIconEvent, TrayIconId};
  31. use raw_window_handle::HasDisplayHandle;
  32. use serialize_to_javascript::{default_template, DefaultTemplate, Template};
  33. use tauri_macros::default_runtime;
  34. #[cfg(desktop)]
  35. use tauri_runtime::EventLoopProxy;
  36. use tauri_runtime::{
  37. dpi::{PhysicalPosition, PhysicalSize},
  38. window::DragDropEvent,
  39. RuntimeInitArgs,
  40. };
  41. use tauri_utils::PackageInfo;
  42. use std::{
  43. borrow::Cow,
  44. collections::HashMap,
  45. fmt,
  46. sync::{mpsc::Sender, Arc, MutexGuard},
  47. };
  48. use crate::{event::EventId, runtime::RuntimeHandle, Event, EventTarget};
  49. #[cfg(target_os = "macos")]
  50. use crate::ActivationPolicy;
  51. pub(crate) mod plugin;
  52. #[cfg(desktop)]
  53. pub(crate) type GlobalMenuEventListener<T> = Box<dyn Fn(&T, crate::menu::MenuEvent) + Send + Sync>;
  54. #[cfg(all(desktop, feature = "tray-icon"))]
  55. pub(crate) type GlobalTrayIconEventListener<T> =
  56. Box<dyn Fn(&T, crate::tray::TrayIconEvent) + Send + Sync>;
  57. pub(crate) type GlobalWindowEventListener<R> = Box<dyn Fn(&Window<R>, &WindowEvent) + Send + Sync>;
  58. pub(crate) type GlobalWebviewEventListener<R> =
  59. Box<dyn Fn(&Webview<R>, &WebviewEvent) + Send + Sync>;
  60. /// A closure that is run when the Tauri application is setting up.
  61. pub type SetupHook<R> =
  62. Box<dyn FnOnce(&mut App<R>) -> Result<(), Box<dyn std::error::Error>> + Send>;
  63. /// A closure that is run every time a page starts or finishes loading.
  64. pub type OnPageLoad<R> = dyn Fn(&Webview<R>, &PageLoadPayload<'_>) + Send + Sync + 'static;
  65. /// The exit code on [`RunEvent::ExitRequested`] when [`AppHandle#method.restart`] is called.
  66. pub const RESTART_EXIT_CODE: i32 = i32::MAX;
  67. /// Api exposed on the `ExitRequested` event.
  68. #[derive(Debug)]
  69. pub struct ExitRequestApi(Sender<ExitRequestedEventAction>);
  70. impl ExitRequestApi {
  71. /// Prevents the app from exiting.
  72. ///
  73. /// **Note:** This is ignored when using [`AppHandle#method.restart`].
  74. pub fn prevent_exit(&self) {
  75. self.0.send(ExitRequestedEventAction::Prevent).unwrap();
  76. }
  77. }
  78. /// Api exposed on the `CloseRequested` event.
  79. #[derive(Debug, Clone)]
  80. pub struct CloseRequestApi(Sender<bool>);
  81. impl CloseRequestApi {
  82. /// Prevents the window from being closed.
  83. pub fn prevent_close(&self) {
  84. self.0.send(true).unwrap();
  85. }
  86. }
  87. /// An event from a window.
  88. #[derive(Debug, Clone)]
  89. #[non_exhaustive]
  90. pub enum WindowEvent {
  91. /// The size of the window has changed. Contains the client area's new dimensions.
  92. Resized(PhysicalSize<u32>),
  93. /// The position of the window has changed. Contains the window's new position.
  94. Moved(PhysicalPosition<i32>),
  95. /// The window has been requested to close.
  96. #[non_exhaustive]
  97. CloseRequested {
  98. /// An API modify the behavior of the close requested event.
  99. api: CloseRequestApi,
  100. },
  101. /// The window has been destroyed.
  102. Destroyed,
  103. /// The window gained or lost focus.
  104. ///
  105. /// The parameter is true if the window has gained focus, and false if it has lost focus.
  106. Focused(bool),
  107. /// The window's scale factor has changed.
  108. ///
  109. /// The following user actions can cause DPI changes:
  110. ///
  111. /// - Changing the display's resolution.
  112. /// - Changing the display's scale factor (e.g. in Control Panel on Windows).
  113. /// - Moving the window to a display with a different scale factor.
  114. #[non_exhaustive]
  115. ScaleFactorChanged {
  116. /// The new scale factor.
  117. scale_factor: f64,
  118. /// The window inner size.
  119. new_inner_size: PhysicalSize<u32>,
  120. },
  121. /// An event associated with the drag and drop action.
  122. DragDrop(DragDropEvent),
  123. /// The system window theme has changed. Only delivered if the window [`theme`](`crate::window::WindowBuilder#method.theme`) is `None`.
  124. ///
  125. /// Applications might wish to react to this to change the theme of the content of the window when the system changes the window theme.
  126. ///
  127. /// ## Platform-specific
  128. ///
  129. /// - **Linux**: Not supported.
  130. ThemeChanged(Theme),
  131. }
  132. impl From<RuntimeWindowEvent> for WindowEvent {
  133. fn from(event: RuntimeWindowEvent) -> Self {
  134. match event {
  135. RuntimeWindowEvent::Resized(size) => Self::Resized(size),
  136. RuntimeWindowEvent::Moved(position) => Self::Moved(position),
  137. RuntimeWindowEvent::CloseRequested { signal_tx } => Self::CloseRequested {
  138. api: CloseRequestApi(signal_tx),
  139. },
  140. RuntimeWindowEvent::Destroyed => Self::Destroyed,
  141. RuntimeWindowEvent::Focused(flag) => Self::Focused(flag),
  142. RuntimeWindowEvent::ScaleFactorChanged {
  143. scale_factor,
  144. new_inner_size,
  145. } => Self::ScaleFactorChanged {
  146. scale_factor,
  147. new_inner_size,
  148. },
  149. RuntimeWindowEvent::DragDrop(event) => Self::DragDrop(event),
  150. RuntimeWindowEvent::ThemeChanged(theme) => Self::ThemeChanged(theme),
  151. }
  152. }
  153. }
  154. /// An event from a window.
  155. #[derive(Debug, Clone)]
  156. #[non_exhaustive]
  157. pub enum WebviewEvent {
  158. /// An event associated with the drag and drop action.
  159. DragDrop(DragDropEvent),
  160. }
  161. impl From<RuntimeWebviewEvent> for WebviewEvent {
  162. fn from(event: RuntimeWebviewEvent) -> Self {
  163. match event {
  164. RuntimeWebviewEvent::DragDrop(e) => Self::DragDrop(e),
  165. }
  166. }
  167. }
  168. /// An application event, triggered from the event loop.
  169. ///
  170. /// See [`App::run`](crate::App#method.run) for usage examples.
  171. #[derive(Debug)]
  172. #[non_exhaustive]
  173. pub enum RunEvent {
  174. /// Event loop is exiting.
  175. Exit,
  176. /// The app is about to exit
  177. #[non_exhaustive]
  178. ExitRequested {
  179. /// Exit code.
  180. /// [`Option::None`] when the exit is requested by user interaction,
  181. /// [`Option::Some`] when requested programmatically via [`AppHandle#method.exit`] and [`AppHandle#method.restart`].
  182. code: Option<i32>,
  183. /// Event API
  184. api: ExitRequestApi,
  185. },
  186. /// An event associated with a window.
  187. #[non_exhaustive]
  188. WindowEvent {
  189. /// The window label.
  190. label: String,
  191. /// The detailed event.
  192. event: WindowEvent,
  193. },
  194. /// An event associated with a webview.
  195. #[non_exhaustive]
  196. WebviewEvent {
  197. /// The window label.
  198. label: String,
  199. /// The detailed event.
  200. event: WebviewEvent,
  201. },
  202. /// Application ready.
  203. Ready,
  204. /// Sent if the event loop is being resumed.
  205. Resumed,
  206. /// Emitted when all of the event loop's input events have been processed and redraw processing is about to begin.
  207. ///
  208. /// 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.
  209. MainEventsCleared,
  210. /// Emitted when the user wants to open the specified resource with the app.
  211. #[cfg(any(target_os = "macos", target_os = "ios"))]
  212. #[cfg_attr(docsrs, doc(cfg(any(target_os = "macos", feature = "ios"))))]
  213. Opened {
  214. /// The URL of the resources that is being open.
  215. urls: Vec<url::Url>,
  216. },
  217. /// An event from a menu item, could be on the window menu bar, application menu bar (on macOS) or tray icon menu.
  218. #[cfg(desktop)]
  219. #[cfg_attr(docsrs, doc(cfg(desktop)))]
  220. MenuEvent(crate::menu::MenuEvent),
  221. /// An event from a tray icon.
  222. #[cfg(all(desktop, feature = "tray-icon"))]
  223. #[cfg_attr(docsrs, doc(cfg(all(desktop, feature = "tray-icon"))))]
  224. TrayIconEvent(crate::tray::TrayIconEvent),
  225. /// Emitted when the NSApplicationDelegate's applicationShouldHandleReopen gets called
  226. #[non_exhaustive]
  227. #[cfg(target_os = "macos")]
  228. #[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
  229. Reopen {
  230. /// Indicates whether the NSApplication object found any visible windows in your application.
  231. has_visible_windows: bool,
  232. },
  233. }
  234. impl From<EventLoopMessage> for RunEvent {
  235. fn from(event: EventLoopMessage) -> Self {
  236. match event {
  237. #[cfg(desktop)]
  238. EventLoopMessage::MenuEvent(e) => Self::MenuEvent(e),
  239. #[cfg(all(desktop, feature = "tray-icon"))]
  240. EventLoopMessage::TrayIconEvent(e) => Self::TrayIconEvent(e),
  241. }
  242. }
  243. }
  244. /// The asset resolver is a helper to access the [`tauri_utils::assets::Assets`] interface.
  245. #[derive(Debug, Clone)]
  246. pub struct AssetResolver<R: Runtime> {
  247. manager: Arc<AppManager<R>>,
  248. }
  249. impl<R: Runtime> AssetResolver<R> {
  250. /// Gets the app asset associated with the given path.
  251. pub fn get(&self, path: String) -> Option<Asset> {
  252. self.manager.get_asset(path).ok()
  253. }
  254. /// Iterate on all assets.
  255. pub fn iter(&self) -> Box<dyn Iterator<Item = (&str, &[u8])> + '_> {
  256. self.manager.assets.iter()
  257. }
  258. }
  259. /// A handle to the currently running application.
  260. ///
  261. /// This type implements [`Manager`] which allows for manipulation of global application items.
  262. #[default_runtime(crate::Wry, wry)]
  263. #[derive(Debug)]
  264. pub struct AppHandle<R: Runtime> {
  265. pub(crate) runtime_handle: R::Handle,
  266. pub(crate) manager: Arc<AppManager<R>>,
  267. }
  268. /// APIs specific to the wry runtime.
  269. #[cfg(feature = "wry")]
  270. impl AppHandle<crate::Wry> {
  271. /// Create a new tao window using a callback. The event loop must be running at this point.
  272. pub fn create_tao_window<
  273. F: FnOnce() -> (String, tauri_runtime_wry::TaoWindowBuilder) + Send + 'static,
  274. >(
  275. &self,
  276. f: F,
  277. ) -> crate::Result<std::sync::Weak<tauri_runtime_wry::Window>> {
  278. self.runtime_handle.create_tao_window(f).map_err(Into::into)
  279. }
  280. /// Sends a window message to the event loop.
  281. pub fn send_tao_window_event(
  282. &self,
  283. window_id: tauri_runtime_wry::TaoWindowId,
  284. message: tauri_runtime_wry::WindowMessage,
  285. ) -> crate::Result<()> {
  286. self
  287. .runtime_handle
  288. .send_event(tauri_runtime_wry::Message::Window(
  289. self.runtime_handle.window_id(window_id),
  290. message,
  291. ))
  292. .map_err(Into::into)
  293. }
  294. }
  295. impl<R: Runtime> Clone for AppHandle<R> {
  296. fn clone(&self) -> Self {
  297. Self {
  298. runtime_handle: self.runtime_handle.clone(),
  299. manager: self.manager.clone(),
  300. }
  301. }
  302. }
  303. impl<'de, R: Runtime> CommandArg<'de, R> for AppHandle<R> {
  304. /// Grabs the [`Window`] from the [`CommandItem`] and returns the associated [`AppHandle`]. This will never fail.
  305. fn from_command(command: CommandItem<'de, R>) -> Result<Self, InvokeError> {
  306. Ok(command.message.webview().window().app_handle.clone())
  307. }
  308. }
  309. impl<R: Runtime> AppHandle<R> {
  310. /// Runs the given closure on the main thread.
  311. pub fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> crate::Result<()> {
  312. self
  313. .runtime_handle
  314. .run_on_main_thread(f)
  315. .map_err(Into::into)
  316. }
  317. /// Adds a Tauri application plugin.
  318. /// This function can be used to register a plugin that is loaded dynamically e.g. after login.
  319. /// For plugins that are created when the app is started, prefer [`Builder::plugin`].
  320. ///
  321. /// See [`Builder::plugin`] for more information.
  322. ///
  323. /// # Examples
  324. ///
  325. /// ```
  326. /// use tauri::{plugin::{Builder as PluginBuilder, TauriPlugin}, Runtime};
  327. ///
  328. /// fn init_plugin<R: Runtime>() -> TauriPlugin<R> {
  329. /// PluginBuilder::new("dummy").build()
  330. /// }
  331. ///
  332. /// tauri::Builder::default()
  333. /// .setup(move |app| {
  334. /// let handle = app.handle().clone();
  335. /// std::thread::spawn(move || {
  336. /// handle.plugin(init_plugin());
  337. /// });
  338. ///
  339. /// Ok(())
  340. /// });
  341. /// ```
  342. #[cfg_attr(feature = "tracing", tracing::instrument(name = "app::plugin::register", skip(plugin), fields(name = plugin.name())))]
  343. pub fn plugin<P: Plugin<R> + 'static>(&self, plugin: P) -> crate::Result<()> {
  344. let mut plugin = Box::new(plugin) as Box<dyn Plugin<R>>;
  345. let mut store = self.manager().plugins.lock().unwrap();
  346. store.initialize(&mut plugin, self, &self.config().plugins)?;
  347. store.register(plugin);
  348. Ok(())
  349. }
  350. /// Removes the plugin with the given name.
  351. ///
  352. /// # Examples
  353. ///
  354. /// ```
  355. /// use tauri::{plugin::{Builder as PluginBuilder, TauriPlugin, Plugin}, Runtime};
  356. ///
  357. /// fn init_plugin<R: Runtime>() -> TauriPlugin<R> {
  358. /// PluginBuilder::new("dummy").build()
  359. /// }
  360. ///
  361. /// let plugin = init_plugin();
  362. /// // `.name()` requires the `PLugin` trait import
  363. /// let plugin_name = plugin.name();
  364. /// tauri::Builder::default()
  365. /// .plugin(plugin)
  366. /// .setup(move |app| {
  367. /// let handle = app.handle().clone();
  368. /// std::thread::spawn(move || {
  369. /// handle.remove_plugin(plugin_name);
  370. /// });
  371. ///
  372. /// Ok(())
  373. /// });
  374. /// ```
  375. pub fn remove_plugin(&self, plugin: &'static str) -> bool {
  376. self.manager().plugins.lock().unwrap().unregister(plugin)
  377. }
  378. /// Exits the app by triggering [`RunEvent::ExitRequested`] and [`RunEvent::Exit`].
  379. pub fn exit(&self, exit_code: i32) {
  380. if let Err(e) = self.runtime_handle.request_exit(exit_code) {
  381. log::error!("failed to exit: {}", e);
  382. self.cleanup_before_exit();
  383. std::process::exit(exit_code);
  384. }
  385. }
  386. /// Restarts the app by triggering [`RunEvent::ExitRequested`] with code [`RESTART_EXIT_CODE`] and [`RunEvent::Exit`]..
  387. pub fn restart(&self) {
  388. if self.runtime_handle.request_exit(RESTART_EXIT_CODE).is_err() {
  389. self.cleanup_before_exit();
  390. }
  391. crate::process::restart(&self.env());
  392. }
  393. }
  394. impl<R: Runtime> Manager<R> for AppHandle<R> {
  395. fn resources_table(&self) -> MutexGuard<'_, ResourceTable> {
  396. self.manager.resources_table()
  397. }
  398. }
  399. impl<R: Runtime> ManagerBase<R> for AppHandle<R> {
  400. fn manager(&self) -> &AppManager<R> {
  401. &self.manager
  402. }
  403. fn manager_owned(&self) -> Arc<AppManager<R>> {
  404. self.manager.clone()
  405. }
  406. fn runtime(&self) -> RuntimeOrDispatch<'_, R> {
  407. RuntimeOrDispatch::RuntimeHandle(self.runtime_handle.clone())
  408. }
  409. fn managed_app_handle(&self) -> &AppHandle<R> {
  410. self
  411. }
  412. }
  413. /// The instance of the currently running application.
  414. ///
  415. /// This type implements [`Manager`] which allows for manipulation of global application items.
  416. #[default_runtime(crate::Wry, wry)]
  417. pub struct App<R: Runtime> {
  418. runtime: Option<R>,
  419. setup: Option<SetupHook<R>>,
  420. manager: Arc<AppManager<R>>,
  421. handle: AppHandle<R>,
  422. ran_setup: bool,
  423. }
  424. impl<R: Runtime> fmt::Debug for App<R> {
  425. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  426. f.debug_struct("App")
  427. .field("runtime", &self.runtime)
  428. .field("manager", &self.manager)
  429. .field("handle", &self.handle)
  430. .finish()
  431. }
  432. }
  433. impl<R: Runtime> Manager<R> for App<R> {
  434. fn resources_table(&self) -> MutexGuard<'_, ResourceTable> {
  435. self.manager.resources_table()
  436. }
  437. }
  438. impl<R: Runtime> ManagerBase<R> for App<R> {
  439. fn manager(&self) -> &AppManager<R> {
  440. &self.manager
  441. }
  442. fn manager_owned(&self) -> Arc<AppManager<R>> {
  443. self.manager.clone()
  444. }
  445. fn runtime(&self) -> RuntimeOrDispatch<'_, R> {
  446. if let Some(runtime) = self.runtime.as_ref() {
  447. RuntimeOrDispatch::Runtime(runtime)
  448. } else {
  449. self.handle.runtime()
  450. }
  451. }
  452. fn managed_app_handle(&self) -> &AppHandle<R> {
  453. self.handle()
  454. }
  455. }
  456. /// APIs specific to the wry runtime.
  457. #[cfg(feature = "wry")]
  458. impl App<crate::Wry> {
  459. /// Adds a [`tauri_runtime_wry::Plugin`] using its [`tauri_runtime_wry::PluginBuilder`].
  460. ///
  461. /// # Stability
  462. ///
  463. /// This API is unstable.
  464. pub fn wry_plugin<P: tauri_runtime_wry::PluginBuilder<EventLoopMessage> + Send + 'static>(
  465. &mut self,
  466. plugin: P,
  467. ) where
  468. <P as tauri_runtime_wry::PluginBuilder<EventLoopMessage>>::Plugin: Send,
  469. {
  470. self.handle.runtime_handle.plugin(plugin);
  471. }
  472. }
  473. macro_rules! shared_app_impl {
  474. ($app: ty) => {
  475. impl<R: Runtime> $app {
  476. /// Registers a global menu event listener.
  477. #[cfg(desktop)]
  478. pub fn on_menu_event<F: Fn(&AppHandle<R>, MenuEvent) + Send + Sync + 'static>(
  479. &self,
  480. handler: F,
  481. ) {
  482. self.manager.menu.on_menu_event(handler)
  483. }
  484. /// Registers a global tray icon menu event listener.
  485. #[cfg(all(desktop, feature = "tray-icon"))]
  486. #[cfg_attr(docsrs, doc(cfg(all(desktop, feature = "tray-icon"))))]
  487. pub fn on_tray_icon_event<F: Fn(&AppHandle<R>, TrayIconEvent) + Send + Sync + 'static>(
  488. &self,
  489. handler: F,
  490. ) {
  491. self.manager.tray.on_tray_icon_event(handler)
  492. }
  493. /// Gets a tray icon using the provided id.
  494. #[cfg(all(desktop, feature = "tray-icon"))]
  495. #[cfg_attr(docsrs, doc(cfg(all(desktop, feature = "tray-icon"))))]
  496. pub fn tray_by_id<'a, I>(&self, id: &'a I) -> Option<TrayIcon<R>>
  497. where
  498. I: ?Sized,
  499. TrayIconId: PartialEq<&'a I>,
  500. {
  501. self.manager.tray.tray_by_id(id)
  502. }
  503. /// Removes a tray icon using the provided id from tauri's internal state and returns it.
  504. ///
  505. /// Note that dropping the returned icon, may cause the tray icon to disappear
  506. /// if it wasn't cloned somewhere else or referenced by JS.
  507. #[cfg(all(desktop, feature = "tray-icon"))]
  508. #[cfg_attr(docsrs, doc(cfg(all(desktop, feature = "tray-icon"))))]
  509. pub fn remove_tray_by_id<'a, I>(&self, id: &'a I) -> Option<TrayIcon<R>>
  510. where
  511. I: ?Sized,
  512. TrayIconId: PartialEq<&'a I>,
  513. {
  514. self.manager.tray.remove_tray_by_id(id)
  515. }
  516. /// Gets the app's configuration, defined on the `tauri.conf.json` file.
  517. pub fn config(&self) -> &Config {
  518. self.manager.config()
  519. }
  520. /// Gets the app's package information.
  521. pub fn package_info(&self) -> &PackageInfo {
  522. self.manager.package_info()
  523. }
  524. /// The application's asset resolver.
  525. pub fn asset_resolver(&self) -> AssetResolver<R> {
  526. AssetResolver {
  527. manager: self.manager.clone(),
  528. }
  529. }
  530. /// Returns the primary monitor of the system.
  531. ///
  532. /// Returns None if it can't identify any monitor as a primary one.
  533. pub fn primary_monitor(&self) -> crate::Result<Option<Monitor>> {
  534. Ok(match self.runtime() {
  535. RuntimeOrDispatch::Runtime(h) => h.primary_monitor().map(Into::into),
  536. RuntimeOrDispatch::RuntimeHandle(h) => h.primary_monitor().map(Into::into),
  537. _ => unreachable!(),
  538. })
  539. }
  540. /// Returns the monitor that contains the given point.
  541. pub fn monitor_from_point(&self, x: f64, y: f64) -> crate::Result<Option<Monitor>> {
  542. Ok(match self.runtime() {
  543. RuntimeOrDispatch::Runtime(h) => h.monitor_from_point(x, y).map(Into::into),
  544. RuntimeOrDispatch::RuntimeHandle(h) => h.monitor_from_point(x, y).map(Into::into),
  545. _ => unreachable!(),
  546. })
  547. }
  548. /// Returns the list of all the monitors available on the system.
  549. pub fn available_monitors(&self) -> crate::Result<Vec<Monitor>> {
  550. Ok(match self.runtime() {
  551. RuntimeOrDispatch::Runtime(h) => {
  552. h.available_monitors().into_iter().map(Into::into).collect()
  553. }
  554. RuntimeOrDispatch::RuntimeHandle(h) => {
  555. h.available_monitors().into_iter().map(Into::into).collect()
  556. }
  557. _ => unreachable!(),
  558. })
  559. }
  560. /// Get the cursor position relative to the top-left hand corner of the desktop.
  561. ///
  562. /// Note that the top-left hand corner of the desktop is not necessarily the same as the screen.
  563. /// If the user uses a desktop with multiple monitors,
  564. /// the top-left hand corner of the desktop is the top-left hand corner of the main monitor on Windows and macOS
  565. /// or the top-left of the leftmost monitor on X11.
  566. ///
  567. /// The coordinates can be negative if the top-left hand corner of the window is outside of the visible screen region.
  568. pub fn cursor_position(&self) -> crate::Result<PhysicalPosition<f64>> {
  569. Ok(match self.runtime() {
  570. RuntimeOrDispatch::Runtime(h) => h.cursor_position()?,
  571. RuntimeOrDispatch::RuntimeHandle(h) => h.cursor_position()?,
  572. _ => unreachable!(),
  573. })
  574. }
  575. /// Returns the default window icon.
  576. pub fn default_window_icon(&self) -> Option<&Image<'_>> {
  577. self.manager.window.default_icon.as_ref()
  578. }
  579. /// Returns the app-wide menu.
  580. #[cfg(desktop)]
  581. pub fn menu(&self) -> Option<Menu<R>> {
  582. self.manager.menu.menu_lock().clone()
  583. }
  584. /// Sets the app-wide menu and returns the previous one.
  585. ///
  586. /// If a window was not created with an explicit menu or had one set explicitly,
  587. /// this menu will be assigned to it.
  588. #[cfg(desktop)]
  589. pub fn set_menu(&self, menu: Menu<R>) -> crate::Result<Option<Menu<R>>> {
  590. let prev_menu = self.remove_menu()?;
  591. self.manager.menu.insert_menu_into_stash(&menu);
  592. self.manager.menu.menu_lock().replace(menu.clone());
  593. // set it on all windows that don't have one or previously had the app-wide menu
  594. #[cfg(not(target_os = "macos"))]
  595. {
  596. for window in self.manager.windows().values() {
  597. let has_app_wide_menu = window.has_app_wide_menu() || window.menu().is_none();
  598. if has_app_wide_menu {
  599. window.set_menu(menu.clone())?;
  600. window.menu_lock().replace(crate::window::WindowMenu {
  601. is_app_wide: true,
  602. menu: menu.clone(),
  603. });
  604. }
  605. }
  606. }
  607. // set it app-wide for macos
  608. #[cfg(target_os = "macos")]
  609. {
  610. let menu_ = menu.clone();
  611. self.run_on_main_thread(move || {
  612. let _ = init_app_menu(&menu_);
  613. })?;
  614. }
  615. Ok(prev_menu)
  616. }
  617. /// Remove the app-wide menu and returns it.
  618. ///
  619. /// If a window was not created with an explicit menu or had one set explicitly,
  620. /// this will remove the menu from it.
  621. #[cfg(desktop)]
  622. pub fn remove_menu(&self) -> crate::Result<Option<Menu<R>>> {
  623. let menu = self.manager.menu.menu_lock().as_ref().cloned();
  624. #[allow(unused_variables)]
  625. if let Some(menu) = menu {
  626. // remove from windows that have the app-wide menu
  627. #[cfg(not(target_os = "macos"))]
  628. {
  629. for window in self.manager.windows().values() {
  630. let has_app_wide_menu = window.has_app_wide_menu();
  631. if has_app_wide_menu {
  632. window.remove_menu()?;
  633. *window.menu_lock() = None;
  634. }
  635. }
  636. }
  637. // remove app-wide for macos
  638. #[cfg(target_os = "macos")]
  639. {
  640. self.run_on_main_thread(move || {
  641. menu.inner().remove_for_nsapp();
  642. })?;
  643. }
  644. }
  645. let prev_menu = self.manager.menu.menu_lock().take();
  646. self
  647. .manager
  648. .remove_menu_from_stash_by_id(prev_menu.as_ref().map(|m| m.id()));
  649. Ok(prev_menu)
  650. }
  651. /// Hides the app-wide menu from windows that have it.
  652. ///
  653. /// If a window was not created with an explicit menu or had one set explicitly,
  654. /// this will hide the menu from it.
  655. #[cfg(desktop)]
  656. pub fn hide_menu(&self) -> crate::Result<()> {
  657. #[cfg(not(target_os = "macos"))]
  658. {
  659. let is_app_menu_set = self.manager.menu.menu_lock().is_some();
  660. if is_app_menu_set {
  661. for window in self.manager.windows().values() {
  662. if window.has_app_wide_menu() {
  663. window.hide_menu()?;
  664. }
  665. }
  666. }
  667. }
  668. Ok(())
  669. }
  670. /// Shows the app-wide menu for windows that have it.
  671. ///
  672. /// If a window was not created with an explicit menu or had one set explicitly,
  673. /// this will show the menu for it.
  674. #[cfg(desktop)]
  675. pub fn show_menu(&self) -> crate::Result<()> {
  676. #[cfg(not(target_os = "macos"))]
  677. {
  678. let is_app_menu_set = self.manager.menu.menu_lock().is_some();
  679. if is_app_menu_set {
  680. for window in self.manager.windows().values() {
  681. if window.has_app_wide_menu() {
  682. window.show_menu()?;
  683. }
  684. }
  685. }
  686. }
  687. Ok(())
  688. }
  689. /// Shows the application, but does not automatically focus it.
  690. #[cfg(target_os = "macos")]
  691. pub fn show(&self) -> crate::Result<()> {
  692. match self.runtime() {
  693. RuntimeOrDispatch::Runtime(r) => r.show(),
  694. RuntimeOrDispatch::RuntimeHandle(h) => h.show()?,
  695. _ => unreachable!(),
  696. }
  697. Ok(())
  698. }
  699. /// Hides the application.
  700. #[cfg(target_os = "macos")]
  701. pub fn hide(&self) -> crate::Result<()> {
  702. match self.runtime() {
  703. RuntimeOrDispatch::Runtime(r) => r.hide(),
  704. RuntimeOrDispatch::RuntimeHandle(h) => h.hide()?,
  705. _ => unreachable!(),
  706. }
  707. Ok(())
  708. }
  709. /// Runs necessary cleanup tasks before exiting the process.
  710. /// **You should always exit the tauri app immediately after this function returns and not use any tauri-related APIs.**
  711. pub fn cleanup_before_exit(&self) {
  712. #[cfg(all(desktop, feature = "tray-icon"))]
  713. self.manager.tray.icons.lock().unwrap().clear();
  714. self.manager.resources_table().clear();
  715. for (_, window) in self.manager.windows() {
  716. window.resources_table().clear();
  717. #[cfg(windows)]
  718. let _ = window.hide();
  719. }
  720. for (_, webview) in self.manager.webviews() {
  721. webview.resources_table().clear();
  722. }
  723. }
  724. }
  725. /// Event system APIs.
  726. impl<R: Runtime> $app {
  727. /// Listen to an event on this app.
  728. ///
  729. /// # Examples
  730. ///
  731. /// ```
  732. /// use tauri::Manager;
  733. ///
  734. /// tauri::Builder::default()
  735. /// .setup(|app| {
  736. /// app.listen("component-loaded", move |event| {
  737. /// println!("window just loaded a component");
  738. /// });
  739. ///
  740. /// Ok(())
  741. /// });
  742. /// ```
  743. pub fn listen<F>(&self, event: impl Into<String>, handler: F) -> EventId
  744. where
  745. F: Fn(Event) + Send + 'static,
  746. {
  747. self.manager.listen(event.into(), EventTarget::App, handler)
  748. }
  749. /// Unlisten to an event on this app.
  750. ///
  751. /// # Examples
  752. ///
  753. /// ```
  754. /// use tauri::Manager;
  755. ///
  756. /// tauri::Builder::default()
  757. /// .setup(|app| {
  758. /// let handler = app.listen("component-loaded", move |event| {
  759. /// println!("app just loaded a component");
  760. /// });
  761. ///
  762. /// // stop listening to the event when you do not need it anymore
  763. /// app.unlisten(handler);
  764. ///
  765. /// Ok(())
  766. /// });
  767. /// ```
  768. pub fn unlisten(&self, id: EventId) {
  769. self.manager.unlisten(id)
  770. }
  771. /// Listen to an event on this app only once.
  772. ///
  773. /// See [`Self::listen`] for more information.
  774. pub fn once<F>(&self, event: impl Into<String>, handler: F) -> EventId
  775. where
  776. F: FnOnce(Event) + Send + 'static,
  777. {
  778. self.manager.once(event.into(), EventTarget::App, handler)
  779. }
  780. }
  781. };
  782. }
  783. shared_app_impl!(App<R>);
  784. shared_app_impl!(AppHandle<R>);
  785. impl<R: Runtime> App<R> {
  786. #[cfg_attr(
  787. feature = "tracing",
  788. tracing::instrument(name = "app::core_plugins::register")
  789. )]
  790. fn register_core_plugins(&self) -> crate::Result<()> {
  791. self.handle.plugin(crate::path::plugin::init())?;
  792. self.handle.plugin(crate::event::plugin::init())?;
  793. self.handle.plugin(crate::window::plugin::init())?;
  794. self.handle.plugin(crate::webview::plugin::init())?;
  795. self.handle.plugin(crate::app::plugin::init())?;
  796. self.handle.plugin(crate::resources::plugin::init())?;
  797. self.handle.plugin(crate::image::plugin::init())?;
  798. #[cfg(desktop)]
  799. self.handle.plugin(crate::menu::plugin::init())?;
  800. #[cfg(all(desktop, feature = "tray-icon"))]
  801. self.handle.plugin(crate::tray::plugin::init())?;
  802. Ok(())
  803. }
  804. /// Runs the given closure on the main thread.
  805. pub fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> crate::Result<()> {
  806. self.app_handle().run_on_main_thread(f)
  807. }
  808. /// Gets a handle to the application instance.
  809. pub fn handle(&self) -> &AppHandle<R> {
  810. &self.handle
  811. }
  812. /// Sets the activation policy for the application. It is set to `NSApplicationActivationPolicyRegular` by default.
  813. ///
  814. /// # Examples
  815. /// ```,no_run
  816. /// let mut app = tauri::Builder::default()
  817. /// // on an actual app, remove the string argument
  818. /// .build(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
  819. /// .expect("error while building tauri application");
  820. /// #[cfg(target_os = "macos")]
  821. /// app.set_activation_policy(tauri::ActivationPolicy::Accessory);
  822. /// app.run(|_app_handle, _event| {});
  823. /// ```
  824. #[cfg(target_os = "macos")]
  825. #[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
  826. pub fn set_activation_policy(&mut self, activation_policy: ActivationPolicy) {
  827. if let Some(runtime) = self.runtime.as_mut() {
  828. runtime.set_activation_policy(activation_policy);
  829. } else {
  830. let _ = self
  831. .app_handle()
  832. .runtime_handle
  833. .set_activation_policy(activation_policy);
  834. }
  835. }
  836. /// Change the device event filter mode.
  837. ///
  838. /// Since the DeviceEvent capture can lead to high CPU usage for unfocused windows, [`tao`]
  839. /// will ignore them by default for unfocused windows on Windows. This method allows changing
  840. /// the filter to explicitly capture them again.
  841. ///
  842. /// ## Platform-specific
  843. ///
  844. /// - ** Linux / macOS / iOS / Android**: Unsupported.
  845. ///
  846. /// # Examples
  847. /// ```,no_run
  848. /// let mut app = tauri::Builder::default()
  849. /// // on an actual app, remove the string argument
  850. /// .build(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
  851. /// .expect("error while building tauri application");
  852. /// app.set_device_event_filter(tauri::DeviceEventFilter::Always);
  853. /// app.run(|_app_handle, _event| {});
  854. /// ```
  855. ///
  856. /// [`tao`]: https://crates.io/crates/tao
  857. pub fn set_device_event_filter(&mut self, filter: DeviceEventFilter) {
  858. self
  859. .runtime
  860. .as_mut()
  861. .unwrap()
  862. .set_device_event_filter(filter);
  863. }
  864. /// Runs the application.
  865. ///
  866. /// # Examples
  867. /// ```,no_run
  868. /// let app = tauri::Builder::default()
  869. /// // on an actual app, remove the string argument
  870. /// .build(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
  871. /// .expect("error while building tauri application");
  872. /// app.run(|_app_handle, event| match event {
  873. /// tauri::RunEvent::ExitRequested { api, .. } => {
  874. /// api.prevent_exit();
  875. /// }
  876. /// _ => {}
  877. /// });
  878. /// ```
  879. pub fn run<F: FnMut(&AppHandle<R>, RunEvent) + 'static>(mut self, mut callback: F) {
  880. let app_handle = self.handle().clone();
  881. let manager = self.manager.clone();
  882. self.runtime.take().unwrap().run(move |event| match event {
  883. RuntimeRunEvent::Ready => {
  884. if let Err(e) = setup(&mut self) {
  885. panic!("Failed to setup app: {e}");
  886. }
  887. let event = on_event_loop_event(&app_handle, RuntimeRunEvent::Ready, &manager);
  888. callback(&app_handle, event);
  889. }
  890. RuntimeRunEvent::Exit => {
  891. let event = on_event_loop_event(&app_handle, RuntimeRunEvent::Exit, &manager);
  892. callback(&app_handle, event);
  893. app_handle.cleanup_before_exit();
  894. }
  895. _ => {
  896. let event = on_event_loop_event(&app_handle, event, &manager);
  897. callback(&app_handle, event);
  898. }
  899. });
  900. }
  901. /// Runs an iteration of the runtime event loop and immediately return.
  902. ///
  903. /// Note that when using this API, app cleanup is not automatically done.
  904. /// The cleanup calls [`App::cleanup_before_exit`] so you may want to call that function before exiting the application.
  905. ///
  906. /// # Examples
  907. /// ```no_run
  908. /// use tauri::Manager;
  909. ///
  910. /// let mut app = tauri::Builder::default()
  911. /// // on an actual app, remove the string argument
  912. /// .build(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
  913. /// .expect("error while building tauri application");
  914. ///
  915. /// loop {
  916. /// app.run_iteration(|_app, _event| {});
  917. /// if app.webview_windows().is_empty() {
  918. /// app.cleanup_before_exit();
  919. /// break;
  920. /// }
  921. /// }
  922. /// ```
  923. #[cfg(desktop)]
  924. pub fn run_iteration<F: FnMut(&AppHandle<R>, RunEvent) + 'static>(&mut self, mut callback: F) {
  925. let manager = self.manager.clone();
  926. let app_handle = self.handle().clone();
  927. if !self.ran_setup {
  928. if let Err(e) = setup(self) {
  929. panic!("Failed to setup app: {e}");
  930. }
  931. }
  932. self.runtime.as_mut().unwrap().run_iteration(move |event| {
  933. let event = on_event_loop_event(&app_handle, event, &manager);
  934. callback(&app_handle, event);
  935. })
  936. }
  937. }
  938. /// Builds a Tauri application.
  939. ///
  940. /// # Examples
  941. /// ```,no_run
  942. /// tauri::Builder::default()
  943. /// // on an actual app, remove the string argument
  944. /// .run(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
  945. /// .expect("error while running tauri application");
  946. /// ```
  947. #[allow(clippy::type_complexity)]
  948. pub struct Builder<R: Runtime> {
  949. /// A flag indicating that the runtime must be started on an environment that supports the event loop not on the main thread.
  950. #[cfg(any(windows, target_os = "linux"))]
  951. runtime_any_thread: bool,
  952. /// The JS message handler.
  953. invoke_handler: Box<InvokeHandler<R>>,
  954. /// The JS message responder.
  955. invoke_responder: Option<Arc<InvokeResponder<R>>>,
  956. /// The script that initializes the `window.__TAURI_INTERNALS__.postMessage` function.
  957. invoke_initialization_script: String,
  958. /// The setup hook.
  959. setup: SetupHook<R>,
  960. /// Page load hook.
  961. on_page_load: Option<Arc<OnPageLoad<R>>>,
  962. /// All passed plugins
  963. plugins: PluginStore<R>,
  964. /// The webview protocols available to all windows.
  965. uri_scheme_protocols: HashMap<String, Arc<UriSchemeProtocol<R>>>,
  966. /// App state.
  967. state: StateManager,
  968. /// A closure that returns the menu set to all windows.
  969. #[cfg(desktop)]
  970. menu: Option<Box<dyn FnOnce(&AppHandle<R>) -> crate::Result<Menu<R>> + Send>>,
  971. /// Enable macOS default menu creation.
  972. #[allow(unused)]
  973. enable_macos_default_menu: bool,
  974. /// Window event handlers that listens to all windows.
  975. window_event_listeners: Vec<GlobalWindowEventListener<R>>,
  976. /// Webview event handlers that listens to all webviews.
  977. webview_event_listeners: Vec<GlobalWebviewEventListener<R>>,
  978. /// The device event filter.
  979. device_event_filter: DeviceEventFilter,
  980. }
  981. #[derive(Template)]
  982. #[default_template("../scripts/ipc-protocol.js")]
  983. struct InvokeInitializationScript<'a> {
  984. /// The function that processes the IPC message.
  985. #[raw]
  986. process_ipc_message_fn: &'a str,
  987. os_name: &'a str,
  988. fetch_channel_data_command: &'a str,
  989. linux_ipc_protocol_enabled: bool,
  990. }
  991. /// Make `Wry` the default `Runtime` for `Builder`
  992. #[cfg(feature = "wry")]
  993. #[cfg_attr(docsrs, doc(cfg(feature = "wry")))]
  994. impl Default for Builder<crate::Wry> {
  995. fn default() -> Self {
  996. Self::new()
  997. }
  998. }
  999. #[cfg(not(feature = "wry"))]
  1000. #[cfg_attr(docsrs, doc(cfg(not(feature = "wry"))))]
  1001. impl<R: Runtime> Default for Builder<R> {
  1002. fn default() -> Self {
  1003. Self::new()
  1004. }
  1005. }
  1006. impl<R: Runtime> Builder<R> {
  1007. /// Creates a new App builder.
  1008. pub fn new() -> Self {
  1009. Self {
  1010. #[cfg(any(windows, target_os = "linux"))]
  1011. runtime_any_thread: false,
  1012. setup: Box::new(|_| Ok(())),
  1013. invoke_handler: Box::new(|_| false),
  1014. invoke_responder: None,
  1015. invoke_initialization_script: InvokeInitializationScript {
  1016. process_ipc_message_fn: crate::manager::webview::PROCESS_IPC_MESSAGE_FN,
  1017. os_name: std::env::consts::OS,
  1018. fetch_channel_data_command: crate::ipc::channel::FETCH_CHANNEL_DATA_COMMAND,
  1019. linux_ipc_protocol_enabled: cfg!(feature = "linux-ipc-protocol"),
  1020. }
  1021. .render_default(&Default::default())
  1022. .unwrap()
  1023. .into_string(),
  1024. on_page_load: None,
  1025. plugins: PluginStore::default(),
  1026. uri_scheme_protocols: Default::default(),
  1027. state: StateManager::new(),
  1028. #[cfg(desktop)]
  1029. menu: None,
  1030. enable_macos_default_menu: true,
  1031. window_event_listeners: Vec::new(),
  1032. webview_event_listeners: Vec::new(),
  1033. device_event_filter: Default::default(),
  1034. }
  1035. }
  1036. }
  1037. impl<R: Runtime> Builder<R> {
  1038. /// Builds a new Tauri application running on any thread, bypassing the main thread requirement.
  1039. ///
  1040. /// ## Platform-specific
  1041. ///
  1042. /// - **macOS:** on macOS the application *must* be executed on the main thread, so this function is not exposed.
  1043. #[cfg(any(windows, target_os = "linux"))]
  1044. #[cfg_attr(docsrs, doc(cfg(any(windows, target_os = "linux"))))]
  1045. #[must_use]
  1046. pub fn any_thread(mut self) -> Self {
  1047. self.runtime_any_thread = true;
  1048. self
  1049. }
  1050. /// Defines the JS message handler callback.
  1051. ///
  1052. /// # Examples
  1053. /// ```
  1054. /// #[tauri::command]
  1055. /// fn command_1() -> String {
  1056. /// return "hello world".to_string();
  1057. /// }
  1058. /// tauri::Builder::default()
  1059. /// .invoke_handler(tauri::generate_handler![
  1060. /// command_1,
  1061. /// // etc...
  1062. /// ]);
  1063. /// ```
  1064. #[must_use]
  1065. pub fn invoke_handler<F>(mut self, invoke_handler: F) -> Self
  1066. where
  1067. F: Fn(Invoke<R>) -> bool + Send + Sync + 'static,
  1068. {
  1069. self.invoke_handler = Box::new(invoke_handler);
  1070. self
  1071. }
  1072. /// Defines a custom JS message system.
  1073. ///
  1074. /// The `responder` is a function that will be called when a command has been executed and must send a response to the JS layer.
  1075. ///
  1076. /// The `initialization_script` is a script that initializes `window.__TAURI_INTERNALS__.postMessage`.
  1077. /// That function must take the `(message: object, options: object)` arguments and send it to the backend.
  1078. #[must_use]
  1079. pub fn invoke_system<F>(mut self, initialization_script: String, responder: F) -> Self
  1080. where
  1081. F: Fn(&Webview<R>, &str, &InvokeResponse, CallbackFn, CallbackFn) + Send + Sync + 'static,
  1082. {
  1083. self.invoke_initialization_script = initialization_script;
  1084. self.invoke_responder.replace(Arc::new(responder));
  1085. self
  1086. }
  1087. /// Defines the setup hook.
  1088. ///
  1089. /// # Examples
  1090. #[cfg_attr(
  1091. feature = "unstable",
  1092. doc = r####"
  1093. ```
  1094. use tauri::Manager;
  1095. tauri::Builder::default()
  1096. .setup(|app| {
  1097. let main_window = app.get_window("main").unwrap();
  1098. main_window.set_title("Tauri!");
  1099. Ok(())
  1100. });
  1101. ```
  1102. "####
  1103. )]
  1104. #[must_use]
  1105. pub fn setup<F>(mut self, setup: F) -> Self
  1106. where
  1107. F: FnOnce(&mut App<R>) -> Result<(), Box<dyn std::error::Error>> + Send + 'static,
  1108. {
  1109. self.setup = Box::new(setup);
  1110. self
  1111. }
  1112. /// Defines the page load hook.
  1113. #[must_use]
  1114. pub fn on_page_load<F>(mut self, on_page_load: F) -> Self
  1115. where
  1116. F: Fn(&Webview<R>, &PageLoadPayload<'_>) + Send + Sync + 'static,
  1117. {
  1118. self.on_page_load.replace(Arc::new(on_page_load));
  1119. self
  1120. }
  1121. /// Adds a Tauri application plugin.
  1122. ///
  1123. /// A plugin is created using the [`crate::plugin::Builder`] struct.Check its documentation for more information.
  1124. ///
  1125. /// # Examples
  1126. ///
  1127. /// ```
  1128. /// mod plugin {
  1129. /// use tauri::{plugin::{Builder as PluginBuilder, TauriPlugin}, RunEvent, Runtime};
  1130. ///
  1131. /// // this command can be called in the frontend using `invoke('plugin:window|do_something')`.
  1132. /// #[tauri::command]
  1133. /// async fn do_something<R: Runtime>(app: tauri::AppHandle<R>, window: tauri::Window<R>) -> Result<(), String> {
  1134. /// println!("command called");
  1135. /// Ok(())
  1136. /// }
  1137. /// pub fn init<R: Runtime>() -> TauriPlugin<R> {
  1138. /// PluginBuilder::new("window")
  1139. /// .setup(|app, api| {
  1140. /// // initialize the plugin here
  1141. /// Ok(())
  1142. /// })
  1143. /// .on_event(|app, event| {
  1144. /// match event {
  1145. /// RunEvent::Ready => {
  1146. /// println!("app is ready");
  1147. /// }
  1148. /// RunEvent::WindowEvent { label, event, .. } => {
  1149. /// println!("window {} received an event: {:?}", label, event);
  1150. /// }
  1151. /// _ => (),
  1152. /// }
  1153. /// })
  1154. /// .invoke_handler(tauri::generate_handler![do_something])
  1155. /// .build()
  1156. /// }
  1157. /// }
  1158. ///
  1159. /// tauri::Builder::default()
  1160. /// .plugin(plugin::init());
  1161. /// ```
  1162. #[must_use]
  1163. pub fn plugin<P: Plugin<R> + 'static>(mut self, plugin: P) -> Self {
  1164. self.plugins.register(Box::new(plugin));
  1165. self
  1166. }
  1167. /// Add `state` to the state managed by the application.
  1168. ///
  1169. /// This method can be called any number of times as long as each call
  1170. /// refers to a different `T`.
  1171. ///
  1172. /// Managed state can be retrieved by any command handler via the
  1173. /// [`crate::State`] guard. In particular, if a value of type `T`
  1174. /// is managed by Tauri, adding `State<T>` to the list of arguments in a
  1175. /// command handler instructs Tauri to retrieve the managed value.
  1176. /// Additionally, [`state`](crate::Manager#method.state) can be used to retrieve the value manually.
  1177. ///
  1178. /// # Panics
  1179. ///
  1180. /// Panics if state of type `T` is already being managed.
  1181. ///
  1182. /// # Mutability
  1183. ///
  1184. /// Since the managed state is global and must be [`Send`] + [`Sync`], mutations can only happen through interior mutability:
  1185. ///
  1186. /// ```,no_run
  1187. /// use std::{collections::HashMap, sync::Mutex};
  1188. /// use tauri::State;
  1189. /// // here we use Mutex to achieve interior mutability
  1190. /// struct Storage {
  1191. /// store: Mutex<HashMap<u64, String>>,
  1192. /// }
  1193. /// struct Connection;
  1194. /// struct DbConnection {
  1195. /// db: Mutex<Option<Connection>>,
  1196. /// }
  1197. ///
  1198. /// #[tauri::command]
  1199. /// fn connect(connection: State<DbConnection>) {
  1200. /// // initialize the connection, mutating the state with interior mutability
  1201. /// *connection.db.lock().unwrap() = Some(Connection {});
  1202. /// }
  1203. ///
  1204. /// #[tauri::command]
  1205. /// fn storage_insert(key: u64, value: String, storage: State<Storage>) {
  1206. /// // mutate the storage behind the Mutex
  1207. /// storage.store.lock().unwrap().insert(key, value);
  1208. /// }
  1209. ///
  1210. /// tauri::Builder::default()
  1211. /// .manage(Storage { store: Default::default() })
  1212. /// .manage(DbConnection { db: Default::default() })
  1213. /// .invoke_handler(tauri::generate_handler![connect, storage_insert])
  1214. /// // on an actual app, remove the string argument
  1215. /// .run(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
  1216. /// .expect("error while running tauri application");
  1217. /// ```
  1218. ///
  1219. /// # Examples
  1220. ///
  1221. /// ```,no_run
  1222. /// use tauri::State;
  1223. ///
  1224. /// struct MyInt(isize);
  1225. /// struct MyString(String);
  1226. ///
  1227. /// #[tauri::command]
  1228. /// fn int_command(state: State<MyInt>) -> String {
  1229. /// format!("The stateful int is: {}", state.0)
  1230. /// }
  1231. ///
  1232. /// #[tauri::command]
  1233. /// fn string_command<'r>(state: State<'r, MyString>) {
  1234. /// println!("state: {}", state.inner().0);
  1235. /// }
  1236. ///
  1237. /// tauri::Builder::default()
  1238. /// .manage(MyInt(10))
  1239. /// .manage(MyString("Hello, managed state!".to_string()))
  1240. /// .invoke_handler(tauri::generate_handler![int_command, string_command])
  1241. /// // on an actual app, remove the string argument
  1242. /// .run(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
  1243. /// .expect("error while running tauri application");
  1244. /// ```
  1245. #[must_use]
  1246. pub fn manage<T>(self, state: T) -> Self
  1247. where
  1248. T: Send + Sync + 'static,
  1249. {
  1250. let type_name = std::any::type_name::<T>();
  1251. assert!(
  1252. self.state.set(state),
  1253. "state for type '{type_name}' is already being managed",
  1254. );
  1255. self
  1256. }
  1257. /// Sets the menu to use on all windows.
  1258. ///
  1259. /// # Examples
  1260. /// ```
  1261. /// use tauri::menu::{Menu, MenuItem, PredefinedMenuItem, Submenu};
  1262. ///
  1263. /// tauri::Builder::default()
  1264. /// .menu(|handle| Menu::with_items(handle, &[
  1265. /// &Submenu::with_items(
  1266. /// handle,
  1267. /// "File",
  1268. /// true,
  1269. /// &[
  1270. /// &PredefinedMenuItem::close_window(handle, None)?,
  1271. /// #[cfg(target_os = "macos")]
  1272. /// &MenuItem::new(handle, "Hello", true, None::<&str>)?,
  1273. /// ],
  1274. /// )?
  1275. /// ]));
  1276. /// ```
  1277. #[must_use]
  1278. #[cfg(desktop)]
  1279. pub fn menu<F: FnOnce(&AppHandle<R>) -> crate::Result<Menu<R>> + Send + 'static>(
  1280. mut self,
  1281. f: F,
  1282. ) -> Self {
  1283. self.menu.replace(Box::new(f));
  1284. self
  1285. }
  1286. /// Enable or disable the default menu on macOS. Enabled by default.
  1287. ///
  1288. /// # Examples
  1289. /// ```
  1290. /// tauri::Builder::default()
  1291. /// .enable_macos_default_menu(false);
  1292. /// ```
  1293. #[must_use]
  1294. pub fn enable_macos_default_menu(mut self, enable: bool) -> Self {
  1295. self.enable_macos_default_menu = enable;
  1296. self
  1297. }
  1298. /// Registers a window event handler for all windows.
  1299. ///
  1300. /// # Examples
  1301. /// ```
  1302. /// tauri::Builder::default()
  1303. /// .on_window_event(|window, event| match event {
  1304. /// tauri::WindowEvent::Focused(focused) => {
  1305. /// // hide window whenever it loses focus
  1306. /// if !focused {
  1307. /// window.hide().unwrap();
  1308. /// }
  1309. /// }
  1310. /// _ => {}
  1311. /// });
  1312. /// ```
  1313. #[must_use]
  1314. pub fn on_window_event<F: Fn(&Window<R>, &WindowEvent) + Send + Sync + 'static>(
  1315. mut self,
  1316. handler: F,
  1317. ) -> Self {
  1318. self.window_event_listeners.push(Box::new(handler));
  1319. self
  1320. }
  1321. /// Registers a webview event handler for all webviews.
  1322. ///
  1323. /// # Examples
  1324. /// ```
  1325. /// tauri::Builder::default()
  1326. /// .on_webview_event(|window, event| match event {
  1327. /// tauri::WebviewEvent::DragDrop(event) => {
  1328. /// println!("{:?}", event);
  1329. /// }
  1330. /// _ => {}
  1331. /// });
  1332. /// ```
  1333. #[must_use]
  1334. pub fn on_webview_event<F: Fn(&Webview<R>, &WebviewEvent) + Send + Sync + 'static>(
  1335. mut self,
  1336. handler: F,
  1337. ) -> Self {
  1338. self.webview_event_listeners.push(Box::new(handler));
  1339. self
  1340. }
  1341. /// Registers a URI scheme protocol available to all webviews.
  1342. /// Leverages [setURLSchemeHandler](https://developer.apple.com/documentation/webkit/wkwebviewconfiguration/2875766-seturlschemehandler) on macOS,
  1343. /// [AddWebResourceRequestedFilter](https://docs.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2.addwebresourcerequestedfilter?view=webview2-dotnet-1.0.774.44) on Windows
  1344. /// and [webkit-web-context-register-uri-scheme](https://webkitgtk.org/reference/webkit2gtk/stable/WebKitWebContext.html#webkit-web-context-register-uri-scheme) on Linux.
  1345. ///
  1346. /// # Arguments
  1347. ///
  1348. /// * `uri_scheme` The URI scheme to register, such as `example`.
  1349. /// * `protocol` the protocol associated with the given URI scheme. It's a function that takes a request and returns a response.
  1350. ///
  1351. /// # Examples
  1352. /// ```
  1353. /// tauri::Builder::default()
  1354. /// .register_uri_scheme_protocol("app-files", |_app, request| {
  1355. /// // skip leading `/`
  1356. /// if let Ok(data) = std::fs::read(&request.uri().path()[1..]) {
  1357. /// http::Response::builder()
  1358. /// .body(data)
  1359. /// .unwrap()
  1360. /// } else {
  1361. /// http::Response::builder()
  1362. /// .status(http::StatusCode::BAD_REQUEST)
  1363. /// .header(http::header::CONTENT_TYPE, mime::TEXT_PLAIN.essence_str())
  1364. /// .body("failed to read file".as_bytes().to_vec())
  1365. /// .unwrap()
  1366. /// }
  1367. /// });
  1368. /// ```
  1369. #[must_use]
  1370. pub fn register_uri_scheme_protocol<
  1371. N: Into<String>,
  1372. T: Into<Cow<'static, [u8]>>,
  1373. H: Fn(&AppHandle<R>, http::Request<Vec<u8>>) -> http::Response<T> + Send + Sync + 'static,
  1374. >(
  1375. mut self,
  1376. uri_scheme: N,
  1377. protocol: H,
  1378. ) -> Self {
  1379. self.uri_scheme_protocols.insert(
  1380. uri_scheme.into(),
  1381. Arc::new(UriSchemeProtocol {
  1382. protocol: Box::new(move |app, request, responder| {
  1383. responder.respond(protocol(app, request))
  1384. }),
  1385. }),
  1386. );
  1387. self
  1388. }
  1389. /// Similar to [`Self::register_uri_scheme_protocol`] but with an asynchronous responder that allows you
  1390. /// to process the request in a separate thread and respond asynchronously.
  1391. ///
  1392. /// # Arguments
  1393. ///
  1394. /// * `uri_scheme` The URI scheme to register, such as `example`.
  1395. /// * `protocol` the protocol associated with the given URI scheme. It's a function that takes an URL such as `example://localhost/asset.css`.
  1396. ///
  1397. /// # Examples
  1398. /// ```
  1399. /// tauri::Builder::default()
  1400. /// .register_asynchronous_uri_scheme_protocol("app-files", |_app, request, responder| {
  1401. /// // skip leading `/`
  1402. /// let path = request.uri().path()[1..].to_string();
  1403. /// std::thread::spawn(move || {
  1404. /// if let Ok(data) = std::fs::read(path) {
  1405. /// responder.respond(
  1406. /// http::Response::builder()
  1407. /// .body(data)
  1408. /// .unwrap()
  1409. /// );
  1410. /// } else {
  1411. /// responder.respond(
  1412. /// http::Response::builder()
  1413. /// .status(http::StatusCode::BAD_REQUEST)
  1414. /// .header(http::header::CONTENT_TYPE, mime::TEXT_PLAIN.essence_str())
  1415. /// .body("failed to read file".as_bytes().to_vec())
  1416. /// .unwrap()
  1417. /// );
  1418. /// }
  1419. /// });
  1420. /// });
  1421. /// ```
  1422. #[must_use]
  1423. pub fn register_asynchronous_uri_scheme_protocol<
  1424. N: Into<String>,
  1425. H: Fn(&AppHandle<R>, http::Request<Vec<u8>>, UriSchemeResponder) + Send + Sync + 'static,
  1426. >(
  1427. mut self,
  1428. uri_scheme: N,
  1429. protocol: H,
  1430. ) -> Self {
  1431. self.uri_scheme_protocols.insert(
  1432. uri_scheme.into(),
  1433. Arc::new(UriSchemeProtocol {
  1434. protocol: Box::new(protocol),
  1435. }),
  1436. );
  1437. self
  1438. }
  1439. /// Change the device event filter mode.
  1440. ///
  1441. /// Since the DeviceEvent capture can lead to high CPU usage for unfocused windows, [`tao`]
  1442. /// will ignore them by default for unfocused windows on Windows. This method allows changing
  1443. /// the filter to explicitly capture them again.
  1444. ///
  1445. /// ## Platform-specific
  1446. ///
  1447. /// - ** Linux / macOS / iOS / Android**: Unsupported.
  1448. ///
  1449. /// # Examples
  1450. /// ```,no_run
  1451. /// tauri::Builder::default()
  1452. /// .device_event_filter(tauri::DeviceEventFilter::Always);
  1453. /// ```
  1454. ///
  1455. /// [`tao`]: https://crates.io/crates/tao
  1456. pub fn device_event_filter(mut self, filter: DeviceEventFilter) -> Self {
  1457. self.device_event_filter = filter;
  1458. self
  1459. }
  1460. /// Builds the application.
  1461. #[allow(clippy::type_complexity, unused_mut)]
  1462. #[cfg_attr(
  1463. feature = "tracing",
  1464. tracing::instrument(name = "app::build", skip_all)
  1465. )]
  1466. pub fn build(mut self, context: Context<R>) -> crate::Result<App<R>> {
  1467. #[cfg(target_os = "macos")]
  1468. if self.menu.is_none() && self.enable_macos_default_menu {
  1469. self.menu = Some(Box::new(|app_handle| {
  1470. crate::menu::Menu::default(app_handle)
  1471. }));
  1472. }
  1473. let manager = Arc::new(AppManager::with_handlers(
  1474. context,
  1475. self.plugins,
  1476. self.invoke_handler,
  1477. self.on_page_load,
  1478. self.uri_scheme_protocols,
  1479. self.state,
  1480. self.window_event_listeners,
  1481. self.webview_event_listeners,
  1482. #[cfg(desktop)]
  1483. HashMap::new(),
  1484. (self.invoke_responder, self.invoke_initialization_script),
  1485. ));
  1486. let runtime_args = RuntimeInitArgs {
  1487. #[cfg(windows)]
  1488. msg_hook: {
  1489. let menus = manager.menu.menus.clone();
  1490. Some(Box::new(move |msg| {
  1491. use windows::Win32::UI::WindowsAndMessaging::{TranslateAcceleratorW, HACCEL, MSG};
  1492. unsafe {
  1493. let msg = msg as *const MSG;
  1494. for menu in menus.lock().unwrap().values() {
  1495. let translated =
  1496. TranslateAcceleratorW((*msg).hwnd, HACCEL(menu.inner().haccel()), msg);
  1497. if translated == 1 {
  1498. return true;
  1499. }
  1500. }
  1501. false
  1502. }
  1503. }))
  1504. },
  1505. };
  1506. #[cfg(any(windows, target_os = "linux"))]
  1507. let mut runtime = if self.runtime_any_thread {
  1508. R::new_any_thread(runtime_args)?
  1509. } else {
  1510. R::new(runtime_args)?
  1511. };
  1512. #[cfg(not(any(windows, target_os = "linux")))]
  1513. let mut runtime = R::new(runtime_args)?;
  1514. #[cfg(desktop)]
  1515. {
  1516. // setup menu event handler
  1517. let proxy = runtime.create_proxy();
  1518. muda::MenuEvent::set_event_handler(Some(move |e: muda::MenuEvent| {
  1519. let _ = proxy.send_event(EventLoopMessage::MenuEvent(e.into()));
  1520. }));
  1521. // setup tray event handler
  1522. #[cfg(feature = "tray-icon")]
  1523. {
  1524. let proxy = runtime.create_proxy();
  1525. tray_icon::TrayIconEvent::set_event_handler(Some(move |e: tray_icon::TrayIconEvent| {
  1526. let _ = proxy.send_event(EventLoopMessage::TrayIconEvent(e.into()));
  1527. }));
  1528. }
  1529. }
  1530. runtime.set_device_event_filter(self.device_event_filter);
  1531. let runtime_handle = runtime.handle();
  1532. #[allow(unused_mut)]
  1533. let mut app = App {
  1534. runtime: Some(runtime),
  1535. setup: Some(self.setup),
  1536. manager: manager.clone(),
  1537. handle: AppHandle {
  1538. runtime_handle,
  1539. manager,
  1540. },
  1541. ran_setup: false,
  1542. };
  1543. #[cfg(desktop)]
  1544. if let Some(menu) = self.menu {
  1545. let menu = menu(&app.handle)?;
  1546. app
  1547. .manager
  1548. .menu
  1549. .menus_stash_lock()
  1550. .insert(menu.id().clone(), menu.clone());
  1551. #[cfg(target_os = "macos")]
  1552. init_app_menu(&menu)?;
  1553. app.manager.menu.menu_lock().replace(menu);
  1554. }
  1555. app.register_core_plugins()?;
  1556. let env = Env::default();
  1557. app.manage(env);
  1558. app.manage(Scopes {
  1559. #[cfg(feature = "protocol-asset")]
  1560. asset_protocol: crate::scope::fs::Scope::new(
  1561. &app,
  1562. &app.config().app.security.asset_protocol.scope,
  1563. )?,
  1564. });
  1565. app.manage(ChannelDataIpcQueue::default());
  1566. app.handle.plugin(crate::ipc::channel::plugin())?;
  1567. #[cfg(windows)]
  1568. {
  1569. if let crate::utils::config::WebviewInstallMode::FixedRuntime { path } =
  1570. &app.manager.config().bundle.windows.webview_install_mode
  1571. {
  1572. if let Ok(resource_dir) = app.path().resource_dir() {
  1573. std::env::set_var(
  1574. "WEBVIEW2_BROWSER_EXECUTABLE_FOLDER",
  1575. resource_dir.join(path),
  1576. );
  1577. } else {
  1578. #[cfg(debug_assertions)]
  1579. eprintln!(
  1580. "failed to resolve resource directory; fallback to the installed Webview2 runtime."
  1581. );
  1582. }
  1583. }
  1584. }
  1585. let handle = app.handle();
  1586. // initialize default tray icon if defined
  1587. #[cfg(all(desktop, feature = "tray-icon"))]
  1588. {
  1589. let config = app.config();
  1590. if let Some(tray_config) = &config.app.tray_icon {
  1591. let mut tray =
  1592. TrayIconBuilder::with_id(tray_config.id.clone().unwrap_or_else(|| "main".into()))
  1593. .icon_as_template(tray_config.icon_as_template)
  1594. .menu_on_left_click(tray_config.menu_on_left_click);
  1595. if let Some(icon) = &app.manager.tray.icon {
  1596. tray = tray.icon(icon.clone());
  1597. }
  1598. if let Some(title) = &tray_config.title {
  1599. tray = tray.title(title);
  1600. }
  1601. if let Some(tooltip) = &tray_config.tooltip {
  1602. tray = tray.tooltip(tooltip);
  1603. }
  1604. tray.build(handle)?;
  1605. }
  1606. }
  1607. app.manager.initialize_plugins(handle)?;
  1608. Ok(app)
  1609. }
  1610. /// Runs the configured Tauri application.
  1611. pub fn run(self, context: Context<R>) -> crate::Result<()> {
  1612. self.build(context)?.run(|_, _| {});
  1613. Ok(())
  1614. }
  1615. }
  1616. pub(crate) type UriSchemeResponderFn = Box<dyn FnOnce(http::Response<Cow<'static, [u8]>>) + Send>;
  1617. pub struct UriSchemeResponder(pub(crate) UriSchemeResponderFn);
  1618. impl UriSchemeResponder {
  1619. /// Resolves the request with the given response.
  1620. pub fn respond<T: Into<Cow<'static, [u8]>>>(self, response: http::Response<T>) {
  1621. let (parts, body) = response.into_parts();
  1622. (self.0)(http::Response::from_parts(parts, body.into()))
  1623. }
  1624. }
  1625. #[cfg(target_os = "macos")]
  1626. fn init_app_menu<R: Runtime>(menu: &Menu<R>) -> crate::Result<()> {
  1627. menu.inner().init_for_nsapp();
  1628. if let Some(window_menu) = menu.get(crate::menu::WINDOW_SUBMENU_ID) {
  1629. if let Some(m) = window_menu.as_submenu() {
  1630. m.set_as_windows_menu_for_nsapp()?;
  1631. }
  1632. }
  1633. if let Some(help_menu) = menu.get(crate::menu::HELP_SUBMENU_ID) {
  1634. if let Some(m) = help_menu.as_submenu() {
  1635. m.set_as_help_menu_for_nsapp()?;
  1636. }
  1637. }
  1638. Ok(())
  1639. }
  1640. impl<R: Runtime> HasDisplayHandle for AppHandle<R> {
  1641. fn display_handle(
  1642. &self,
  1643. ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, raw_window_handle::HandleError> {
  1644. self.runtime_handle.display_handle()
  1645. }
  1646. }
  1647. impl<R: Runtime> HasDisplayHandle for App<R> {
  1648. fn display_handle(
  1649. &self,
  1650. ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, raw_window_handle::HandleError> {
  1651. self.handle.display_handle()
  1652. }
  1653. }
  1654. #[cfg_attr(feature = "tracing", tracing::instrument(name = "app::setup"))]
  1655. fn setup<R: Runtime>(app: &mut App<R>) -> crate::Result<()> {
  1656. app.ran_setup = true;
  1657. let window_labels = app
  1658. .config()
  1659. .app
  1660. .windows
  1661. .iter()
  1662. .map(|p| p.label.clone())
  1663. .collect::<Vec<_>>();
  1664. let webview_labels = window_labels
  1665. .iter()
  1666. .map(|label| WebviewLabelDef {
  1667. window_label: label.clone(),
  1668. label: label.clone(),
  1669. })
  1670. .collect::<Vec<_>>();
  1671. for window_config in app.config().app.windows.clone() {
  1672. WebviewWindowBuilder::from_config(app.handle(), &window_config)?
  1673. .build_internal(&window_labels, &webview_labels)?;
  1674. }
  1675. app.manager.assets.setup(app);
  1676. if let Some(setup) = app.setup.take() {
  1677. (setup)(app).map_err(|e| crate::Error::Setup(e.into()))?;
  1678. }
  1679. Ok(())
  1680. }
  1681. fn on_event_loop_event<R: Runtime>(
  1682. app_handle: &AppHandle<R>,
  1683. event: RuntimeRunEvent<EventLoopMessage>,
  1684. manager: &AppManager<R>,
  1685. ) -> RunEvent {
  1686. if let RuntimeRunEvent::WindowEvent {
  1687. label,
  1688. event: RuntimeWindowEvent::Destroyed,
  1689. } = &event
  1690. {
  1691. manager.on_window_close(label);
  1692. }
  1693. let event = match event {
  1694. RuntimeRunEvent::Exit => RunEvent::Exit,
  1695. RuntimeRunEvent::ExitRequested { code, tx } => RunEvent::ExitRequested {
  1696. code,
  1697. api: ExitRequestApi(tx),
  1698. },
  1699. RuntimeRunEvent::WindowEvent { label, event } => RunEvent::WindowEvent {
  1700. label,
  1701. event: event.into(),
  1702. },
  1703. RuntimeRunEvent::WebviewEvent { label, event } => RunEvent::WebviewEvent {
  1704. label,
  1705. event: event.into(),
  1706. },
  1707. RuntimeRunEvent::Ready => {
  1708. // set the app icon in development
  1709. #[cfg(all(dev, target_os = "macos"))]
  1710. unsafe {
  1711. use cocoa::{
  1712. appkit::NSImage,
  1713. base::{id, nil},
  1714. foundation::NSData,
  1715. };
  1716. use objc::*;
  1717. if let Some(icon) = app_handle.manager.app_icon.clone() {
  1718. let ns_app: id = msg_send![class!(NSApplication), sharedApplication];
  1719. let data = NSData::dataWithBytes_length_(
  1720. nil,
  1721. icon.as_ptr() as *const std::os::raw::c_void,
  1722. icon.len() as u64,
  1723. );
  1724. let app_icon = NSImage::initWithData_(NSImage::alloc(nil), data);
  1725. let _: () = msg_send![ns_app, setApplicationIconImage: app_icon];
  1726. }
  1727. }
  1728. RunEvent::Ready
  1729. }
  1730. RuntimeRunEvent::Resumed => RunEvent::Resumed,
  1731. RuntimeRunEvent::MainEventsCleared => RunEvent::MainEventsCleared,
  1732. RuntimeRunEvent::UserEvent(t) => {
  1733. match t {
  1734. #[cfg(desktop)]
  1735. EventLoopMessage::MenuEvent(ref e) => {
  1736. for listener in &*app_handle
  1737. .manager
  1738. .menu
  1739. .global_event_listeners
  1740. .lock()
  1741. .unwrap()
  1742. {
  1743. listener(app_handle, e.clone());
  1744. }
  1745. for (label, listener) in &*app_handle.manager.menu.event_listeners.lock().unwrap() {
  1746. if let Some(w) = app_handle.manager().get_window(label) {
  1747. listener(&w, e.clone());
  1748. }
  1749. }
  1750. }
  1751. #[cfg(all(desktop, feature = "tray-icon"))]
  1752. EventLoopMessage::TrayIconEvent(ref e) => {
  1753. for listener in &*app_handle
  1754. .manager
  1755. .tray
  1756. .global_event_listeners
  1757. .lock()
  1758. .unwrap()
  1759. {
  1760. listener(app_handle, e.clone());
  1761. }
  1762. for (id, listener) in &*app_handle.manager.tray.event_listeners.lock().unwrap() {
  1763. if e.id == id {
  1764. if let Some(tray) = app_handle.tray_by_id(id) {
  1765. listener(&tray, e.clone());
  1766. }
  1767. }
  1768. }
  1769. }
  1770. }
  1771. #[allow(unreachable_code)]
  1772. t.into()
  1773. }
  1774. #[cfg(any(target_os = "macos", target_os = "ios"))]
  1775. RuntimeRunEvent::Opened { urls } => RunEvent::Opened { urls },
  1776. #[cfg(target_os = "macos")]
  1777. RuntimeRunEvent::Reopen {
  1778. has_visible_windows,
  1779. } => RunEvent::Reopen {
  1780. has_visible_windows,
  1781. },
  1782. _ => unimplemented!(),
  1783. };
  1784. manager
  1785. .plugins
  1786. .lock()
  1787. .expect("poisoned plugin store")
  1788. .on_event(app_handle, &event);
  1789. event
  1790. }
  1791. #[cfg(test)]
  1792. mod tests {
  1793. #[test]
  1794. fn is_send_sync() {
  1795. crate::test_utils::assert_send::<super::AppHandle>();
  1796. crate::test_utils::assert_sync::<super::AppHandle>();
  1797. #[cfg(feature = "wry")]
  1798. {
  1799. crate::test_utils::assert_send::<super::AssetResolver<crate::Wry>>();
  1800. crate::test_utils::assert_sync::<super::AssetResolver<crate::Wry>>();
  1801. }
  1802. }
  1803. }