Struct tauri::window::Window

source ·
pub struct Window<R: Runtime = Wry> { /* private fields */ }
Expand description

A webview window managed by Tauri.

This type also implements Manager which allows you to manage other windows attached to the same application.

Implementations§

source§

impl Window<Wry>

APIs specific to the wry runtime.

source

pub fn with_webview<F: FnOnce(PlatformWebview) + Send + 'static>( &self, f: F ) -> Result<()>

Available on crate feature wry and desktop only.

Executes a closure, providing it with the webview handle that is specific to the current platform.

The closure is executed on the main thread.

§Examples
#[cfg(target_os = "macos")]
#[macro_use]
extern crate objc;
use tauri::Manager;

fn main() {
  tauri::Builder::default()
    .setup(|app| {
      let main_window = app.get_window("main").unwrap();
      main_window.with_webview(|webview| {
        #[cfg(target_os = "linux")]
        {
          // see https://docs.rs/webkit2gtk/0.18.2/webkit2gtk/struct.WebView.html
          // and https://docs.rs/webkit2gtk/0.18.2/webkit2gtk/trait.WebViewExt.html
          use webkit2gtk::traits::WebViewExt;
          webview.inner().set_zoom_level(4.);
        }

        #[cfg(windows)]
        unsafe {
          // see https://docs.rs/webview2-com/0.19.1/webview2_com/Microsoft/Web/WebView2/Win32/struct.ICoreWebView2Controller.html
          webview.controller().SetZoomFactor(4.).unwrap();
        }

        #[cfg(target_os = "macos")]
        unsafe {
          let () = msg_send![webview.inner(), setPageZoom: 4.];
          let () = msg_send![webview.controller(), removeAllUserScripts];
          let bg_color: cocoa::base::id = msg_send![class!(NSColor), colorWithDeviceRed:0.5 green:0.2 blue:0.4 alpha:1.];
          let () = msg_send![webview.ns_window(), setBackgroundColor: bg_color];
        }
      });
      Ok(())
  });
}
source§

impl<R: Runtime> Window<R>

Base window functions.

source

pub fn builder<'a, M: Manager<R>, L: Into<String>>( manager: &'a M, label: L, url: WindowUrl ) -> WindowBuilder<'a, R>

Initializes a webview window builder with the given window label and URL to load on the webview.

Data URLs are only supported with the window-data-url feature flag.

source

pub fn run_on_main_thread<F: FnOnce() + Send + 'static>( &self, f: F ) -> Result<()>

Runs the given closure on the main thread.

source

pub fn label(&self) -> &str

The label of this window.

source

pub fn on_window_event<F: Fn(&WindowEvent) + Send + 'static>(&self, f: F)

Registers a window event listener.

source

pub fn on_menu_event<F: Fn(MenuEvent) + Send + 'static>(&self, f: F) -> Uuid

Registers a menu event listener.

source§

impl<R: Runtime> Window<R>

Window getters.

source

pub fn menu_handle(&self) -> MenuHandle<R>

Gets a handle to the window menu.

source

pub fn scale_factor(&self) -> Result<f64>

Returns the scale factor that can be used to map logical pixels to physical pixels, and vice versa.

source

pub fn inner_position(&self) -> Result<PhysicalPosition<i32>>

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.

source

pub fn outer_position(&self) -> Result<PhysicalPosition<i32>>

Returns the position of the top-left hand corner of the window relative to the top-left hand corner of the desktop.

source

pub fn inner_size(&self) -> Result<PhysicalSize<u32>>

Returns the physical size of the window’s client area.

The client area is the content of the window, excluding the title bar and borders.

source

pub fn outer_size(&self) -> Result<PhysicalSize<u32>>

Returns the physical size of the entire window.

These dimensions include the title bar and borders. If you don’t want that (and you usually don’t), use inner_size instead.

source

pub fn is_fullscreen(&self) -> Result<bool>

Gets the window’s current fullscreen state.

source

pub fn is_minimized(&self) -> Result<bool>

Gets the window’s current minimized state.

source

pub fn is_maximized(&self) -> Result<bool>

Gets the window’s current maximized state.

source

pub fn is_focused(&self) -> Result<bool>

Gets the window’s current focus state.

source

pub fn is_decorated(&self) -> Result<bool>

Gets the window’s current decoration state.

source

pub fn is_resizable(&self) -> Result<bool>

Gets the window’s current resizable state.

source

pub fn is_maximizable(&self) -> Result<bool>

Gets the window’s native maximize button state

§Platform-specific
  • Linux / iOS / Android: Unsupported.
source

pub fn is_minimizable(&self) -> Result<bool>

Gets the window’s native minimize button state

§Platform-specific
  • Linux / iOS / Android: Unsupported.
source

pub fn is_closable(&self) -> Result<bool>

Gets the window’s native close button state

§Platform-specific
  • Linux / iOS / Android: Unsupported.
source

pub fn is_visible(&self) -> Result<bool>

Gets the window’s current visibility state.

source

pub fn title(&self) -> Result<String>

Gets the window’s current title.

source

pub fn current_monitor(&self) -> Result<Option<Monitor>>

Returns the monitor on which the window currently resides.

Returns None if current monitor can’t be detected.

source

pub fn primary_monitor(&self) -> Result<Option<Monitor>>

Returns the primary monitor of the system.

Returns None if it can’t identify any monitor as a primary one.

source

pub fn available_monitors(&self) -> Result<Vec<Monitor>>

Returns the list of all the monitors available on the system.

source

pub fn gtk_window(&self) -> Result<ApplicationWindow>

Returns the ApplicationWindow from gtk crate that is used by this window.

Note that this can only be used on the main thread.

source

pub fn theme(&self) -> Result<Theme>

Returns the current window theme.

§Platform-specific
  • macOS: Only supported on macOS 10.14+.
source§

impl<R: Runtime> Window<R>

Window setters and actions.

source

pub fn center(&self) -> Result<()>

Centers the window.

source

pub fn request_user_attention( &self, request_type: Option<UserAttentionType> ) -> Result<()>

Requests user attention to the window, this has no effect if the application is already focused. How requesting for user attention manifests is platform dependent, see UserAttentionType for details.

Providing None will unset the request for user attention. Unsetting the request for user attention might not be done automatically by the WM when the window receives input.

§Platform-specific
  • macOS: None has no effect.
  • Linux: Urgency levels have the same effect.
source

pub fn print(&self) -> Result<()>

Opens the dialog to prints the contents of the webview. Currently only supported on macOS on wry. window.print() works on all platforms.

source

pub fn set_resizable(&self, resizable: bool) -> Result<()>

Determines if this window should be resizable. When resizable is set to false, native window’s maximize button is automatically disabled.

source

pub fn set_maximizable(&self, maximizable: bool) -> Result<()>

Determines if this window’s native maximize button should be enabled. If resizable is set to false, this setting is ignored.

§Platform-specific
  • macOS: Disables the “zoom” button in the window titlebar, which is also used to enter fullscreen mode.
  • Linux / iOS / Android: Unsupported.
source

pub fn set_minimizable(&self, minimizable: bool) -> Result<()>

Determines if this window’s native minize button should be enabled.

§Platform-specific
  • Linux / iOS / Android: Unsupported.
source

pub fn set_closable(&self, closable: bool) -> Result<()>

Determines if this window’s native close button should be enabled.

§Platform-specific
  • Linux: “GTK+ will do its best to convince the window manager not to show a close button. Depending on the system, this function may not have any effect when called on a window that is already visible”
  • iOS / Android: Unsupported.
source

pub fn set_title(&self, title: &str) -> Result<()>

Set this window’s title.

source

pub fn maximize(&self) -> Result<()>

Maximizes this window.

source

pub fn unmaximize(&self) -> Result<()>

Un-maximizes this window.

source

pub fn minimize(&self) -> Result<()>

Minimizes this window.

source

pub fn unminimize(&self) -> Result<()>

Un-minimizes this window.

source

pub fn show(&self) -> Result<()>

Show this window.

source

pub fn hide(&self) -> Result<()>

Hide this window.

source

pub fn close(&self) -> Result<()>

Closes this window.

§Panics
  • Panics if the event loop is not running yet, usually when called on the setup closure.
  • Panics when called on the main thread, usually on the run closure.

You can spawn a task to use the API using crate::async_runtime::spawn or std::thread::spawn to prevent the panic.

source

pub fn set_decorations(&self, decorations: bool) -> Result<()>

Determines if this window should be decorated.

source

pub fn set_always_on_top(&self, always_on_top: bool) -> Result<()>

Determines if this window should always be on top of other windows.

source

pub fn set_content_protected(&self, protected: bool) -> Result<()>

Prevents the window contents from being captured by other apps.

source

pub fn set_size<S: Into<Size>>(&self, size: S) -> Result<()>

Resizes this window.

source

pub fn set_min_size<S: Into<Size>>(&self, size: Option<S>) -> Result<()>

Sets this window’s minimum size.

source

pub fn set_max_size<S: Into<Size>>(&self, size: Option<S>) -> Result<()>

Sets this window’s maximum size.

source

pub fn set_position<Pos: Into<Position>>(&self, position: Pos) -> Result<()>

Sets this window’s position.

source

pub fn set_fullscreen(&self, fullscreen: bool) -> Result<()>

Determines if this window should be fullscreen.

source

pub fn set_focus(&self) -> Result<()>

Bring the window to front and focus.

source

pub fn set_icon(&self, icon: Icon) -> Result<()>

Sets this window’ icon.

source

pub fn set_skip_taskbar(&self, skip: bool) -> Result<()>

Whether to hide the window icon from the taskbar or not.

§Platform-specific
  • macOS: Unsupported.
source

pub fn set_cursor_grab(&self, grab: bool) -> Result<()>

Grabs the cursor, preventing it from leaving the window.

There’s no guarantee that the cursor will be hidden. You should hide it by yourself if you want so.

§Platform-specific
  • Linux: Unsupported.
  • macOS: This locks the cursor in a fixed location, which looks visually awkward.
source

pub fn set_cursor_visible(&self, visible: bool) -> Result<()>

Modifies the cursor’s visibility.

If false, this will hide the cursor. If true, this will show the cursor.

§Platform-specific
  • Windows: The cursor is only hidden within the confines of the window.
  • macOS: The cursor is hidden as long as the window has input focus, even if the cursor is outside of the window.
source

pub fn set_cursor_icon(&self, icon: CursorIcon) -> Result<()>

Modifies the cursor icon of the window.

source

pub fn set_cursor_position<Pos: Into<Position>>( &self, position: Pos ) -> Result<()>

Changes the position of the cursor in window coordinates.

source

pub fn set_ignore_cursor_events(&self, ignore: bool) -> Result<()>

Ignores the window cursor events.

source

pub fn start_dragging(&self) -> Result<()>

Starts dragging the window.

source§

impl<R: Runtime> Window<R>

Webview APIs.

source

pub fn url(&self) -> Url

Returns the current url of the webview.

source

pub fn on_message(self, payload: InvokePayload) -> Result<()>

Handles this window receiving an InvokeMessage.

source

pub fn eval(&self, js: &str) -> Result<()>

Evaluates JavaScript on this window.

source

pub fn open_devtools(&self)

Available on debug-assertions enabled or crate feature devtools only.

Opens the developer tools window (Web Inspector). The devtools is only enabled on debug builds or with the devtools feature flag.

§Platform-specific
  • macOS: Only supported on macOS 10.15+. This is a private API on macOS, so you cannot use this if your application will be published on the App Store.
§Examples
use tauri::Manager;
tauri::Builder::default()
  .setup(|app| {
    #[cfg(debug_assertions)]
    app.get_window("main").unwrap().open_devtools();
    Ok(())
  });
source

pub fn close_devtools(&self)

Available on debug-assertions enabled or crate feature devtools only.

Closes the developer tools window (Web Inspector). The devtools is only enabled on debug builds or with the devtools feature flag.

§Platform-specific
  • macOS: Only supported on macOS 10.15+. This is a private API on macOS, so you cannot use this if your application will be published on the App Store.
  • Windows: Unsupported.
§Examples
use tauri::Manager;
tauri::Builder::default()
  .setup(|app| {
    #[cfg(debug_assertions)]
    {
      let window = app.get_window("main").unwrap();
      window.open_devtools();
      std::thread::spawn(move || {
        std::thread::sleep(std::time::Duration::from_secs(10));
        window.close_devtools();
      });
    }
    Ok(())
  });
source

pub fn is_devtools_open(&self) -> bool

Available on debug-assertions enabled or crate feature devtools only.

Checks if the developer tools window (Web Inspector) is opened. The devtools is only enabled on debug builds or with the devtools feature flag.

§Platform-specific
  • macOS: Only supported on macOS 10.15+. This is a private API on macOS, so you cannot use this if your application will be published on the App Store.
  • Windows: Unsupported.
§Examples
use tauri::Manager;
tauri::Builder::default()
  .setup(|app| {
    #[cfg(debug_assertions)]
    {
      let window = app.get_window("main").unwrap();
      if !window.is_devtools_open() {
        window.open_devtools();
      }
    }
    Ok(())
  });
source§

impl<R: Runtime> Window<R>

Event system APIs.

source

pub fn emit_and_trigger<S: Serialize + Clone>( &self, event: &str, payload: S ) -> Result<()>

Emits an event to both the JavaScript and the Rust listeners.

This API is a combination of Self::trigger and Self::emit.

§Examples
use tauri::Manager;

#[tauri::command]
fn download(window: tauri::Window) {
  window.emit_and_trigger("download-started", ());

  for i in 1..100 {
    std::thread::sleep(std::time::Duration::from_millis(150));
    // emit a download progress event to all listeners
    window.emit_and_trigger("download-progress", i);
  }
}
source

pub fn emit<S: Serialize + Clone>(&self, event: &str, payload: S) -> Result<()>

Emits an event to the JavaScript listeners on the current window or globally.

§Examples
use tauri::Manager;

#[tauri::command]
fn download(window: tauri::Window) {
  for i in 1..100 {
    std::thread::sleep(std::time::Duration::from_millis(150));
    // emit a download progress event to all listeners registed in the webview
    window.emit("download-progress", i);
  }
}
source

pub fn listen<F>(&self, event: impl Into<String>, handler: F) -> EventHandler
where F: Fn(Event) + Send + 'static,

Listen to an event on this window.

This listener only receives events that are triggered using the trigger and emit_and_trigger methods or the appWindow.emit function from the @tauri-apps/api window module.

§Examples
use tauri::Manager;

tauri::Builder::default()
  .setup(|app| {
    let window = app.get_window("main").unwrap();
    window.listen("component-loaded", move |event| {
      println!("window just loaded a component");
    });

    Ok(())
  });
source

pub fn unlisten(&self, handler_id: EventHandler)

Unlisten to an event on this window.

§Examples
use tauri::Manager;

tauri::Builder::default()
  .setup(|app| {
    let window = app.get_window("main").unwrap();
    let window_ = window.clone();
    let handler = window.listen("component-loaded", move |event| {
      println!("window just loaded a component");

      // we no longer need to listen to the event
      // we also could have used `window.once` instead
      window_.unlisten(event.id());
    });

    // stop listening to the event when you do not need it anymore
    window.unlisten(handler);


    Ok(())
  });
source

pub fn once<F>(&self, event: impl Into<String>, handler: F) -> EventHandler
where F: FnOnce(Event) + Send + 'static,

Listen to an event on this window a single time.

See Self::listen for more information.

source

pub fn trigger(&self, event: &str, data: Option<String>)

Triggers an event to the Rust listeners on this window or global listeners.

§Examples
use tauri::Manager;

#[tauri::command]
fn download(window: tauri::Window) {
  for i in 1..100 {
    std::thread::sleep(std::time::Duration::from_millis(150));
    // emit a download progress event to all listeners registed on `window` in Rust
    window.trigger("download-progress", Some(i.to_string()));
  }
}

Trait Implementations§

source§

impl<R: Runtime> Clone for Window<R>

source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<'de, R: Runtime> CommandArg<'de, R> for Window<R>

source§

fn from_command(command: CommandItem<'de, R>) -> Result<Self, InvokeError>

Grabs the Window from the CommandItem. This will never fail.

source§

impl<R: Debug + Runtime> Debug for Window<R>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<R: Runtime> HasRawWindowHandle for Window<R>

source§

impl<R: Runtime> Hash for Window<R>

source§

fn hash<H: Hasher>(&self, state: &mut H)

Only use the Window’s label to represent its hash.

1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl<R: Runtime> Manager<R> for Window<R>

source§

fn emit_to<S: Serialize + Clone>( &self, label: &str, event: &str, payload: S ) -> Result<()>

Emits an event to the window with the specified label. Read more
source§

fn emit_all<S: Serialize + Clone>(&self, event: &str, payload: S) -> Result<()>

Emits an event to all windows. Read more
source§

fn app_handle(&self) -> AppHandle<R>

The application handle associated with this manager.
source§

fn config(&self) -> Arc<Config>

The Config the manager was created with.
source§

fn emit_filter<S, F>(&self, event: &str, payload: S, filter: F) -> Result<()>
where S: Serialize + Clone, F: Fn(&Window<R>) -> bool,

Emits an event to windows matching the filter critera. Read more
source§

fn listen_global<F>(&self, event: impl Into<String>, handler: F) -> EventHandler
where F: Fn(Event) + Send + 'static,

Listen to a event triggered on any window (Window::trigger or Window::emit_and_trigger) or with Self::trigger_global. Read more
source§

fn once_global<F>(&self, event: impl Into<String>, handler: F) -> EventHandler
where F: FnOnce(Event) + Send + 'static,

Listen to a global event only once. Read more
source§

fn trigger_global(&self, event: &str, data: Option<String>)

Trigger a global event to Rust listeners. To send the events to the webview, see Self::emit_all and Self::emit_to. To trigger listeners registed on an specific window, see Window::trigger. To trigger all listeners, see Window::emit_and_trigger. Read more
source§

fn unlisten(&self, handler_id: EventHandler)

Remove an event listener. Read more
source§

fn get_window(&self, label: &str) -> Option<Window<R>>

Fetch a single window from the manager.
source§

fn get_focused_window(&self) -> Option<Window<R>>

Fetch the focused window. Returns None if there is not any focused window.
source§

fn windows(&self) -> HashMap<String, Window<R>>

Fetch all managed windows.
source§

fn manage<T>(&self, state: T) -> bool
where T: Send + Sync + 'static,

Add state to the state managed by the application. Read more
source§

fn state<T>(&self) -> State<'_, T>
where T: Send + Sync + 'static,

Retrieves the managed state for the type T. Read more
source§

fn try_state<T>(&self) -> Option<State<'_, T>>
where T: Send + Sync + 'static,

Attempts to retrieve the managed state for the type T. Read more
source§

fn env(&self) -> Env

Gets the managed Env.
source§

fn fs_scope(&self) -> FsScope

Gets the scope for the filesystem APIs.
source§

fn ipc_scope(&self) -> IpcScope

Gets the scope for the IPC.
source§

fn asset_protocol_scope(&self) -> FsScope

Gets the scope for the asset protocol.
source§

fn shell_scope(&self) -> ShellScope

Gets the scope for the shell execute APIs.
source§

impl<R: Runtime> PartialEq for Window<R>

source§

fn eq(&self, other: &Self) -> bool

Only use the Window’s label to compare equality.

1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<R: Runtime> Eq for Window<R>

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> Pointable for T

source§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

source§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

impl<T> UserEvent for T
where T: Debug + Clone + Send + 'static,