lib.rs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. //! Internal runtime between Tauri and the underlying webview runtime.
  5. #![cfg_attr(doc_cfg, feature(doc_cfg))]
  6. use raw_window_handle::RawDisplayHandle;
  7. use serde::Deserialize;
  8. use std::{fmt::Debug, sync::mpsc::Sender};
  9. use tauri_utils::Theme;
  10. use url::Url;
  11. use uuid::Uuid;
  12. pub mod http;
  13. /// Create window and system tray menus.
  14. pub mod menu;
  15. /// Types useful for interacting with a user's monitors.
  16. pub mod monitor;
  17. pub mod webview;
  18. pub mod window;
  19. use monitor::Monitor;
  20. use webview::WindowBuilder;
  21. use window::{
  22. dpi::{PhysicalPosition, PhysicalSize, Position, Size},
  23. CursorIcon, DetachedWindow, PendingWindow, WindowEvent,
  24. };
  25. use crate::http::{
  26. header::{InvalidHeaderName, InvalidHeaderValue},
  27. method::InvalidMethod,
  28. status::InvalidStatusCode,
  29. InvalidUri,
  30. };
  31. #[cfg(all(desktop, feature = "system-tray"))]
  32. use std::fmt;
  33. pub type TrayId = u16;
  34. pub type TrayEventHandler = dyn Fn(&SystemTrayEvent) + Send + 'static;
  35. #[cfg(all(desktop, feature = "system-tray"))]
  36. #[non_exhaustive]
  37. pub struct SystemTray {
  38. pub id: TrayId,
  39. pub icon: Option<Icon>,
  40. pub menu: Option<menu::SystemTrayMenu>,
  41. #[cfg(target_os = "macos")]
  42. pub icon_as_template: bool,
  43. #[cfg(target_os = "macos")]
  44. pub menu_on_left_click: bool,
  45. #[cfg(target_os = "macos")]
  46. pub title: Option<String>,
  47. pub on_event: Option<Box<TrayEventHandler>>,
  48. pub tooltip: Option<String>,
  49. }
  50. #[cfg(all(desktop, feature = "system-tray"))]
  51. impl fmt::Debug for SystemTray {
  52. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  53. let mut d = f.debug_struct("SystemTray");
  54. d.field("id", &self.id)
  55. .field("icon", &self.icon)
  56. .field("menu", &self.menu);
  57. #[cfg(target_os = "macos")]
  58. {
  59. d.field("icon_as_template", &self.icon_as_template)
  60. .field("menu_on_left_click", &self.menu_on_left_click)
  61. .field("title", &self.title);
  62. }
  63. d.finish()
  64. }
  65. }
  66. #[cfg(all(desktop, feature = "system-tray"))]
  67. impl Clone for SystemTray {
  68. fn clone(&self) -> Self {
  69. Self {
  70. id: self.id,
  71. icon: self.icon.clone(),
  72. menu: self.menu.clone(),
  73. on_event: None,
  74. #[cfg(target_os = "macos")]
  75. icon_as_template: self.icon_as_template,
  76. #[cfg(target_os = "macos")]
  77. menu_on_left_click: self.menu_on_left_click,
  78. #[cfg(target_os = "macos")]
  79. title: self.title.clone(),
  80. tooltip: self.tooltip.clone(),
  81. }
  82. }
  83. }
  84. #[cfg(all(desktop, feature = "system-tray"))]
  85. impl Default for SystemTray {
  86. fn default() -> Self {
  87. Self {
  88. id: rand::random(),
  89. icon: None,
  90. menu: None,
  91. #[cfg(target_os = "macos")]
  92. icon_as_template: false,
  93. #[cfg(target_os = "macos")]
  94. menu_on_left_click: false,
  95. #[cfg(target_os = "macos")]
  96. title: None,
  97. on_event: None,
  98. tooltip: None,
  99. }
  100. }
  101. }
  102. #[cfg(all(desktop, feature = "system-tray"))]
  103. impl SystemTray {
  104. /// Creates a new system tray that only renders an icon.
  105. pub fn new() -> Self {
  106. Default::default()
  107. }
  108. pub fn menu(&self) -> Option<&menu::SystemTrayMenu> {
  109. self.menu.as_ref()
  110. }
  111. /// Sets the tray id.
  112. #[must_use]
  113. pub fn with_id(mut self, id: TrayId) -> Self {
  114. self.id = id;
  115. self
  116. }
  117. /// Sets the tray icon.
  118. #[must_use]
  119. pub fn with_icon(mut self, icon: Icon) -> Self {
  120. self.icon.replace(icon);
  121. self
  122. }
  123. /// Sets the tray icon as template.
  124. #[cfg(target_os = "macos")]
  125. #[must_use]
  126. pub fn with_icon_as_template(mut self, is_template: bool) -> Self {
  127. self.icon_as_template = is_template;
  128. self
  129. }
  130. /// Sets whether the menu should appear when the tray receives a left click. Defaults to `true`.
  131. #[cfg(target_os = "macos")]
  132. #[must_use]
  133. pub fn with_menu_on_left_click(mut self, menu_on_left_click: bool) -> Self {
  134. self.menu_on_left_click = menu_on_left_click;
  135. self
  136. }
  137. #[cfg(target_os = "macos")]
  138. #[must_use]
  139. pub fn with_title(mut self, title: &str) -> Self {
  140. self.title = Some(title.to_owned());
  141. self
  142. }
  143. /// Sets the tray icon tooltip.
  144. ///
  145. /// ## Platform-specific:
  146. ///
  147. /// - **Linux:** Unsupported
  148. #[must_use]
  149. pub fn with_tooltip(mut self, tooltip: &str) -> Self {
  150. self.tooltip = Some(tooltip.to_owned());
  151. self
  152. }
  153. /// Sets the menu to show when the system tray is right clicked.
  154. #[must_use]
  155. pub fn with_menu(mut self, menu: menu::SystemTrayMenu) -> Self {
  156. self.menu.replace(menu);
  157. self
  158. }
  159. #[must_use]
  160. pub fn on_event<F: Fn(&SystemTrayEvent) + Send + 'static>(mut self, f: F) -> Self {
  161. self.on_event.replace(Box::new(f));
  162. self
  163. }
  164. }
  165. /// Type of user attention requested on a window.
  166. #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
  167. #[serde(tag = "type")]
  168. pub enum UserAttentionType {
  169. /// ## Platform-specific
  170. /// - **macOS:** Bounces the dock icon until the application is in focus.
  171. /// - **Windows:** Flashes both the window and the taskbar button until the application is in focus.
  172. Critical,
  173. /// ## Platform-specific
  174. /// - **macOS:** Bounces the dock icon once.
  175. /// - **Windows:** Flashes the taskbar button until the application is in focus.
  176. Informational,
  177. }
  178. #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
  179. #[serde(tag = "type")]
  180. pub enum DeviceEventFilter {
  181. /// Always filter out device events.
  182. Always,
  183. /// Filter out device events while the window is not focused.
  184. Unfocused,
  185. /// Report all device events regardless of window focus.
  186. Never,
  187. }
  188. impl Default for DeviceEventFilter {
  189. fn default() -> Self {
  190. Self::Unfocused
  191. }
  192. }
  193. #[derive(Debug, thiserror::Error)]
  194. #[non_exhaustive]
  195. pub enum Error {
  196. /// Failed to create webview.
  197. #[error("failed to create webview: {0}")]
  198. CreateWebview(Box<dyn std::error::Error + Send + Sync>),
  199. /// Failed to create window.
  200. #[error("failed to create window")]
  201. CreateWindow,
  202. /// The given window label is invalid.
  203. #[error("Window labels must only include alphanumeric characters, `-`, `/`, `:` and `_`.")]
  204. InvalidWindowLabel,
  205. /// Failed to send message to webview.
  206. #[error("failed to send message to the webview")]
  207. FailedToSendMessage,
  208. /// Failed to receive message from webview.
  209. #[error("failed to receive message from webview")]
  210. FailedToReceiveMessage,
  211. /// Failed to serialize/deserialize.
  212. #[error("JSON error: {0}")]
  213. Json(#[from] serde_json::Error),
  214. /// Encountered an error creating the app system tray.
  215. #[cfg(all(desktop, feature = "system-tray"))]
  216. #[cfg_attr(doc_cfg, doc(cfg(feature = "system-tray")))]
  217. #[error("error encountered during tray setup: {0}")]
  218. SystemTray(Box<dyn std::error::Error + Send + Sync>),
  219. /// Failed to load window icon.
  220. #[error("invalid icon: {0}")]
  221. InvalidIcon(Box<dyn std::error::Error + Send + Sync>),
  222. /// Failed to get monitor on window operation.
  223. #[error("failed to get monitor")]
  224. FailedToGetMonitor,
  225. /// Global shortcut error.
  226. #[cfg(all(desktop, feature = "global-shortcut"))]
  227. #[error(transparent)]
  228. GlobalShortcut(Box<dyn std::error::Error + Send + Sync>),
  229. #[error("Invalid header name: {0}")]
  230. InvalidHeaderName(#[from] InvalidHeaderName),
  231. #[error("Invalid header value: {0}")]
  232. InvalidHeaderValue(#[from] InvalidHeaderValue),
  233. #[error("Invalid uri: {0}")]
  234. InvalidUri(#[from] InvalidUri),
  235. #[error("Invalid status code: {0}")]
  236. InvalidStatusCode(#[from] InvalidStatusCode),
  237. #[error("Invalid method: {0}")]
  238. InvalidMethod(#[from] InvalidMethod),
  239. #[error("Infallible error, something went really wrong: {0}")]
  240. Infallible(#[from] std::convert::Infallible),
  241. #[error("the event loop has been closed")]
  242. EventLoopClosed,
  243. }
  244. /// Result type.
  245. pub type Result<T> = std::result::Result<T, Error>;
  246. /// Window icon.
  247. #[derive(Debug, Clone)]
  248. pub struct Icon {
  249. /// RGBA bytes of the icon.
  250. pub rgba: Vec<u8>,
  251. /// Icon width.
  252. pub width: u32,
  253. /// Icon height.
  254. pub height: u32,
  255. }
  256. /// A type that can be used as an user event.
  257. pub trait UserEvent: Debug + Clone + Send + 'static {}
  258. impl<T: Debug + Clone + Send + 'static> UserEvent for T {}
  259. /// Event triggered on the event loop run.
  260. #[non_exhaustive]
  261. pub enum RunEvent<T: UserEvent> {
  262. /// Event loop is exiting.
  263. Exit,
  264. /// Event loop is about to exit
  265. ExitRequested {
  266. tx: Sender<ExitRequestedEventAction>,
  267. },
  268. /// An event associated with a window.
  269. WindowEvent {
  270. /// The window label.
  271. label: String,
  272. /// The detailed event.
  273. event: WindowEvent,
  274. },
  275. /// Application ready.
  276. Ready,
  277. /// Sent if the event loop is being resumed.
  278. Resumed,
  279. /// Emitted when all of the event loop’s input events have been processed and redraw processing is about to begin.
  280. ///
  281. /// This event is useful as a place to put your code that should be run after all state-changing events have been handled and you want to do stuff (updating state, performing calculations, etc) that happens as the “main body” of your event loop.
  282. MainEventsCleared,
  283. /// A custom event defined by the user.
  284. UserEvent(T),
  285. }
  286. /// Action to take when the event loop is about to exit
  287. #[derive(Debug)]
  288. pub enum ExitRequestedEventAction {
  289. /// Prevent the event loop from exiting
  290. Prevent,
  291. }
  292. /// A system tray event.
  293. #[derive(Debug)]
  294. pub enum SystemTrayEvent {
  295. MenuItemClick(u16),
  296. LeftClick {
  297. position: PhysicalPosition<f64>,
  298. size: PhysicalSize<f64>,
  299. },
  300. RightClick {
  301. position: PhysicalPosition<f64>,
  302. size: PhysicalSize<f64>,
  303. },
  304. DoubleClick {
  305. position: PhysicalPosition<f64>,
  306. size: PhysicalSize<f64>,
  307. },
  308. }
  309. /// Metadata for a runtime event loop iteration on `run_iteration`.
  310. #[derive(Debug, Clone, Default)]
  311. pub struct RunIteration {
  312. pub window_count: usize,
  313. }
  314. /// Application's activation policy. Corresponds to NSApplicationActivationPolicy.
  315. #[cfg(target_os = "macos")]
  316. #[cfg_attr(doc_cfg, doc(cfg(target_os = "macos")))]
  317. #[non_exhaustive]
  318. pub enum ActivationPolicy {
  319. /// Corresponds to NSApplicationActivationPolicyRegular.
  320. Regular,
  321. /// Corresponds to NSApplicationActivationPolicyAccessory.
  322. Accessory,
  323. /// Corresponds to NSApplicationActivationPolicyProhibited.
  324. Prohibited,
  325. }
  326. /// A [`Send`] handle to the runtime.
  327. pub trait RuntimeHandle<T: UserEvent>: Debug + Clone + Send + Sync + Sized + 'static {
  328. type Runtime: Runtime<T, Handle = Self>;
  329. /// Creates an `EventLoopProxy` that can be used to dispatch user events to the main event loop.
  330. fn create_proxy(&self) -> <Self::Runtime as Runtime<T>>::EventLoopProxy;
  331. /// Create a new webview window.
  332. fn create_window(
  333. &self,
  334. pending: PendingWindow<T, Self::Runtime>,
  335. ) -> Result<DetachedWindow<T, Self::Runtime>>;
  336. /// Run a task on the main thread.
  337. fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> Result<()>;
  338. /// Adds an icon to the system tray with the specified menu items.
  339. #[cfg(all(desktop, feature = "system-tray"))]
  340. #[cfg_attr(doc_cfg, doc(cfg(all(desktop, feature = "system-tray"))))]
  341. fn system_tray(
  342. &self,
  343. system_tray: SystemTray,
  344. ) -> Result<<Self::Runtime as Runtime<T>>::TrayHandler>;
  345. fn raw_display_handle(&self) -> RawDisplayHandle;
  346. /// Shows the application, but does not automatically focus it.
  347. #[cfg(target_os = "macos")]
  348. #[cfg_attr(doc_cfg, doc(cfg(target_os = "macos")))]
  349. fn show(&self) -> Result<()>;
  350. /// Hides the application.
  351. #[cfg(target_os = "macos")]
  352. #[cfg_attr(doc_cfg, doc(cfg(target_os = "macos")))]
  353. fn hide(&self) -> Result<()>;
  354. }
  355. /// A global shortcut manager.
  356. #[cfg(all(desktop, feature = "global-shortcut"))]
  357. pub trait GlobalShortcutManager: Debug + Clone + Send + Sync {
  358. /// Whether the application has registered the given `accelerator`.
  359. fn is_registered(&self, accelerator: &str) -> Result<bool>;
  360. /// Register a global shortcut of `accelerator`.
  361. fn register<F: Fn() + Send + 'static>(&mut self, accelerator: &str, handler: F) -> Result<()>;
  362. /// Unregister all accelerators registered by the manager instance.
  363. fn unregister_all(&mut self) -> Result<()>;
  364. /// Unregister the provided `accelerator`.
  365. fn unregister(&mut self, accelerator: &str) -> Result<()>;
  366. }
  367. /// Clipboard manager.
  368. #[cfg(feature = "clipboard")]
  369. pub trait ClipboardManager: Debug + Clone + Send + Sync {
  370. /// Writes the text into the clipboard as plain text.
  371. fn write_text<T: Into<String>>(&mut self, text: T) -> Result<()>;
  372. /// Read the content in the clipboard as plain text.
  373. fn read_text(&self) -> Result<Option<String>>;
  374. }
  375. pub trait EventLoopProxy<T: UserEvent>: Debug + Clone + Send + Sync {
  376. fn send_event(&self, event: T) -> Result<()>;
  377. }
  378. /// The webview runtime interface.
  379. pub trait Runtime<T: UserEvent>: Debug + Sized + 'static {
  380. /// The message dispatcher.
  381. type Dispatcher: Dispatch<T, Runtime = Self>;
  382. /// The runtime handle type.
  383. type Handle: RuntimeHandle<T, Runtime = Self>;
  384. /// The global shortcut manager type.
  385. #[cfg(all(desktop, feature = "global-shortcut"))]
  386. type GlobalShortcutManager: GlobalShortcutManager;
  387. /// The clipboard manager type.
  388. #[cfg(feature = "clipboard")]
  389. type ClipboardManager: ClipboardManager;
  390. /// The tray handler type.
  391. #[cfg(all(desktop, feature = "system-tray"))]
  392. type TrayHandler: menu::TrayHandle;
  393. /// The proxy type.
  394. type EventLoopProxy: EventLoopProxy<T>;
  395. /// Creates a new webview runtime. Must be used on the main thread.
  396. fn new() -> Result<Self>;
  397. /// Creates a new webview runtime on any thread.
  398. #[cfg(any(windows, target_os = "linux"))]
  399. #[cfg_attr(doc_cfg, doc(cfg(any(windows, target_os = "linux"))))]
  400. fn new_any_thread() -> Result<Self>;
  401. /// Creates an `EventLoopProxy` that can be used to dispatch user events to the main event loop.
  402. fn create_proxy(&self) -> Self::EventLoopProxy;
  403. /// Gets a runtime handle.
  404. fn handle(&self) -> Self::Handle;
  405. /// Gets the global shortcut manager.
  406. #[cfg(all(desktop, feature = "global-shortcut"))]
  407. fn global_shortcut_manager(&self) -> Self::GlobalShortcutManager;
  408. /// Gets the clipboard manager.
  409. #[cfg(feature = "clipboard")]
  410. fn clipboard_manager(&self) -> Self::ClipboardManager;
  411. /// Create a new webview window.
  412. fn create_window(&self, pending: PendingWindow<T, Self>) -> Result<DetachedWindow<T, Self>>;
  413. /// Adds the icon to the system tray with the specified menu items.
  414. #[cfg(all(desktop, feature = "system-tray"))]
  415. #[cfg_attr(doc_cfg, doc(cfg(feature = "system-tray")))]
  416. fn system_tray(&self, system_tray: SystemTray) -> Result<Self::TrayHandler>;
  417. /// Registers a system tray event handler.
  418. #[cfg(all(desktop, feature = "system-tray"))]
  419. #[cfg_attr(doc_cfg, doc(cfg(feature = "system-tray")))]
  420. fn on_system_tray_event<F: Fn(TrayId, &SystemTrayEvent) + Send + 'static>(&mut self, f: F);
  421. /// Sets the activation policy for the application. It is set to `NSApplicationActivationPolicyRegular` by default.
  422. #[cfg(target_os = "macos")]
  423. #[cfg_attr(doc_cfg, doc(cfg(target_os = "macos")))]
  424. fn set_activation_policy(&mut self, activation_policy: ActivationPolicy);
  425. /// Shows the application, but does not automatically focus it.
  426. #[cfg(target_os = "macos")]
  427. #[cfg_attr(doc_cfg, doc(cfg(target_os = "macos")))]
  428. fn show(&self);
  429. /// Hides the application.
  430. #[cfg(target_os = "macos")]
  431. #[cfg_attr(doc_cfg, doc(cfg(target_os = "macos")))]
  432. fn hide(&self);
  433. /// Change the device event filter mode.
  434. ///
  435. /// Since the DeviceEvent capture can lead to high CPU usage for unfocused windows, [`tao`]
  436. /// will ignore them by default for unfocused windows on Windows. This method allows changing
  437. /// the filter to explicitly capture them again.
  438. ///
  439. /// ## Platform-specific
  440. ///
  441. /// - ** Linux / macOS / iOS / Android**: Unsupported.
  442. ///
  443. /// [`tao`]: https://crates.io/crates/tao
  444. fn set_device_event_filter(&mut self, filter: DeviceEventFilter);
  445. /// Runs the one step of the webview runtime event loop and returns control flow to the caller.
  446. #[cfg(desktop)]
  447. fn run_iteration<F: Fn(RunEvent<T>) + 'static>(&mut self, callback: F) -> RunIteration;
  448. /// Run the webview runtime.
  449. fn run<F: FnMut(RunEvent<T>) + 'static>(self, callback: F);
  450. }
  451. /// Webview dispatcher. A thread-safe handle to the webview API.
  452. pub trait Dispatch<T: UserEvent>: Debug + Clone + Send + Sync + Sized + 'static {
  453. /// The runtime this [`Dispatch`] runs under.
  454. type Runtime: Runtime<T>;
  455. /// The window builder type.
  456. type WindowBuilder: WindowBuilder;
  457. /// Run a task on the main thread.
  458. fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> Result<()>;
  459. /// Registers a window event handler.
  460. fn on_window_event<F: Fn(&WindowEvent) + Send + 'static>(&self, f: F) -> Uuid;
  461. /// Registers a window event handler.
  462. fn on_menu_event<F: Fn(&window::MenuEvent) + Send + 'static>(&self, f: F) -> Uuid;
  463. /// Open the web inspector which is usually called devtools.
  464. #[cfg(any(debug_assertions, feature = "devtools"))]
  465. fn open_devtools(&self);
  466. /// Close the web inspector which is usually called devtools.
  467. #[cfg(any(debug_assertions, feature = "devtools"))]
  468. fn close_devtools(&self);
  469. /// Gets the devtools window's current open state.
  470. #[cfg(any(debug_assertions, feature = "devtools"))]
  471. fn is_devtools_open(&self) -> Result<bool>;
  472. // GETTERS
  473. /// Returns the webview's current URL.
  474. fn url(&self) -> Result<Url>;
  475. /// Returns the scale factor that can be used to map logical pixels to physical pixels, and vice versa.
  476. fn scale_factor(&self) -> Result<f64>;
  477. /// Returns the position of the top-left hand corner of the window's client area relative to the top-left hand corner of the desktop.
  478. fn inner_position(&self) -> Result<PhysicalPosition<i32>>;
  479. /// Returns the position of the top-left hand corner of the window relative to the top-left hand corner of the desktop.
  480. fn outer_position(&self) -> Result<PhysicalPosition<i32>>;
  481. /// Returns the physical size of the window's client area.
  482. ///
  483. /// The client area is the content of the window, excluding the title bar and borders.
  484. fn inner_size(&self) -> Result<PhysicalSize<u32>>;
  485. /// Returns the physical size of the entire window.
  486. ///
  487. /// These dimensions include the title bar and borders. If you don't want that (and you usually don't), use inner_size instead.
  488. fn outer_size(&self) -> Result<PhysicalSize<u32>>;
  489. /// Gets the window's current fullscreen state.
  490. fn is_fullscreen(&self) -> Result<bool>;
  491. /// Gets the window's current minimized state.
  492. fn is_minimized(&self) -> Result<bool>;
  493. /// Gets the window's current maximized state.
  494. fn is_maximized(&self) -> Result<bool>;
  495. /// Gets the window’s current decoration state.
  496. fn is_decorated(&self) -> Result<bool>;
  497. /// Gets the window’s current resizable state.
  498. fn is_resizable(&self) -> Result<bool>;
  499. /// Gets the window's native maximize button state.
  500. ///
  501. /// ## Platform-specific
  502. ///
  503. /// - **Linux / iOS / Android:** Unsupported.
  504. fn is_maximizable(&self) -> Result<bool>;
  505. /// Gets the window's native minize button state.
  506. ///
  507. /// ## Platform-specific
  508. ///
  509. /// - **Linux / iOS / Android:** Unsupported.
  510. fn is_minimizable(&self) -> Result<bool>;
  511. /// Gets the window's native close button state.
  512. ///
  513. /// ## Platform-specific
  514. ///
  515. /// - **iOS / Android:** Unsupported.
  516. fn is_closable(&self) -> Result<bool>;
  517. /// Gets the window's current visibility state.
  518. fn is_visible(&self) -> Result<bool>;
  519. /// Gets the window's current title.
  520. fn title(&self) -> Result<String>;
  521. /// Gets the window menu current visibility state.
  522. fn is_menu_visible(&self) -> Result<bool>;
  523. /// Returns the monitor on which the window currently resides.
  524. ///
  525. /// Returns None if current monitor can't be detected.
  526. fn current_monitor(&self) -> Result<Option<Monitor>>;
  527. /// Returns the primary monitor of the system.
  528. ///
  529. /// Returns None if it can't identify any monitor as a primary one.
  530. fn primary_monitor(&self) -> Result<Option<Monitor>>;
  531. /// Returns the list of all the monitors available on the system.
  532. fn available_monitors(&self) -> Result<Vec<Monitor>>;
  533. /// Returns the `ApplicationWindow` from gtk crate that is used by this window.
  534. #[cfg(any(
  535. target_os = "linux",
  536. target_os = "dragonfly",
  537. target_os = "freebsd",
  538. target_os = "netbsd",
  539. target_os = "openbsd"
  540. ))]
  541. fn gtk_window(&self) -> Result<gtk::ApplicationWindow>;
  542. fn raw_window_handle(&self) -> Result<raw_window_handle::RawWindowHandle>;
  543. /// Returns the current window theme.
  544. fn theme(&self) -> Result<Theme>;
  545. // SETTERS
  546. /// Centers the window.
  547. fn center(&self) -> Result<()>;
  548. /// Opens the dialog to prints the contents of the webview.
  549. fn print(&self) -> Result<()>;
  550. /// Requests user attention to the window.
  551. ///
  552. /// Providing `None` will unset the request for user attention.
  553. fn request_user_attention(&self, request_type: Option<UserAttentionType>) -> Result<()>;
  554. /// Create a new webview window.
  555. fn create_window(
  556. &mut self,
  557. pending: PendingWindow<T, Self::Runtime>,
  558. ) -> Result<DetachedWindow<T, Self::Runtime>>;
  559. /// Updates the window resizable flag.
  560. fn set_resizable(&self, resizable: bool) -> Result<()>;
  561. /// Updates the window's native maximize button state.
  562. ///
  563. /// ## Platform-specific
  564. ///
  565. /// - **macOS:** Disables the "zoom" button in the window titlebar, which is also used to enter fullscreen mode.
  566. /// - **Linux / iOS / Android:** Unsupported.
  567. fn set_maximizable(&self, maximizable: bool) -> Result<()>;
  568. /// Updates the window's native minimize button state.
  569. ///
  570. /// ## Platform-specific
  571. ///
  572. /// - **Linux / iOS / Android:** Unsupported.
  573. fn set_minimizable(&self, minimizable: bool) -> Result<()>;
  574. /// Updates the window's native close button state.
  575. ///
  576. /// ## Platform-specific
  577. ///
  578. /// - **Linux:** "GTK+ will do its best to convince the window manager not to show a close button.
  579. /// Depending on the system, this function may not have any effect when called on a window that is already visible"
  580. /// - **iOS / Android:** Unsupported.
  581. fn set_closable(&self, closable: bool) -> Result<()>;
  582. /// Updates the window title.
  583. fn set_title<S: Into<String>>(&self, title: S) -> Result<()>;
  584. /// Maximizes the window.
  585. fn maximize(&self) -> Result<()>;
  586. /// Unmaximizes the window.
  587. fn unmaximize(&self) -> Result<()>;
  588. /// Minimizes the window.
  589. fn minimize(&self) -> Result<()>;
  590. /// Unminimizes the window.
  591. fn unminimize(&self) -> Result<()>;
  592. /// Shows the window menu.
  593. fn show_menu(&self) -> Result<()>;
  594. /// Hides the window menu.
  595. fn hide_menu(&self) -> Result<()>;
  596. /// Shows the window.
  597. fn show(&self) -> Result<()>;
  598. /// Hides the window.
  599. fn hide(&self) -> Result<()>;
  600. /// Closes the window.
  601. fn close(&self) -> Result<()>;
  602. /// Updates the hasDecorations flag.
  603. fn set_decorations(&self, decorations: bool) -> Result<()>;
  604. /// Updates the window alwaysOnTop flag.
  605. fn set_always_on_top(&self, always_on_top: bool) -> Result<()>;
  606. /// Prevents the window contents from being captured by other apps.
  607. fn set_content_protected(&self, protected: bool) -> Result<()>;
  608. /// Resizes the window.
  609. fn set_size(&self, size: Size) -> Result<()>;
  610. /// Updates the window min size.
  611. fn set_min_size(&self, size: Option<Size>) -> Result<()>;
  612. /// Updates the window max size.
  613. fn set_max_size(&self, size: Option<Size>) -> Result<()>;
  614. /// Updates the window position.
  615. fn set_position(&self, position: Position) -> Result<()>;
  616. /// Updates the window fullscreen state.
  617. fn set_fullscreen(&self, fullscreen: bool) -> Result<()>;
  618. /// Bring the window to front and focus.
  619. fn set_focus(&self) -> Result<()>;
  620. /// Updates the window icon.
  621. fn set_icon(&self, icon: Icon) -> Result<()>;
  622. /// Whether to hide the window icon from the taskbar or not.
  623. fn set_skip_taskbar(&self, skip: bool) -> Result<()>;
  624. /// Grabs the cursor, preventing it from leaving the window.
  625. ///
  626. /// There's no guarantee that the cursor will be hidden. You should
  627. /// hide it by yourself if you want so.
  628. fn set_cursor_grab(&self, grab: bool) -> Result<()>;
  629. /// Modifies the cursor's visibility.
  630. ///
  631. /// If `false`, this will hide the cursor. If `true`, this will show the cursor.
  632. fn set_cursor_visible(&self, visible: bool) -> Result<()>;
  633. // Modifies the cursor icon of the window.
  634. fn set_cursor_icon(&self, icon: CursorIcon) -> Result<()>;
  635. /// Changes the position of the cursor in window coordinates.
  636. fn set_cursor_position<Pos: Into<Position>>(&self, position: Pos) -> Result<()>;
  637. /// Ignores the window cursor events.
  638. fn set_ignore_cursor_events(&self, ignore: bool) -> Result<()>;
  639. /// Starts dragging the window.
  640. fn start_dragging(&self) -> Result<()>;
  641. /// Executes javascript on the window this [`Dispatch`] represents.
  642. fn eval_script<S: Into<String>>(&self, script: S) -> Result<()>;
  643. /// Applies the specified `update` to the menu item associated with the given `id`.
  644. fn update_menu_item(&self, id: u16, update: menu::MenuUpdate) -> Result<()>;
  645. }