lib.rs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  1. // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. //! [![](https://github.com/tauri-apps/tauri/raw/dev/.github/splash.png)](https://tauri.app)
  5. //!
  6. //! Internal runtime between Tauri and the underlying webview runtime.
  7. //!
  8. //! None of the exposed API of this crate is stable, and it may break semver
  9. //! compatibility in the future. The major version only signifies the intended Tauri version.
  10. #![doc(
  11. html_logo_url = "https://github.com/tauri-apps/tauri/raw/dev/.github/icon.png",
  12. html_favicon_url = "https://github.com/tauri-apps/tauri/raw/dev/.github/icon.png"
  13. )]
  14. #![cfg_attr(docsrs, feature(doc_cfg))]
  15. use raw_window_handle::DisplayHandle;
  16. use serde::{Deserialize, Serialize};
  17. use std::{borrow::Cow, fmt::Debug, sync::mpsc::Sender};
  18. use tauri_utils::Theme;
  19. use url::Url;
  20. use webview::{DetachedWebview, PendingWebview};
  21. /// Types useful for interacting with a user's monitors.
  22. pub mod monitor;
  23. pub mod webview;
  24. pub mod window;
  25. use dpi::{PhysicalPosition, PhysicalSize, Position, Size};
  26. use monitor::Monitor;
  27. use window::{
  28. CursorIcon, DetachedWindow, PendingWindow, RawWindow, WebviewEvent, WindowEvent,
  29. WindowSizeConstraints,
  30. };
  31. use window::{WindowBuilder, WindowId};
  32. use http::{
  33. header::{InvalidHeaderName, InvalidHeaderValue},
  34. method::InvalidMethod,
  35. status::InvalidStatusCode,
  36. };
  37. /// UI scaling utilities.
  38. pub use dpi;
  39. pub type WindowEventId = u32;
  40. pub type WebviewEventId = u32;
  41. /// A rectangular region.
  42. #[derive(Clone, Copy, Debug, Serialize)]
  43. pub struct Rect {
  44. /// Rect position.
  45. pub position: dpi::Position,
  46. /// Rect size.
  47. pub size: dpi::Size,
  48. }
  49. impl Default for Rect {
  50. fn default() -> Self {
  51. Self {
  52. position: Position::Logical((0, 0).into()),
  53. size: Size::Logical((0, 0).into()),
  54. }
  55. }
  56. }
  57. /// Progress bar status.
  58. #[derive(Debug, Clone, Copy, Deserialize)]
  59. #[serde(rename_all = "camelCase")]
  60. pub enum ProgressBarStatus {
  61. /// Hide progress bar.
  62. None,
  63. /// Normal state.
  64. Normal,
  65. /// Indeterminate state. **Treated as Normal on Linux and macOS**
  66. Indeterminate,
  67. /// Paused state. **Treated as Normal on Linux**
  68. Paused,
  69. /// Error state. **Treated as Normal on Linux**
  70. Error,
  71. }
  72. /// Progress Bar State
  73. #[derive(Debug, Deserialize)]
  74. #[serde(rename_all = "camelCase")]
  75. pub struct ProgressBarState {
  76. /// The progress bar status.
  77. pub status: Option<ProgressBarStatus>,
  78. /// The progress bar progress. This can be a value ranging from `0` to `100`
  79. pub progress: Option<u64>,
  80. /// The `.desktop` filename with the Unity desktop window manager, for example `myapp.desktop` **Linux Only**
  81. pub desktop_filename: Option<String>,
  82. }
  83. /// Type of user attention requested on a window.
  84. #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
  85. #[serde(tag = "type")]
  86. pub enum UserAttentionType {
  87. /// ## Platform-specific
  88. /// - **macOS:** Bounces the dock icon until the application is in focus.
  89. /// - **Windows:** Flashes both the window and the taskbar button until the application is in focus.
  90. Critical,
  91. /// ## Platform-specific
  92. /// - **macOS:** Bounces the dock icon once.
  93. /// - **Windows:** Flashes the taskbar button until the application is in focus.
  94. Informational,
  95. }
  96. #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
  97. #[serde(tag = "type")]
  98. pub enum DeviceEventFilter {
  99. /// Always filter out device events.
  100. Always,
  101. /// Filter out device events while the window is not focused.
  102. Unfocused,
  103. /// Report all device events regardless of window focus.
  104. Never,
  105. }
  106. impl Default for DeviceEventFilter {
  107. fn default() -> Self {
  108. Self::Unfocused
  109. }
  110. }
  111. /// Defines the orientation that a window resize will be performed.
  112. #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
  113. pub enum ResizeDirection {
  114. East,
  115. North,
  116. NorthEast,
  117. NorthWest,
  118. South,
  119. SouthEast,
  120. SouthWest,
  121. West,
  122. }
  123. #[derive(Debug, thiserror::Error)]
  124. #[non_exhaustive]
  125. pub enum Error {
  126. /// Failed to create webview.
  127. #[error("failed to create webview: {0}")]
  128. CreateWebview(Box<dyn std::error::Error + Send + Sync>),
  129. /// Failed to create window.
  130. #[error("failed to create window")]
  131. CreateWindow,
  132. /// The given window label is invalid.
  133. #[error("Window labels must only include alphanumeric characters, `-`, `/`, `:` and `_`.")]
  134. InvalidWindowLabel,
  135. /// Failed to send message to webview.
  136. #[error("failed to send message to the webview")]
  137. FailedToSendMessage,
  138. /// Failed to receive message from webview.
  139. #[error("failed to receive message from webview")]
  140. FailedToReceiveMessage,
  141. /// Failed to serialize/deserialize.
  142. #[error("JSON error: {0}")]
  143. Json(#[from] serde_json::Error),
  144. /// Failed to load window icon.
  145. #[error("invalid icon: {0}")]
  146. InvalidIcon(Box<dyn std::error::Error + Send + Sync>),
  147. /// Failed to get monitor on window operation.
  148. #[error("failed to get monitor")]
  149. FailedToGetMonitor,
  150. /// Failed to get cursor position.
  151. #[error("failed to get cursor position")]
  152. FailedToGetCursorPosition,
  153. #[error("Invalid header name: {0}")]
  154. InvalidHeaderName(#[from] InvalidHeaderName),
  155. #[error("Invalid header value: {0}")]
  156. InvalidHeaderValue(#[from] InvalidHeaderValue),
  157. #[error("Invalid status code: {0}")]
  158. InvalidStatusCode(#[from] InvalidStatusCode),
  159. #[error("Invalid method: {0}")]
  160. InvalidMethod(#[from] InvalidMethod),
  161. #[error("Infallible error, something went really wrong: {0}")]
  162. Infallible(#[from] std::convert::Infallible),
  163. #[error("the event loop has been closed")]
  164. EventLoopClosed,
  165. #[error("Invalid proxy url")]
  166. InvalidProxyUrl,
  167. #[error("window not found")]
  168. WindowNotFound,
  169. }
  170. /// Result type.
  171. pub type Result<T> = std::result::Result<T, Error>;
  172. /// Window icon.
  173. #[derive(Debug, Clone)]
  174. pub struct Icon<'a> {
  175. /// RGBA bytes of the icon.
  176. pub rgba: Cow<'a, [u8]>,
  177. /// Icon width.
  178. pub width: u32,
  179. /// Icon height.
  180. pub height: u32,
  181. }
  182. /// A type that can be used as an user event.
  183. pub trait UserEvent: Debug + Clone + Send + 'static {}
  184. impl<T: Debug + Clone + Send + 'static> UserEvent for T {}
  185. /// Event triggered on the event loop run.
  186. #[derive(Debug)]
  187. #[non_exhaustive]
  188. pub enum RunEvent<T: UserEvent> {
  189. /// Event loop is exiting.
  190. Exit,
  191. /// Event loop is about to exit
  192. ExitRequested {
  193. /// The exit code.
  194. code: Option<i32>,
  195. tx: Sender<ExitRequestedEventAction>,
  196. },
  197. /// An event associated with a window.
  198. WindowEvent {
  199. /// The window label.
  200. label: String,
  201. /// The detailed event.
  202. event: WindowEvent,
  203. },
  204. /// An event associated with a webview.
  205. WebviewEvent {
  206. /// The webview label.
  207. label: String,
  208. /// The detailed event.
  209. event: WebviewEvent,
  210. },
  211. /// Application ready.
  212. Ready,
  213. /// Sent if the event loop is being resumed.
  214. Resumed,
  215. /// Emitted when all of the event loop's input events have been processed and redraw processing is about to begin.
  216. ///
  217. /// 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.
  218. MainEventsCleared,
  219. /// Emitted when the user wants to open the specified resource with the app.
  220. #[cfg(any(target_os = "macos", target_os = "ios"))]
  221. Opened { urls: Vec<url::Url> },
  222. /// Emitted when the NSApplicationDelegate's applicationShouldHandleReopen gets called
  223. #[cfg(target_os = "macos")]
  224. Reopen {
  225. /// Indicates whether the NSApplication object found any visible windows in your application.
  226. has_visible_windows: bool,
  227. },
  228. /// A custom event defined by the user.
  229. UserEvent(T),
  230. }
  231. /// Action to take when the event loop is about to exit
  232. #[derive(Debug)]
  233. pub enum ExitRequestedEventAction {
  234. /// Prevent the event loop from exiting
  235. Prevent,
  236. }
  237. /// Application's activation policy. Corresponds to NSApplicationActivationPolicy.
  238. #[cfg(target_os = "macos")]
  239. #[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
  240. #[non_exhaustive]
  241. pub enum ActivationPolicy {
  242. /// Corresponds to NSApplicationActivationPolicyRegular.
  243. Regular,
  244. /// Corresponds to NSApplicationActivationPolicyAccessory.
  245. Accessory,
  246. /// Corresponds to NSApplicationActivationPolicyProhibited.
  247. Prohibited,
  248. }
  249. /// A [`Send`] handle to the runtime.
  250. pub trait RuntimeHandle<T: UserEvent>: Debug + Clone + Send + Sync + Sized + 'static {
  251. type Runtime: Runtime<T, Handle = Self>;
  252. /// Creates an `EventLoopProxy` that can be used to dispatch user events to the main event loop.
  253. fn create_proxy(&self) -> <Self::Runtime as Runtime<T>>::EventLoopProxy;
  254. /// Sets the activation policy for the application.
  255. #[cfg(target_os = "macos")]
  256. #[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
  257. fn set_activation_policy(&self, activation_policy: ActivationPolicy) -> Result<()>;
  258. /// Requests an exit of the event loop.
  259. fn request_exit(&self, code: i32) -> Result<()>;
  260. /// Create a new window.
  261. fn create_window<F: Fn(RawWindow) + Send + 'static>(
  262. &self,
  263. pending: PendingWindow<T, Self::Runtime>,
  264. before_window_creation: Option<F>,
  265. ) -> Result<DetachedWindow<T, Self::Runtime>>;
  266. /// Create a new webview.
  267. fn create_webview(
  268. &self,
  269. window_id: WindowId,
  270. pending: PendingWebview<T, Self::Runtime>,
  271. ) -> Result<DetachedWebview<T, Self::Runtime>>;
  272. /// Run a task on the main thread.
  273. fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> Result<()>;
  274. fn display_handle(&self) -> std::result::Result<DisplayHandle, raw_window_handle::HandleError>;
  275. fn primary_monitor(&self) -> Option<Monitor>;
  276. fn monitor_from_point(&self, x: f64, y: f64) -> Option<Monitor>;
  277. fn available_monitors(&self) -> Vec<Monitor>;
  278. fn cursor_position(&self) -> Result<PhysicalPosition<f64>>;
  279. fn set_theme(&self, theme: Option<Theme>);
  280. /// Shows the application, but does not automatically focus it.
  281. #[cfg(target_os = "macos")]
  282. #[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
  283. fn show(&self) -> Result<()>;
  284. /// Hides the application.
  285. #[cfg(target_os = "macos")]
  286. #[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
  287. fn hide(&self) -> Result<()>;
  288. /// Finds an Android class in the project scope.
  289. #[cfg(target_os = "android")]
  290. fn find_class<'a>(
  291. &self,
  292. env: &mut jni::JNIEnv<'a>,
  293. activity: &jni::objects::JObject<'_>,
  294. name: impl Into<String>,
  295. ) -> std::result::Result<jni::objects::JClass<'a>, jni::errors::Error>;
  296. /// Dispatch a closure to run on the Android context.
  297. ///
  298. /// The closure takes the JNI env, the Android activity instance and the possibly null webview.
  299. #[cfg(target_os = "android")]
  300. fn run_on_android_context<F>(&self, f: F)
  301. where
  302. F: FnOnce(&mut jni::JNIEnv, &jni::objects::JObject, &jni::objects::JObject) + Send + 'static;
  303. }
  304. pub trait EventLoopProxy<T: UserEvent>: Debug + Clone + Send + Sync {
  305. fn send_event(&self, event: T) -> Result<()>;
  306. }
  307. #[derive(Default)]
  308. pub struct RuntimeInitArgs {
  309. #[cfg(any(
  310. target_os = "linux",
  311. target_os = "dragonfly",
  312. target_os = "freebsd",
  313. target_os = "netbsd",
  314. target_os = "openbsd"
  315. ))]
  316. pub app_id: Option<String>,
  317. #[cfg(windows)]
  318. pub msg_hook: Option<Box<dyn FnMut(*const std::ffi::c_void) -> bool + 'static>>,
  319. }
  320. /// The webview runtime interface.
  321. pub trait Runtime<T: UserEvent>: Debug + Sized + 'static {
  322. /// The window message dispatcher.
  323. type WindowDispatcher: WindowDispatch<T, Runtime = Self>;
  324. /// The webview message dispatcher.
  325. type WebviewDispatcher: WebviewDispatch<T, Runtime = Self>;
  326. /// The runtime handle type.
  327. type Handle: RuntimeHandle<T, Runtime = Self>;
  328. /// The proxy type.
  329. type EventLoopProxy: EventLoopProxy<T>;
  330. /// Creates a new webview runtime. Must be used on the main thread.
  331. fn new(args: RuntimeInitArgs) -> Result<Self>;
  332. /// Creates a new webview runtime on any thread.
  333. #[cfg(any(windows, target_os = "linux"))]
  334. #[cfg_attr(docsrs, doc(cfg(any(windows, target_os = "linux"))))]
  335. fn new_any_thread(args: RuntimeInitArgs) -> Result<Self>;
  336. /// Creates an `EventLoopProxy` that can be used to dispatch user events to the main event loop.
  337. fn create_proxy(&self) -> Self::EventLoopProxy;
  338. /// Gets a runtime handle.
  339. fn handle(&self) -> Self::Handle;
  340. /// Create a new window.
  341. fn create_window<F: Fn(RawWindow) + Send + 'static>(
  342. &self,
  343. pending: PendingWindow<T, Self>,
  344. after_window_creation: Option<F>,
  345. ) -> Result<DetachedWindow<T, Self>>;
  346. /// Create a new webview.
  347. fn create_webview(
  348. &self,
  349. window_id: WindowId,
  350. pending: PendingWebview<T, Self>,
  351. ) -> Result<DetachedWebview<T, Self>>;
  352. fn primary_monitor(&self) -> Option<Monitor>;
  353. fn monitor_from_point(&self, x: f64, y: f64) -> Option<Monitor>;
  354. fn available_monitors(&self) -> Vec<Monitor>;
  355. fn cursor_position(&self) -> Result<PhysicalPosition<f64>>;
  356. fn set_theme(&self, theme: Option<Theme>);
  357. /// Sets the activation policy for the application.
  358. #[cfg(target_os = "macos")]
  359. #[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
  360. fn set_activation_policy(&mut self, activation_policy: ActivationPolicy);
  361. /// Shows the application, but does not automatically focus it.
  362. #[cfg(target_os = "macos")]
  363. #[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
  364. fn show(&self);
  365. /// Hides the application.
  366. #[cfg(target_os = "macos")]
  367. #[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
  368. fn hide(&self);
  369. /// Change the device event filter mode.
  370. ///
  371. /// Since the DeviceEvent capture can lead to high CPU usage for unfocused windows, [`tao`]
  372. /// will ignore them by default for unfocused windows on Windows. This method allows changing
  373. /// the filter to explicitly capture them again.
  374. ///
  375. /// ## Platform-specific
  376. ///
  377. /// - ** Linux / macOS / iOS / Android**: Unsupported.
  378. ///
  379. /// [`tao`]: https://crates.io/crates/tao
  380. fn set_device_event_filter(&mut self, filter: DeviceEventFilter);
  381. /// Runs an iteration of the runtime event loop and returns control flow to the caller.
  382. #[cfg(desktop)]
  383. fn run_iteration<F: FnMut(RunEvent<T>) + 'static>(&mut self, callback: F);
  384. /// Run the webview runtime.
  385. fn run<F: FnMut(RunEvent<T>) + 'static>(self, callback: F);
  386. }
  387. /// Webview dispatcher. A thread-safe handle to the webview APIs.
  388. pub trait WebviewDispatch<T: UserEvent>: Debug + Clone + Send + Sync + Sized + 'static {
  389. /// The runtime this [`WebviewDispatch`] runs under.
  390. type Runtime: Runtime<T>;
  391. /// Run a task on the main thread.
  392. fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> Result<()>;
  393. /// Registers a webview event handler.
  394. fn on_webview_event<F: Fn(&WebviewEvent) + Send + 'static>(&self, f: F) -> WebviewEventId;
  395. /// Runs a closure with the platform webview object as argument.
  396. fn with_webview<F: FnOnce(Box<dyn std::any::Any>) + Send + 'static>(&self, f: F) -> Result<()>;
  397. /// Open the web inspector which is usually called devtools.
  398. #[cfg(any(debug_assertions, feature = "devtools"))]
  399. fn open_devtools(&self);
  400. /// Close the web inspector which is usually called devtools.
  401. #[cfg(any(debug_assertions, feature = "devtools"))]
  402. fn close_devtools(&self);
  403. /// Gets the devtools window's current open state.
  404. #[cfg(any(debug_assertions, feature = "devtools"))]
  405. fn is_devtools_open(&self) -> Result<bool>;
  406. // GETTERS
  407. /// Returns the webview's current URL.
  408. fn url(&self) -> Result<String>;
  409. /// Returns the webview's bounds.
  410. fn bounds(&self) -> Result<Rect>;
  411. /// Returns the position of the top-left hand corner of the webviews's client area relative to the top-left hand corner of the window.
  412. fn position(&self) -> Result<PhysicalPosition<i32>>;
  413. /// Returns the physical size of the webviews's client area.
  414. fn size(&self) -> Result<PhysicalSize<u32>>;
  415. // SETTER
  416. /// Navigate to the given URL.
  417. fn navigate(&self, url: Url) -> Result<()>;
  418. /// Opens the dialog to prints the contents of the webview.
  419. fn print(&self) -> Result<()>;
  420. /// Closes the webview.
  421. fn close(&self) -> Result<()>;
  422. /// Sets the webview's bounds.
  423. fn set_bounds(&self, bounds: Rect) -> Result<()>;
  424. /// Resizes the webview.
  425. fn set_size(&self, size: Size) -> Result<()>;
  426. /// Updates the webview position.
  427. fn set_position(&self, position: Position) -> Result<()>;
  428. /// Bring the window to front and focus the webview.
  429. fn set_focus(&self) -> Result<()>;
  430. /// Hide the webview
  431. fn hide(&self) -> Result<()>;
  432. /// Show the webview
  433. fn show(&self) -> Result<()>;
  434. /// Executes javascript on the window this [`WindowDispatch`] represents.
  435. fn eval_script<S: Into<String>>(&self, script: S) -> Result<()>;
  436. /// Moves the webview to the given window.
  437. fn reparent(&self, window_id: WindowId) -> Result<()>;
  438. /// Sets whether the webview should automatically grow and shrink its size and position when the parent window resizes.
  439. fn set_auto_resize(&self, auto_resize: bool) -> Result<()>;
  440. /// Set the webview zoom level
  441. fn set_zoom(&self, scale_factor: f64) -> Result<()>;
  442. /// Clear all browsing data for this webview.
  443. fn clear_all_browsing_data(&self) -> Result<()>;
  444. }
  445. /// Window dispatcher. A thread-safe handle to the window APIs.
  446. pub trait WindowDispatch<T: UserEvent>: Debug + Clone + Send + Sync + Sized + 'static {
  447. /// The runtime this [`WindowDispatch`] runs under.
  448. type Runtime: Runtime<T>;
  449. /// The window builder type.
  450. type WindowBuilder: WindowBuilder;
  451. /// Run a task on the main thread.
  452. fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> Result<()>;
  453. /// Registers a window event handler.
  454. fn on_window_event<F: Fn(&WindowEvent) + Send + 'static>(&self, f: F) -> WindowEventId;
  455. // GETTERS
  456. /// Returns the scale factor that can be used to map logical pixels to physical pixels, and vice versa.
  457. fn scale_factor(&self) -> Result<f64>;
  458. /// 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.
  459. fn inner_position(&self) -> Result<PhysicalPosition<i32>>;
  460. /// Returns the position of the top-left hand corner of the window relative to the top-left hand corner of the desktop.
  461. fn outer_position(&self) -> Result<PhysicalPosition<i32>>;
  462. /// Returns the physical size of the window's client area.
  463. ///
  464. /// The client area is the content of the window, excluding the title bar and borders.
  465. fn inner_size(&self) -> Result<PhysicalSize<u32>>;
  466. /// Returns the physical size of the entire window.
  467. ///
  468. /// These dimensions include the title bar and borders. If you don't want that (and you usually don't), use inner_size instead.
  469. fn outer_size(&self) -> Result<PhysicalSize<u32>>;
  470. /// Gets the window's current fullscreen state.
  471. fn is_fullscreen(&self) -> Result<bool>;
  472. /// Gets the window's current minimized state.
  473. fn is_minimized(&self) -> Result<bool>;
  474. /// Gets the window's current maximized state.
  475. fn is_maximized(&self) -> Result<bool>;
  476. /// Gets the window's current focus state.
  477. fn is_focused(&self) -> Result<bool>;
  478. /// Gets the window's current decoration state.
  479. fn is_decorated(&self) -> Result<bool>;
  480. /// Gets the window's current resizable state.
  481. fn is_resizable(&self) -> Result<bool>;
  482. /// Gets the window's native maximize button state.
  483. ///
  484. /// ## Platform-specific
  485. ///
  486. /// - **Linux / iOS / Android:** Unsupported.
  487. fn is_maximizable(&self) -> Result<bool>;
  488. /// Gets the window's native minimize button state.
  489. ///
  490. /// ## Platform-specific
  491. ///
  492. /// - **Linux / iOS / Android:** Unsupported.
  493. fn is_minimizable(&self) -> Result<bool>;
  494. /// Gets the window's native close button state.
  495. ///
  496. /// ## Platform-specific
  497. ///
  498. /// - **iOS / Android:** Unsupported.
  499. fn is_closable(&self) -> Result<bool>;
  500. /// Gets the window's current visibility state.
  501. fn is_visible(&self) -> Result<bool>;
  502. /// Gets the window's current title.
  503. fn title(&self) -> Result<String>;
  504. /// Returns the monitor on which the window currently resides.
  505. ///
  506. /// Returns None if current monitor can't be detected.
  507. fn current_monitor(&self) -> Result<Option<Monitor>>;
  508. /// Returns the primary monitor of the system.
  509. ///
  510. /// Returns None if it can't identify any monitor as a primary one.
  511. fn primary_monitor(&self) -> Result<Option<Monitor>>;
  512. /// Returns the monitor that contains the given point.
  513. fn monitor_from_point(&self, x: f64, y: f64) -> Result<Option<Monitor>>;
  514. /// Returns the list of all the monitors available on the system.
  515. fn available_monitors(&self) -> Result<Vec<Monitor>>;
  516. /// Returns the `ApplicationWindow` from gtk crate that is used by this window.
  517. #[cfg(any(
  518. target_os = "linux",
  519. target_os = "dragonfly",
  520. target_os = "freebsd",
  521. target_os = "netbsd",
  522. target_os = "openbsd"
  523. ))]
  524. fn gtk_window(&self) -> Result<gtk::ApplicationWindow>;
  525. /// Returns the vertical [`gtk::Box`] that is added by default as the sole child of this window.
  526. #[cfg(any(
  527. target_os = "linux",
  528. target_os = "dragonfly",
  529. target_os = "freebsd",
  530. target_os = "netbsd",
  531. target_os = "openbsd"
  532. ))]
  533. fn default_vbox(&self) -> Result<gtk::Box>;
  534. /// Raw window handle.
  535. fn window_handle(
  536. &self,
  537. ) -> std::result::Result<raw_window_handle::WindowHandle<'_>, raw_window_handle::HandleError>;
  538. /// Returns the current window theme.
  539. fn theme(&self) -> Result<Theme>;
  540. // SETTERS
  541. /// Centers the window.
  542. fn center(&self) -> Result<()>;
  543. /// Requests user attention to the window.
  544. ///
  545. /// Providing `None` will unset the request for user attention.
  546. fn request_user_attention(&self, request_type: Option<UserAttentionType>) -> Result<()>;
  547. /// Create a new window.
  548. fn create_window<F: Fn(RawWindow) + Send + 'static>(
  549. &mut self,
  550. pending: PendingWindow<T, Self::Runtime>,
  551. after_window_creation: Option<F>,
  552. ) -> Result<DetachedWindow<T, Self::Runtime>>;
  553. /// Create a new webview.
  554. fn create_webview(
  555. &mut self,
  556. pending: PendingWebview<T, Self::Runtime>,
  557. ) -> Result<DetachedWebview<T, Self::Runtime>>;
  558. /// Updates the window resizable flag.
  559. fn set_resizable(&self, resizable: bool) -> Result<()>;
  560. /// Updates the window's native maximize button state.
  561. ///
  562. /// ## Platform-specific
  563. ///
  564. /// - **macOS:** Disables the "zoom" button in the window titlebar, which is also used to enter fullscreen mode.
  565. /// - **Linux / iOS / Android:** Unsupported.
  566. fn set_maximizable(&self, maximizable: bool) -> Result<()>;
  567. /// Updates the window's native minimize button state.
  568. ///
  569. /// ## Platform-specific
  570. ///
  571. /// - **Linux / iOS / Android:** Unsupported.
  572. fn set_minimizable(&self, minimizable: bool) -> Result<()>;
  573. /// Updates the window's native close button state.
  574. ///
  575. /// ## Platform-specific
  576. ///
  577. /// - **Linux:** "GTK+ will do its best to convince the window manager not to show a close button.
  578. /// Depending on the system, this function may not have any effect when called on a window that is already visible"
  579. /// - **iOS / Android:** Unsupported.
  580. fn set_closable(&self, closable: bool) -> Result<()>;
  581. /// Updates the window title.
  582. fn set_title<S: Into<String>>(&self, title: S) -> Result<()>;
  583. /// Maximizes the window.
  584. fn maximize(&self) -> Result<()>;
  585. /// Unmaximizes the window.
  586. fn unmaximize(&self) -> Result<()>;
  587. /// Minimizes the window.
  588. fn minimize(&self) -> Result<()>;
  589. /// Unminimizes the window.
  590. fn unminimize(&self) -> Result<()>;
  591. /// Shows the window.
  592. fn show(&self) -> Result<()>;
  593. /// Hides the window.
  594. fn hide(&self) -> Result<()>;
  595. /// Closes the window.
  596. fn close(&self) -> Result<()>;
  597. /// Destroys the window.
  598. fn destroy(&self) -> Result<()>;
  599. /// Updates the decorations flag.
  600. fn set_decorations(&self, decorations: bool) -> Result<()>;
  601. /// Updates the shadow flag.
  602. fn set_shadow(&self, enable: bool) -> Result<()>;
  603. /// Updates the window alwaysOnBottom flag.
  604. fn set_always_on_bottom(&self, always_on_bottom: bool) -> Result<()>;
  605. /// Updates the window alwaysOnTop flag.
  606. fn set_always_on_top(&self, always_on_top: bool) -> Result<()>;
  607. /// Updates the window visibleOnAllWorkspaces flag.
  608. fn set_visible_on_all_workspaces(&self, visible_on_all_workspaces: bool) -> Result<()>;
  609. /// Prevents the window contents from being captured by other apps.
  610. fn set_content_protected(&self, protected: bool) -> Result<()>;
  611. /// Resizes the window.
  612. fn set_size(&self, size: Size) -> Result<()>;
  613. /// Updates the window min inner size.
  614. fn set_min_size(&self, size: Option<Size>) -> Result<()>;
  615. /// Updates the window max inner size.
  616. fn set_max_size(&self, size: Option<Size>) -> Result<()>;
  617. /// Sets this window's minimum inner width.
  618. fn set_size_constraints(&self, constraints: WindowSizeConstraints) -> Result<()>;
  619. /// Updates the window position.
  620. fn set_position(&self, position: Position) -> Result<()>;
  621. /// Updates the window fullscreen state.
  622. fn set_fullscreen(&self, fullscreen: bool) -> Result<()>;
  623. /// Bring the window to front and focus.
  624. fn set_focus(&self) -> Result<()>;
  625. /// Updates the window icon.
  626. fn set_icon(&self, icon: Icon) -> Result<()>;
  627. /// Whether to hide the window icon from the taskbar or not.
  628. fn set_skip_taskbar(&self, skip: bool) -> Result<()>;
  629. /// Grabs the cursor, preventing it from leaving the window.
  630. ///
  631. /// There's no guarantee that the cursor will be hidden. You should
  632. /// hide it by yourself if you want so.
  633. fn set_cursor_grab(&self, grab: bool) -> Result<()>;
  634. /// Modifies the cursor's visibility.
  635. ///
  636. /// If `false`, this will hide the cursor. If `true`, this will show the cursor.
  637. fn set_cursor_visible(&self, visible: bool) -> Result<()>;
  638. // Modifies the cursor icon of the window.
  639. fn set_cursor_icon(&self, icon: CursorIcon) -> Result<()>;
  640. /// Changes the position of the cursor in window coordinates.
  641. fn set_cursor_position<Pos: Into<Position>>(&self, position: Pos) -> Result<()>;
  642. /// Ignores the window cursor events.
  643. fn set_ignore_cursor_events(&self, ignore: bool) -> Result<()>;
  644. /// Starts dragging the window.
  645. fn start_dragging(&self) -> Result<()>;
  646. /// Starts resize-dragging the window.
  647. fn start_resize_dragging(&self, direction: ResizeDirection) -> Result<()>;
  648. /// Sets the taskbar progress state.
  649. ///
  650. /// ## Platform-specific
  651. ///
  652. /// - **Linux / macOS**: Progress bar is app-wide and not specific to this window. Only supported desktop environments with `libunity` (e.g. GNOME).
  653. /// - **iOS / Android:** Unsupported.
  654. fn set_progress_bar(&self, progress_state: ProgressBarState) -> Result<()>;
  655. /// Sets the title bar style. Available on macOS only.
  656. ///
  657. /// ## Platform-specific
  658. ///
  659. /// - **Linux / Windows / iOS / Android:** Unsupported.
  660. fn set_title_bar_style(&self, style: tauri_utils::TitleBarStyle) -> Result<()>;
  661. /// Sets the theme for this window.
  662. ///
  663. /// ## Platform-specific
  664. ///
  665. /// - **Linux / macOS**: Theme is app-wide and not specific to this window.
  666. /// - **iOS / Android:** Unsupported.
  667. fn set_theme(&self, theme: Option<Theme>) -> Result<()>;
  668. }