lib.rs 36 KB

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