Skip to main content

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