### Tauri Builder Setup Example Source: https://docs.rs/tauri/2.9.3/src/tauri/webview/mod.rs.html Shows an example of setting up a Tauri application, retrieving a webview window, and resolving its command scope. ```rust use tauri::Manager; #[derive(Debug, serde::Deserialize)] struct ScopeType { some_value: String, } tauri::Builder::default() .setup(|app| { let webview = app.get_webview_window("main").unwrap(); let scope = webview.resolve_command_scope::("my-plugin", "read"); Ok(()) }); ``` -------------------------------- ### Example: Setting Menu for Webview Window Source: https://docs.rs/tauri/2.9.3/src/tauri/webview/webview_window.rs.html?search= Demonstrates how to create a menu with a 'Save' item and assign it to a WebviewWindow during application setup. ```rust use tauri::menu::{Menu, Submenu, MenuItem}; use tauri::{WebviewWindowBuilder, WebviewUrl}; tauri::Builder::default() .setup(|app| { let handle = app.handle(); let save_menu_item = MenuItem::new(handle, "Save", true, None::<&str>)?; let menu = Menu::with_items(handle, &[ &Submenu::with_items(handle, "File", true, &[ &save_menu_item, ])?, ])?; let webview_window = WebviewWindowBuilder::new(app, "editor", WebviewUrl::default()) .menu(menu) .build() .unwrap(); webview_window.on_menu_event(move |window, event| { if event.id == save_menu_item.id() { // save menu item } }); Ok(()) }); ``` -------------------------------- ### Setup Hook Example Source: https://docs.rs/tauri/2.9.3/src/tauri/app.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Defines the setup hook for the Tauri application. This function is called once when the application is initialized. ```rust use tauri::Manager; tauri::Builder::default() .setup(|app| { let main_window = app.get_webview_window("main").unwrap(); main_window.set_title("Tauri!")?; Ok(()) }); ``` -------------------------------- ### Create Webview in Setup Hook Source: https://docs.rs/tauri/2.9.3/src/tauri/webview/mod.rs.html?search=std%3A%3Avec Example of creating a webview within the Tauri application's setup hook. Ensure to handle potential errors during window and webview creation. ```rust tauri::Builder::default() .setup(|app| { let window = tauri::window::WindowBuilder::new(app, "label").build()?; let webview_builder = tauri::webview::WebviewBuilder::new("label", tauri::WebviewUrl::App("index.html".into())); let webview = window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap()); Ok(()) }); ``` -------------------------------- ### Example: Initialize and Add Tauri Plugin Source: https://docs.rs/tauri/2.9.3/src/tauri/app.rs.html Shows how to initialize a plugin and add it to the Tauri application during the setup phase. The plugin is added in a separate thread. ```rust use tauri::{plugin::{Builder as PluginBuilder, TauriPlugin}, Runtime}; fn init_plugin() -> TauriPlugin { PluginBuilder::new("dummy").build() } tauri::Builder::default() .setup(move |app| { let handle = app.handle().clone(); std::thread::spawn(move || { handle.plugin(init_plugin()); }); Ok(()) }); ``` -------------------------------- ### Builder::setup() Source: https://docs.rs/tauri/2.9.3/tauri/struct.Builder.html?search=std%3A%3Avec Defines the setup hook for the Tauri application. This hook is executed once when the application starts, allowing for initial configuration and setup tasks. ```APIDOC ## Builder::setup() ### Description Defines the setup hook. ### Method `setup(self, setup: F) -> Self` ### Parameters * `setup` (F): A closure that takes a mutable reference to the `App` and returns a `Result`. This closure is executed once when the application starts. ### Examples ```rust use tauri::Manager; tauri::Builder::default() .setup(|app| { let main_window = app.get_webview_window("main").unwrap(); main_window.set_title("Tauri!")?; Ok(()) }); ``` ``` -------------------------------- ### MenuBuilder Example Source: https://docs.rs/tauri/2.9.3/tauri/menu/struct.MenuBuilder.html?search=u32+-%3E+bool Demonstrates how to create and configure a menu using MenuBuilder, including adding various item types and setting it for the application. This example should be used within the setup hook of a Tauri application. ```rust use tauri::menu::* tauri::Builder::default() .setup(move |app| { let handle = app.handle(); let menu = MenuBuilder::new(handle) .item(&MenuItem::new(handle, "MenuItem 1", true, None::<&str>)?) .items(&[ &CheckMenuItem::new(handle, "CheckMenuItem 1", true, true, None::<&str>)?, &IconMenuItem::new(handle, "IconMenuItem 1", true, Some(icon1), None::<&str>)?, ]) .separator() .cut() .copy() .paste() .separator() .text("item2", "MenuItem 2") .check("checkitem2", "CheckMenuItem 2") .icon("iconitem2", "IconMenuItem 2", app.default_window_icon().cloned().unwrap()) .build()?; app.set_menu(menu); Ok(()) }); ``` -------------------------------- ### Example Invoke Handler Setup Source: https://docs.rs/tauri/2.9.3/src/tauri/app.rs.html Demonstrates how to set up an invoke handler using `tauri::Builder` and `tauri::generate_handler!`. This registers the `command_1` function to be callable from the frontend. ```rust tauri::Builder::default() .invoke_handler(tauri::generate_handler![ command_1, // etc... ]); ``` -------------------------------- ### Example: Setting Activation Policy on macOS Source: https://docs.rs/tauri/2.9.3/src/tauri/app.rs.html?search=std%3A%3Avec Demonstrates how to set the activation policy for a Tauri application on macOS within the `setup` hook. ```rust tauri::Builder::default() .setup(move |app| { #[cfg(target_os = "macos")] app.handle().set_activation_policy(tauri::ActivationPolicy::Accessory); Ok(()) }); ``` -------------------------------- ### setup Function Source: https://docs.rs/tauri/2.9.3/src/tauri/app.rs.html?search=u32+-%3E+bool Initializes the application, creates windows, and runs the setup closure if provided. ```APIDOC ## setup ### Description Initializes the application, creates windows based on configuration, sets up assets, and executes a user-provided setup closure. ### Parameters - `app`: A mutable reference to the `App` instance. ### Returns - `crate::Result<()>`: Ok if setup is successful, otherwise an error. ``` -------------------------------- ### Tauri Application Setup with Managed State and Commands Source: https://docs.rs/tauri/2.9.3/src/tauri/lib.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E An example of setting up a Tauri application, managing custom states (`MyInt`, `MyString`), and defining commands that utilize this state. It shows how to initialize state, assert its presence, and retrieve it using different methods. ```rust use tauri::{Manager, State}; struct MyInt(isize); struct MyString(String); #[tauri::command] fn int_command(state: State) -> 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::(); assert_eq!(int.0, 0); // read the `MyString` managed state with the `State` guard let val: State = 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"); ``` -------------------------------- ### Running the Application Source: https://docs.rs/tauri/2.9.3/src/tauri/app.rs.html?search=u32+-%3E+bool The `run` function starts the application's event loop. It never returns and exits the process directly upon completion. It can panic if the setup function fails. ```APIDOC ## run Runs the application. This function never returns. When the application finishes, the process is exited directly using [`std::process::exit`]. See [`run_return`](Self::run_return) if you need to run code after the application event loop exits. # Panics This function will panic if the setup-function supplied in [`Builder::setup`] fails. # Examples ```,no_run let app = tauri::Builder::default() // on an actual app, remove the string argument .build(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json")) .expect("error while building tauri application"); app.run(|_app_handle, event| match event { tauri::RunEvent::ExitRequested { api, .. } => { api.prevent_exit(); } _ => {} }); ``` ```rust pub fn run, RunEvent) + 'static>(mut self, callback: F) ``` ``` -------------------------------- ### Example: Resolve Command Scope in Setup Hook Source: https://docs.rs/tauri/2.9.3/src/tauri/webview/webview_window.rs.html?search=std%3A%3Avec Illustrates resolving a command scope within the `setup` hook of a Tauri application. This example retrieves a webview window and attempts to resolve a scope for a plugin. ```rust use tauri::Manager; #[derive(Debug, serde::Deserialize)] struct ScopeType { some_value: String, } tauri::Builder::default() .setup(|app| { let webview = app.get_webview_window("main").unwrap(); let scope = webview.resolve_command_scope::("my-plugin", "read"); Ok(()) }); ``` -------------------------------- ### Example: Setting Dock Visibility on macOS Source: https://docs.rs/tauri/2.9.3/src/tauri/app.rs.html?search=std%3A%3Avec Demonstrates how to set the dock visibility for a Tauri application on macOS within the `setup` hook. ```rust tauri::Builder::default() .setup(move |app| { #[cfg(target_os = "macos")] app.handle().set_dock_visibility(false); Ok(()) }); ``` -------------------------------- ### Create and Configure a Submenu Source: https://docs.rs/tauri/2.9.3/tauri/menu/struct.SubmenuBuilder.html?search=u32+-%3E+bool Example demonstrating how to create a new submenu with various items, including standard menu items, check menu items, icon menu items, separators, and predefined actions like cut, copy, and paste. This is typically done within the application's setup function. ```rust use tauri::menu::* tauri::Builder::default() .setup(move |app| { let handle = app.handle(); let menu = Menu::new(handle)?; let submenu = SubmenuBuilder::new(handle, "File") .item(&MenuItem::new(handle, "MenuItem 1", true, None::<&str>)?) .items(&[ &CheckMenuItem::new(handle, "CheckMenuItem 1", true, true, None::<&str>)?, &IconMenuItem::new(handle, "IconMenuItem 1", true, Some(icon1), None::<&str>)?, ]) .separator() .cut() .copy() .paste() .separator() .text("item2", "MenuItem 2") .check("checkitem2", "CheckMenuItem 2") .icon("iconitem2", "IconMenuItem 2", app.default_window_icon().cloned().unwrap()) .build()?; menu.append(&submenu)?; app.set_menu(menu); Ok(()) }); ``` -------------------------------- ### App Setup and Event Handling Source: https://docs.rs/tauri/2.9.3/src/tauri/app.rs.html Details the setup process for the application and how events are processed. ```APIDOC ## App Setup and Event Handling ### Description This section covers the `setup` function for initializing the application and the `on_event_loop_event` function for processing various runtime events. ### `setup` Function - **Purpose**: Initializes the application, creates windows based on configuration, sets up assets, and runs the user-defined setup closure. - **Signature**: `fn setup(app: &mut App) -> crate::Result<()>` ### `on_event_loop_event` Function - **Purpose**: Handles events from the runtime's event loop, including window events, webview events, application ready state, and user-defined events like menu or tray icon interactions. - **Signature**: `fn on_event_loop_event( app_handle: &AppHandle, event: RuntimeRunEvent, manager: &AppManager, ) -> RunEvent` ### Event Handling Details - **Window Close**: Detects window destruction and calls `manager.on_window_close()`. - **Exit Events**: Handles application exit requests. - **Window/Webview Events**: Propagates window and webview events. - **Ready Event**: Includes logic for setting the application icon on macOS in development. - **User Events**: Processes menu events and tray icon events, dispatching them to registered listeners. ### Example Usage (Conceptual) ```rust // Inside your main.rs or similar tauri::Builder::default() .setup(|app| { // Call the setup function setup(app)?; // Assuming setup is accessible Ok(()) }) .run(tauri::generate_context!()) .expect("error while running tauri application"); // Event loop processing is handled internally by Tauri's run method, // but `on_event_loop_event` is the core logic. ``` ``` -------------------------------- ### Builder::setup Source: https://docs.rs/tauri/2.9.3/tauri/struct.Builder.html?search=u32+-%3E+bool Defines the setup hook for the Tauri application. This hook is executed once when the application starts. ```APIDOC ## Builder::setup ### Description Defines the setup hook. ### Method `setup(self, setup: F) -> Self` where F: FnOnce(&mut App) -> Result<(), Box> + Send + 'static ### Examples ```rust use tauri::Manager; tauri::Builder::default() .setup(|app| { let main_window = app.get_webview_window("main").unwrap(); main_window.set_title("Tauri!")?; Ok(()) }); ``` ``` -------------------------------- ### WebviewBuilder::new Source: https://docs.rs/tauri/2.9.3/src/tauri/webview/mod.rs.html Initializes a webview builder with a given label and URL. Includes notes on known issues and usage examples in setup hooks, separate threads, and commands. ```APIDOC ## WebviewBuilder::new ### Description Initializes a webview builder with the given webview label and URL to load. ### Method `WebviewBuilder::new(label: L, url: WebviewUrl)` ### Parameters - **label** (String) - The unique label for the webview window. - **url** (WebviewUrl) - The URL or path to load in the webview. ### Known Issues On Windows, this function can cause deadlocks when used in synchronous commands or event handlers. It is recommended to use `async` commands and separate threads for creating webviews. ### Examples - **Create a webview in the setup hook:** ```rust tauri::Builder::default() .setup(|app| { let window = tauri::window::WindowBuilder::new(app, "label").build()?; let webview_builder = tauri::webview::WebviewBuilder::new("label", tauri::WebviewUrl::App("index.html".into())); let webview = window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap()); Ok(()) }); ``` - **Create a webview in a separate thread:** ```rust tauri::Builder::default() .setup(|app| { let handle = app.handle().clone(); std::thread::spawn(move || { let window = tauri::window::WindowBuilder::new(&handle, "label").build().unwrap(); let webview_builder = tauri::webview::WebviewBuilder::new("label", tauri::WebviewUrl::App("index.html".into())); window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap()); }); Ok(()) }); ``` - **Create a webview in a command:** ```rust #[tauri::command] async fn create_window(app: tauri::AppHandle) { let window = tauri::window::WindowBuilder::new(&app, "label").build().unwrap(); let webview_builder = tauri::webview::WebviewBuilder::new("label", tauri::WebviewUrl::External("https://tauri.app/".parse().unwrap())); window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap()); } ``` ``` -------------------------------- ### Example: Listen to Component Loaded Event Source: https://docs.rs/tauri/2.9.3/src/tauri/app.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to set up an event listener for 'component-loaded' within the Tauri application's setup phase. ```rust use tauri::Listener; tauri::Builder::default() .setup(|app| { app.listen("component-loaded", move |event| { println!("window just loaded a component"); }); Ok(()) }); ``` -------------------------------- ### Initialize Tauri Plugin with Setup Closure Source: https://docs.rs/tauri/2.9.3/src/tauri/plugin.rs.html Use the `setup` method to define a closure that runs when the plugin is registered. This closure receives the `AppHandle` and `PluginApi` and can be used to manage plugin state or perform initial setup. ```rust use tauri::{plugin::{Builder, TauriPlugin}, Runtime, Manager}; use std::path::PathBuf; #[derive(Debug, Default)] struct PluginState { dir: Option } fn init() -> TauriPlugin { Builder::new("example") .setup(|app, api| { app.manage(PluginState::default()); Ok(()) }) .build() } ``` -------------------------------- ### Example: Dynamically Adding a Plugin Source: https://docs.rs/tauri/2.9.3/src/tauri/app.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to dynamically add a plugin to a Tauri application using `AppHandle::plugin`. The plugin is initialized in a separate thread after the application setup. ```rust use tauri::{plugin::{Builder as PluginBuilder, TauriPlugin}, Runtime}; fn init_plugin() -> TauriPlugin { PluginBuilder::new("dummy").build() } tauri::Builder::default() .setup(move |app| { let handle = app.handle().clone(); std::thread::spawn(move || { handle.plugin(init_plugin()); }); Ok(()) }); ``` -------------------------------- ### WindowBuilder New Function Example Source: https://docs.rs/tauri/2.9.3/src/tauri/window/mod.rs.html Demonstrates how to create a new window using the WindowBuilder in the setup hook of a Tauri application. Note the warning about potential deadlocks on Windows when used in synchronous contexts. ```rust #[cfg_attr(not(feature = "unstable"), allow(dead_code))] impl<'a, R: Runtime, M: Manager> WindowBuilder<'a, R, M> { /// Initializes a window builder with the given window label. /// /// # Known issues /// /// On Windows, this function deadlocks when used in a synchronous command or event handlers, see [the Webview2 issue]. /// You should use `async` commands and separate threads when creating windows. /// /// # Examples /// /// - Create a window in the setup hook: /// #[cfg_attr( feature = "unstable", doc = r####" ``` tauri::Builder::default() .setup(|app| { let window = tauri::window::WindowBuilder::new(app, "label") .build()?; Ok(()) }); ``` "#### )] ``` -------------------------------- ### Example Usage: Restart Application Source: https://docs.rs/tauri/2.9.3/src/tauri/process.rs.html Shows how to trigger an application restart using the `restart` function within a Tauri application's setup hook. Requires importing `restart`, `Env`, and `Manager`. ```rust use tauri::{process::restart, Env, Manager}; tauri::Builder::default() .setup(|app| { restart(&app.env()); Ok(()) }); ``` -------------------------------- ### Example tauri.config.json Source: https://docs.rs/tauri/2.9.3/tauri/struct.Config.html An example of a typical `tauri.conf.json` file, illustrating common configuration options. ```APIDOC ### Example tauri.config.json file ```json { "productName": "tauri-app", "version": "0.1.0", "build": { "beforeBuildCommand": "", "beforeDevCommand": "", "devUrl": "http://localhost:3000", "frontendDist": "../dist" }, "app": { "security": { "csp": null }, "windows": [ { "fullscreen": false, "height": 600, "resizable": true, "title": "Tauri App", "width": 800 } ] }, "bundle": {}, "plugins": {} } ``` ``` -------------------------------- ### Open Developer Tools in Tauri Source: https://docs.rs/tauri/2.9.3/src/tauri/webview/webview_window.rs.html This example shows how to open the developer tools for a specific webview window. It is typically used within the `setup` function and is enabled by default on debug builds or when the `devtools` feature is enabled. ```rust use tauri::Manager; tauri::Builder::default() .setup(|app| { #[cfg(debug_assertions)] app.get_webview_window("main").unwrap().open_devtools(); Ok(()) }); ``` -------------------------------- ### Plugin Setup Configuration Source: https://docs.rs/tauri/2.9.3/src/tauri/plugin.rs.html Configure the setup closure that runs when the plugin is registered. ```APIDOC ## POST /plugin/setup ### Description Define a closure that runs when the plugin is registered. ### Method POST ### Endpoint /plugin/setup ### Parameters #### Request Body - **setup** (FnOnce(&AppHandle, PluginApi) -> Result<(), Box>) - Required - The closure to execute during plugin setup. ### Request Example ```json { "setup": "fn(app, api) => { ... }" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates successful configuration. #### Response Example ```json { "status": "setup configured successfully" } ``` ``` -------------------------------- ### Example Usage: Get Current Binary Path Source: https://docs.rs/tauri/2.9.3/src/tauri/process.rs.html Demonstrates how to obtain the current binary path using `current_binary` within a Tauri application's setup hook. Requires importing `current_binary`, `Env`, and `Manager`. ```rust use tauri::{process::current_binary, Env, Manager}; let current_binary_path = current_binary(&Env::default()).unwrap(); tauri::Builder::default() .setup(|app| { let current_binary_path = current_binary(&app.env())?; Ok(()) }); ``` -------------------------------- ### Setup Hook Configuration Source: https://docs.rs/tauri/2.9.3/tauri/struct.Builder.html?search=u32+-%3E+bool Defines the setup hook for your Tauri application. This function is executed once when the application starts. ```rust use tauri::Manager; tauri::Builder::default() .setup(|app| { let main_window = app.get_webview_window("main").unwrap(); main_window.set_title("Tauri!")?; Ok(()) }); ``` -------------------------------- ### Example: Setting up a Menu and Event Listener Source: https://docs.rs/tauri/2.9.3/src/tauri/window/mod.rs.html?search=u32+-%3E+bool Demonstrates how to create a menu, assign it to a window, and handle menu events. This example requires the `unstable` feature flag. ```rust use tauri::menu::{Menu, Submenu, MenuItem}; tauri::Builder::default() .setup(|app| { let handle = app.handle(); let save_menu_item = MenuItem::new(handle, "Save", true, None::<&str>)?; let menu = Menu::with_items(handle, &[ &Submenu::with_items(handle, "File", true, &[ &save_menu_item, ])?, ])?; let window = tauri::window::WindowBuilder::new(app, "editor") .menu(menu) .build() .unwrap(); window.on_menu_event(move |window, event| { if event.id == save_menu_item.id() { // save menu item } }); Ok(()) }); ``` -------------------------------- ### Example: Setting up a Menu and Event Listener Source: https://docs.rs/tauri/2.9.3/src/tauri/window/mod.rs.html Demonstrates how to create a menu with items and attach an event listener to handle menu interactions. This example requires the `unstable` feature. ```rust use tauri::menu::{Menu, Submenu, MenuItem}; tauri::Builder::default() .setup(|app| { let handle = app.handle(); let save_menu_item = MenuItem::new(handle, "Save", true, None::<&str>)?; let menu = Menu::with_items(handle, &[ &Submenu::with_items(handle, "File", true, &[ &save_menu_item, ])?, ])?; let window = tauri::window::WindowBuilder::new(app, "editor") .menu(menu) .build() .unwrap(); window.on_menu_event(move |window, event| { if event.id == save_menu_item.id() { // save menu item } }); Ok(()) }); ``` -------------------------------- ### Setup Window with Menu and Event Listener Source: https://docs.rs/tauri/2.9.3/tauri/webview/struct.WebviewWindow.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to create a webview window with a custom menu and register a listener for menu events. This is specific to desktop platforms. ```rust use tauri::menu::{Menu, Submenu, MenuItem}; use tauri::{WebviewWindowBuilder, WebviewUrl}; tauri::Builder::default() .setup(|app| { let handle = app.handle(); let save_menu_item = MenuItem::new(handle, "Save", true, None::<&str>)?; let menu = Menu::with_items(handle, &[ &Submenu::with_items(handle, "File", true, &[ &save_menu_item, ])?, ])?; let webview_window = WebviewWindowBuilder::new(app, "editor", WebviewUrl::default()) .menu(menu) .build() .unwrap(); webview_window.on_menu_event(move |window, event| { if event.id == save_menu_item.id() { // save menu item } }); Ok(()) }); ``` -------------------------------- ### Example: Setting up and running a Tauri app for testing Source: https://docs.rs/tauri/2.9.3/src/tauri/test/mod.rs.html?search=std%3A%3Avec Demonstrates how to create a testable Tauri application using mock builder and context, define a command, and then invoke it via the webview to assert the response. ```rust use tauri::test::{mock_builder, mock_context, noop_assets}; #[tauri::command] fn ping() -> &'static str { "pong" } fn create_app(builder: tauri::Builder) -> tauri::App { builder .invoke_handler(tauri::generate_handler![ping]) // remove the string argument to use your app's config file .build(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json")) .expect("failed to build app") } fn main() { // Use `tauri::Builder::default()` to use the default runtime rather than the `MockRuntime`; // let app = create_app(tauri::Builder::default()); let app = create_app(mock_builder()); let webview = tauri::WebviewWindowBuilder::new(&app, "main", Default::default()).build().unwrap(); // run the `ping` command and assert it returns `pong` let res = tauri::test::get_ipc_response( &webview, tauri::webview::InvokeRequest { cmd: "ping".into(), callback: tauri::ipc::CallbackFn(0), error: tauri::ipc::CallbackFn(1), // alternatively use "tauri://localhost" url: "http://tauri.localhost".parse().unwrap(), body: tauri::ipc::InvokeBody::default(), headers: Default::default(), invoke_key: tauri::test::INVOKE_KEY.to_string(), }, ).map(|b| b.deserialize::().unwrap()); } ``` -------------------------------- ### Example: Removing a Plugin Source: https://docs.rs/tauri/2.9.3/src/tauri/app.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Illustrates how to remove a plugin from a Tauri application by its name. The example shows plugin initialization and then its removal in a separate thread during the application setup. ```rust use tauri::{plugin::{Builder as PluginBuilder, TauriPlugin, Plugin}, Runtime}; fn init_plugin() -> TauriPlugin { PluginBuilder::new("dummy").build() } let plugin = init_plugin(); // `.name()` requires the `Plugin` trait import let plugin_name = plugin.name(); tauri::Builder::default() .plugin(plugin) .setup(move |app| { let handle = app.handle().clone(); std::thread::spawn(move || { handle.remove_plugin(plugin_name); }); Ok(()) }); ``` -------------------------------- ### Example Usage of SubmenuBuilder Source: https://docs.rs/tauri/2.9.3/tauri/menu/struct.SubmenuBuilder.html Demonstrates how to create a menu with a submenu containing various items using SubmenuBuilder. This example requires a tauri application setup and is platform-specific to desktop. ```rust use tauri::menu::* tauri::Builder::default() .setup(move |app| { let handle = app.handle(); let menu = Menu::new(handle)?; let submenu = SubmenuBuilder::new(handle, "File") .item(&MenuItem::new(handle, "MenuItem 1", true, None::<&str>)?) .items(&[ &CheckMenuItem::new(handle, "CheckMenuItem 1", true, true, None::<&str>)?, &IconMenuItem::new(handle, "IconMenuItem 1", true, Some(icon1), None::<&str>)?, ]) .separator() .cut() .copy() .paste() .separator() .text("item2", "MenuItem 2") .check("checkitem2", "CheckMenuItem 2") .icon("iconitem2", "IconMenuItem 2", app.default_window_icon().cloned().unwrap()) .build()?; menu.append(&submenu)?; app.set_menu(menu); Ok(()) }); ``` -------------------------------- ### Create Webview Window in Setup Hook Source: https://docs.rs/tauri/2.9.3/src/tauri/webview/webview_window.rs.html?search=std%3A%3Avec Demonstrates creating a webview window with a specific label and URL during the application's setup phase. Ensure the application manager is available. ```rust tauri::Builder::default() .setup(|app| { let webview_window = tauri::WebviewWindowBuilder::new(app, "label", tauri::WebviewUrl::App("index.html".into())) .build()?; Ok(()) }); ``` -------------------------------- ### Create Window in Setup Hook Source: https://docs.rs/tauri/2.9.3/tauri/window/struct.WindowBuilder.html?search= Demonstrates creating a new window with a specific label during the application's setup phase. ```rust tauri::Builder::default() .setup(|app| { let window = tauri::window::WindowBuilder::new(app, "label") .build()?; Ok(()) }); ``` -------------------------------- ### Get Username from URL Source: https://docs.rs/tauri/2.9.3/tauri/struct.Url.html?search=u32+-%3E+bool Extracts the username from a URL, showing examples with and without a username, and with an empty username. ```rust use url::Url; let url = Url::parse("ftp://rms@example.com")?; assert_eq!(url.username(), "rms"); let url = Url::parse("ftp://:secret123@example.com")?; assert_eq!(url.username(), ""); let url = Url::parse("https://example.com")?; assert_eq!(url.username(), ""); ``` -------------------------------- ### Webview Builder Example Source: https://docs.rs/tauri/2.9.3/src/tauri/webview/mod.rs.html Demonstrates how to use the WebviewBuilder to create a new webview with a specified label and initial URL. ```rust /// Initializes a webview builder with the given window label and URL to load on the webview. /// /// Data URLs are only supported with the `webview-data-url` feature flag. #[cfg(feature = "unstable")] #[cfg_attr(docsrs, doc(cfg(feature = "unstable")))] pub fn builder>(label: L, url: WebviewUrl) -> WebviewBuilder { WebviewBuilder::new(label.into(), url) } ``` -------------------------------- ### TokioHandle - try_current() Source: https://docs.rs/tauri/2.9.3/tauri/async_runtime/struct.TokioHandle.html Attempts to get a Handle view over the currently running Runtime, returning an error if no Runtime has been started. ```APIDOC ## TokioHandle::try_current() ### Description Returns a Handle view over the currently running Runtime. Returns an error if no Runtime has been started. Contrary to `current`, this never panics. ### Method `pub fn try_current() -> Result` ``` -------------------------------- ### parse Source: https://docs.rs/tauri/2.9.3/tauri/path/struct.PathResolver.html?search= Parse the given path, resolving a `BaseDirectory` variable if the path starts with one. Includes an example of usage. ```APIDOC ## parse>(&self, path: P) -> Result ### Description Parse the given path, resolving a `BaseDirectory` variable if the path starts with one. ### Examples ```rust use tauri::Manager; tauri::Builder::default() .setup(|app| { let path = app.path().parse("$HOME/.bashrc")?; assert_eq!(path.to_str().unwrap(), "/home/${whoami}/.bashrc"); Ok(()) }); ``` ``` -------------------------------- ### Create Window in Setup Hook Source: https://docs.rs/tauri/2.9.3/tauri/window/struct.WindowBuilder.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates creating a new window with a specific label during the Tauri application's setup phase. ```rust tauri::Builder::default() .setup(|app| { let window = tauri::window::WindowBuilder::new(app, "label") .build()?; Ok(()) }); ``` -------------------------------- ### Run Tauri Application Source: https://docs.rs/tauri/2.9.3/src/tauri/app.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Executes the built Tauri application, starting the event loop and handling initial setup. ```rust /// Builds the configured application and runs it. /// /// This is a shorthand for [`Self::build`] followed by [`App::run`]. /// For more flexibility, consider using those functions manually. pub fn run(self, context: Context) -> crate::Result<()> { self.build(context)?.run(|_, _| {}); Ok(()) } ``` -------------------------------- ### Menu API Example Source: https://docs.rs/tauri/2.9.3/tauri/webview/struct.WebviewWindow.html Example demonstrating how to create and set a menu for a webview window, including registering an event listener for menu items. This is available only on desktop platforms. ```rust use tauri::menu::{Menu, Submenu, MenuItem}; use tauri::{WebviewWindowBuilder, WebviewUrl}; tauri::Builder::default() .setup(|app| { let handle = app.handle(); let save_menu_item = MenuItem::new(handle, "Save", true, None::<&str>)?; let menu = Menu::with_items(handle, &[ &Submenu::with_items(handle, "File", true, &[ &save_menu_item, ])?, ])?; let webview_window = WebviewWindowBuilder::new(app, "editor", WebviewUrl::default()) .menu(menu) .build() .unwrap(); webview_window.on_menu_event(move |window, event| { if event.id == save_menu_item.id() { // save menu item } }); Ok(()) }); ``` -------------------------------- ### Get URL Path Source: https://docs.rs/tauri/2.9.3/tauri/struct.Url.html Retrieves the path component of a URL as a percent-encoded string. The path starts with '/' for most URLs, except for 'cannot-be-a-base' URLs. ```rust use url::{Url, ParseError}; let url = Url::parse("https://example.com/api/versions?page=2")?; assert_eq!(url.path(), "/api/versions"); let url = Url::parse("https://example.com")?; assert_eq!(url.path(), "/"); let url = Url::parse("https://example.com/countries/việt nam")?; assert_eq!(url.path(), "/countries/vi%E1%BB%87t%20nam"); ``` -------------------------------- ### Windows Verbatim UNC Network Path Access Source: https://docs.rs/tauri/2.9.3/src/tauri/scope/fs.rs.html?search=std%3A%3Avec Configures access to a verbatim UNC network path. This example is a setup for further assertions not fully shown. ```rust scope .allow_directory("\\localhost\c$", true) .unwrap(); assert!(scope.is_allowed("\\localhost\c$")); assert!(scope.is_allowed("\\localhost\c$\Windows")); assert!(scope.is_allowed("\\localhost\c$\NonExistentFile")); assert!(!scope.is_allowed("\\localhost\d$")); assert!(!scope.is_allowed("\\OtherServer\Share")); ``` -------------------------------- ### Scope Initialization and Configuration Source: https://docs.rs/tauri/2.9.3/src/tauri/scope/fs.rs.html Demonstrates how to create a new file system scope with specified allowed and forbidden paths, and configures matching options. ```APIDOC ## POST /api/scope/new ### Description Creates a new file system scope based on the provided configuration. This includes setting allowed and forbidden paths, and defining matching behavior for glob patterns. ### Method POST ### Endpoint `/api/scope/new` ### Request Body - **allowed_paths** (array of strings) - Required - A list of glob patterns for paths that are allowed to be accessed. - **forbidden_paths** (array of strings) - Optional - A list of glob patterns for paths that are explicitly forbidden. - **require_literal_leading_dot** (boolean) - Optional - If true, requires literal leading dots in glob patterns to match dotfiles. ### Request Example ```json { "allowed_paths": ["/Users/user/Documents/**", "/Users/user/Downloads/*.pdf"], "forbidden_paths": ["/Users/user/Documents/sensitive/*"], "require_literal_leading_dot": true } ``` ### Response #### Success Response (200) - **scope_id** (string) - A unique identifier for the newly created scope. #### Response Example ```json { "scope_id": "scope_12345" } ``` ``` -------------------------------- ### Builder::setup Source: https://docs.rs/tauri/2.9.3/src/tauri/app.rs.html?search=std%3A%3Avec Sets up a setup hook that is called when the application is initialized. This hook can be used for initial application configuration. ```APIDOC ## Builder::setup ### Description Sets up a setup hook that is called when the application is initialized. This hook can be used for initial application configuration. ### Signature ```rust pub fn setup) -> Result<(), SetupError> + Send + 'static>(mut self, setup: F) -> Self ``` ``` -------------------------------- ### Create and Test Tauri App with Mocking Source: https://docs.rs/tauri/2.9.3/tauri/test/index.html This example demonstrates how to set up a mock Tauri application environment for testing. It includes defining a command, creating a mock app builder and context, and simulating an IPC request to test command execution. Ensure the 'test' feature is enabled. ```rust use tauri::test::{mock_builder, mock_context, noop_assets}; #[tauri::command] fn ping() -> &'static str { "pong" } fn create_app(builder: tauri::Builder) -> tauri::App { builder .invoke_handler(tauri::generate_handler![ping]) // remove the string argument to use your app's config file .build(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json")) .expect("failed to build app") } fn main() { // Use `tauri::Builder::default()` to use the default runtime rather than the `MockRuntime`; // let app = create_app(tauri::Builder::default()); let app = create_app(mock_builder()); let webview = tauri::WebviewWindowBuilder::new(&app, "main", Default::default()).build().unwrap(); // run the `ping` command and assert it returns `pong` let res = tauri::test::get_ipc_response( &webview, tauri::webview::InvokeRequest { cmd: "ping".into(), callback: tauri::ipc::CallbackFn(0), error: tauri::ipc::CallbackFn(1), // alternatively use "tauri://localhost" url: "http://tauri.localhost".parse().unwrap(), body: tauri::ipc::InvokeBody::default(), headers: Default::default(), invoke_key: tauri::test::INVOKE_KEY.to_string(), }, ).map(|b| b.deserialize::().unwrap()); } ``` -------------------------------- ### Get URL Path as Percent-Encoded String Source: https://docs.rs/tauri/2.9.3/tauri/struct.Url.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieves the path component of a URL as a percent-encoded ASCII string. The path always starts with '/' for valid base URLs. ```rust use url::{Url, ParseError}; let url = Url::parse("https://example.com/api/versions?page=2").unwrap(); assert_eq!(url.path(), "/api/versions"); let url = Url::parse("https://example.com").unwrap(); assert_eq!(url.path(), "/"); let url = Url::parse("https://example.com/countries/việt nam").unwrap(); assert_eq!(url.path(), "/countries/vi%E1%BB%87t%20nam") ``` -------------------------------- ### Builder Initialization and Running Source: https://docs.rs/tauri/2.9.3/tauri/struct.Builder.html Demonstrates how to create a new application builder and run the Tauri application. ```APIDOC ## Builder Initialization and Running ### Description Initializes a new Tauri application builder and configures it to run. ### Method `tauri::Builder::default()` ### Endpoint N/A (This is a builder pattern) ### Parameters None for `default()`. ### Request Body None ### Request Example ```rust tauri::Builder::default() .run(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json")) .expect("error while running tauri application"); ``` ### Response N/A (This method runs the application) ``` -------------------------------- ### Create Webview Window in Setup Hook Source: https://docs.rs/tauri/2.9.3/src/tauri/webview/webview_window.rs.html Use this to create a webview window when the application initializes. Ensure the label is unique. ```rust tauri::Builder::default() .setup(|app| { let webview_window = tauri::WebviewWindowBuilder::new(app, "label", tauri::WebviewUrl::App("index.html".into())) .build()?; Ok(()) }); ``` -------------------------------- ### Reopen Window from Configuration Source: https://docs.rs/tauri/2.9.3/src/tauri/webview/webview_window.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to create a webview window by loading its configuration from `tauri.conf.json`, useful for reopening windows. ```rust #[tauri::command] async fn reopen_window(app: tauri::AppHandle) { let webview_window = tauri::WebviewWindowBuilder::from_config(&app, &app.config().app.windows.get(0).unwrap()) .unwrap() .build() .unwrap(); } ``` -------------------------------- ### Get Cursor Position from Tauri Mock Runtime Source: https://docs.rs/tauri/2.9.3/src/tauri/test/mock_runtime.rs.html?search= This example shows how to retrieve the cursor position from the Tauri mock runtime. It returns a default physical position of (0.0, 0.0). ```rust fn cursor_position(&self) -> Result> { Ok(PhysicalPosition::new(0.0, 0.0)) } ``` -------------------------------- ### setup Source: https://docs.rs/tauri/2.9.3/src/tauri/plugin.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Defines a closure that runs when the plugin is registered. ```APIDOC ## setup ### Description Define a closure that runs when the plugin is registered. This is useful for initializing plugin state or performing setup tasks. ### Method Signature ```rust pub fn setup(mut self, setup: F) -> Self where F: FnOnce(&AppHandle, PluginApi) -> Result<(), Box> + Send + 'static ``` ### Parameters * `setup` (FnOnce): A closure that takes the `AppHandle` and `PluginApi` and returns a `Result`. ### Example ```rust use tauri::{plugin::{Builder, TauriPlugin}, Runtime, Manager}; use std::path::PathBuf; #[derive(Debug, Default)] struct PluginState { dir: Option } fn init() -> TauriPlugin { Builder::new("example") .setup(|app, api| { app.manage(PluginState::default()); Ok(()) }) .build() } ``` ``` -------------------------------- ### Get Runtime Flavor (Current Thread) Source: https://docs.rs/tauri/2.9.3/tauri/async_runtime/struct.TokioHandle.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to retrieve the flavor of the current Tokio runtime using `Handle::current().runtime_flavor()`. This example specifically asserts that the flavor is `RuntimeFlavor::CurrentThread`. ```rust use tokio::runtime::{Handle, RuntimeFlavor}; #[tokio::main(flavor = "current_thread")] async fn main() { assert_eq!(RuntimeFlavor::CurrentThread, Handle::current().runtime_flavor()); } ``` -------------------------------- ### Get multi-thread runtime flavor Source: https://docs.rs/tauri/2.9.3/tauri/async_runtime/struct.TokioHandle.html?search=u32+-%3E+bool Demonstrates how to retrieve the runtime flavor, specifically for a multi-threaded runtime. This example would typically be placed within a `#[tokio::main]` context configured for multi-threading. ```rust use tokio::runtime::{Handle, RuntimeFlavor}; ``` -------------------------------- ### Tauri App Setup Function Source: https://docs.rs/tauri/2.9.3/src/tauri/app.rs.html?search=u32+-%3E+bool Sets up the Tauri application, including creating windows, setting assets, and running the setup closure. ```rust fn setup(app: &mut App) -> crate::Result<()> { app.ran_setup = true; for window_config in app.config().app.windows.iter().filter(|w| w.create) { WebviewWindowBuilder::from_config(app.handle(), window_config)?.build()?; } app.manager.assets.setup(app); if let Some(setup) = app.setup.take() { (setup)(app).map_err(|e| crate::Error::Setup(e.into()))?; } Ok(()) } ``` -------------------------------- ### Initialize Window Builder from Config Source: https://docs.rs/tauri/2.9.3/src/tauri/window/mod.rs.html Explains how to create a window builder using configuration from `tauri.conf.json`. ```APIDOC ## POST /api/create_window_from_config ### Description Initializes a window builder from a `WindowConfig` object, typically loaded from `tauri.conf.json`. ### Method POST ### Endpoint /api/create_window_from_config ### Request Body - **config** (WindowConfig) - The configuration object for the new window. ### Request Example ```json { "config": { "label": "main-window", "title": "My App", "width": 800, "height": 600 } } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation of window creation. #### Response Example ```json { "message": "Window created successfully from config" } ``` ```