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