window.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. // Copyright 2019-2022 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. //! A layer between raw [`Runtime`] webview windows and Tauri.
  5. use crate::{
  6. http::{Request as HttpRequest, Response as HttpResponse},
  7. menu::{Menu, MenuEntry, MenuHash, MenuId},
  8. webview::{WebviewAttributes, WebviewIpcHandler},
  9. Dispatch, Runtime, UserEvent, WindowBuilder,
  10. };
  11. use serde::{Deserialize, Deserializer, Serialize};
  12. use tauri_utils::{config::WindowConfig, Theme};
  13. use url::Url;
  14. use std::{
  15. collections::{HashMap, HashSet},
  16. hash::{Hash, Hasher},
  17. path::PathBuf,
  18. sync::{mpsc::Sender, Arc, Mutex},
  19. };
  20. type UriSchemeProtocol =
  21. dyn Fn(&HttpRequest) -> Result<HttpResponse, Box<dyn std::error::Error>> + Send + Sync + 'static;
  22. /// UI scaling utilities.
  23. pub mod dpi;
  24. /// An event from a window.
  25. #[derive(Debug, Clone)]
  26. pub enum WindowEvent {
  27. /// The size of the window has changed. Contains the client area's new dimensions.
  28. Resized(dpi::PhysicalSize<u32>),
  29. /// The position of the window has changed. Contains the window's new position.
  30. Moved(dpi::PhysicalPosition<i32>),
  31. /// The window has been requested to close.
  32. CloseRequested {
  33. /// A signal sender. If a `true` value is emitted, the window won't be closed.
  34. signal_tx: Sender<bool>,
  35. },
  36. /// The window has been destroyed.
  37. Destroyed,
  38. /// The window gained or lost focus.
  39. ///
  40. /// The parameter is true if the window has gained focus, and false if it has lost focus.
  41. Focused(bool),
  42. /// The window's scale factor has changed.
  43. ///
  44. /// The following user actions can cause DPI changes:
  45. ///
  46. /// - Changing the display's resolution.
  47. /// - Changing the display's scale factor (e.g. in Control Panel on Windows).
  48. /// - Moving the window to a display with a different scale factor.
  49. ScaleFactorChanged {
  50. /// The new scale factor.
  51. scale_factor: f64,
  52. /// The window inner size.
  53. new_inner_size: dpi::PhysicalSize<u32>,
  54. },
  55. /// An event associated with the file drop action.
  56. FileDrop(FileDropEvent),
  57. /// The system window theme has changed.
  58. ///
  59. /// Applications might wish to react to this to change the theme of the content of the window when the system changes the window theme.
  60. ThemeChanged(Theme),
  61. }
  62. /// The file drop event payload.
  63. #[derive(Debug, Clone)]
  64. #[non_exhaustive]
  65. pub enum FileDropEvent {
  66. /// The file(s) have been dragged onto the window, but have not been dropped yet.
  67. Hovered(Vec<PathBuf>),
  68. /// The file(s) have been dropped onto the window.
  69. Dropped(Vec<PathBuf>),
  70. /// The file drop was aborted.
  71. Cancelled,
  72. }
  73. /// A menu event.
  74. #[derive(Debug, Serialize)]
  75. #[serde(rename_all = "camelCase")]
  76. pub struct MenuEvent {
  77. pub menu_item_id: u16,
  78. }
  79. fn get_menu_ids(map: &mut HashMap<MenuHash, MenuId>, menu: &Menu) {
  80. for item in &menu.items {
  81. match item {
  82. MenuEntry::CustomItem(c) => {
  83. map.insert(c.id, c.id_str.clone());
  84. }
  85. MenuEntry::Submenu(s) => get_menu_ids(map, &s.inner),
  86. _ => {}
  87. }
  88. }
  89. }
  90. /// Describes the appearance of the mouse cursor.
  91. #[non_exhaustive]
  92. #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
  93. pub enum CursorIcon {
  94. /// The platform-dependent default cursor.
  95. Default,
  96. /// A simple crosshair.
  97. Crosshair,
  98. /// A hand (often used to indicate links in web browsers).
  99. Hand,
  100. /// Self explanatory.
  101. Arrow,
  102. /// Indicates something is to be moved.
  103. Move,
  104. /// Indicates text that may be selected or edited.
  105. Text,
  106. /// Program busy indicator.
  107. Wait,
  108. /// Help indicator (often rendered as a "?")
  109. Help,
  110. /// Progress indicator. Shows that processing is being done. But in contrast
  111. /// with "Wait" the user may still interact with the program. Often rendered
  112. /// as a spinning beach ball, or an arrow with a watch or hourglass.
  113. Progress,
  114. /// Cursor showing that something cannot be done.
  115. NotAllowed,
  116. ContextMenu,
  117. Cell,
  118. VerticalText,
  119. Alias,
  120. Copy,
  121. NoDrop,
  122. /// Indicates something can be grabbed.
  123. Grab,
  124. /// Indicates something is grabbed.
  125. Grabbing,
  126. AllScroll,
  127. ZoomIn,
  128. ZoomOut,
  129. /// Indicate that some edge is to be moved. For example, the 'SeResize' cursor
  130. /// is used when the movement starts from the south-east corner of the box.
  131. EResize,
  132. NResize,
  133. NeResize,
  134. NwResize,
  135. SResize,
  136. SeResize,
  137. SwResize,
  138. WResize,
  139. EwResize,
  140. NsResize,
  141. NeswResize,
  142. NwseResize,
  143. ColResize,
  144. RowResize,
  145. }
  146. impl<'de> Deserialize<'de> for CursorIcon {
  147. fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  148. where
  149. D: Deserializer<'de>,
  150. {
  151. let s = String::deserialize(deserializer)?;
  152. Ok(match s.to_lowercase().as_str() {
  153. "default" => CursorIcon::Default,
  154. "crosshair" => CursorIcon::Crosshair,
  155. "hand" => CursorIcon::Hand,
  156. "arrow" => CursorIcon::Arrow,
  157. "move" => CursorIcon::Move,
  158. "text" => CursorIcon::Text,
  159. "wait" => CursorIcon::Wait,
  160. "help" => CursorIcon::Help,
  161. "progress" => CursorIcon::Progress,
  162. "notallowed" => CursorIcon::NotAllowed,
  163. "contextmenu" => CursorIcon::ContextMenu,
  164. "cell" => CursorIcon::Cell,
  165. "verticaltext" => CursorIcon::VerticalText,
  166. "alias" => CursorIcon::Alias,
  167. "copy" => CursorIcon::Copy,
  168. "nodrop" => CursorIcon::NoDrop,
  169. "grab" => CursorIcon::Grab,
  170. "grabbing" => CursorIcon::Grabbing,
  171. "allscroll" => CursorIcon::AllScroll,
  172. "zoomun" => CursorIcon::ZoomIn,
  173. "zoomout" => CursorIcon::ZoomOut,
  174. "eresize" => CursorIcon::EResize,
  175. "nresize" => CursorIcon::NResize,
  176. "neresize" => CursorIcon::NeResize,
  177. "nwresize" => CursorIcon::NwResize,
  178. "sresize" => CursorIcon::SResize,
  179. "seresize" => CursorIcon::SeResize,
  180. "swresize" => CursorIcon::SwResize,
  181. "wresize" => CursorIcon::WResize,
  182. "ewresize" => CursorIcon::EwResize,
  183. "nsresize" => CursorIcon::NsResize,
  184. "neswresize" => CursorIcon::NeswResize,
  185. "nwseresize" => CursorIcon::NwseResize,
  186. "colresize" => CursorIcon::ColResize,
  187. "rowresize" => CursorIcon::RowResize,
  188. _ => CursorIcon::Default,
  189. })
  190. }
  191. }
  192. impl Default for CursorIcon {
  193. fn default() -> Self {
  194. CursorIcon::Default
  195. }
  196. }
  197. /// A webview window that has yet to be built.
  198. pub struct PendingWindow<T: UserEvent, R: Runtime<T>> {
  199. /// The label that the window will be named.
  200. pub label: String,
  201. /// The [`WindowBuilder`] that the window will be created with.
  202. pub window_builder: <R::Dispatcher as Dispatch<T>>::WindowBuilder,
  203. /// The [`WebviewAttributes`] that the webview will be created with.
  204. pub webview_attributes: WebviewAttributes,
  205. pub uri_scheme_protocols: HashMap<String, Box<UriSchemeProtocol>>,
  206. /// How to handle IPC calls on the webview window.
  207. pub ipc_handler: Option<WebviewIpcHandler<T, R>>,
  208. /// The resolved URL to load on the webview.
  209. pub url: String,
  210. /// Maps runtime id to a string menu id.
  211. pub menu_ids: Arc<Mutex<HashMap<MenuHash, MenuId>>>,
  212. /// A HashMap mapping JS event names with associated listener ids.
  213. pub js_event_listeners: Arc<Mutex<HashMap<JsEventListenerKey, HashSet<u64>>>>,
  214. /// A handler to decide if incoming url is allowed to navigate.
  215. pub navigation_handler: Option<Box<dyn Fn(Url) -> bool + Send>>,
  216. }
  217. pub fn is_label_valid(label: &str) -> bool {
  218. label
  219. .chars()
  220. .all(|c| char::is_alphanumeric(c) || c == '-' || c == '/' || c == ':' || c == '_')
  221. }
  222. pub fn assert_label_is_valid(label: &str) {
  223. assert!(
  224. is_label_valid(label),
  225. "Window label must include only alphanumeric characters, `-`, `/`, `:` and `_`."
  226. );
  227. }
  228. impl<T: UserEvent, R: Runtime<T>> PendingWindow<T, R> {
  229. /// Create a new [`PendingWindow`] with a label and starting url.
  230. pub fn new(
  231. window_builder: <R::Dispatcher as Dispatch<T>>::WindowBuilder,
  232. webview_attributes: WebviewAttributes,
  233. label: impl Into<String>,
  234. ) -> crate::Result<Self> {
  235. let mut menu_ids = HashMap::new();
  236. if let Some(menu) = window_builder.get_menu() {
  237. get_menu_ids(&mut menu_ids, menu);
  238. }
  239. let label = label.into();
  240. if !is_label_valid(&label) {
  241. Err(crate::Error::InvalidWindowLabel)
  242. } else {
  243. Ok(Self {
  244. window_builder,
  245. webview_attributes,
  246. uri_scheme_protocols: Default::default(),
  247. label,
  248. ipc_handler: None,
  249. url: "tauri://localhost".to_string(),
  250. menu_ids: Arc::new(Mutex::new(menu_ids)),
  251. js_event_listeners: Default::default(),
  252. navigation_handler: Default::default(),
  253. })
  254. }
  255. }
  256. /// Create a new [`PendingWindow`] from a [`WindowConfig`] with a label and starting url.
  257. pub fn with_config(
  258. window_config: WindowConfig,
  259. webview_attributes: WebviewAttributes,
  260. label: impl Into<String>,
  261. ) -> crate::Result<Self> {
  262. let window_builder =
  263. <<R::Dispatcher as Dispatch<T>>::WindowBuilder>::with_config(window_config);
  264. let mut menu_ids = HashMap::new();
  265. if let Some(menu) = window_builder.get_menu() {
  266. get_menu_ids(&mut menu_ids, menu);
  267. }
  268. let label = label.into();
  269. if !is_label_valid(&label) {
  270. Err(crate::Error::InvalidWindowLabel)
  271. } else {
  272. Ok(Self {
  273. window_builder,
  274. webview_attributes,
  275. uri_scheme_protocols: Default::default(),
  276. label,
  277. ipc_handler: None,
  278. url: "tauri://localhost".to_string(),
  279. menu_ids: Arc::new(Mutex::new(menu_ids)),
  280. js_event_listeners: Default::default(),
  281. navigation_handler: Default::default(),
  282. })
  283. }
  284. }
  285. #[must_use]
  286. pub fn set_menu(mut self, menu: Menu) -> Self {
  287. let mut menu_ids = HashMap::new();
  288. get_menu_ids(&mut menu_ids, &menu);
  289. *self.menu_ids.lock().unwrap() = menu_ids;
  290. self.window_builder = self.window_builder.menu(menu);
  291. self
  292. }
  293. pub fn register_uri_scheme_protocol<
  294. N: Into<String>,
  295. H: Fn(&HttpRequest) -> Result<HttpResponse, Box<dyn std::error::Error>> + Send + Sync + 'static,
  296. >(
  297. &mut self,
  298. uri_scheme: N,
  299. protocol: H,
  300. ) {
  301. let uri_scheme = uri_scheme.into();
  302. self
  303. .uri_scheme_protocols
  304. .insert(uri_scheme, Box::new(move |data| (protocol)(data)));
  305. }
  306. }
  307. /// Key for a JS event listener.
  308. #[derive(Debug, Clone, PartialEq, Eq, Hash)]
  309. pub struct JsEventListenerKey {
  310. /// The associated window label.
  311. pub window_label: Option<String>,
  312. /// The event name.
  313. pub event: String,
  314. }
  315. /// A webview window that is not yet managed by Tauri.
  316. #[derive(Debug)]
  317. pub struct DetachedWindow<T: UserEvent, R: Runtime<T>> {
  318. /// Name of the window
  319. pub label: String,
  320. /// The [`Dispatch`](crate::Dispatch) associated with the window.
  321. pub dispatcher: R::Dispatcher,
  322. /// Maps runtime id to a string menu id.
  323. pub menu_ids: Arc<Mutex<HashMap<MenuHash, MenuId>>>,
  324. /// A HashMap mapping JS event names with associated listener ids.
  325. pub js_event_listeners: Arc<Mutex<HashMap<JsEventListenerKey, HashSet<u64>>>>,
  326. }
  327. impl<T: UserEvent, R: Runtime<T>> Clone for DetachedWindow<T, R> {
  328. fn clone(&self) -> Self {
  329. Self {
  330. label: self.label.clone(),
  331. dispatcher: self.dispatcher.clone(),
  332. menu_ids: self.menu_ids.clone(),
  333. js_event_listeners: self.js_event_listeners.clone(),
  334. }
  335. }
  336. }
  337. impl<T: UserEvent, R: Runtime<T>> Hash for DetachedWindow<T, R> {
  338. /// Only use the [`DetachedWindow`]'s label to represent its hash.
  339. fn hash<H: Hasher>(&self, state: &mut H) {
  340. self.label.hash(state)
  341. }
  342. }
  343. impl<T: UserEvent, R: Runtime<T>> Eq for DetachedWindow<T, R> {}
  344. impl<T: UserEvent, R: Runtime<T>> PartialEq for DetachedWindow<T, R> {
  345. /// Only use the [`DetachedWindow`]'s label to compare equality.
  346. fn eq(&self, other: &Self) -> bool {
  347. self.label.eq(&other.label)
  348. }
  349. }