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