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