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