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::Theme;
20use tauri_utils::config::Color;
21use url::Url;
22use webview::{DetachedWebview, PendingWebview};
23
24/// UI scaling utilities.
25pub mod dpi;
26pub mod dynamic;
27#[cfg(any(
28 target_os = "linux",
29 target_os = "dragonfly",
30 target_os = "freebsd",
31 target_os = "netbsd",
32 target_os = "openbsd"
33))]
34pub mod gtk;
35/// Types useful for interacting with a user's monitors.
36pub mod monitor;
37pub mod webview;
38mod webview_permissions;
39pub mod window;
40
41use dpi::{PhysicalPosition, PhysicalSize, Position, Rect, Size};
42use monitor::Monitor;
43use window::{
44 CursorIcon, DetachedWindow, PendingWindow, RawWindow, WebviewEvent, WindowEvent,
45 WindowSizeConstraints,
46};
47use window::{WindowBuilder, WindowId};
48
49use http::{
50 header::{InvalidHeaderName, InvalidHeaderValue},
51 method::InvalidMethod,
52 status::InvalidStatusCode,
53};
54
55/// Cookie extraction
56pub use cookie::Cookie;
57
58/// Progress bar status.
59#[derive(Debug, Clone, Copy, Deserialize)]
60#[serde(rename_all = "camelCase")]
61pub enum ProgressBarStatus {
62 /// Hide progress bar.
63 None,
64 /// Normal state.
65 Normal,
66 /// Indeterminate state. **Treated as Normal on Linux and macOS**
67 Indeterminate,
68 /// Paused state. **Treated as Normal on Linux**
69 Paused,
70 /// Error state. **Treated as Normal on Linux**
71 Error,
72}
73
74/// Progress Bar State
75#[derive(Debug, Deserialize)]
76#[serde(rename_all = "camelCase")]
77pub struct ProgressBarState {
78 /// The progress bar status.
79 pub status: Option<ProgressBarStatus>,
80 /// The progress bar progress. This can be a value ranging from `0` to `100`
81 pub progress: Option<u64>,
82 /// The `.desktop` filename with the Unity desktop window manager, for example `myapp.desktop` **Linux Only**
83 pub desktop_filename: Option<String>,
84}
85
86/// Type of user attention requested on a window.
87#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
88#[serde(tag = "type")]
89pub enum UserAttentionType {
90 /// ## Platform-specific
91 /// - **macOS:** Bounces the dock icon until the application is in focus.
92 /// - **Windows:** Flashes both the window and the taskbar button until the application is in focus.
93 Critical,
94 /// ## Platform-specific
95 /// - **macOS:** Bounces the dock icon once.
96 /// - **Windows:** Flashes the taskbar button until the application is in focus.
97 Informational,
98}
99
100/// Defines which device events (raw input from mice, keyboards and other HID devices that is not
101/// bound to a specific window) the event loop should deliver to the application.
102///
103/// Listening to device events can be expensive, so the runtime filters them out by default
104/// while the application has no focused window. See [`crate::Runtime::set_device_event_filter`].
105///
106/// ## Platform-specific
107///
108/// - **Linux / macOS / iOS / Android**: Unsupported, device events are always filtered out.
109#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
110#[serde(tag = "type")]
111pub enum DeviceEventFilter {
112 /// Always filter out device events.
113 Always,
114 /// Filter out device events while the window is not focused.
115 #[default]
116 Unfocused,
117 /// Report all device events regardless of window focus.
118 Never,
119}
120
121/// Defines the orientation that a window resize will be performed.
122#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
123pub enum ResizeDirection {
124 East,
125 North,
126 NorthEast,
127 NorthWest,
128 South,
129 SouthEast,
130 SouthWest,
131 West,
132}
133
134/// Errors returned by the webview runtime.
135///
136/// These are surfaced to Tauri applications wrapped in
137/// [`tauri::Error::Runtime`](https://docs.rs/tauri/latest/tauri/enum.Error.html).
138///
139/// This enum is `#[non_exhaustive]`: new variants can be added in minor releases.
140#[derive(Debug, thiserror::Error)]
141#[non_exhaustive]
142pub enum Error {
143 /// Failed to create webview.
144 #[error("failed to create webview: {0}")]
145 CreateWebview(Box<dyn std::error::Error + Send + Sync>),
146 /// Failed to create window.
147 #[error("failed to create window: {0}")]
148 CreateWindow(Box<dyn std::error::Error + Send + Sync>),
149 /// The given window label is invalid.
150 #[error("Window labels must only include alphanumeric characters, `-`, `/`, `:` and `_`.")]
151 InvalidWindowLabel,
152 /// Failed to send message to webview.
153 #[error("failed to send message to the webview")]
154 FailedToSendMessage,
155 /// Failed to receive message from webview.
156 #[error("failed to receive message from webview")]
157 FailedToReceiveMessage,
158 /// Failed to serialize/deserialize.
159 #[error("JSON error: {0}")]
160 Json(#[from] serde_json::Error),
161 /// Failed to load window icon.
162 #[error("invalid icon: {0}")]
163 InvalidIcon(Box<dyn std::error::Error + Send + Sync>),
164 /// Failed to get monitor on window operation.
165 #[error("failed to get monitor")]
166 FailedToGetMonitor,
167 /// Failed to get cursor position.
168 #[error("failed to get cursor position")]
169 FailedToGetCursorPosition,
170 #[error("Invalid header name: {0}")]
171 InvalidHeaderName(#[from] InvalidHeaderName),
172 #[error("Invalid header value: {0}")]
173 InvalidHeaderValue(#[from] InvalidHeaderValue),
174 #[error("Invalid status code: {0}")]
175 InvalidStatusCode(#[from] InvalidStatusCode),
176 #[error("Invalid method: {0}")]
177 InvalidMethod(#[from] InvalidMethod),
178 #[error("Infallible error, something went really wrong: {0}")]
179 Infallible(#[from] std::convert::Infallible),
180 #[error("the event loop has been closed")]
181 EventLoopClosed,
182 #[error("Invalid proxy url")]
183 InvalidProxyUrl,
184 #[error("window not found")]
185 WindowNotFound,
186 #[cfg(any(target_os = "macos", target_os = "ios"))]
187 #[error("failed to remove data store")]
188 FailedToRemoveDataStore,
189 #[error("Could not find the webview runtime, make sure it is installed")]
190 WebviewRuntimeNotInstalled,
191 /// The type-erased runtime was initialized without selecting a concrete runtime.
192 #[error(
193 "no runtime was configured; select one with e.g. `tauri::Builder::default().runtime(tauri_runtime_wry::Wry::default())`"
194 )]
195 RuntimeNotConfigured,
196 /// A runtime-specific value was given to a different runtime than the one it belongs to.
197 #[error("runtime type mismatch: {0}")]
198 RuntimeTypeMismatch(String),
199 /// Failed to determine the webview version.
200 #[error("failed to get the webview version: {0}")]
201 WebviewVersion(Box<dyn std::error::Error + Send + Sync>),
202}
203
204/// Result type.
205pub type Result<T> = std::result::Result<T, Error>;
206
207/// Window icon.
208#[derive(Debug, Clone)]
209pub struct Icon<'a> {
210 /// RGBA bytes of the icon.
211 pub rgba: Cow<'a, [u8]>,
212 /// Icon width.
213 pub width: u32,
214 /// Icon height.
215 pub height: u32,
216}
217
218impl<'a> Icon<'a> {
219 pub fn into_owned(self) -> Icon<'static> {
220 Icon {
221 rgba: std::borrow::Cow::Owned(self.rgba.into_owned()),
222 width: self.width,
223 height: self.height,
224 }
225 }
226}
227
228/// A type that can be used as an user event.
229pub trait UserEvent: Debug + Clone + Send + 'static {}
230
231impl<T: Debug + Clone + Send + 'static> UserEvent for T {}
232
233/// Event triggered on the event loop run.
234#[derive(Debug)]
235#[non_exhaustive]
236pub enum RunEvent<T: UserEvent> {
237 /// Event loop is exiting.
238 Exit,
239 /// Event loop is about to exit
240 ExitRequested {
241 /// The exit code.
242 code: Option<i32>,
243 tx: Sender<ExitRequestedEventAction>,
244 },
245 /// An event associated with a window.
246 WindowEvent {
247 /// The window label.
248 label: String,
249 /// The detailed event.
250 event: WindowEvent,
251 },
252 /// An event associated with a webview.
253 WebviewEvent {
254 /// The webview label.
255 label: String,
256 /// The detailed event.
257 event: WebviewEvent,
258 },
259 /// Application ready.
260 Ready,
261 /// Sent if the event loop is being resumed.
262 Resumed,
263 /// Emitted when all of the event loop's input events have been processed and redraw processing is about to begin.
264 ///
265 /// 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.
266 MainEventsCleared,
267 /// Emitted when the user wants to open the specified resource with the app.
268 Opened { urls: Vec<url::Url> },
269 /// Emitted when the NSApplicationDelegate's applicationShouldHandleReopen gets called
270 #[cfg(target_os = "macos")]
271 Reopen {
272 /// Indicates whether the NSApplication object found any visible windows in your application.
273 has_visible_windows: bool,
274 },
275 /// A custom event defined by the user.
276 UserEvent(T),
277 /// Emitted when a scene is requested by the system.
278 ///
279 /// This event is emitted when a scene is requested by the system.
280 /// Scenes created by [`Window::new`] are not emitted with this event.
281 /// It is also not emitted for the main scene.
282 #[cfg(target_os = "ios")]
283 SceneRequested {
284 /// Scene that was requested by the system.
285 scene: objc2::rc::Retained<objc2_ui_kit::UIScene>,
286 /// Options that were used to request the scene.
287 ///
288 /// This lets you determine why the scene was requested.
289 options: objc2::rc::Retained<objc2_ui_kit::UISceneConnectionOptions>,
290 },
291}
292
293/// Action to take when the event loop is about to exit
294#[derive(Debug)]
295pub enum ExitRequestedEventAction {
296 /// Prevent the event loop from exiting
297 Prevent,
298}
299
300/// Application's activation policy. Corresponds to NSApplicationActivationPolicy.
301#[cfg(target_os = "macos")]
302#[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
303#[non_exhaustive]
304pub enum ActivationPolicy {
305 /// Corresponds to NSApplicationActivationPolicyRegular.
306 Regular,
307 /// Corresponds to NSApplicationActivationPolicyAccessory.
308 Accessory,
309 /// Corresponds to NSApplicationActivationPolicyProhibited.
310 Prohibited,
311}
312
313/// A [`Send`] handle to the runtime.
314pub trait RuntimeHandle<T: UserEvent>: Debug + Clone + Send + Sync + Sized + 'static {
315 type Runtime: Runtime<T, Handle = Self>;
316
317 /// Creates an `EventLoopProxy` that can be used to dispatch user events to the main event loop.
318 fn create_proxy(&self) -> <Self::Runtime as Runtime<T>>::EventLoopProxy;
319
320 /// Sets the activation policy for the application.
321 #[cfg(target_os = "macos")]
322 #[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
323 fn set_activation_policy(&self, activation_policy: ActivationPolicy) -> Result<()>;
324
325 /// Sets the dock visibility for the application.
326 #[cfg(target_os = "macos")]
327 #[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
328 fn set_dock_visibility(&self, visible: bool) -> Result<()>;
329
330 /// Requests an exit of the event loop.
331 fn request_exit(&self, code: i32) -> Result<()>;
332
333 /// Create a new window.
334 fn create_window<F: Fn(RawWindow) + Send + 'static>(
335 &self,
336 pending: PendingWindow<T, Self::Runtime>,
337 after_window_creation: Option<F>,
338 ) -> Result<DetachedWindow<T, Self::Runtime>>;
339
340 /// Create a new webview.
341 fn create_webview(
342 &self,
343 window_id: WindowId,
344 pending: PendingWebview<T, Self::Runtime>,
345 ) -> Result<DetachedWebview<T, Self::Runtime>>;
346
347 /// Run a task on the main thread.
348 fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> Result<()>;
349
350 /// Get a handle to the display controller of the windowing system.
351 fn display_handle(
352 &self,
353 ) -> std::result::Result<DisplayHandle<'_>, raw_window_handle::HandleError>;
354
355 /// Returns the primary monitor of the system.
356 ///
357 /// Returns None if it can't identify any monitor as a primary one.
358 fn primary_monitor(&self) -> Result<Option<Monitor>>;
359
360 /// Returns the monitor that contains the given point.
361 fn monitor_from_point(&self, x: f64, y: f64) -> Result<Option<Monitor>>;
362
363 /// Returns the list of all the monitors available on the system.
364 fn available_monitors(&self) -> Result<Vec<Monitor>>;
365
366 /// Get the cursor position relative to the top-left hand corner of the desktop.
367 fn cursor_position(&self) -> Result<PhysicalPosition<f64>>;
368
369 /// Sets the app theme.
370 fn set_theme(&self, theme: Option<Theme>);
371
372 /// Shows the application, but does not automatically focus it.
373 #[cfg(target_os = "macos")]
374 #[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
375 fn show(&self) -> Result<()>;
376
377 /// Hides the application.
378 #[cfg(target_os = "macos")]
379 #[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
380 fn hide(&self) -> Result<()>;
381
382 /// Change the device event filter mode.
383 ///
384 /// See [Runtime::set_device_event_filter] for details.
385 ///
386 /// ## Platform-specific
387 ///
388 /// See [Runtime::set_device_event_filter] for details.
389 fn set_device_event_filter(&self, filter: DeviceEventFilter);
390
391 /// Returns the URL a custom scheme is served from,
392 /// e.g. `tauri://localhost` or `http://tauri.localhost`.
393 ///
394 /// The format is entirely up to the runtime. Tauri never assumes a particular scheme or host
395 /// layout: every custom protocol URL it builds or compares against goes through this function,
396 /// and the asset path of an incoming custom protocol request is always taken from its URI path.
397 ///
398 /// `scheme` is usually a registered protocol name such as `tauri`, `ipc` or `asset`, but it can
399 /// also be the literal placeholder `{protocol}`, which Tauri uses to build the URL template
400 /// injected into the webview (the frontend expands it in `convertFileSrc`). Implementations must
401 /// therefore interpolate `scheme` verbatim, without validating, escaping or normalizing it.
402 ///
403 /// `https` reflects [`crate::webview::WebviewAttributes::use_https_scheme`]; runtimes that do not
404 /// serve custom protocols over `http(s)` can ignore it.
405 fn custom_scheme_url(&self, scheme: &str, https: bool) -> String;
406
407 /// Returns the version of the underlying webview engine.
408 fn webview_version(&self) -> Result<String>;
409
410 /// Finds an Android class in the project scope.
411 #[cfg(target_os = "android")]
412 fn find_class<'a>(
413 &self,
414 env: &mut jni::JNIEnv<'a>,
415 activity: &jni::objects::JObject<'_>,
416 name: impl Into<String>,
417 ) -> std::result::Result<jni::objects::JClass<'a>, jni::errors::Error>;
418
419 /// Dispatch a closure to run on the Android context.
420 ///
421 /// The closure takes the JNI env, the Android activity instance and the possibly null webview.
422 #[cfg(target_os = "android")]
423 fn run_on_android_context<F>(&self, f: F)
424 where
425 F: FnOnce(&mut jni::JNIEnv, &jni::objects::JObject, &jni::objects::JObject) + Send + 'static;
426
427 #[cfg(any(target_os = "macos", target_os = "ios"))]
428 #[cfg_attr(docsrs, doc(cfg(any(target_os = "macos", target_os = "ios"))))]
429 fn fetch_data_store_identifiers<F: FnOnce(Vec<[u8; 16]>) + Send + 'static>(
430 &self,
431 cb: F,
432 ) -> Result<()>;
433
434 #[cfg(any(target_os = "macos", target_os = "ios"))]
435 #[cfg_attr(docsrs, doc(cfg(any(target_os = "macos", target_os = "ios"))))]
436 fn remove_data_store<F: FnOnce(Result<()>) + Send + 'static>(
437 &self,
438 uuid: [u8; 16],
439 cb: F,
440 ) -> Result<()>;
441}
442
443pub trait EventLoopProxy<T: UserEvent>: Debug + Clone + Send + Sync {
444 fn send_event(&self, event: T) -> Result<()>;
445}
446
447#[derive(Default)]
448pub struct RuntimeInitArgs<A> {
449 #[cfg(any(
450 target_os = "linux",
451 target_os = "dragonfly",
452 target_os = "freebsd",
453 target_os = "netbsd",
454 target_os = "openbsd"
455 ))]
456 pub app_id: Option<String>,
457 #[cfg(windows)]
458 pub msg_hook: Option<Box<dyn FnMut(*const std::ffi::c_void) -> bool + 'static>>,
459 pub identifier: String,
460 pub custom_schemes: Vec<String>,
461 pub runtime_init_attrs: A,
462}
463
464impl<A> RuntimeInitArgs<A> {
465 /// Replaces the runtime-specific attributes, returning the new arguments and the previous attributes.
466 ///
467 /// Used by the type-erased [`dynamic::DynRuntime`] to move the attributes of the selected runtime
468 /// in and out of the arguments, since the erased layer only carries `RuntimeInitArgs<()>`.
469 pub(crate) fn with_attrs<B>(self, runtime_init_attrs: B) -> (RuntimeInitArgs<B>, A) {
470 let RuntimeInitArgs {
471 #[cfg(any(
472 target_os = "linux",
473 target_os = "dragonfly",
474 target_os = "freebsd",
475 target_os = "netbsd",
476 target_os = "openbsd"
477 ))]
478 app_id,
479 #[cfg(windows)]
480 msg_hook,
481 identifier,
482 custom_schemes,
483 runtime_init_attrs: previous,
484 } = self;
485 (
486 RuntimeInitArgs {
487 #[cfg(any(
488 target_os = "linux",
489 target_os = "dragonfly",
490 target_os = "freebsd",
491 target_os = "netbsd",
492 target_os = "openbsd"
493 ))]
494 app_id,
495 #[cfg(windows)]
496 msg_hook,
497 identifier,
498 custom_schemes,
499 runtime_init_attrs,
500 },
501 previous,
502 )
503 }
504}
505
506/// Runtime-specific initialization attributes.
507///
508/// Every [`Runtime`] defines its own attributes type. That type is also what *selects* the runtime
509/// when the application uses the type-erased [`dynamic::DynRuntime`]: passing the attributes
510/// (e.g. `tauri_runtime_wry::Wry::default()` or `tauri_runtime_cef::Cef::default()`) to
511/// `tauri::Builder::runtime` picks the runtime they belong to.
512///
513/// For that to work, runtime crates also implement `From<Self>` for [`dynamic::DynRuntimeInitAttrs`]
514/// (wrapping the attributes with [`dynamic::DynRuntimeInitAttrs::new`]).
515pub trait RuntimeInitAttrs<T: UserEvent>: Default + Send + Sync + 'static {
516 /// The runtime initialized with these attributes.
517 type Runtime: Runtime<T, RuntimeInitAttrs = Self>;
518
519 /// Applies attributes derived from the application configuration.
520 fn apply_config(&mut self, _config: &tauri_utils::config::Config) -> Result<()> {
521 Ok(())
522 }
523}
524
525/// The webview runtime interface.
526pub trait Runtime<T: UserEvent>: Debug + Sized + 'static {
527 /// The window message dispatcher.
528 type WindowDispatcher: WindowDispatch<T, Runtime = Self>;
529 /// The webview message dispatcher.
530 type WebviewDispatcher: WebviewDispatch<T, Runtime = Self>;
531 /// The runtime handle type.
532 type Handle: RuntimeHandle<T, Runtime = Self>;
533 /// The proxy type.
534 type EventLoopProxy: EventLoopProxy<T>;
535 /// The runtime-specific webview attributes, set on the webview builders through the runtime's extension traits.
536 ///
537 /// The default value is used when the application sets none.
538 type RuntimeWebviewAttributes: Default + Send + Sync + 'static;
539 /// The platform webview handle exposed through [`WebviewDispatch::with_webview`].
540 ///
541 /// This is the runtime-specific type the user interacts with to reach the
542 /// underlying platform webview APIs.
543 type Webview: 'static;
544 /// Runtime-specific initialization attributes. Also used to select this runtime, see [`RuntimeInitAttrs`].
545 type RuntimeInitAttrs: RuntimeInitAttrs<T, Runtime = Self>;
546 /// Data about the window that requested the new window for [`PendingWebview::new_window_handler`].
547 type WindowOpener: Send + Sync + Debug + 'static;
548
549 /// Creates a new webview runtime. Must be used on the main thread.
550 fn new(args: RuntimeInitArgs<Self::RuntimeInitAttrs>) -> Result<Self>;
551
552 /// Creates a new webview runtime on any thread.
553 #[cfg(any(
554 windows,
555 target_os = "linux",
556 target_os = "dragonfly",
557 target_os = "freebsd",
558 target_os = "netbsd",
559 target_os = "openbsd"
560 ))]
561 #[cfg_attr(
562 docsrs,
563 doc(cfg(any(
564 windows,
565 target_os = "linux",
566 target_os = "dragonfly",
567 target_os = "freebsd",
568 target_os = "netbsd",
569 target_os = "openbsd"
570 )))
571 )]
572 fn new_any_thread(args: RuntimeInitArgs<Self::RuntimeInitAttrs>) -> Result<Self>;
573
574 /// Creates an `EventLoopProxy` that can be used to dispatch user events to the main event loop.
575 fn create_proxy(&self) -> Self::EventLoopProxy;
576
577 /// Gets a runtime handle.
578 fn handle(&self) -> Self::Handle;
579
580 /// Create a new window.
581 fn create_window<F: Fn(RawWindow) + Send + 'static>(
582 &self,
583 pending: PendingWindow<T, Self>,
584 after_window_creation: Option<F>,
585 ) -> Result<DetachedWindow<T, Self>>;
586
587 /// Create a new webview.
588 fn create_webview(
589 &self,
590 window_id: WindowId,
591 pending: PendingWebview<T, Self>,
592 ) -> Result<DetachedWebview<T, Self>>;
593
594 /// Returns the primary monitor of the system.
595 ///
596 /// Returns None if it can't identify any monitor as a primary one.
597 fn primary_monitor(&self) -> Option<Monitor>;
598
599 /// Returns the monitor that contains the given point.
600 fn monitor_from_point(&self, x: f64, y: f64) -> Option<Monitor>;
601
602 /// Returns the list of all the monitors available on the system.
603 fn available_monitors(&self) -> Vec<Monitor>;
604
605 /// Get the cursor position relative to the top-left hand corner of the desktop.
606 fn cursor_position(&self) -> Result<PhysicalPosition<f64>>;
607
608 /// Sets the app theme.
609 fn set_theme(&self, theme: Option<Theme>);
610
611 /// Sets the activation policy for the application.
612 #[cfg(target_os = "macos")]
613 #[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
614 fn set_activation_policy(&mut self, activation_policy: ActivationPolicy);
615
616 /// Sets whether the application activates when launched while another application is already active.
617 ///
618 /// This API must be called before the event loop starts.
619 ///
620 /// If `false`, the app activates only if no other app is currently active.
621 /// If `true`, the app activates regardless.
622 #[cfg(target_os = "macos")]
623 #[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
624 fn set_activate_ignoring_other_apps(&mut self, ignore: bool);
625
626 /// Sets the dock visibility for the application.
627 #[cfg(target_os = "macos")]
628 #[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
629 fn set_dock_visibility(&mut self, visible: bool);
630
631 /// Shows the application, but does not automatically focus it.
632 #[cfg(target_os = "macos")]
633 #[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
634 fn show(&self);
635
636 /// Hides the application.
637 #[cfg(target_os = "macos")]
638 #[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
639 fn hide(&self);
640
641 /// Change the device event filter mode.
642 ///
643 /// Since the DeviceEvent capture can lead to high CPU usage for unfocused windows, [`tao`]
644 /// will ignore them by default for unfocused windows on Windows. This method allows changing
645 /// the filter to explicitly capture them again.
646 ///
647 /// ## Platform-specific
648 ///
649 /// - ** Linux / macOS / iOS / Android**: Unsupported.
650 ///
651 /// [`tao`]: https://crates.io/crates/tao
652 fn set_device_event_filter(&mut self, filter: DeviceEventFilter);
653
654 /// Runs an iteration of the runtime event loop and returns control flow to the caller.
655 #[cfg(desktop)]
656 fn run_iteration<F: FnMut(RunEvent<T>) + 'static>(&mut self, callback: F);
657
658 /// Equivalent to [`Runtime::run`] but returns the exit code instead of exiting the process.
659 fn run_return<F: FnMut(RunEvent<T>) + 'static>(self, callback: F) -> i32;
660
661 /// Run the webview runtime.
662 fn run<F: FnMut(RunEvent<T>) + 'static>(self, callback: F);
663}
664
665/// Webview dispatcher. A thread-safe handle to the webview APIs.
666pub trait WebviewDispatch<T: UserEvent>: Debug + Clone + Send + Sync + Sized + 'static {
667 /// The runtime this [`WebviewDispatch`] runs under.
668 type Runtime: Runtime<T>;
669
670 /// Run a task on the main thread.
671 fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> Result<()>;
672
673 /// Runs a closure with the platform webview object as argument.
674 fn with_webview<F: FnOnce(<Self::Runtime as Runtime<T>>::Webview) + Send + 'static>(
675 &self,
676 f: F,
677 ) -> Result<()>;
678
679 /// Runs a closure with the iOS handles of the webview (the `WKWebView`, its user content controller and view controller).
680 ///
681 /// The closure is executed on the main thread.
682 #[cfg(target_os = "ios")]
683 fn with_ios_webview<F: FnOnce(webview::IosWebviewHandle) + Send + 'static>(
684 &self,
685 f: F,
686 ) -> Result<()>;
687
688 /// Open the web inspector which is usually called devtools.
689 ///
690 /// Runtimes compiled without devtools support (release builds without their `devtools` feature) do nothing.
691 fn open_devtools(&self);
692
693 /// Close the web inspector which is usually called devtools.
694 ///
695 /// Runtimes compiled without devtools support (release builds without their `devtools` feature) do nothing.
696 fn close_devtools(&self);
697
698 /// Gets the devtools window's current open state.
699 ///
700 /// Runtimes compiled without devtools support (release builds without their `devtools` feature) return `false`.
701 fn is_devtools_open(&self) -> Result<bool>;
702
703 // GETTERS
704
705 /// Returns the webview's current URL.
706 fn url(&self) -> Result<String>;
707
708 /// Returns the webview's bounds.
709 fn bounds(&self) -> Result<Rect>;
710
711 /// 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.
712 fn position(&self) -> Result<PhysicalPosition<i32>>;
713
714 /// Returns the physical size of the webviews's client area.
715 fn size(&self) -> Result<PhysicalSize<u32>>;
716
717 // SETTER
718
719 /// Navigate to the given URL.
720 fn navigate(&self, url: Url) -> Result<()>;
721
722 /// Reloads the current page.
723 fn reload(&self) -> Result<()>;
724
725 fn go_back(&self) -> Result<()>;
726
727 fn can_go_back(&self) -> Result<bool>;
728
729 fn go_forward(&self) -> Result<()>;
730
731 fn can_go_forward(&self) -> Result<bool>;
732
733 /// Opens the dialog to prints the contents of the webview.
734 fn print(&self) -> Result<()>;
735
736 /// Closes the webview.
737 fn close(&self) -> Result<()>;
738
739 /// Sets the webview's bounds.
740 fn set_bounds(&self, bounds: Rect) -> Result<()>;
741
742 /// Resizes the webview.
743 fn set_size(&self, size: Size) -> Result<()>;
744
745 /// Updates the webview position.
746 fn set_position(&self, position: Position) -> Result<()>;
747
748 /// Bring the window to front and focus the webview.
749 fn set_focus(&self) -> Result<()>;
750
751 /// Hide the webview
752 fn hide(&self) -> Result<()>;
753
754 /// Show the webview
755 fn show(&self) -> Result<()>;
756
757 /// Executes javascript on the window this [`WindowDispatch`] represents.
758 fn eval_script<S: Into<String>>(&self, script: S) -> Result<()>;
759
760 /// Evaluate JavaScript with callback function on the webview this [`WebviewDispatch`] represents.
761 /// The evaluation result will be serialized into a JSON string and passed to the callback function.
762 ///
763 /// Exception is ignored because of the limitation on Windows. You can catch it yourself and return as string as a workaround.
764 fn eval_script_with_callback<S: Into<String>>(
765 &self,
766 script: S,
767 callback: impl Fn(String) + Send + 'static,
768 ) -> Result<()>;
769
770 /// Moves the webview to the given window.
771 fn reparent(&self, window_id: WindowId) -> Result<()>;
772
773 /// Get cookies for a particular url.
774 ///
775 /// # Stability
776 ///
777 /// See [WebviewDispatch::cookies].
778 fn cookies_for_url(&self, url: Url) -> Result<Vec<Cookie<'static>>>;
779
780 /// Return all cookies in the cookie store.
781 ///
782 /// # Stability
783 ///
784 /// The return value of this function leverages [`cookie::Cookie`] which re-exports the cookie crate.
785 /// This dependency might receive updates in minor Tauri releases.
786 fn cookies(&self) -> Result<Vec<Cookie<'static>>>;
787
788 /// Set a cookie for the webview.
789 ///
790 /// # Stability
791 ///
792 /// See [WebviewDispatch::cookies].
793 fn set_cookie(&self, cookie: cookie::Cookie<'_>) -> Result<()>;
794
795 /// Delete a cookie for the webview.
796 ///
797 /// # Stability
798 ///
799 /// See [WebviewDispatch::cookies].
800 fn delete_cookie(&self, cookie: cookie::Cookie<'_>) -> Result<()>;
801
802 /// Sets whether the webview should automatically grow and shrink its size and position when the parent window resizes.
803 fn set_auto_resize(&self, auto_resize: bool) -> Result<()>;
804
805 /// Set the webview zoom level
806 fn set_zoom(&self, scale_factor: f64) -> Result<()>;
807
808 /// Set the webview background.
809 fn set_background_color(&self, color: Option<Color>) -> Result<()>;
810
811 /// Clear all browsing data for this webview.
812 fn clear_all_browsing_data(&self) -> Result<()>;
813}
814
815/// Window dispatcher. A thread-safe handle to the window APIs.
816pub trait WindowDispatch<T: UserEvent>: Debug + Clone + Send + Sync + Sized + 'static {
817 /// The runtime this [`WindowDispatch`] runs under.
818 type Runtime: Runtime<T>;
819
820 /// The window builder type.
821 type WindowBuilder: WindowBuilder;
822
823 /// Run a task on the main thread.
824 fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> Result<()>;
825
826 // GETTERS
827
828 /// Returns the scale factor that can be used to map logical pixels to physical pixels, and vice versa.
829 fn scale_factor(&self) -> Result<f64>;
830
831 /// 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.
832 fn inner_position(&self) -> Result<PhysicalPosition<i32>>;
833
834 /// Returns the position of the top-left hand corner of the window relative to the top-left hand corner of the desktop.
835 fn outer_position(&self) -> Result<PhysicalPosition<i32>>;
836
837 /// Returns the physical size of the window's client area.
838 ///
839 /// The client area is the content of the window, excluding the title bar and borders.
840 fn inner_size(&self) -> Result<PhysicalSize<u32>>;
841
842 /// Returns the physical size of the entire window.
843 ///
844 /// These dimensions include the title bar and borders. If you don't want that (and you usually don't), use inner_size instead.
845 fn outer_size(&self) -> Result<PhysicalSize<u32>>;
846
847 /// Gets the window's current fullscreen state.
848 fn is_fullscreen(&self) -> Result<bool>;
849
850 /// Gets the window's current minimized state.
851 fn is_minimized(&self) -> Result<bool>;
852
853 /// Gets the window's current maximized state.
854 fn is_maximized(&self) -> Result<bool>;
855
856 /// Gets the window's current focus state.
857 fn is_focused(&self) -> Result<bool>;
858
859 /// Gets the window's current decoration state.
860 fn is_decorated(&self) -> Result<bool>;
861
862 /// Gets the window's current resizable state.
863 fn is_resizable(&self) -> Result<bool>;
864
865 /// Gets the window's native maximize button state.
866 ///
867 /// ## Platform-specific
868 ///
869 /// - **Linux / iOS / Android:** Unsupported.
870 fn is_maximizable(&self) -> Result<bool>;
871
872 /// Gets the window's native minimize button state.
873 ///
874 /// ## Platform-specific
875 ///
876 /// - **Linux / iOS / Android:** Unsupported.
877 fn is_minimizable(&self) -> Result<bool>;
878
879 /// Gets the window's native close button state.
880 ///
881 /// ## Platform-specific
882 ///
883 /// - **iOS / Android:** Unsupported.
884 fn is_closable(&self) -> Result<bool>;
885
886 /// Gets the window's current visibility state.
887 fn is_visible(&self) -> Result<bool>;
888
889 /// Whether the window is enabled or disable.
890 fn is_enabled(&self) -> Result<bool>;
891
892 /// Gets the window alwaysOnTop flag state.
893 ///
894 /// ## Platform-specific
895 ///
896 /// - **iOS / Android:** Unsupported.
897 fn is_always_on_top(&self) -> Result<bool>;
898
899 /// Gets the window's current title.
900 fn title(&self) -> Result<String>;
901
902 /// Returns the monitor on which the window currently resides.
903 ///
904 /// Returns None if current monitor can't be detected.
905 fn current_monitor(&self) -> Result<Option<Monitor>>;
906
907 /// Returns the primary monitor of the system.
908 ///
909 /// Returns None if it can't identify any monitor as a primary one.
910 fn primary_monitor(&self) -> Result<Option<Monitor>>;
911
912 /// Returns the monitor that contains the given point.
913 fn monitor_from_point(&self, x: f64, y: f64) -> Result<Option<Monitor>>;
914
915 /// Returns the list of all the monitors available on the system.
916 fn available_monitors(&self) -> Result<Vec<Monitor>>;
917
918 /// Returns the GTK application window pointer (`GtkApplicationWindow*`) that is used by this window.
919 ///
920 /// # Ownership
921 ///
922 /// The pointer is *transfer full*: implementations must hand out a strong reference
923 /// (`g_object_ref`, i.e. glib's `to_glib_full`) and the caller is responsible for releasing it
924 /// (`g_object_unref`, i.e. glib's `from_glib_full`). It is never null on success.
925 ///
926 /// The GTK major version of the object is the one the runtime was built against, so callers must
927 /// wrap it with matching bindings - the `tauri` crate selects them through its `gtk3`/`gtk4`
928 /// features, which the runtime crate enables. Runtimes must report that version with
929 /// [`gtk::declare_version`] so a mismatch can be detected instead of reinterpreting the object.
930 ///
931 /// The object may only be used on the main thread.
932 #[cfg(any(
933 target_os = "linux",
934 target_os = "dragonfly",
935 target_os = "freebsd",
936 target_os = "netbsd",
937 target_os = "openbsd"
938 ))]
939 fn gtk_window(&self) -> Result<*mut std::ffi::c_void>;
940
941 /// Returns the vertical GTK box pointer (`GtkBox*`) that is added by default as the sole child of this window.
942 ///
943 /// # Ownership
944 ///
945 /// Same contract as [`WindowDispatch::gtk_window`]: *transfer full*, never null on success, main
946 /// thread only.
947 #[cfg(any(
948 target_os = "linux",
949 target_os = "dragonfly",
950 target_os = "freebsd",
951 target_os = "netbsd",
952 target_os = "openbsd"
953 ))]
954 fn default_vbox(&self) -> Result<*mut std::ffi::c_void>;
955
956 /// Returns the name of the Android activity associated with this window.
957 #[cfg(target_os = "android")]
958 fn activity_name(&self) -> Result<String>;
959
960 /// Returns the identifier of the UIScene tied to this UIWindow.
961 #[cfg(target_os = "ios")]
962 fn scene_identifier(&self) -> Result<String>;
963
964 /// Raw window handle.
965 fn window_handle(
966 &self,
967 ) -> std::result::Result<raw_window_handle::WindowHandle<'_>, raw_window_handle::HandleError>;
968
969 /// Returns the current window theme.
970 fn theme(&self) -> Result<Theme>;
971
972 // SETTERS
973
974 /// Centers the window.
975 fn center(&self) -> Result<()>;
976
977 /// Requests user attention to the window.
978 ///
979 /// Providing `None` will unset the request for user attention.
980 fn request_user_attention(&self, request_type: Option<UserAttentionType>) -> Result<()>;
981
982 /// Create a new window.
983 fn create_window<F: Fn(RawWindow) + Send + 'static>(
984 &mut self,
985 pending: PendingWindow<T, Self::Runtime>,
986 after_window_creation: Option<F>,
987 ) -> Result<DetachedWindow<T, Self::Runtime>>;
988
989 /// Create a new webview.
990 fn create_webview(
991 &mut self,
992 pending: PendingWebview<T, Self::Runtime>,
993 ) -> Result<DetachedWebview<T, Self::Runtime>>;
994
995 /// Updates the window resizable flag.
996 fn set_resizable(&self, resizable: bool) -> Result<()>;
997
998 /// Enable or disable the window.
999 ///
1000 /// ## Platform-specific
1001 ///
1002 /// - **Android / iOS**: Unsupported.
1003 fn set_enabled(&self, enabled: bool) -> Result<()>;
1004
1005 /// Updates the window's native maximize button state.
1006 ///
1007 /// ## Platform-specific
1008 ///
1009 /// - **macOS:** Disables the "zoom" button in the window titlebar, which is also used to enter fullscreen mode.
1010 /// - **Linux / iOS / Android:** Unsupported.
1011 fn set_maximizable(&self, maximizable: bool) -> Result<()>;
1012
1013 /// Updates the window's native minimize button state.
1014 ///
1015 /// ## Platform-specific
1016 ///
1017 /// - **Linux / iOS / Android:** Unsupported.
1018 fn set_minimizable(&self, minimizable: bool) -> Result<()>;
1019
1020 /// Updates the window's native close button state.
1021 ///
1022 /// ## Platform-specific
1023 ///
1024 /// - **Linux:** "GTK+ will do its best to convince the window manager not to show a close button.
1025 /// Depending on the system, this function may not have any effect when called on a window that is already visible"
1026 /// - **iOS / Android:** Unsupported.
1027 fn set_closable(&self, closable: bool) -> Result<()>;
1028
1029 /// Updates the window title.
1030 fn set_title<S: Into<String>>(&self, title: S) -> Result<()>;
1031
1032 /// Maximizes the window.
1033 fn maximize(&self) -> Result<()>;
1034
1035 /// Unmaximizes the window.
1036 fn unmaximize(&self) -> Result<()>;
1037
1038 /// Minimizes the window.
1039 fn minimize(&self) -> Result<()>;
1040
1041 /// Unminimizes the window.
1042 fn unminimize(&self) -> Result<()>;
1043
1044 /// Shows the window.
1045 fn show(&self) -> Result<()>;
1046
1047 /// Hides the window.
1048 fn hide(&self) -> Result<()>;
1049
1050 /// Closes the window.
1051 fn close(&self) -> Result<()>;
1052
1053 /// Destroys the window.
1054 fn destroy(&self) -> Result<()>;
1055
1056 /// Updates the decorations flag.
1057 fn set_decorations(&self, decorations: bool) -> Result<()>;
1058
1059 /// Updates the shadow flag.
1060 fn set_shadow(&self, enable: bool) -> Result<()>;
1061
1062 /// Updates the window alwaysOnBottom flag.
1063 fn set_always_on_bottom(&self, always_on_bottom: bool) -> Result<()>;
1064
1065 /// Updates the window alwaysOnTop flag.
1066 fn set_always_on_top(&self, always_on_top: bool) -> Result<()>;
1067
1068 /// Updates the window visibleOnAllWorkspaces flag.
1069 fn set_visible_on_all_workspaces(&self, visible_on_all_workspaces: bool) -> Result<()>;
1070
1071 /// Set the window background.
1072 fn set_background_color(&self, color: Option<Color>) -> Result<()>;
1073
1074 /// Prevents the window contents from being captured by other apps.
1075 fn set_content_protected(&self, protected: bool) -> Result<()>;
1076
1077 /// Resizes the window.
1078 fn set_size(&self, size: Size) -> Result<()>;
1079
1080 /// Updates the window min inner size.
1081 fn set_min_size(&self, size: Option<Size>) -> Result<()>;
1082
1083 /// Updates the window max inner size.
1084 fn set_max_size(&self, size: Option<Size>) -> Result<()>;
1085
1086 /// Sets this window's minimum inner width.
1087 fn set_size_constraints(&self, constraints: WindowSizeConstraints) -> Result<()>;
1088
1089 /// Updates the window position.
1090 fn set_position(&self, position: Position) -> Result<()>;
1091
1092 /// Updates the window fullscreen state.
1093 fn set_fullscreen(&self, fullscreen: bool) -> Result<()>;
1094
1095 /// Sets the window as fullscreen on the monitor that contains the given physical position.
1096 ///
1097 /// Does nothing if no monitor contains the position.
1098 fn set_fullscreen_on_monitor(&self, position: PhysicalPosition<f64>) -> Result<()>;
1099
1100 #[cfg(target_os = "macos")]
1101 fn set_simple_fullscreen(&self, enable: bool) -> Result<()>;
1102
1103 /// Bring the window to front and focus.
1104 fn set_focus(&self) -> Result<()>;
1105
1106 /// Sets whether the window can be focused.
1107 fn set_focusable(&self, focusable: bool) -> Result<()>;
1108
1109 /// Updates the window icon.
1110 fn set_icon(&self, icon: Icon) -> Result<()>;
1111
1112 /// Whether to hide the window icon from the taskbar or not.
1113 fn set_skip_taskbar(&self, skip: bool) -> Result<()>;
1114
1115 /// Grabs the cursor, preventing it from leaving the window.
1116 ///
1117 /// There's no guarantee that the cursor will be hidden. You should
1118 /// hide it by yourself if you want so.
1119 fn set_cursor_grab(&self, grab: bool) -> Result<()>;
1120
1121 /// Modifies the cursor's visibility.
1122 ///
1123 /// If `false`, this will hide the cursor. If `true`, this will show the cursor.
1124 fn set_cursor_visible(&self, visible: bool) -> Result<()>;
1125
1126 // Modifies the cursor icon of the window.
1127 fn set_cursor_icon(&self, icon: CursorIcon) -> Result<()>;
1128
1129 /// Changes the position of the cursor in window coordinates.
1130 fn set_cursor_position<Pos: Into<Position>>(&self, position: Pos) -> Result<()>;
1131
1132 /// Ignores the window cursor events.
1133 fn set_ignore_cursor_events(&self, ignore: bool) -> Result<()>;
1134
1135 /// Starts dragging the window.
1136 fn start_dragging(&self) -> Result<()>;
1137
1138 /// Starts resize-dragging the window.
1139 fn start_resize_dragging(&self, direction: ResizeDirection) -> Result<()>;
1140
1141 /// Sets the badge count on the taskbar
1142 /// The badge count appears as a whole for the application
1143 /// Using `0` or using `None` will remove the badge
1144 ///
1145 /// ## Platform-specific
1146 /// - **Windows:** Unsupported, use [`WindowDispatch::set_overlay_icon`] instead.
1147 /// - **Android:** Unsupported.
1148 /// - **iOS:** iOS expects i32, if the value is larger than i32::MAX, it will be clamped to i32::MAX.
1149 fn set_badge_count(&self, count: Option<i64>, desktop_filename: Option<String>) -> Result<()>;
1150
1151 /// Sets the badge count on the taskbar **macOS only**. Using `None` will remove the badge
1152 fn set_badge_label(&self, label: Option<String>) -> Result<()>;
1153
1154 /// Sets the overlay icon on the taskbar **Windows only**. Using `None` will remove the icon
1155 ///
1156 /// The overlay icon can be unique for each window.
1157 fn set_overlay_icon(&self, icon: Option<Icon>) -> Result<()>;
1158
1159 /// Sets the taskbar progress state.
1160 ///
1161 /// ## Platform-specific
1162 ///
1163 /// - **Linux / macOS**: Progress bar is app-wide and not specific to this window. Only supported desktop environments with `libunity` (e.g. GNOME).
1164 /// - **iOS / Android:** Unsupported.
1165 fn set_progress_bar(&self, progress_state: ProgressBarState) -> Result<()>;
1166
1167 /// Sets the title bar style. Available on macOS only.
1168 ///
1169 /// ## Platform-specific
1170 ///
1171 /// - **Linux / Windows / iOS / Android:** Unsupported.
1172 fn set_title_bar_style(&self, style: tauri_utils::TitleBarStyle) -> Result<()>;
1173
1174 /// Change the position of the window controls. Available on macOS only.
1175 ///
1176 /// Requires titleBarStyle: Overlay and decorations: true.
1177 ///
1178 /// ## Platform-specific
1179 ///
1180 /// - **Linux / Windows / iOS / Android:** Unsupported.
1181 fn set_traffic_light_position(&self, position: Position) -> Result<()>;
1182
1183 /// Sets the theme for this window.
1184 ///
1185 /// ## Platform-specific
1186 ///
1187 /// - **Linux / macOS**: Theme is app-wide and not specific to this window.
1188 /// - **iOS / Android:** Unsupported.
1189 fn set_theme(&self, theme: Option<Theme>) -> Result<()>;
1190}