lib.rs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. // Copyright 2019-2021 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. //! Tauri is a framework for building tiny, blazing fast binaries for all major desktop platforms.
  5. //! Developers can integrate any front-end framework that compiles to HTML, JS and CSS for building their user interface.
  6. //! The backend of the application is a rust-sourced binary with an API that the front-end can interact with.
  7. //!
  8. //! # Cargo features
  9. //!
  10. //! The following are a list of [Cargo features](https://doc.rust-lang.org/stable/cargo/reference/manifest.html#the-features-section) that can be enabled or disabled:
  11. //!
  12. //! - **wry** *(enabled by default)*: Enables the [wry](https://github.com/tauri-apps/wry) runtime. Only disable it if you want a custom runtime.
  13. //! - **isolation**: Enables the isolation pattern. Enabled by default if the `tauri > pattern > use` config option is set to `isolation` on the `tauri.conf.json` file.
  14. //! - **custom-protocol**: Feature managed by the Tauri CLI. When enabled, Tauri assumes a production environment instead of a development one.
  15. //! - **updater**: Enables the application auto updater. Enabled by default if the `updater` config is defined on the `tauri.conf.json` file.
  16. //! - **devtools**: Enables the developer tools (Web inspector) and [`Window::open_devtools`]. Enabled by default on debug builds.
  17. //! On macOS it uses private APIs, so you can't enable it if your app will be published to the App Store.
  18. //! - **http-api**: Enables the [`api::http`] module.
  19. //! - **reqwest-client**: Uses `reqwest` as HTTP client on the `http` APIs. Improves performance, but increases the bundle size.
  20. //! - **command**: Enables the [`api::process::Command`] APIs.
  21. //! - **dialog**: Enables the [`api::dialog`] module.
  22. //! - **notification**: Enables the [`api::notification`] module.
  23. //! - **cli**: Enables usage of `clap` for CLI argument parsing. Enabled by default if the `cli` config is defined on the `tauri.conf.json` file.
  24. //! - **system-tray**: Enables application system tray API. Enabled by default if the `systemTray` config is defined on the `tauri.conf.json` file.
  25. //! - **macos-private-api**: Enables features only available in **macOS**'s private APIs, currently the `transparent` window functionality and the `fullScreenEnabled` preference setting to `true`. Enabled by default if the `tauri > macosPrivateApi` config flag is set to `true` on the `tauri.conf.json` file.
  26. //! - **window-data-url**: Enables usage of data URLs on the webview.
  27. //!
  28. //! ## Cargo allowlist features
  29. //!
  30. //! The following are a list of [Cargo features](https://doc.rust-lang.org/stable/cargo/reference/manifest.html#the-features-section) that enables commands for Tauri's API package.
  31. //! These features are automatically enabled by the Tauri CLI based on the `allowlist` configuration under `tauri.conf.json`.
  32. //!
  33. //! - **api-all**: Enables all API endpoints.
  34. //!
  35. //! ### Clipboard allowlist
  36. //!
  37. //! - **clipboard-all**: Enables all [Clipboard APIs](https://tauri.studio/en/docs/api/js/modules/clipboard/).
  38. //! - **clipboard-read-text**: Enables the [`readText` API](https://tauri.studio/en/docs/api/js/modules/clipboard/#readtext).
  39. //! - **clipboard-write-text**: Enables the [`writeText` API](https://tauri.studio/en/docs/api/js/modules/clipboard/#writetext).
  40. //!
  41. //! ### Dialog allowlist
  42. //!
  43. //! - **dialog-all**: Enables all [Dialog APIs](https://tauri.studio/en/docs/api/js/modules/dialog).
  44. //! - **dialog-ask**: Enables the [`ask` API](https://tauri.studio/en/docs/api/js/modules/dialog#ask).
  45. //! - **dialog-confirm**: Enables the [`confirm` API](https://tauri.studio/en/docs/api/js/modules/dialog#confirm).
  46. //! - **dialog-message**: Enables the [`message` API](https://tauri.studio/en/docs/api/js/modules/dialog#message).
  47. //! - **dialog-open**: Enables the [`open` API](https://tauri.studio/en/docs/api/js/modules/dialog#open).
  48. //! - **dialog-save**: Enables the [`save` API](https://tauri.studio/en/docs/api/js/modules/dialog#save).
  49. //!
  50. //! ### Filesystem allowlist
  51. //!
  52. //! - **fs-all**: Enables all [Filesystem APIs](https://tauri.studio/en/docs/api/js/modules/fs).
  53. //! - **fs-copy-file**: Enables the [`copyFile` API](https://tauri.studio/en/docs/api/js/modules/fs#copyfile).
  54. //! - **fs-create-dir**: Enables the [`createDir` API](https://tauri.studio/en/docs/api/js/modules/fs#createdir).
  55. //! - **fs-read-dir**: Enables the [`readDir` API](https://tauri.studio/en/docs/api/js/modules/fs#readdir).
  56. //! - **fs-read-file**: Enables the [`readTextFile` API](https://tauri.studio/en/docs/api/js/modules/fs#readtextfile) and the [`readBinaryFile` API](https://tauri.studio/en/docs/api/js/modules/fs#readbinaryfile).
  57. //! - **fs-remove-dir**: Enables the [`removeDir` API](https://tauri.studio/en/docs/api/js/modules/fs#removedir).
  58. //! - **fs-remove-file**: Enables the [`removeFile` API](https://tauri.studio/en/docs/api/js/modules/fs#removefile).
  59. //! - **fs-rename-file**: Enables the [`renameFile` API](https://tauri.studio/en/docs/api/js/modules/fs#renamefile).
  60. //! - **fs-write-file**: Enables the [`writeFile` API](https://tauri.studio/en/docs/api/js/modules/fs#writefile) and the [`writeBinaryFile` API](https://tauri.studio/en/docs/api/js/modules/fs#writebinaryfile).
  61. //!
  62. //! ### Global shortcut allowlist
  63. //!
  64. //! - **global-shortcut-all**: Enables all [GlobalShortcut APIs](https://tauri.studio/en/docs/api/js/modules/globalShortcut).
  65. //!
  66. //! ### HTTP allowlist
  67. //!
  68. //! - **http-all**: Enables all [HTTP APIs](https://tauri.studio/en/docs/api/js/modules/http).
  69. //! - **http-request**: Enables the [`request` APIs](https://tauri.studio/en/docs/api/js/classes/http.client/).
  70. //!
  71. //! ### Notification allowlist
  72. //!
  73. //! - **notification-all**: Enables all [Notification APIs](https://tauri.studio/en/docs/api/js/modules/notification).
  74. //!
  75. //! ### OS allowlist
  76. //!
  77. //! - **os-all**: Enables all [OS APIs](https://tauri.studio/en/docs/api/js/modules/os).
  78. //!
  79. //! ### Path allowlist
  80. //!
  81. //! - **path-all**: Enables all [Path APIs](https://tauri.studio/en/docs/api/js/modules/path).
  82. //!
  83. //! ### Process allowlist
  84. //!
  85. //! - **process-all**: Enables all [Process APIs](https://tauri.studio/en/docs/api/js/modules/process).
  86. //! - **process-exit**: Enables the [`exit` API](https://tauri.studio/en/docs/api/js/modules/process#exit).
  87. //! - **process-relaunch**: Enables the [`relaunch` API](https://tauri.studio/en/docs/api/js/modules/process#relaunch).
  88. //!
  89. //! ### Protocol allowlist
  90. //!
  91. //! - **protocol-all**: Enables all Protocol APIs.
  92. //! - **protocol-asset**: Enables the `asset` custom protocol.
  93. //!
  94. //! ### Shell allowlist
  95. //!
  96. //! - **shell-all**: Enables all [Clipboard APIs](https://tauri.studio/en/docs/api/js/modules/shell).
  97. //! - **shell-execute**: Enables [executing arbitrary programs](https://tauri.studio/en/docs/api/js/classes/shell.Command#constructor).
  98. //! - **shell-sidecar**: Enables [executing a `sidecar` program](https://tauri.studio/en/docs/api/js/classes/shell.Command#sidecar).
  99. //! - **shell-open**: Enables the [`open` API](https://tauri.studio/en/docs/api/js/modules/shell#open).
  100. //!
  101. //! ### Window allowlist
  102. //!
  103. //! - **window-all**: Enables all [Window APIs](https://tauri.studio/en/docs/api/js/modules/window).
  104. //! - **window-create**: Enables the API used to [create new windows](https://tauri.studio/en/docs/api/js/classes/window.webviewwindow/).
  105. //! - **window-center**: Enables the [`center` API](https://tauri.studio/en/docs/api/js/classes/window.WebviewWindow#center).
  106. //! - **window-request-user-attention**: Enables the [`requestUserAttention` API](https://tauri.studio/en/docs/api/js/classes/window.WebviewWindow#requestuserattention).
  107. //! - **window-set-resizable**: Enables the [`setResizable` API](https://tauri.studio/en/docs/api/js/classes/window.WebviewWindow#setresizable).
  108. //! - **window-set-title**: Enables the [`setTitle` API](https://tauri.studio/en/docs/api/js/classes/window.WebviewWindow#settitle).
  109. //! - **window-maximize**: Enables the [`maximize` API](https://tauri.studio/en/docs/api/js/classes/window.WebviewWindow#maximize).
  110. //! - **window-unmaximize**: Enables the [`unmaximize` API](https://tauri.studio/en/docs/api/js/classes/window.WebviewWindow#unmaximize).
  111. //! - **window-minimize**: Enables the [`minimize` API](https://tauri.studio/en/docs/api/js/classes/window.WebviewWindow#minimize).
  112. //! - **window-unminimize**: Enables the [`unminimize` API](https://tauri.studio/en/docs/api/js/classes/window.WebviewWindow#unminimize).
  113. //! - **window-show**: Enables the [`show` API](https://tauri.studio/en/docs/api/js/classes/window.WebviewWindow#show).
  114. //! - **window-hide**: Enables the [`hide` API](https://tauri.studio/en/docs/api/js/classes/window.WebviewWindow#hide).
  115. //! - **window-close**: Enables the [`close` API](https://tauri.studio/en/docs/api/js/classes/window.WebviewWindow#close).
  116. //! - **window-set-decorations**: Enables the [`setDecorations` API](https://tauri.studio/en/docs/api/js/classes/window.WebviewWindow#setdecorations).
  117. //! - **window-set-always-on-top**: Enables the [`setAlwaysOnTop` API](https://tauri.studio/en/docs/api/js/classes/window.WebviewWindow#setalwaysontop).
  118. //! - **window-set-size**: Enables the [`setSize` API](https://tauri.studio/en/docs/api/js/classes/window.WebviewWindow#setsize).
  119. //! - **window-set-min-size**: Enables the [`setMinSize` API](https://tauri.studio/en/docs/api/js/classes/window.WebviewWindow#setminsize).
  120. //! - **window-set-max-size**: Enables the [`setMaxSize` API](https://tauri.studio/en/docs/api/js/classes/window.WebviewWindow#setmaxsize).
  121. //! - **window-set-position**: Enables the [`setPosition` API](https://tauri.studio/en/docs/api/js/classes/window.WebviewWindow#setposition).
  122. //! - **window-set-fullscreen**: Enables the [`setFullscreen` API](https://tauri.studio/en/docs/api/js/classes/window.WebviewWindow#setfullscreen).
  123. //! - **window-set-focus**: Enables the [`setFocus` API](https://tauri.studio/en/docs/api/js/classes/window.WebviewWindow#setfocus).
  124. //! - **window-set-icon**: Enables the [`setIcon` API](https://tauri.studio/en/docs/api/js/classes/window.WebviewWindow#seticon).
  125. //! - **window-set-skip-taskbar**: Enables the [`setSkipTaskbar` API](https://tauri.studio/en/docs/api/js/classes/window.WebviewWindow#setskiptaskbar).
  126. //! - **window-start-dragging**: Enables the [`startDragging` API](https://tauri.studio/en/docs/api/js/classes/window.WebviewWindow#startdragging).
  127. //! - **window-print**: Enables the [`print` API](https://tauri.studio/en/docs/api/js/classes/window.WebviewWindow#print).
  128. #![warn(missing_docs, rust_2018_idioms)]
  129. #![cfg_attr(doc_cfg, feature(doc_cfg))]
  130. #[cfg(target_os = "macos")]
  131. #[doc(hidden)]
  132. pub use embed_plist;
  133. /// The Tauri error enum.
  134. pub use error::Error;
  135. #[cfg(shell_scope)]
  136. #[doc(hidden)]
  137. pub use regex;
  138. pub use tauri_macros::{command, generate_handler};
  139. pub mod api;
  140. pub(crate) mod app;
  141. pub mod async_runtime;
  142. pub mod command;
  143. /// The Tauri API endpoints.
  144. mod endpoints;
  145. mod error;
  146. mod event;
  147. mod hooks;
  148. mod manager;
  149. mod pattern;
  150. pub mod plugin;
  151. pub mod window;
  152. use tauri_runtime as runtime;
  153. /// The allowlist scopes.
  154. pub mod scope;
  155. pub mod settings;
  156. mod state;
  157. #[cfg(updater)]
  158. #[cfg_attr(doc_cfg, doc(cfg(feature = "updater")))]
  159. pub mod updater;
  160. pub use tauri_utils as utils;
  161. /// A Tauri [`Runtime`] wrapper around wry.
  162. #[cfg(feature = "wry")]
  163. #[cfg_attr(doc_cfg, doc(cfg(feature = "wry")))]
  164. pub type Wry = tauri_runtime_wry::Wry<EventLoopMessage>;
  165. /// `Result<T, ::tauri::Error>`
  166. pub type Result<T> = std::result::Result<T, Error>;
  167. /// A task to run on the main thread.
  168. pub type SyncTask = Box<dyn FnOnce() + Send>;
  169. use serde::Serialize;
  170. use std::{collections::HashMap, fmt, sync::Arc};
  171. // Export types likely to be used by the application.
  172. pub use runtime::http;
  173. #[cfg(target_os = "macos")]
  174. #[cfg_attr(doc_cfg, doc(cfg(target_os = "macos")))]
  175. pub use runtime::{menu::NativeImage, ActivationPolicy};
  176. #[cfg(feature = "system-tray")]
  177. #[cfg_attr(doc_cfg, doc(cfg(feature = "system-tray")))]
  178. pub use {
  179. self::app::tray::{SystemTrayEvent, SystemTrayHandle},
  180. self::runtime::{
  181. menu::{SystemTrayMenu, SystemTrayMenuItem, SystemTraySubmenu},
  182. SystemTray,
  183. },
  184. };
  185. pub use {
  186. self::app::WindowMenuEvent,
  187. self::event::{Event, EventHandler},
  188. self::runtime::menu::{AboutMetadata, CustomMenuItem, Menu, MenuEntry, MenuItem, Submenu},
  189. self::window::menu::MenuEvent,
  190. };
  191. pub use {
  192. self::app::{
  193. App, AppHandle, AssetResolver, Builder, CloseRequestApi, GlobalWindowEvent, PathResolver,
  194. RunEvent, WindowEvent,
  195. },
  196. self::hooks::{
  197. Invoke, InvokeError, InvokeHandler, InvokeMessage, InvokePayload, InvokeResolver,
  198. InvokeResponder, InvokeResponse, OnPageLoad, PageLoadPayload, SetupHook,
  199. },
  200. self::manager::Asset,
  201. self::runtime::{
  202. webview::{WebviewAttributes, WindowBuilder},
  203. window::{
  204. dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize, Pixel, Position, Size},
  205. FileDropEvent,
  206. },
  207. ClipboardManager, GlobalShortcutManager, RunIteration, TrayIcon, UserAttentionType,
  208. },
  209. self::state::{State, StateManager},
  210. self::utils::{
  211. assets::Assets,
  212. config::{Config, WindowUrl},
  213. Env, PackageInfo,
  214. },
  215. self::window::{Monitor, Window},
  216. scope::*,
  217. };
  218. /// Updater events.
  219. #[cfg(updater)]
  220. #[cfg_attr(doc_cfg, doc(cfg(feature = "updater")))]
  221. #[derive(Debug, Clone)]
  222. pub enum UpdaterEvent {
  223. /// An update is available.
  224. UpdateAvailable {
  225. /// The update body.
  226. body: String,
  227. /// The update release date.
  228. date: String,
  229. /// The update version.
  230. version: String,
  231. },
  232. /// The update is pending and about to be downloaded.
  233. Pending,
  234. /// The update download received a progress event.
  235. DownloadProgress {
  236. /// The amount that was downloaded on this iteration.
  237. /// Does not accumulate with previous chunks.
  238. chunk_length: usize,
  239. /// The total
  240. content_length: Option<u64>,
  241. },
  242. /// The update has been applied and the app is now up to date.
  243. Updated,
  244. /// The app is already up to date.
  245. AlreadyUpToDate,
  246. /// An error occurred while updating.
  247. Error(String),
  248. }
  249. #[cfg(updater)]
  250. impl UpdaterEvent {
  251. pub(crate) fn status_message(self) -> &'static str {
  252. match self {
  253. Self::Pending => updater::EVENT_STATUS_PENDING,
  254. Self::Updated => updater::EVENT_STATUS_SUCCESS,
  255. Self::AlreadyUpToDate => updater::EVENT_STATUS_UPTODATE,
  256. Self::Error(_) => updater::EVENT_STATUS_ERROR,
  257. _ => unreachable!(),
  258. }
  259. }
  260. }
  261. /// The user event type.
  262. #[derive(Debug, Clone)]
  263. pub enum EventLoopMessage {
  264. /// Updater event.
  265. #[cfg(updater)]
  266. #[cfg_attr(doc_cfg, doc(cfg(feature = "updater")))]
  267. Updater(UpdaterEvent),
  268. }
  269. /// The webview runtime interface. A wrapper around [`runtime::Runtime`] with the proper user event type associated.
  270. pub trait Runtime: runtime::Runtime<EventLoopMessage> {}
  271. impl<W: runtime::Runtime<EventLoopMessage>> Runtime for W {}
  272. /// Reads the config file at compile time and generates a [`Context`] based on its content.
  273. ///
  274. /// The default config file path is a `tauri.conf.json` file inside the Cargo manifest directory of
  275. /// the crate being built.
  276. ///
  277. /// # Custom Config Path
  278. ///
  279. /// You may pass a string literal to this macro to specify a custom path for the Tauri config file.
  280. /// If the path is relative, it will be search for relative to the Cargo manifest of the compiling
  281. /// crate.
  282. ///
  283. /// # Note
  284. ///
  285. /// This macro should not be called if you are using [`tauri-build`] to generate the context from
  286. /// inside your build script as it will just cause excess computations that will be discarded. Use
  287. /// either the [`tauri-build`] method or this macro - not both.
  288. ///
  289. /// [`tauri-build`]: https://docs.rs/tauri-build
  290. pub use tauri_macros::generate_context;
  291. /// Include a [`Context`] that was generated by [`tauri-build`] inside your build script.
  292. ///
  293. /// You should either use [`tauri-build`] and this macro to include the compile time generated code,
  294. /// or [`generate_context!`]. Do not use both at the same time, as they generate the same code and
  295. /// will cause excess computations that will be discarded.
  296. ///
  297. /// [`tauri-build`]: https://docs.rs/tauri-build
  298. #[macro_export]
  299. macro_rules! tauri_build_context {
  300. () => {
  301. include!(concat!(env!("OUT_DIR"), "/tauri-build-context.rs"))
  302. };
  303. }
  304. pub use pattern::Pattern;
  305. /// A icon definition.
  306. #[derive(Debug, Clone)]
  307. #[non_exhaustive]
  308. pub enum Icon {
  309. /// Icon from file path.
  310. #[cfg(any(feature = "icon-ico", feature = "icon-png"))]
  311. #[cfg_attr(doc_cfg, doc(cfg(any(feature = "icon-ico", feature = "icon-png"))))]
  312. File(std::path::PathBuf),
  313. /// Icon from raw RGBA bytes. Width and height is parsed at runtime.
  314. #[cfg(any(feature = "icon-ico", feature = "icon-png"))]
  315. #[cfg_attr(doc_cfg, doc(cfg(any(feature = "icon-ico", feature = "icon-png"))))]
  316. Raw(Vec<u8>),
  317. /// Icon from raw RGBA bytes.
  318. Rgba {
  319. /// RGBA byes of the icon image.
  320. rgba: Vec<u8>,
  321. /// Icon width.
  322. width: u32,
  323. /// Icon height.
  324. height: u32,
  325. },
  326. }
  327. impl TryFrom<Icon> for runtime::WindowIcon {
  328. type Error = Error;
  329. fn try_from(icon: Icon) -> Result<Self> {
  330. #[allow(irrefutable_let_patterns)]
  331. if let Icon::Rgba {
  332. rgba,
  333. width,
  334. height,
  335. } = icon
  336. {
  337. Ok(Self {
  338. rgba,
  339. width,
  340. height,
  341. })
  342. } else {
  343. #[cfg(not(any(feature = "icon-ico", feature = "icon-png")))]
  344. panic!("unexpected Icon variant");
  345. #[cfg(any(feature = "icon-ico", feature = "icon-png"))]
  346. {
  347. let bytes = match icon {
  348. Icon::File(p) => std::fs::read(p)?,
  349. Icon::Raw(r) => r,
  350. Icon::Rgba { .. } => unreachable!(),
  351. };
  352. let extension = infer::get(&bytes)
  353. .expect("could not determine icon extension")
  354. .extension();
  355. match extension {
  356. #[cfg(feature = "icon-ico")]
  357. "ico" => {
  358. let icon_dir = ico::IconDir::read(std::io::Cursor::new(bytes))?;
  359. let entry = &icon_dir.entries()[0];
  360. Ok(Self {
  361. rgba: entry.decode()?.rgba_data().to_vec(),
  362. width: entry.width(),
  363. height: entry.height(),
  364. })
  365. }
  366. #[cfg(feature = "icon-png")]
  367. "png" => {
  368. let decoder = png::Decoder::new(std::io::Cursor::new(bytes));
  369. let mut reader = decoder.read_info()?;
  370. let mut buffer = Vec::new();
  371. while let Ok(Some(row)) = reader.next_row() {
  372. buffer.extend(row.data());
  373. }
  374. Ok(Self {
  375. rgba: buffer,
  376. width: reader.info().width,
  377. height: reader.info().height,
  378. })
  379. }
  380. _ => panic!(
  381. "image `{}` extension not supported; please file a Tauri feature request. `png` or `ico` icons are supported with the `icon-png` and `icon-ico` feature flags",
  382. extension
  383. ),
  384. }
  385. }
  386. }
  387. }
  388. }
  389. /// User supplied data required inside of a Tauri application.
  390. ///
  391. /// # Stability
  392. /// This is the output of the [`generate_context`] macro, and is not considered part of the stable API.
  393. /// Unless you know what you are doing and are prepared for this type to have breaking changes, do not create it yourself.
  394. pub struct Context<A: Assets> {
  395. pub(crate) config: Config,
  396. pub(crate) assets: Arc<A>,
  397. pub(crate) default_window_icon: Option<Icon>,
  398. pub(crate) system_tray_icon: Option<TrayIcon>,
  399. pub(crate) package_info: PackageInfo,
  400. pub(crate) _info_plist: (),
  401. pub(crate) pattern: Pattern,
  402. #[cfg(shell_scope)]
  403. pub(crate) shell_scope: scope::ShellScopeConfig,
  404. }
  405. impl<A: Assets> fmt::Debug for Context<A> {
  406. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  407. let mut d = f.debug_struct("Context");
  408. d.field("config", &self.config)
  409. .field("default_window_icon", &self.default_window_icon)
  410. .field("system_tray_icon", &self.system_tray_icon)
  411. .field("package_info", &self.package_info)
  412. .field("pattern", &self.pattern);
  413. #[cfg(shell_scope)]
  414. d.field("shell_scope", &self.shell_scope);
  415. d.finish()
  416. }
  417. }
  418. impl<A: Assets> Context<A> {
  419. /// The config the application was prepared with.
  420. #[inline(always)]
  421. pub fn config(&self) -> &Config {
  422. &self.config
  423. }
  424. /// A mutable reference to the config the application was prepared with.
  425. #[inline(always)]
  426. pub fn config_mut(&mut self) -> &mut Config {
  427. &mut self.config
  428. }
  429. /// The assets to be served directly by Tauri.
  430. #[inline(always)]
  431. pub fn assets(&self) -> Arc<A> {
  432. self.assets.clone()
  433. }
  434. /// A mutable reference to the assets to be served directly by Tauri.
  435. #[inline(always)]
  436. pub fn assets_mut(&mut self) -> &mut Arc<A> {
  437. &mut self.assets
  438. }
  439. /// The default window icon Tauri should use when creating windows.
  440. #[inline(always)]
  441. pub fn default_window_icon(&self) -> Option<&Icon> {
  442. self.default_window_icon.as_ref()
  443. }
  444. /// A mutable reference to the default window icon Tauri should use when creating windows.
  445. #[inline(always)]
  446. pub fn default_window_icon_mut(&mut self) -> &mut Option<Icon> {
  447. &mut self.default_window_icon
  448. }
  449. /// The icon to use on the system tray UI.
  450. #[inline(always)]
  451. pub fn system_tray_icon(&self) -> Option<&TrayIcon> {
  452. self.system_tray_icon.as_ref()
  453. }
  454. /// A mutable reference to the icon to use on the system tray UI.
  455. #[inline(always)]
  456. pub fn system_tray_icon_mut(&mut self) -> &mut Option<TrayIcon> {
  457. &mut self.system_tray_icon
  458. }
  459. /// Package information.
  460. #[inline(always)]
  461. pub fn package_info(&self) -> &PackageInfo {
  462. &self.package_info
  463. }
  464. /// A mutable reference to the package information.
  465. #[inline(always)]
  466. pub fn package_info_mut(&mut self) -> &mut PackageInfo {
  467. &mut self.package_info
  468. }
  469. /// The application pattern.
  470. #[inline(always)]
  471. pub fn pattern(&self) -> &Pattern {
  472. &self.pattern
  473. }
  474. /// The scoped shell commands, where the `HashMap` key is the name each configuration.
  475. #[cfg(shell_scope)]
  476. #[inline(always)]
  477. pub fn allowed_commands(&self) -> &scope::ShellScopeConfig {
  478. &self.shell_scope
  479. }
  480. /// Create a new [`Context`] from the minimal required items.
  481. #[inline(always)]
  482. #[allow(clippy::too_many_arguments)]
  483. pub fn new(
  484. config: Config,
  485. assets: Arc<A>,
  486. default_window_icon: Option<Icon>,
  487. system_tray_icon: Option<TrayIcon>,
  488. package_info: PackageInfo,
  489. info_plist: (),
  490. pattern: Pattern,
  491. #[cfg(shell_scope)] shell_scope: scope::ShellScopeConfig,
  492. ) -> Self {
  493. Self {
  494. config,
  495. assets,
  496. default_window_icon,
  497. system_tray_icon,
  498. package_info,
  499. _info_plist: info_plist,
  500. pattern,
  501. #[cfg(shell_scope)]
  502. shell_scope,
  503. }
  504. }
  505. }
  506. // TODO: expand these docs
  507. /// Manages a running application.
  508. pub trait Manager<R: Runtime>: sealed::ManagerBase<R> {
  509. /// The application handle associated with this manager.
  510. fn app_handle(&self) -> AppHandle<R> {
  511. self.managed_app_handle()
  512. }
  513. /// The [`Config`] the manager was created with.
  514. fn config(&self) -> Arc<Config> {
  515. self.manager().config()
  516. }
  517. /// Emits a event to all windows.
  518. fn emit_all<S: Serialize + Clone>(&self, event: &str, payload: S) -> Result<()> {
  519. self.manager().emit_filter(event, None, payload, |_| true)
  520. }
  521. /// Emits an event to a window with the specified label.
  522. fn emit_to<S: Serialize + Clone>(&self, label: &str, event: &str, payload: S) -> Result<()> {
  523. self
  524. .manager()
  525. .emit_filter(event, None, payload, |w| label == w.label())
  526. }
  527. /// Listen to a global event.
  528. fn listen_global<F>(&self, event: impl Into<String>, handler: F) -> EventHandler
  529. where
  530. F: Fn(Event) + Send + 'static,
  531. {
  532. self.manager().listen(event.into(), None, handler)
  533. }
  534. /// Listen to a global event only once.
  535. fn once_global<F>(&self, event: impl Into<String>, handler: F) -> EventHandler
  536. where
  537. F: FnOnce(Event) + Send + 'static,
  538. {
  539. self.manager().once(event.into(), None, handler)
  540. }
  541. /// Trigger a global event.
  542. fn trigger_global(&self, event: &str, data: Option<String>) {
  543. self.manager().trigger(event, None, data)
  544. }
  545. /// Remove an event listener.
  546. fn unlisten(&self, handler_id: EventHandler) {
  547. self.manager().unlisten(handler_id)
  548. }
  549. /// Fetch a single window from the manager.
  550. fn get_window(&self, label: &str) -> Option<Window<R>> {
  551. self.manager().get_window(label)
  552. }
  553. /// Fetch all managed windows.
  554. fn windows(&self) -> HashMap<String, Window<R>> {
  555. self.manager().windows()
  556. }
  557. /// Add `state` to the state managed by the application.
  558. ///
  559. /// This method can be called any number of times as long as each call
  560. /// refers to a different `T`.
  561. /// If a state for `T` is already managed, the function returns false and the value is ignored.
  562. ///
  563. /// Managed state can be retrieved by any command handler via the
  564. /// [`State`](crate::State) guard. In particular, if a value of type `T`
  565. /// is managed by Tauri, adding `State<T>` to the list of arguments in a
  566. /// command handler instructs Tauri to retrieve the managed value.
  567. ///
  568. /// # Panics
  569. ///
  570. /// Panics if state of type `T` is already being managed.
  571. ///
  572. /// # Mutability
  573. ///
  574. /// Since the managed state is global and must be [`Send`] + [`Sync`], mutations can only happen through interior mutability:
  575. ///
  576. /// ```rust,no_run
  577. /// use std::{collections::HashMap, sync::Mutex};
  578. /// use tauri::State;
  579. /// // here we use Mutex to achieve interior mutability
  580. /// struct Storage {
  581. /// store: Mutex<HashMap<u64, String>>,
  582. /// }
  583. /// struct Connection;
  584. /// struct DbConnection {
  585. /// db: Mutex<Option<Connection>>,
  586. /// }
  587. ///
  588. /// #[tauri::command]
  589. /// fn connect(connection: State<DbConnection>) {
  590. /// // initialize the connection, mutating the state with interior mutability
  591. /// *connection.db.lock().unwrap() = Some(Connection {});
  592. /// }
  593. ///
  594. /// #[tauri::command]
  595. /// fn storage_insert(key: u64, value: String, storage: State<Storage>) {
  596. /// // mutate the storage behind the Mutex
  597. /// storage.store.lock().unwrap().insert(key, value);
  598. /// }
  599. ///
  600. /// tauri::Builder::default()
  601. /// .manage(Storage { store: Default::default() })
  602. /// .manage(DbConnection { db: Default::default() })
  603. /// .invoke_handler(tauri::generate_handler![connect, storage_insert])
  604. /// // on an actual app, remove the string argument
  605. /// .run(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
  606. /// .expect("error while running tauri application");
  607. /// ```
  608. ///
  609. /// # Examples
  610. ///
  611. /// ```rust,no_run
  612. /// use tauri::{Manager, State};
  613. ///
  614. /// struct MyInt(isize);
  615. /// struct MyString(String);
  616. ///
  617. /// #[tauri::command]
  618. /// fn int_command(state: State<MyInt>) -> String {
  619. /// format!("The stateful int is: {}", state.0)
  620. /// }
  621. ///
  622. /// #[tauri::command]
  623. /// fn string_command<'r>(state: State<'r, MyString>) {
  624. /// println!("state: {}", state.inner().0);
  625. /// }
  626. ///
  627. /// tauri::Builder::default()
  628. /// .setup(|app| {
  629. /// app.manage(MyInt(0));
  630. /// app.manage(MyString("tauri".into()));
  631. /// // `MyInt` is already managed, so `manage()` returns false
  632. /// assert!(!app.manage(MyInt(1)));
  633. /// // read the `MyInt` managed state with the turbofish syntax
  634. /// let int = app.state::<MyInt>();
  635. /// assert_eq!(int.0, 0);
  636. /// // read the `MyString` managed state with the `State` guard
  637. /// let val: State<MyString> = app.state();
  638. /// assert_eq!(val.0, "tauri");
  639. /// Ok(())
  640. /// })
  641. /// .invoke_handler(tauri::generate_handler![int_command, string_command])
  642. /// // on an actual app, remove the string argument
  643. /// .run(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
  644. /// .expect("error while running tauri application");
  645. /// ```
  646. fn manage<T>(&self, state: T) -> bool
  647. where
  648. T: Send + Sync + 'static,
  649. {
  650. self.manager().state().set(state)
  651. }
  652. /// Retrieves the managed state for the type `T`.
  653. ///
  654. /// # Panics
  655. ///
  656. /// Panics if the state for the type `T` has not been previously [managed](Self::manage).
  657. /// Use [try_state](Self::try_state) for a non-panicking version.
  658. fn state<T>(&self) -> State<'_, T>
  659. where
  660. T: Send + Sync + 'static,
  661. {
  662. self
  663. .manager()
  664. .inner
  665. .state
  666. .try_get()
  667. .expect("state() called before manage() for given type")
  668. }
  669. /// Attempts to retrieve the managed state for the type `T`.
  670. ///
  671. /// Returns `Some` if the state has previously been [managed](Self::manage). Otherwise returns `None`.
  672. fn try_state<T>(&self) -> Option<State<'_, T>>
  673. where
  674. T: Send + Sync + 'static,
  675. {
  676. self.manager().inner.state.try_get()
  677. }
  678. /// Gets the managed [`Env`].
  679. fn env(&self) -> Env {
  680. self.state::<Env>().inner().clone()
  681. }
  682. /// Gets the scope for the filesystem APIs.
  683. fn fs_scope(&self) -> FsScope {
  684. self.state::<Scopes>().inner().fs.clone()
  685. }
  686. /// Gets the scope for the asset protocol.
  687. #[cfg(protocol_asset)]
  688. fn asset_protocol_scope(&self) -> FsScope {
  689. self.state::<Scopes>().inner().asset_protocol.clone()
  690. }
  691. /// Gets the scope for the shell execute APIs.
  692. #[cfg(shell_scope)]
  693. fn shell_scope(&self) -> ShellScope {
  694. self.state::<Scopes>().inner().shell.clone()
  695. }
  696. }
  697. /// Prevent implementation details from leaking out of the [`Manager`] trait.
  698. pub(crate) mod sealed {
  699. use super::Runtime;
  700. use crate::{app::AppHandle, manager::WindowManager};
  701. /// A running [`Runtime`] or a dispatcher to it.
  702. pub enum RuntimeOrDispatch<'r, R: Runtime> {
  703. /// Reference to the running [`Runtime`].
  704. Runtime(&'r R),
  705. /// Handle to the running [`Runtime`].
  706. RuntimeHandle(R::Handle),
  707. /// A dispatcher to the running [`Runtime`].
  708. Dispatch(R::Dispatcher),
  709. }
  710. /// Managed handle to the application runtime.
  711. pub trait ManagerBase<R: Runtime> {
  712. /// The manager behind the [`Managed`] item.
  713. fn manager(&self) -> &WindowManager<R>;
  714. fn runtime(&self) -> RuntimeOrDispatch<'_, R>;
  715. fn managed_app_handle(&self) -> AppHandle<R>;
  716. }
  717. }
  718. /// Utilities for unit testing on Tauri applications.
  719. #[cfg(test)]
  720. pub mod test;
  721. #[cfg(test)]
  722. mod test_utils {
  723. use proptest::prelude::*;
  724. pub fn assert_send<T: Send>() {}
  725. pub fn assert_sync<T: Sync>() {}
  726. #[allow(dead_code)]
  727. pub fn assert_not_allowlist_error<T>(res: anyhow::Result<T>) {
  728. if let Err(e) = res {
  729. assert!(!e.to_string().contains("not on the allowlist"));
  730. }
  731. }
  732. proptest! {
  733. #![proptest_config(ProptestConfig::with_cases(10000))]
  734. #[test]
  735. // check to see if spawn executes a function.
  736. fn check_spawn_task(task in "[a-z]+") {
  737. // create dummy task function
  738. let dummy_task = async move {
  739. format!("{}-run-dummy-task", task);
  740. };
  741. // call spawn
  742. crate::async_runtime::spawn(dummy_task);
  743. }
  744. }
  745. }