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§

impl<R: Runtime> Builder<R>

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>) -> bool + 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(self, initialization_script: String) -> Self

Defines a custom JS message system.

The initialization_script is a script that initializes window.__TAURI_INTERNALS__.postMessage. That function must take the (message: object, options: object) arguments and send it to the backend.

Additionally, the script must include a __INVOKE_KEY__ token that is replaced with a value that must be sent with the IPC payload to check the integrity of the message by the crate::WebviewWindow::on_message API, e.g.

const invokeKey = __INVOKE_KEY__;
fetch('my-impl://command', {
  headers: {
    'Tauri-Invoke-Key': invokeKey,
  }
})

Note that the implementation details is up to your implementation.

Source

pub fn channel_interceptor<F: Fn(&Webview<R>, CallbackFn, usize, &InvokeResponseBody) -> bool + Send + Sync + 'static>( self, interceptor: F, ) -> Self

Registers a channel interceptor that can overwrite the default channel implementation.

If the event has been consumed, it must return true.

The channel automatically orders the messages, so the third closure argument represents the message number. The payload expected by the channel receiver is in the form of { id: usize, message: T }.

Source

pub fn append_invoke_initialization_script( self, initialization_script: impl AsRef<str>, ) -> Self

Append a custom initialization script.

Allow to append custom initialization script instend of replacing entire invoke system.

§Examples
let custom_script = r#"
// A custom call system bridge build on top of tauri invoke system.
async function invoke(cmd, args = {}) {
  if (!args) args = {};

  let prefix = "";

  if (args?.__module) {
    prefix = `plugin:hybridcall.${args.__module}|`;
  }

  const command = `${prefix}tauri_${cmd}`;

  const invoke = window.__TAURI_INTERNALS__.invoke;

  return invoke(command, args).then(result => {
    if (window.build.debug) {
      console.log(`call: ${command}`);
      console.log(`args: ${JSON.stringify(args)}`);
      console.log(`return: ${JSON.stringify(result)}`);
    }

    return result;
  });
}
"#;

tauri::Builder::default()
  .append_invoke_initialization_script(custom_script);
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();
    main_window.set_title("Tauri!")?;
    Ok(())
  });
Source

pub fn on_page_load<F>(self, on_page_load: F) -> Self
where F: Fn(&Webview<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, api| {
        // 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 crate::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 menu<F: FnOnce(&AppHandle<R>) -> Result<Menu<R>> + Send + 'static>( self, f: F, ) -> Self

Sets the menu to use on all windows.

§Examples
use tauri::menu::{Menu, MenuItem, PredefinedMenuItem, Submenu};

tauri::Builder::default()
  .menu(|handle| Menu::with_items(handle, &[
    &Submenu::with_items(
      handle,
      "File",
      true,
      &[
        &PredefinedMenuItem::close_window(handle, None)?,
        #[cfg(target_os = "macos")]
        &MenuItem::new(handle, "Hello", true, None::<&str>)?,
      ],
    )?
  ]));
Source

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

Registers an event handler for any menu event.

§Examples
use tauri::menu::*;

tauri::Builder::default()
  .on_menu_event(|app, event| {
     if event.id() == "quit" {
       app.exit(0);
     }
  });
Source

pub fn on_tray_icon_event<F: Fn(&AppHandle<R>, TrayIconEvent) + Send + Sync + 'static>( self, f: F, ) -> Self

Available on desktop and crate feature tray-icon only.

Registers an event handler for any tray icon event.

§Examples
use tauri::Manager;

tauri::Builder::default()
  .on_tray_icon_event(|app, event| {
     let tray = app.tray_by_id(event.id()).expect("can't find tray icon");
     let _ = tray.set_visible(false);
  });
Source

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

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

§Examples
tauri::Builder::default()
  .enable_macos_default_menu(false);
Source

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

Registers a window event handler for all windows.

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

pub fn on_webview_event<F: Fn(&Webview<R>, &WebviewEvent) + Send + Sync + 'static>( self, handler: F, ) -> Self

Registers a webview event handler for all webviews.

§Examples
tauri::Builder::default()
  .on_webview_event(|window, event| match event {
    tauri::WebviewEvent::DragDrop(event) => {
      println!("{:?}", event);
    }
    _ => {}
  });
Source

pub fn register_uri_scheme_protocol<N: Into<String>, T: Into<Cow<'static, [u8]>>, H: Fn(UriSchemeContext<'_, R>, Request<Vec<u8>>) -> Response<T> + 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 a request and returns a response.
§Examples
tauri::Builder::default()
  .register_uri_scheme_protocol("app-files", |_ctx, request| {
    // skip leading `/`
    if let Ok(data) = std::fs::read(&request.uri().path()[1..]) {
      http::Response::builder()
        .body(data)
        .unwrap()
    } else {
      http::Response::builder()
        .status(http::StatusCode::BAD_REQUEST)
        .header(http::header::CONTENT_TYPE, mime::TEXT_PLAIN.essence_str())
        .body("failed to read file".as_bytes().to_vec())
        .unwrap()
    }
  });
Source

pub fn register_asynchronous_uri_scheme_protocol<N: Into<String>, H: Fn(UriSchemeContext<'_, R>, Request<Vec<u8>>, UriSchemeResponder) + Send + Sync + 'static>( self, uri_scheme: N, protocol: H, ) -> Self

Similar to Self::register_uri_scheme_protocol but with an asynchronous responder that allows you to process the request in a separate thread and respond asynchronously.

§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_asynchronous_uri_scheme_protocol("app-files", |_ctx, request, responder| {
    // skip leading `/`
    let path = request.uri().path()[1..].to_string();
    std::thread::spawn(move || {
      if let Ok(data) = std::fs::read(path) {
        responder.respond(
          http::Response::builder()
            .body(data)
            .unwrap()
        );
      } else {
        responder.respond(
          http::Response::builder()
            .status(http::StatusCode::BAD_REQUEST)
            .header(http::header::CONTENT_TYPE, mime::TEXT_PLAIN.essence_str())
            .body("failed to read file".as_bytes().to_vec())
            .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(self, context: Context<R>) -> Result<App<R>>

Builds the application.

Source

pub fn run(self, context: Context<R>) -> 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§

§

impl<R> !Freeze for Builder<R>

§

impl<R> !RefUnwindSafe for Builder<R>

§

impl<R> Send for Builder<R>

§

impl<R> !Sync for Builder<R>

§

impl<R> Unpin for Builder<R>

§

impl<R> !UnwindSafe for Builder<R>

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, 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, 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<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> MaybeSendSync for T