tauri_runtime/
lib.rs

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