Trait tauri::Manager

source ·
pub trait Manager<R: Runtime>: ManagerBase<R> {
Show 24 methods // Required method fn resources_table(&self) -> MutexGuard<'_, ResourceTable>; // Provided methods fn app_handle(&self) -> &AppHandle<R> { ... } fn config(&self) -> &Config { ... } fn package_info(&self) -> &PackageInfo { ... } fn listen_any<F>(&self, event: impl Into<String>, handler: F) -> EventId where F: Fn(Event) + Send + 'static { ... } fn unlisten(&self, id: EventId) { ... } fn once_any<F>(&self, event: impl Into<String>, handler: F) -> EventId where F: FnOnce(Event) + Send + 'static { ... } fn emit<S: Serialize + Clone>(&self, event: &str, payload: S) -> Result<()> { ... } fn emit_to<I, S>(&self, target: I, event: &str, payload: S) -> Result<()> where I: Into<EventTarget>, S: Serialize + Clone { ... } fn emit_filter<S, F>( &self, event: &str, payload: S, filter: F ) -> Result<()> where S: Serialize + Clone, F: Fn(&EventTarget) -> bool { ... } fn get_window(&self, label: &str) -> Option<Window<R>> { ... } fn get_focused_window(&self) -> Option<Window<R>> { ... } fn windows(&self) -> HashMap<String, Window<R>> { ... } fn get_webview(&self, label: &str) -> Option<Webview<R>> { ... } fn webviews(&self) -> HashMap<String, Webview<R>> { ... } fn get_webview_window(&self, label: &str) -> Option<WebviewWindow<R>> { ... } fn webview_windows(&self) -> HashMap<String, WebviewWindow<R>> { ... } fn manage<T>(&self, state: T) -> bool where T: Send + Sync + 'static { ... } fn state<T>(&self) -> State<'_, T> where T: Send + Sync + 'static { ... } fn try_state<T>(&self) -> Option<State<'_, T>> where T: Send + Sync + 'static { ... } fn env(&self) -> Env { ... } fn asset_protocol_scope(&self) -> Scope { ... } fn path(&self) -> &PathResolver<R> { ... } fn add_capability(&self, capability: impl RuntimeCapability) -> Result<()> { ... }
}
Expand description

Manages a running application.

Required Methods§

source

fn resources_table(&self) -> MutexGuard<'_, ResourceTable>

Get a reference to the resources table of this manager.

Provided Methods§

source

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

The application handle associated with this manager.

source

fn config(&self) -> &Config

The Config the manager was created with.

source

fn package_info(&self) -> &PackageInfo

The PackageInfo the manager was created with.

source

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

Listen to an emitted event to any target.

§Examples
use tauri::Manager;

#[tauri::command]
fn synchronize(window: tauri::Window) {
  // emits the synchronized event to all windows
  window.emit("synchronized", ());
}

tauri::Builder::default()
  .setup(|app| {
    app.listen_any("synchronized", |event| {
      println!("app is in sync");
    });
    Ok(())
  })
  .invoke_handler(tauri::generate_handler![synchronize]);
source

fn unlisten(&self, id: EventId)

Remove an event listener.

§Examples
use tauri::Manager;

tauri::Builder::default()
  .setup(|app| {
    let handle = app.handle().clone();
    let handler = app.listen_any("ready", move |event| {
      println!("app is ready");

      // we no longer need to listen to the event
      // we also could have used `app.once_global` instead
      handle.unlisten(event.id());
    });

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


    Ok(())
  });
source

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

Listens once to an emitted event to any target .

See Self::listen_any for more information.

source

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

Emits an event to all targets.

§Examples
use tauri::Manager;

#[tauri::command]
fn synchronize(app: tauri::AppHandle) {
  // emits the synchronized event to all webviews
  app.emit("synchronized", ());
}
source

fn emit_to<I, S>(&self, target: I, event: &str, payload: S) -> Result<()>
where I: Into<EventTarget>, S: Serialize + Clone,

Emits an event to all targets matching the given target.

§Examples
use tauri::{Manager, EventTarget};

#[tauri::command]
fn download(app: tauri::AppHandle) {
  for i in 1..100 {
    std::thread::sleep(std::time::Duration::from_millis(150));
    // emit a download progress event to all listeners
    app.emit_to(EventTarget::any(), "download-progress", i);
    // emit an event to listeners that used App::listen or AppHandle::listen
    app.emit_to(EventTarget::app(), "download-progress", i);
    // emit an event to any webview/window/webviewWindow matching the given label
    app.emit_to("updater", "download-progress", i); // similar to using EventTarget::labeled
    app.emit_to(EventTarget::labeled("updater"), "download-progress", i);
    // emit an event to listeners that used WebviewWindow::listen
    app.emit_to(EventTarget::webview_window("updater"), "download-progress", i);
  }
}
source

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

Emits an event to all targets based on the given filter.

§Examples
use tauri::{Manager, EventTarget};

#[tauri::command]
fn download(app: tauri::AppHandle) {
  for i in 1..100 {
    std::thread::sleep(std::time::Duration::from_millis(150));
    // emit a download progress event to the updater window
    app.emit_filter("download-progress", i, |t| match t {
      EventTarget::WebviewWindow { label } => label == "main",
      _ => false,
    });
  }
}
source

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

Available on crate feature unstable only.

Fetch a single window from the manager.

source

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

Available on crate feature unstable only.

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

source

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

Available on crate feature unstable only.

Fetch all managed windows.

source

fn get_webview(&self, label: &str) -> Option<Webview<R>>

Available on crate feature unstable only.

Fetch a single webview from the manager.

source

fn webviews(&self) -> HashMap<String, Webview<R>>

Available on crate feature unstable only.

Fetch all managed webviews.

source

fn get_webview_window(&self, label: &str) -> Option<WebviewWindow<R>>

Fetch a single webview window from the manager.

source

fn webview_windows(&self) -> HashMap<String, WebviewWindow<R>>

Fetch all managed webview windows.

source

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

Add state to the state managed by the application.

If the state for the T type has previously been set, the state is unchanged and false is returned. Otherwise true is returned.

Managed state can be retrieved by any command handler via the State guard. In particular, if a value of type T is managed by Tauri, adding State<T> to the list of arguments in a command handler instructs Tauri to retrieve the managed value. Additionally, state can be used to retrieve the value manually.

§Mutability

Since the managed state is global and must be Send + Sync, mutations can only happen through interior mutability:

use std::{collections::HashMap, sync::Mutex};
use tauri::State;
// here we use Mutex to achieve interior mutability
struct Storage {
  store: Mutex<HashMap<u64, String>>,
}
struct Connection;
struct DbConnection {
  db: Mutex<Option<Connection>>,
}

#[tauri::command]
fn connect(connection: State<DbConnection>) {
  // initialize the connection, mutating the state with interior mutability
  *connection.db.lock().unwrap() = Some(Connection {});
}

#[tauri::command]
fn storage_insert(key: u64, value: String, storage: State<Storage>) {
  // mutate the storage behind the Mutex
  storage.store.lock().unwrap().insert(key, value);
}

tauri::Builder::default()
  .manage(Storage { store: Default::default() })
  .manage(DbConnection { db: Default::default() })
  .invoke_handler(tauri::generate_handler![connect, storage_insert])
  // on an actual app, remove the string argument
  .run(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
  .expect("error while running tauri application");
§Examples
use tauri::{Manager, State};

struct MyInt(isize);
struct MyString(String);

#[tauri::command]
fn int_command(state: State<MyInt>) -> String {
    format!("The stateful int is: {}", state.0)
}

#[tauri::command]
fn string_command<'r>(state: State<'r, MyString>) {
    println!("state: {}", state.inner().0);
}

tauri::Builder::default()
  .setup(|app| {
    app.manage(MyInt(0));
    app.manage(MyString("tauri".into()));
    // `MyInt` is already managed, so `manage()` returns false
    assert!(!app.manage(MyInt(1)));
    // read the `MyInt` managed state with the turbofish syntax
    let int = app.state::<MyInt>();
    assert_eq!(int.0, 0);
    // read the `MyString` managed state with the `State` guard
    let val: State<MyString> = app.state();
    assert_eq!(val.0, "tauri");
    Ok(())
  })
  .invoke_handler(tauri::generate_handler![int_command, string_command])
  // on an actual app, remove the string argument
  .run(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
  .expect("error while running tauri application");
source

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

Retrieves the managed state for the type T.

§Panics

Panics if the state for the type T has not been previously managed. Use try_state for a non-panicking version.

source

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

Attempts to retrieve the managed state for the type T.

Returns Some if the state has previously been managed. Otherwise returns None.

source

fn env(&self) -> Env

Gets the managed Env.

source

fn asset_protocol_scope(&self) -> Scope

Gets the scope for the asset protocol.

source

fn path(&self) -> &PathResolver<R>

The path resolver.

source

fn add_capability(&self, capability: impl RuntimeCapability) -> Result<()>

Adds a capability to the app.

§Examples
use tauri::Manager;

tauri::Builder::default()
  .setup(|app| {
    #[cfg(feature = "beta")]
    app.add_capability(include_str!("../capabilities/beta.json"));
    Ok(())
  });

Object Safety§

This trait is not object safe.

Implementors§

source§

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

source§

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

source§

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

source§

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

source§

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