tauri

Struct Builder

source
pub struct Builder<R: Runtime> { /* private fields */ }
Expand description

Builds a Tauri application.

§Examples

tauri::Builder::default()
  // 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");

Implementations§

source§

impl<R: Runtime> Builder<R>

source

pub fn new() -> Self

Creates a new App builder.

source

pub fn any_thread(self) -> Self

Available on Windows or Linux only.

Builds a new Tauri application running on any thread, bypassing the main thread requirement.

§Platform-specific
  • macOS: on macOS the application must be executed on the main thread, so this function is not exposed.
source

pub fn invoke_handler<F>(self, invoke_handler: F) -> Self
where F: Fn(Invoke<R>) + Send + Sync + 'static,

Defines the JS message handler callback.

§Examples
#[tauri::command]
fn command_1() -> String {
  return "hello world".to_string();
}
tauri::Builder::default()
  .invoke_handler(tauri::generate_handler![
    command_1,
    // etc...
  ]);
source

pub fn invoke_system<F>( self, initialization_script: String, responder: F, ) -> Self
where F: Fn(Window<R>, InvokeResponse, CallbackFn, CallbackFn) + Send + Sync + 'static,

Defines a custom JS message system.

The responder is a function that will be called when a command has been executed and must send a response to the JS layer.

The initialization_script is a script that initializes window.__TAURI_POST_MESSAGE__. That function must take the message: object argument and send it to the backend.

source

pub fn setup<F>(self, setup: F) -> Self
where F: FnOnce(&mut App<R>) -> Result<(), Box<dyn Error>> + Send + 'static,

Defines the setup hook.

§Examples
use tauri::Manager;
tauri::Builder::default()
  .setup(|app| {
    let main_window = app.get_window("main").unwrap();
     tauri::api::dialog::blocking::message(Some(&main_window), "Hello", "Welcome back!");
    Ok(())
  });
source

pub fn on_page_load<F>(self, on_page_load: F) -> Self
where F: Fn(Window<R>, PageLoadPayload) + Send + Sync + 'static,

Defines the page load hook.

source

pub fn plugin<P: Plugin<R> + 'static>(self, plugin: P) -> Self

Adds a Tauri application plugin.

A plugin is created using the crate::plugin::Builder struct.Check its documentation for more information.

§Examples
mod plugin {
  use tauri::{plugin::{Builder as PluginBuilder, TauriPlugin}, RunEvent, Runtime};

  // this command can be called in the frontend using `invoke('plugin:window|do_something')`.
  #[tauri::command]
  async fn do_something<R: Runtime>(app: tauri::AppHandle<R>, window: tauri::Window<R>) -> Result<(), String> {
    println!("command called");
    Ok(())
  }
  pub fn init<R: Runtime>() -> TauriPlugin<R> {
    PluginBuilder::new("window")
      .setup(|app| {
        // initialize the plugin here
        Ok(())
      })
      .on_event(|app, event| {
        match event {
          RunEvent::Ready => {
            println!("app is ready");
          }
          RunEvent::WindowEvent { label, event, .. } => {
            println!("window {} received an event: {:?}", label, event);
          }
          _ => (),
        }
      })
      .invoke_handler(tauri::generate_handler![do_something])
      .build()
  }
}

tauri::Builder::default()
  .plugin(plugin::init());
source

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

Add state to the state managed by the application.

This method can be called any number of times as long as each call refers to a different T.

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.

§Panics

Panics if state of type T is already being managed.

§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::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()
  .manage(MyInt(10))
  .manage(MyString("Hello, managed state!".to_string()))
  .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

pub fn system_tray(self, system_tray: SystemTray) -> Self

Available on crate feature system-tray only.

Sets the given system tray to be built before the app runs.

Prefer the SystemTray#method.build method to create the tray at runtime instead.

§Examples
use tauri::{CustomMenuItem, SystemTray, SystemTrayMenu};

tauri::Builder::default()
  .system_tray(SystemTray::new().with_menu(
    SystemTrayMenu::new()
      .add_item(CustomMenuItem::new("quit", "Quit"))
      .add_item(CustomMenuItem::new("open", "Open"))
  ));
source

pub fn menu(self, menu: Menu) -> Self

Sets the menu to use on all windows.

§Examples
use tauri::{MenuEntry, Submenu, MenuItem, Menu, CustomMenuItem};

tauri::Builder::default()
  .menu(Menu::with_items([
    MenuEntry::Submenu(Submenu::new(
      "File",
      Menu::with_items([
        MenuItem::CloseWindow.into(),
        #[cfg(target_os = "macos")]
        CustomMenuItem::new("hello", "Hello").into(),
      ]),
    )),
  ]));
source

pub fn enable_macos_default_menu(self, enable: bool) -> Self

Enable or disable the default menu on macOS. Enabled by default.

§Examples
use tauri::{MenuEntry, Submenu, MenuItem, Menu, CustomMenuItem};

tauri::Builder::default()
  .enable_macos_default_menu(false);
source

pub fn on_menu_event<F: Fn(WindowMenuEvent<R>) + Send + Sync + 'static>( self, handler: F, ) -> Self

Registers a menu event handler for all windows.

§Examples
use tauri::{Menu, MenuEntry, Submenu, CustomMenuItem, api, Manager};
tauri::Builder::default()
  .menu(Menu::with_items([
    MenuEntry::Submenu(Submenu::new(
      "File",
      Menu::with_items([
        CustomMenuItem::new("New", "New").into(),
        CustomMenuItem::new("Learn More", "Learn More").into(),
      ]),
    )),
  ]))
  .on_menu_event(|event| {
    match event.menu_item_id() {
      "Learn More" => {
        // open in browser (requires the `shell-open-api` feature)
         api::shell::open(&event.window().shell_scope(), "https://github.com/tauri-apps/tauri".to_string(), None).unwrap();
      }
      id => {
        // do something with other events
        println!("got menu event: {}", id);
      }
    }
  });
source

pub fn on_window_event<F: Fn(GlobalWindowEvent<R>) + Send + Sync + 'static>( self, handler: F, ) -> Self

Registers a window event handler for all windows.

§Examples
tauri::Builder::default()
  .on_window_event(|event| match event.event() {
    tauri::WindowEvent::Focused(focused) => {
      // hide window whenever it loses focus
      if !focused {
        event.window().hide().unwrap();
      }
    }
    _ => {}
  });
source

pub fn on_system_tray_event<F: Fn(&AppHandle<R>, SystemTrayEvent) + Send + Sync + 'static>( self, handler: F, ) -> Self

Available on crate feature system-tray only.

Registers a system tray event handler.

Prefer the SystemTray#method.on_event method when creating a tray at runtime instead.

§Examples
use tauri::{Manager, SystemTrayEvent};
tauri::Builder::default()
  .on_system_tray_event(|app, event| match event {
    // show window with id "main" when the tray is left clicked
    SystemTrayEvent::LeftClick { .. } => {
      let window = app.get_window("main").unwrap();
      window.show().unwrap();
      window.set_focus().unwrap();
    }
    _ => {}
  });
source

pub fn register_uri_scheme_protocol<N: Into<String>, H: Fn(&AppHandle<R>, &HttpRequest) -> Result<HttpResponse, Box<dyn Error>> + Send + Sync + 'static>( self, uri_scheme: N, protocol: H, ) -> Self

Registers a URI scheme protocol available to all webviews. Leverages setURLSchemeHandler on macOS, AddWebResourceRequestedFilter on Windows and webkit-web-context-register-uri-scheme on Linux.

§Arguments
  • uri_scheme The URI scheme to register, such as example.
  • protocol the protocol associated with the given URI scheme. It’s a function that takes an URL such as example://localhost/asset.css.
§Examples
tauri::Builder::default()
  .register_uri_scheme_protocol("myscheme", |app, req| {
    tauri::http::ResponseBuilder::new().body(Vec::new())
  });
source

pub fn updater_target<T: Into<String>>(self, target: T) -> Self

Sets the current platform’s target name for the updater.

See UpdateBuilder::target for more information.

§Examples
  • Use a macOS Universal binary target name:
let mut builder = tauri::Builder::default();
#[cfg(target_os = "macos")]
{
  builder = builder.updater_target("darwin-universal");
}
  • Append debug information to the target:
let kind = if cfg!(debug_assertions) { "debug" } else { "release" };
tauri::Builder::default()
  .updater_target(format!("{}-{kind}", tauri::updater::target().unwrap()));
  • Use the platform’s target triple:
tauri::Builder::default()
  .updater_target(tauri::utils::platform::target_triple().unwrap());
source

pub fn device_event_filter(self, filter: DeviceEventFilter) -> Self

Change the device event filter mode.

Since the DeviceEvent capture can lead to high CPU usage for unfocused windows, tao will ignore them by default for unfocused windows on Windows. This method allows changing the filter to explicitly capture them again.

§Platform-specific
  • ** Linux / macOS / iOS / Android**: Unsupported.
§Examples
tauri::Builder::default()
  .device_event_filter(tauri::DeviceEventFilter::Always);
source

pub fn build<A: Assets>(self, context: Context<A>) -> Result<App<R>>

Builds the application.

source

pub fn run<A: Assets>(self, context: Context<A>) -> Result<()>

Runs the configured Tauri application.

Trait Implementations§

source§

impl Default for Builder<Wry>

Available on crate feature wry only.

Make Wry the default Runtime for Builder

source§

fn default() -> Self

Returns the “default value” for a type. Read more

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<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.
source§

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, U> TryFrom<U> for T
where U: Into<T>,

source§

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>,

source§

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