window.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. //! A layer between raw [`Runtime`] windows and Tauri.
  5. use crate::{
  6. webview::{DetachedWebview, PendingWebview},
  7. Icon, Runtime, UserEvent, WindowDispatch,
  8. };
  9. use serde::{Deserialize, Deserializer};
  10. use tauri_utils::{config::WindowConfig, Theme};
  11. #[cfg(windows)]
  12. use windows::Win32::Foundation::HWND;
  13. use std::{
  14. hash::{Hash, Hasher},
  15. marker::PhantomData,
  16. path::PathBuf,
  17. sync::mpsc::Sender,
  18. };
  19. /// An event from a window.
  20. #[derive(Debug, Clone)]
  21. pub enum WindowEvent {
  22. /// The size of the window has changed. Contains the client area's new dimensions.
  23. Resized(dpi::PhysicalSize<u32>),
  24. /// The position of the window has changed. Contains the window's new position.
  25. Moved(dpi::PhysicalPosition<i32>),
  26. /// The window has been requested to close.
  27. CloseRequested {
  28. /// A signal sender. If a `true` value is emitted, the window won't be closed.
  29. signal_tx: Sender<bool>,
  30. },
  31. /// The window has been destroyed.
  32. Destroyed,
  33. /// The window gained or lost focus.
  34. ///
  35. /// The parameter is true if the window has gained focus, and false if it has lost focus.
  36. Focused(bool),
  37. /// The window's scale factor has changed.
  38. ///
  39. /// The following user actions can cause DPI changes:
  40. ///
  41. /// - Changing the display's resolution.
  42. /// - Changing the display's scale factor (e.g. in Control Panel on Windows).
  43. /// - Moving the window to a display with a different scale factor.
  44. ScaleFactorChanged {
  45. /// The new scale factor.
  46. scale_factor: f64,
  47. /// The window inner size.
  48. new_inner_size: dpi::PhysicalSize<u32>,
  49. },
  50. /// An event associated with the drag and drop action.
  51. DragDrop(DragDropEvent),
  52. /// The system window theme has changed.
  53. ///
  54. /// Applications might wish to react to this to change the theme of the content of the window when the system changes the window theme.
  55. ThemeChanged(Theme),
  56. }
  57. /// An event from a window.
  58. #[derive(Debug, Clone)]
  59. pub enum WebviewEvent {
  60. /// An event associated with the drag and drop action.
  61. DragDrop(DragDropEvent),
  62. }
  63. /// The drag drop event payload.
  64. #[derive(Debug, Clone)]
  65. #[non_exhaustive]
  66. pub enum DragDropEvent {
  67. /// A drag operation started.
  68. Dragged {
  69. /// Paths of the files that are being dragged.
  70. paths: Vec<PathBuf>,
  71. /// The position of the mouse cursor.
  72. position: dpi::PhysicalPosition<f64>,
  73. },
  74. /// The files have been dragged onto the window, but have not been dropped yet.
  75. DragOver {
  76. /// The position of the mouse cursor.
  77. position: dpi::PhysicalPosition<f64>,
  78. },
  79. /// The user dropped the operation.
  80. Dropped {
  81. /// Path of the files that were dropped.
  82. paths: Vec<PathBuf>,
  83. /// The position of the mouse cursor.
  84. position: dpi::PhysicalPosition<f64>,
  85. },
  86. /// The drag operation was cancelled.
  87. Cancelled,
  88. }
  89. /// Describes the appearance of the mouse cursor.
  90. #[non_exhaustive]
  91. #[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash)]
  92. pub enum CursorIcon {
  93. /// The platform-dependent default cursor.
  94. #[default]
  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. "zoomin" => 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. /// Do **NOT** implement this trait except for use in a custom [`Runtime`]
  193. ///
  194. /// This trait is separate from [`WindowBuilder`] to prevent "accidental" implementation.
  195. pub trait WindowBuilderBase: std::fmt::Debug + Clone + Sized {}
  196. /// A builder for all attributes related to a single window.
  197. ///
  198. /// This trait is only meant to be implemented by a custom [`Runtime`]
  199. /// and not by applications.
  200. pub trait WindowBuilder: WindowBuilderBase {
  201. /// Initializes a new window attributes builder.
  202. fn new() -> Self;
  203. /// Initializes a new window builder from a [`WindowConfig`]
  204. fn with_config(config: &WindowConfig) -> Self;
  205. /// Show window in the center of the screen.
  206. #[must_use]
  207. fn center(self) -> Self;
  208. /// The initial position of the window's.
  209. #[must_use]
  210. fn position(self, x: f64, y: f64) -> Self;
  211. /// Window size.
  212. #[must_use]
  213. fn inner_size(self, width: f64, height: f64) -> Self;
  214. /// Window min inner size.
  215. #[must_use]
  216. fn min_inner_size(self, min_width: f64, min_height: f64) -> Self;
  217. /// Window max inner size.
  218. #[must_use]
  219. fn max_inner_size(self, max_width: f64, max_height: f64) -> Self;
  220. /// Whether the window is resizable or not.
  221. /// When resizable is set to false, native window's maximize button is automatically disabled.
  222. #[must_use]
  223. fn resizable(self, resizable: bool) -> Self;
  224. /// Whether the window's native maximize button is enabled or not.
  225. /// If resizable is set to false, this setting is ignored.
  226. ///
  227. /// ## Platform-specific
  228. ///
  229. /// - **macOS:** Disables the "zoom" button in the window titlebar, which is also used to enter fullscreen mode.
  230. /// - **Linux / iOS / Android:** Unsupported.
  231. #[must_use]
  232. fn maximizable(self, maximizable: bool) -> Self;
  233. /// Whether the window's native minimize button is enabled or not.
  234. ///
  235. /// ## Platform-specific
  236. ///
  237. /// - **Linux / iOS / Android:** Unsupported.
  238. #[must_use]
  239. fn minimizable(self, minimizable: bool) -> Self;
  240. /// Whether the window's native close button is enabled or not.
  241. ///
  242. /// ## Platform-specific
  243. ///
  244. /// - **Linux:** "GTK+ will do its best to convince the window manager not to show a close button.
  245. /// Depending on the system, this function may not have any effect when called on a window that is already visible"
  246. /// - **iOS / Android:** Unsupported.
  247. #[must_use]
  248. fn closable(self, closable: bool) -> Self;
  249. /// The title of the window in the title bar.
  250. #[must_use]
  251. fn title<S: Into<String>>(self, title: S) -> Self;
  252. /// Whether to start the window in fullscreen or not.
  253. #[must_use]
  254. fn fullscreen(self, fullscreen: bool) -> Self;
  255. /// Whether the window will be initially focused or not.
  256. #[must_use]
  257. fn focused(self, focused: bool) -> Self;
  258. /// Whether the window should be maximized upon creation.
  259. #[must_use]
  260. fn maximized(self, maximized: bool) -> Self;
  261. /// Whether the window should be immediately visible upon creation.
  262. #[must_use]
  263. fn visible(self, visible: bool) -> Self;
  264. /// Whether the window should be transparent. If this is true, writing colors
  265. /// with alpha values different than `1.0` will produce a transparent window.
  266. #[cfg(any(not(target_os = "macos"), feature = "macos-private-api"))]
  267. #[cfg_attr(
  268. docsrs,
  269. doc(cfg(any(not(target_os = "macos"), feature = "macos-private-api")))
  270. )]
  271. #[must_use]
  272. fn transparent(self, transparent: bool) -> Self;
  273. /// Whether the window should have borders and bars.
  274. #[must_use]
  275. fn decorations(self, decorations: bool) -> Self;
  276. /// Whether the window should always be below other windows.
  277. #[must_use]
  278. fn always_on_bottom(self, always_on_bottom: bool) -> Self;
  279. /// Whether the window should always be on top of other windows.
  280. #[must_use]
  281. fn always_on_top(self, always_on_top: bool) -> Self;
  282. /// Whether the window should be visible on all workspaces or virtual desktops.
  283. #[must_use]
  284. fn visible_on_all_workspaces(self, visible_on_all_workspaces: bool) -> Self;
  285. /// Prevents the window contents from being captured by other apps.
  286. #[must_use]
  287. fn content_protected(self, protected: bool) -> Self;
  288. /// Sets the window icon.
  289. fn icon(self, icon: Icon) -> crate::Result<Self>;
  290. /// Sets whether or not the window icon should be added to the taskbar.
  291. #[must_use]
  292. fn skip_taskbar(self, skip: bool) -> Self;
  293. /// Sets whether or not the window has shadow.
  294. ///
  295. /// ## Platform-specific
  296. ///
  297. /// - **Windows:**
  298. /// - `false` has no effect on decorated window, shadows are always ON.
  299. /// - `true` will make ndecorated window have a 1px white border,
  300. /// and on Windows 11, it will have a rounded corners.
  301. /// - **Linux:** Unsupported.
  302. #[must_use]
  303. fn shadow(self, enable: bool) -> Self;
  304. /// Set an owner to the window to be created.
  305. ///
  306. /// From MSDN:
  307. /// - An owned window is always above its owner in the z-order.
  308. /// - The system automatically destroys an owned window when its owner is destroyed.
  309. /// - An owned window is hidden when its owner is minimized.
  310. ///
  311. /// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows>
  312. #[cfg(windows)]
  313. #[must_use]
  314. fn owner(self, owner: HWND) -> Self;
  315. /// Sets a parent to the window to be created.
  316. ///
  317. /// A child window has the WS_CHILD style and is confined to the client area of its parent window.
  318. ///
  319. /// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#child-windows>
  320. #[cfg(windows)]
  321. #[must_use]
  322. fn parent(self, parent: HWND) -> Self;
  323. /// Sets a parent to the window to be created.
  324. ///
  325. /// See <https://developer.apple.com/documentation/appkit/nswindow/1419152-addchildwindow?language=objc>
  326. #[cfg(target_os = "macos")]
  327. #[must_use]
  328. fn parent(self, parent: *mut std::ffi::c_void) -> Self;
  329. /// Sets the window to be created transient for parent.
  330. ///
  331. /// See <https://docs.gtk.org/gtk3/method.Window.set_transient_for.html>
  332. #[cfg(any(
  333. target_os = "linux",
  334. target_os = "dragonfly",
  335. target_os = "freebsd",
  336. target_os = "netbsd",
  337. target_os = "openbsd"
  338. ))]
  339. fn transient_for(self, parent: &impl gtk::glib::IsA<gtk::Window>) -> Self;
  340. /// Enables or disables drag and drop support.
  341. #[cfg(windows)]
  342. #[must_use]
  343. fn drag_and_drop(self, enabled: bool) -> Self;
  344. /// Hide the titlebar. Titlebar buttons will still be visible.
  345. #[cfg(target_os = "macos")]
  346. #[must_use]
  347. fn title_bar_style(self, style: tauri_utils::TitleBarStyle) -> Self;
  348. /// Hide the window title.
  349. #[cfg(target_os = "macos")]
  350. #[must_use]
  351. fn hidden_title(self, hidden: bool) -> Self;
  352. /// Defines the window [tabbing identifier] for macOS.
  353. ///
  354. /// Windows with matching tabbing identifiers will be grouped together.
  355. /// If the tabbing identifier is not set, automatic tabbing will be disabled.
  356. ///
  357. /// [tabbing identifier]: <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier>
  358. #[cfg(target_os = "macos")]
  359. #[must_use]
  360. fn tabbing_identifier(self, identifier: &str) -> Self;
  361. /// Forces a theme or uses the system settings if None was provided.
  362. fn theme(self, theme: Option<Theme>) -> Self;
  363. /// Whether the icon was set or not.
  364. fn has_icon(&self) -> bool;
  365. fn get_theme(&self) -> Option<Theme>;
  366. }
  367. /// A window that has yet to be built.
  368. pub struct PendingWindow<T: UserEvent, R: Runtime<T>> {
  369. /// The label that the window will be named.
  370. pub label: String,
  371. /// The [`WindowBuilder`] that the window will be created with.
  372. pub window_builder: <R::WindowDispatcher as WindowDispatch<T>>::WindowBuilder,
  373. /// The webview that gets added to the window. Optional in case you want to use child webviews or other window content instead.
  374. pub webview: Option<PendingWebview<T, R>>,
  375. }
  376. pub fn is_label_valid(label: &str) -> bool {
  377. label
  378. .chars()
  379. .all(|c| char::is_alphanumeric(c) || c == '-' || c == '/' || c == ':' || c == '_')
  380. }
  381. pub fn assert_label_is_valid(label: &str) {
  382. assert!(
  383. is_label_valid(label),
  384. "Window label must include only alphanumeric characters, `-`, `/`, `:` and `_`."
  385. );
  386. }
  387. impl<T: UserEvent, R: Runtime<T>> PendingWindow<T, R> {
  388. /// Create a new [`PendingWindow`] with a label from the given [`WindowBuilder`].
  389. pub fn new(
  390. window_builder: <R::WindowDispatcher as WindowDispatch<T>>::WindowBuilder,
  391. label: impl Into<String>,
  392. ) -> crate::Result<Self> {
  393. let label = label.into();
  394. if !is_label_valid(&label) {
  395. Err(crate::Error::InvalidWindowLabel)
  396. } else {
  397. Ok(Self {
  398. window_builder,
  399. label,
  400. webview: None,
  401. })
  402. }
  403. }
  404. /// Sets a webview to be created on the window.
  405. pub fn set_webview(&mut self, webview: PendingWebview<T, R>) -> &mut Self {
  406. self.webview.replace(webview);
  407. self
  408. }
  409. }
  410. /// Identifier of a window.
  411. #[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, Ord, PartialOrd)]
  412. pub struct WindowId(u32);
  413. impl From<u32> for WindowId {
  414. fn from(value: u32) -> Self {
  415. Self(value)
  416. }
  417. }
  418. /// A window that is not yet managed by Tauri.
  419. #[derive(Debug)]
  420. pub struct DetachedWindow<T: UserEvent, R: Runtime<T>> {
  421. /// The identifier of the window.
  422. pub id: WindowId,
  423. /// Name of the window
  424. pub label: String,
  425. /// The [`WindowDispatch`] associated with the window.
  426. pub dispatcher: R::WindowDispatcher,
  427. /// The webview dispatcher in case this window has an attached webview.
  428. pub webview: Option<DetachedWebview<T, R>>,
  429. }
  430. impl<T: UserEvent, R: Runtime<T>> Clone for DetachedWindow<T, R> {
  431. fn clone(&self) -> Self {
  432. Self {
  433. id: self.id,
  434. label: self.label.clone(),
  435. dispatcher: self.dispatcher.clone(),
  436. webview: self.webview.clone(),
  437. }
  438. }
  439. }
  440. impl<T: UserEvent, R: Runtime<T>> Hash for DetachedWindow<T, R> {
  441. /// Only use the [`DetachedWindow`]'s label to represent its hash.
  442. fn hash<H: Hasher>(&self, state: &mut H) {
  443. self.label.hash(state)
  444. }
  445. }
  446. impl<T: UserEvent, R: Runtime<T>> Eq for DetachedWindow<T, R> {}
  447. impl<T: UserEvent, R: Runtime<T>> PartialEq for DetachedWindow<T, R> {
  448. /// Only use the [`DetachedWindow`]'s label to compare equality.
  449. fn eq(&self, other: &Self) -> bool {
  450. self.label.eq(&other.label)
  451. }
  452. }
  453. /// A raw window type that contains fields to access
  454. /// the HWND on Windows, gtk::ApplicationWindow on Linux and
  455. /// NSView on macOS.
  456. pub struct RawWindow<'a> {
  457. #[cfg(windows)]
  458. pub hwnd: isize,
  459. #[cfg(any(
  460. target_os = "linux",
  461. target_os = "dragonfly",
  462. target_os = "freebsd",
  463. target_os = "netbsd",
  464. target_os = "openbsd"
  465. ))]
  466. pub gtk_window: &'a gtk::ApplicationWindow,
  467. #[cfg(any(
  468. target_os = "linux",
  469. target_os = "dragonfly",
  470. target_os = "freebsd",
  471. target_os = "netbsd",
  472. target_os = "openbsd"
  473. ))]
  474. pub default_vbox: Option<&'a gtk::Box>,
  475. pub _marker: &'a PhantomData<()>,
  476. }