lib.rs 25 KB

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