### Run Tauri Application Example Source: https://docs.rs/tauri/2.7.0/src/tauri/app Demonstrates how to initialize and run a Tauri application using the Builder. This example shows the basic structure for starting an app with a configuration file. ```rust 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"); ``` -------------------------------- ### Tauri Setup with Event Listener Example (Rust) Source: https://docs.rs/tauri/2.7.0/src/tauri/lib Demonstrates how to set up an event listener within the `setup` hook of a Tauri application. This example shows how to listen for a 'synchronized' event and print a message when it's received. It also includes an example of emitting an event from a command. ```rust 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("synchronized", |event| { println!("app is in sync"); }); Ok(()) }) .invoke_handler(tauri::generate_handler![synchronize]); ``` -------------------------------- ### WebviewBuilder Example: Setup Hook (Rust) Source: https://docs.rs/tauri/2.7.0/src/tauri/webview/mod Demonstrates how to create a webview using WebviewBuilder within the setup hook of a Tauri application. This is a common pattern for initializing the main webview. ```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 Tauri Webview Window in Setup Hook (Rust) Source: https://docs.rs/tauri/2.7.0/src/tauri/webview/webview_window Demonstrates how to create a new webview window with a specified label and URL within the Tauri application's setup hook. This is a common pattern for initializing main windows or secondary windows upon application start. ```rust tauri::Builder::default() .setup(|app| { let webview_window = tauri::WebviewWindowBuilder::new(app, "label", tauri::WebviewUrl::App("index.html".into())) .build()?; Ok(()) }); ``` -------------------------------- ### Setup Tauri Application Configuration Source: https://docs.rs/tauri/2.7.0/src/tauri/app Initializes the Tauri application by creating specified windows from configuration, setting up asset management, and executing any custom setup logic. It iterates through window configurations, builds webview windows, and handles potential errors during the setup process. Dependencies include the application's configuration and runtime capabilities. ```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(()) } ``` -------------------------------- ### Tauri: Setup Hook for App Initialization Source: https://docs.rs/tauri/2.7.0/src/tauri/app Defines a setup hook that runs once the Tauri application is initialized. This hook receives an `App` instance, allowing for configuration tasks such as setting window titles or performing initial data loading before the application UI is fully interactive. It returns a `Result` to indicate success or failure during setup. ```rust impl Builder { /// Defines the setup hook. /// /// # Examples /// #[cfg_attr( /// feature = "unstable", /// doc = r####"``` /// use tauri::Manager; /// tauri::Builder::default() /// .setup(|app| { /// let main_window = app.get_window("main").unwrap(); /// main_window.set_title("Tauri!")?; /// Ok(()) /// }); /// ``` /// "#### /// )] /// #[must_use] /// pub fn setup(mut self, setup: F) -> Self /// where /// F: FnOnce(&mut tauri::App) -> Result<(), Box> + Send + 'static, /// { /// self.setup = Some(Box::new(setup)); /// self /// } } ``` -------------------------------- ### Define Stateful Commands in Tauri Source: https://docs.rs/tauri/2.7.0/src/tauri/lib Demonstrates defining commands in Tauri that interact with managed application state. Includes examples of commands that read state and manage state initialization during application setup. It utilizes `tauri::State` and the `tauri::Builder` for managing state. ```rust /// # Examples /// /// ```rust,no_run /// 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"); ``` -------------------------------- ### App Run API Source: https://docs.rs/tauri/2.7.0/src/tauri/app Runs the Tauri application, handling setup and event callbacks. It panics if the setup function fails. ```APIDOC ## POST /run ### Description Runs the Tauri application with a provided callback function for event handling. This function will panic if the setup-function supplied in [`Builder::setup`] fails. ### Method POST ### Endpoint `/run` ### Parameters #### Query Parameters - **callback** (FnMut(&AppHandle, RunEvent)) - Required - The callback function to handle application events. ### Request Body This endpoint does not accept a request body. ### Response #### Success Response (200) This endpoint does not return a value upon successful execution; it runs the application until exit. #### Response Example N/A ### Examples ```rust let app = tauri::Builder::default() .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(); } _ => {} }); ``` ``` -------------------------------- ### Tauri Application Setup Callback Source: https://docs.rs/tauri/2.7.0/src/tauri/app Internal callback function for the Tauri runtime event loop. It manages application setup, processes events like `Ready` and `Exit`, invokes the user-provided callback, and handles application cleanup and restarts. This function is part of the core runtime management. ```rust fn make_run_event_loop_callback, RunEvent) + 'static>( mut self, mut callback: F, ) -> impl FnMut(RuntimeRunEvent) { let app_handle = self.handle().clone(); let manager = self.manager.clone(); move |event| match event { RuntimeRunEvent::Ready => { if let Err(e) = setup(&mut self) { panic!("Failed to setup app: {e}"); } let event = on_event_loop_event(&app_handle, RuntimeRunEvent::Ready, &manager); callback(&app_handle, event); } RuntimeRunEvent::Exit => { let event = on_event_loop_event(&app_handle, RuntimeRunEvent::Exit, &manager); callback(&app_handle, event); app_handle.cleanup_before_exit(); if self.manager.restart_on_exit.load(atomic::Ordering::Relaxed) { crate::process::restart(&self.env()); } } _ => { let event = on_event_loop_event(&app_handle, event, &manager); callback(&app_handle, event); } } } ``` -------------------------------- ### Setup Plugin Initialization (Rust) Source: https://docs.rs/tauri/2.7.0/src/tauri/plugin Defines a closure that runs when the plugin is registered with the Tauri application. This is useful for initializing plugin state or performing setup tasks. The closure receives the AppHandle and PluginApi as arguments. ```rust pub fn setup(mut self, setup: F) -> Self where F: FnOnce(&AppHandle, PluginApi) -> Result<(), Box> + Send + 'static, { self.setup.replace(Box::new(setup)); self } ``` -------------------------------- ### Rust: Tauri Builder Example for Menu Event Handling Source: https://docs.rs/tauri/2.7.0/src/tauri/window/mod Example demonstrating how to set up a menu for a window and handle menu events using Tauri's `Builder`. This includes creating menu items and submenus, assigning them to a window, and defining a callback for menu interactions. ```rust 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(()) }); ``` -------------------------------- ### Define Tauri Setup Hook Source: https://docs.rs/tauri/2.7.0/src/tauri/app Defines the setup function for the Tauri application. This function is called once when the application is initialized and can return an error. ```Rust pub fn setup(mut self, setup: F) -> Self where F: FnOnce(&mut App) -> std::result::Result<(), Box> + Send + 'static, { self.setup = Box::new(setup); self } ``` -------------------------------- ### Tauri Plugin Builder with Custom Options (Rust Example) Source: https://docs.rs/tauri/2.7.0/src/tauri/plugin Provides an example of a custom `Builder` struct for Tauri plugins that allows configuration through multiple options. It demonstrates setting options and then building the plugin with these configurations. ```rust /// When plugins expose more complex configuration options, it can be helpful to provide a Builder instead: /// /// ```rust /// use tauri::{plugin::{Builder as PluginBuilder, TauriPlugin}, Runtime}; /// /// pub struct Builder { /// option_a: String, /// option_b: String, /// option_c: bool /// } /// /// impl Default for Builder { /// fn default() -> Self { /// Self { /// option_a: "foo".to_string(), /// option_b: "bar".to_string(), /// option_c: false /// } /// } /// } /// /// impl Builder { /// pub fn new() -> Self { /// Default::default() /// } /// /// pub fn option_a(mut self, option_a: String) -> Self { /// self.option_a = option_a; /// self /// } /// /// pub fn option_b(mut self, option_b: String) -> Self { /// self.option_b = option_b; /// self /// } /// /// pub fn option_c(mut self, option_c: bool) -> Self { /// self.option_c = option_c; /// self /// } /// /// pub fn build(self) -> TauriPlugin { /// PluginBuilder::new("example") /// .setup(move |app_handle, api| { /// // use the options here to do stuff /// println!("a: {}, b: {}, c: {}", self.option_a, self.option_b, self.option_c); /// /// Ok(()) /// }) /// .build() /// } /// } /// ``` ``` -------------------------------- ### Example: Filtered Download Progress Emission (Rust) Source: https://docs.rs/tauri/2.7.0/src/tauri/lib Demonstrates emitting download progress events using a filter function. The example filters events to only be sent to the main webview window. This allows for more granular control over event distribution. ```rust use tauri::{Emitter, 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, }); } } ``` -------------------------------- ### Start Dragging API Source: https://docs.rs/tauri/2.7.0/src/tauri/webview/webview_window Initiates the window dragging operation. ```APIDOC ## POST /window/drag/start ### Description Initiates the window dragging operation. ### Method POST ### Endpoint /window/drag/start ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Run Tauri Application Source: https://docs.rs/tauri/2.7.0/src/tauri/app Executes the Tauri application's event loop with a provided callback function. It handles application setup and event processing. Panics if the initial setup fails. This method is suitable for the primary application run. ```rust pub fn run, RunEvent) + 'static>(mut self, callback: F) { self.handle.event_loop.lock().unwrap().main_thread_id = std::thread::current().id(); self .runtime .take() .unwrap() .run(self.make_run_event_loop_callback(callback)); } ``` -------------------------------- ### Example: Handling App Files with Synchronous URI Scheme Source: https://docs.rs/tauri/2.7.0/src/tauri/app An example illustrating the synchronous registration of a URI scheme protocol for accessing application files. This code reads a file directly and returns an HTTP response, including error handling for file read operations. ```rust 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() } }); ``` -------------------------------- ### Tauri Add Capability Configuration Example (Rust) Source: https://docs.rs/tauri/2.7.0/src/tauri/lib Provides a configuration snippet for `tauri-build` to specify a custom path pattern for capability JSON files. This example configures the build to only pick up capabilities located in `./capabilities/app/*.json`, overriding the default behavior. ```rust // only pick up capabilities in the capabilities/app folder by default let attributes = tauri_build::Attributes::new().capabilities_path_pattern("./capabilities/app/*.json"); tauri_build::try_build(attributes).unwrap(); ``` -------------------------------- ### Set Tauri Window Effects (Example) Source: https://docs.rs/tauri/2.7.0/src/tauri/window/mod Applies visual effects to the window, such as Popover. Requires the window to be transparent. Platform-specific behavior exists for Windows and Linux. This example demonstrates using EffectsBuilder. ```rust use tauri::{Manager, window::{Color, Effect, EffectState, EffectsBuilder}}; tauri::Builder::default() .setup(|app| { let window = app.get_window("main").unwrap(); window.set_effects( EffectsBuilder::new() .effect(Effect::Popover) .state(EffectState::Active) .radius(5.) .color(Color(0, 0, 0, 255)) .build(), )?; Ok(()) }); ``` -------------------------------- ### Plugin Setup Callback Configuration Source: https://docs.rs/tauri/2.7.0/src/tauri/plugin Define a closure that runs when the plugin is registered with the Tauri application. ```APIDOC ## POST /plugin/config/setup ### Description Specifies a setup function that will be executed once when the plugin is registered. This is useful for initializing plugin state or performing one-time configurations. ### Method POST ### Endpoint `/plugin/config/setup` ### Parameters #### Request Body - **setup** (function) - Required - A closure that takes `AppHandle` and `PluginApi` as arguments and returns a `Result`. ``` -------------------------------- ### Example: Handling and Asserting IPC Commands in Tauri Source: https://docs.rs/tauri/2.7.0/src/tauri/test/mod Demonstrates how to set up a mock Tauri app, define a simple command (`ping`), and then use `assert_ipc_response` to verify that the command returns the expected output ('pong'). This example illustrates the end-to-end testing flow for IPC interactions in Tauri. ```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() { 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` tauri::test::assert_ipc_response( &webview, tauri::webview::InvokeRequest { cmd: "ping".into(), callback: tauri::ipc::CallbackFn(0), error: tauri::ipc::CallbackFn(1), url: "http://tauri.localhost".parse().unwrap(), body: tauri::ipc::InvokeBody::default(), headers: Default::default(), invoke_key: tauri::test::INVOKE_KEY.to_string(), }, Ok("pong") ); } ``` -------------------------------- ### Initialize Tauri App and Plugins (Rust) Source: https://docs.rs/tauri/2.7.0/src/tauri/app This snippet shows the core logic for initializing a Tauri application. It sets up the runtime, manages application state and plugins, and configures platform-specific settings. It returns a `Result` containing the fully initialized `App` instance. ```rust runtime.set_device_event_filter(self.device_event_filter); let runtime_handle = runtime.handle(); #[allow(unused_mut)] let mut app = App { runtime: Some(runtime), setup: Some(self.setup), manager: manager.clone(), handle: AppHandle { runtime_handle, manager, event_loop: Arc::new(Mutex::new(EventLoop { main_thread_id: std::thread::current().id(), })), }, ran_setup: false, }; #[cfg(desktop)] if let Some(menu) = self.menu { let menu = menu(&app.handle)?; app .manager .menu .menus_stash_lock() .insert(menu.id().clone(), menu.clone()); #[cfg(target_os = "macos")] init_app_menu(&menu)?; app.manager.menu.menu_lock().replace(menu); } app.register_core_plugins()?; let env = Env::default(); app.manage(env); app.manage(Scopes { #[cfg(feature = "protocol-asset")] asset_protocol: crate::scope::fs::Scope::new( &app, &app.config().app.security.asset_protocol.scope, )?, }); app.manage(ChannelDataIpcQueue::default()); app.handle.plugin(crate::ipc::channel::plugin())?; #[cfg(windows)] { if let crate::utils::config::WebviewInstallMode::FixedRuntime { path } = &app.manager.config().bundle.windows.webview_install_mode { if let Ok(resource_dir) = app.path().resource_dir() { std::env::set_var( "WEBVIEW2_BROWSER_EXECUTABLE_FOLDER", resource_dir.join(path), ); } else { #[cfg(debug_assertions)] eprintln!( "failed to resolve resource directory; fallback to the installed Webview2 runtime." ); } } } let handle = app.handle(); // initialize default tray icon if defined #[cfg(all(desktop, feature = "tray-icon"))] { let config = app.config(); if let Some(tray_config) = &config.app.tray_icon { #[allow(deprecated)] let mut tray = TrayIconBuilder::with_id(tray_config.id.clone().unwrap_or_else(|| "main".into())) .icon_as_template(tray_config.icon_as_template) .menu_on_left_click(tray_config.menu_on_left_click) .show_menu_on_left_click(tray_config.show_menu_on_left_click); if let Some(icon) = &app.manager.tray.icon { tray = tray.icon(icon.clone()); } if let Some(title) = &tray_config.title { tray = tray.title(title); } if let Some(tooltip) = &tray_config.tooltip { tray = tray.tooltip(tooltip); } tray.build(handle)?; } } app.manager.initialize_plugins(handle)?; Ok(app) ``` -------------------------------- ### Get Cursor Position (Desktop) Source: https://docs.rs/tauri/2.7.0/src/tauri/webview/webview_window Gets the cursor's position relative to the top-left corner of the desktop. This is useful for multi-monitor setups where coordinates can be negative if the window is partially off-screen. ```rust /// Get the cursor position relative to the top-left hand corner of the desktop. /// /// Note that the top-left hand corner of the desktop is not necessarily the same as the screen. /// If the user uses a desktop with multiple monitors, /// the top-left hand corner of the desktop is the top-left hand corner of the main monitor on Windows and macOS /// or the top-left of the leftmost monitor on X11. /// /// The coordinates can be negative if the top-left hand corner of the window is outside of the visible screen region. pub fn cursor_position(&self) -> crate::Result> { self.webview.cursor_position() } ``` -------------------------------- ### Get Mutable Chunk Source: https://docs.rs/tauri/2.7.0/tauri/type Returns a mutable slice starting at the current position, with a length up to the remaining capacity. This allows direct modification of buffer contents. ```rust fn chunk_mut(&mut self) -> &mut UninitSlice ``` -------------------------------- ### Get Cursor Position Source: https://docs.rs/tauri/2.7.0/src/tauri/webview/mod Retrieves the current cursor position relative to the desktop's top-left corner. This accounts for multi-monitor setups. The coordinates can be negative if the window is off-screen. ```rust pub fn cursor_position(&self) -> crate::Result> { self.app_handle.cursor_position() } ``` -------------------------------- ### Tauri Webview: Unlisten to Event Example Source: https://docs.rs/tauri/2.7.0/src/tauri/webview/mod This example demonstrates how to unlisten to a specific event on a Tauri webview. It shows the setup of an event listener and the subsequent removal of that listener using its handler ID. This is crucial for preventing memory leaks and managing event subscriptions effectively. The code utilizes the `unlisten` method provided by the Tauri API. ```rust use tauri::{Manager, Listener}; tauri::Builder::default() .setup(|app| { let webview = app.get_webview("main").unwrap(); let webview_ = webview.clone(); let handler = webview.listen("component-loaded", move |event| { println!("webview just loaded a component"); // we no longer need to listen to the event // we also could have used `webview.once` instead webview_.unlisten(event.id()); }); // stop listening to the event when you do not need it anymore webview.unlisten(handler); Ok(()) }); ``` -------------------------------- ### Create Tauri Window from Configuration Source: https://docs.rs/tauri/2.7.0/src/tauri/webview/mod Shows how to initialize a Tauri webview builder using configuration from `tauri.conf.json`. It emphasizes the need for unique labels for each webview and warns about potential deadlocks on Windows when used in synchronous contexts. ```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::from_config(&app.config().app.windows.get(0).unwrap().clone()); window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap()); } ``` -------------------------------- ### Tauri Plugin Initialization Convention (Rust Example) Source: https://docs.rs/tauri/2.7.0/src/tauri/plugin Demonstrates the conventional `init` function for creating a simple Tauri plugin using the `Builder`. This function abstracts away the builder details for easier plugin integration. ```rust /// Builds a [`TauriPlugin`]. /// /// This Builder offers a more concise way to construct Tauri plugins than implementing the Plugin trait directly. /// /// # Conventions /// /// When using the Builder Pattern it is encouraged to export a function called `init` that constructs and returns the plugin. /// While plugin authors can provide every possible way to construct a plugin, /// sticking to the `init` function convention helps users to quickly identify the correct function to call. /// /// ```rust /// use tauri::{plugin::{Builder, TauriPlugin}, Runtime}; /// /// pub fn init() -> TauriPlugin { /// Builder::new("example") /// .build() /// } /// ``` ``` -------------------------------- ### Listen to Window Events (Rust) Source: https://docs.rs/tauri/2.7.0/src/tauri/webview/webview_window Sets up a listener for a specified event on a webview window. The handler closure is executed whenever the event occurs. The function returns an EventId that can be used to unlisten from the event. This is useful for reacting to frontend events within your Rust backend. Example demonstrates setup within a Tauri application's `setup` hook. ```rust fn listen(&self, event: impl Into, handler: F) -> EventId where F: Fn(Event) + Send + 'static, { let event = EventName::new(event.into()).unwrap(); self.manager().listen( event, EventTarget::WebviewWindow { label: self.label().to_string(), }, handler, ) } ``` -------------------------------- ### Get URL Username in Rust Source: https://docs.rs/tauri/2.7.0/tauri/struct Shows how to extract the username from a URL, if present, as a percent-encoded ASCII string. This example covers URLs with and without usernames, including cases with explicit empty usernames. ```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(), ""); ``` -------------------------------- ### Get Cursor Position Tauri Source: https://docs.rs/tauri/2.7.0/src/tauri/app Fetches the current cursor position relative to the desktop's top-left corner. Handles multi-monitor setups according to OS conventions. Coordinates can be negative if the window is off-screen. ```rust Ok(match self.runtime() { RuntimeOrDispatch::Runtime(h) => h.cursor_position()?, RuntimeOrDispatch::RuntimeHandle(h) => h.cursor_position()?, _ => unreachable!(), }) ``` -------------------------------- ### Example: Download Progress Emission (Rust) Source: https://docs.rs/tauri/2.7.0/src/tauri/lib Illustrates emitting download progress events to various targets. It shows how to emit to all targets (`EventTarget::any()`), the application itself (`EventTarget::app()`), labeled targets, and specific webview windows. Includes a delay to simulate progress. ```rust use tauri::{Emitter, 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); } } ``` -------------------------------- ### Rust Tauri: Get Vectored Chunks (std feature) Source: https://docs.rs/tauri/2.7.0/tauri/type Fills a destination slice with potentially multiple contiguous slices from the buffer, starting at the current position. This method requires the `std` crate feature to be enabled. ```rust fn chunks_vectored<'b>(&'b self, dst: &mut [IoSlice<'b>]) -> usize ``` -------------------------------- ### Get URL Path Source: https://docs.rs/tauri/2.7.0/tauri/struct Retrieves the path component of a URL as a percent-encoded ASCII string. For 'cannot-be-a-base' URLs, it's an arbitrary string. For others, it starts with '/' and includes slash-separated segments. Handles various URL formats and encoding. ```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%E1%BB%87t%20nam")?; assert_eq!(url.path(), "/countries/vi%E1%BB%87t%20nam"); ``` -------------------------------- ### Build Tauri Application in Rust Source: https://docs.rs/tauri/2.7.0/src/tauri/app Constructs and initializes the Tauri application. This function takes a `Context` object and performs various setup tasks, including configuring menus for macOS, setting up the application manager with handlers and protocols, and initializing the runtime. Platform-specific configurations are applied based on the target operating system. ```rust pub fn build(mut self, context: Context) -> crate::Result> { #[cfg(target_os = "macos")] if self.menu.is_none() && self.enable_macos_default_menu { self.menu = Some(Box::new(|app_handle| { crate::menu::Menu::default(app_handle) })); } let manager = Arc::new(AppManager::with_handlers( context, self.plugins, self.invoke_handler, self.on_page_load, self.uri_scheme_protocols, self.state, #[cfg(desktop)] self.menu_event_listeners, #[cfg(all(desktop, feature = "tray-icon"))] self.tray_icon_event_listeners, self.window_event_listeners, self.webview_event_listeners, #[cfg(desktop)] HashMap::new(), self.invoke_initialization_script, self.channel_interceptor, self.invoke_key, )); #[cfg(any( target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd" ))] let app_id = if manager.config.app.enable_gtk_app_id { Some(manager.config.identifier.clone()) } else { None }; let runtime_args = RuntimeInitArgs { #[cfg(any( target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd" ))] app_id, #[cfg(windows)] msg_hook: { let menus = manager.menu.menus.clone(); Some(Box::new(move |msg| { use windows::Win32::UI::WindowsAndMessaging::{TranslateAcceleratorW, HACCEL, MSG}; unsafe { let msg = msg as *const MSG; for menu in menus.lock().unwrap().values() { let translated = TranslateAcceleratorW((*msg).hwnd, HACCEL(menu.inner().haccel() as _), msg); if translated == 1 { return true; } } false } })) }, }; #[cfg(any(windows, target_os = "linux"))] let mut runtime = if self.runtime_any_thread { R::new_any_thread(runtime_args)? } else { R::new(runtime_args)? }; #[cfg(not(any(windows, target_os = "linux")))] let mut runtime = R::new(runtime_args)?; #[cfg(desktop)] { let proxy = runtime.create_proxy(); muda::MenuEvent::set_event_handler(Some(move |e: muda::MenuEvent| { let _ = proxy.send_event(EventLoopMessage::MenuEvent(e.into())); })); #[cfg(feature = "tray-icon")] { let proxy = runtime.create_proxy(); tray_icon::TrayIconEvent::set_event_handler(Some(move |e: tray_icon::TrayIconEvent| { })); } } todo!() } ``` -------------------------------- ### Tauri PluginStore Initialization and Management (Rust) Source: https://docs.rs/tauri/2.7.0/src/tauri/plugin Demonstrates the core methods for managing plugins within the Tauri PluginStore. Includes registration, unregistration, and initialization of individual plugins and the entire store. It also covers generating initialization scripts and handling plugin hooks. ```rust pub(crate) struct PluginStore { store: Vec>>, } impl PluginStore { pub fn register(&mut self, plugin: Box>) -> bool { let len = self.store.len(); self.store.retain(|p| p.name() != plugin.name()); let result = len != self.store.len(); self.store.push(plugin); result } pub fn unregister(&mut self, plugin: &'static str) -> bool { let len = self.store.len(); self.store.retain(|p| p.name() != plugin); len != self.store.len() } pub(crate) fn initialize( &self, plugin: &mut Box>, app: &AppHandle, config: &PluginConfig, ) -> crate::Result<()> { initialize(plugin, app, config) } pub(crate) fn initialize_all( &mut self, app: &AppHandle, config: &PluginConfig, ) -> crate::Result<()> { self .store .iter_mut() .try_for_each(|plugin| initialize(plugin, app, config)) } pub(crate) fn initialization_script(&self) -> Vec { self .store .iter() .filter_map(|p| p.initialization_script_2()) .map( |InitializationScript { script, for_main_frame_only, }| InitializationScript { script: format!("(function () {{ {script} }})();"), for_main_frame_only, }, ) .collect() } } ``` -------------------------------- ### Get Desktop Cursor Position - Rust Source: https://docs.rs/tauri/2.7.0/src/tauri/window/mod Retrieves the cursor's position relative to the top-left corner of the desktop. This function accounts for multi-monitor setups and can return negative coordinates if the window is outside the visible screen. It depends on the `Runtime` trait and returns a `Result` containing `PhysicalPosition`. ```rust impl Window { /// Get the cursor position relative to the top-left hand corner of the desktop. /// /// Note that the top-left hand corner of the desktop is not necessarily the same as the screen. /// If the user uses a desktop with multiple monitors, /// the top-left hand corner of the desktop is the top-left hand corner of the main monitor on Windows and macOS /// or the top-left of the leftmost monitor on X11. /// /// The coordinates can be negative if the top-left hand corner of the window is outside of the visible screen region. pub fn cursor_position(&self) -> crate::Result> { self.app_handle.cursor_position() } } ``` -------------------------------- ### Get Cursor Position in Rust with Tauri Source: https://docs.rs/tauri/2.7.0/src/tauri/test/mock_runtime This Rust function, `cursor_position`, is designed to retrieve the physical position of the cursor. It returns a `Result` which, in this example, always resolves to a `PhysicalPosition` at (0.0, 0.0). The actual implementation for fetching the real cursor position would involve Tauri's windowing or input event APIs. ```rust fn cursor_position(&self) -> Result> { Ok(PhysicalPosition::new(0.0, 0.0)) } } ``` -------------------------------- ### Build Application Source: https://docs.rs/tauri/2.7.0/src/tauri/app Builds and initializes the Tauri application with the specified configuration and context. ```APIDOC ## POST /build ### Description Builds and initializes the Tauri application with the specified configuration and context. ### Method POST ### Endpoint `/build` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **context** (Context) - Required - The application context, including configuration and assets. ### Request Example ```json { "context": { ... } } ``` ### Response #### Success Response (200) - **App** (object) - An instance of the built `App` representing the running application. #### Response Example ```json { "app_handle": "..." } ``` ``` -------------------------------- ### Get Variable String for BaseDirectory in Rust Source: https://docs.rs/tauri/2.7.0/tauri/path/enum Provides a method to retrieve the string representation of a BaseDirectory variant. This function is useful when you need to use the directory name as a string, for example, in constructing file paths or configuration keys. It returns a static string slice representing the variable name. ```rust pub fn variable(self) -> &'static str ``` -------------------------------- ### Rust: Initialize and Configure WindowBuilder Source: https://docs.rs/tauri/2.7.0/src/tauri/manager/window This snippet demonstrates how to prepare a new window using `PendingWindow` and potentially apply a default icon if none is set. It checks for existing windows with the same label to prevent duplicates. ```rust pub fn prepare_window( &self, mut pending: PendingWindow, ) -> crate::Result> { if self.windows_lock().contains_key(&pending.label) { return Err(crate::Error::WindowLabelAlreadyExists(pending.label)); } if !pending.window_builder.has_icon() { if let Some(default_window_icon) = self.default_icon.clone() { pending.window_builder = pending.window_builder.icon(default_window_icon.into())?; } } Ok(pending) } ``` -------------------------------- ### Tauri Monitor Information Functions (Rust) Source: https://docs.rs/tauri/2.7.0/src/tauri/test/mock_runtime This Rust code outlines functions for retrieving monitor information within a Tauri application. It includes placeholders for `unimplemented!()` for getting the primary monitor, a monitor from specific coordinates, and a list of all available monitors. These functions are essential for handling multi-monitor setups. Dependencies include the `Monitor` struct. ```rust fn primary_monitor(&self) -> Option { unimplemented!() } fn monitor_from_point(&self, x: f64, y: f64) -> Option { unimplemented!() } fn available_monitors(&self) -> Vec { unimplemented!() } ``` -------------------------------- ### Implement WebviewWindow builder and methods Source: https://docs.rs/tauri/2.7.0/src/tauri/webview/webview_window Provides methods for creating and managing `WebviewWindow` instances. Includes a builder to initialize new windows, a function to run closures on the main thread, and methods to access window labels and register event listeners. ```rust /// Base webview window functions. impl WebviewWindow { /// Initializes a [`WebviewWindowBuilder`] with the given window label and webview URL. /// /// Data URLs are only supported with the `webview-data-url` feature flag. pub fn builder, L: Into>( manager: &M, label: L, url: WebviewUrl, ) -> WebviewWindowBuilder<'_, R, M> { WebviewWindowBuilder::new(manager, label, url) } /// Runs the given closure on the main thread. pub fn run_on_main_thread(&self, f: F) -> crate::Result<()> { self.webview.run_on_main_thread(f) } /// The webview label. pub fn label(&self) -> &str { self.webview.label() } /// Registers a window event listener. pub fn on_window_event(&self, f: F) { self.window.on_window_event(f); } /// Resolves the given command scope for this webview on the currently loaded URL. /// /// If the command is not allowed, returns None. /// /// If the scope cannot be deserialized to the given type, an error is returned. /// /// In a command context this can be directly resolved from the command arguments via [crate::ipc::CommandScope]: /// /// ``` /// use tauri::ipc::CommandScope; /// /// #[derive(Debug, serde::Deserialize)] /// struct ScopeType { /// some_value: String, /// } ``` -------------------------------- ### Initialize Tauri Plugins Source: https://docs.rs/tauri/2.7.0/src/tauri/manager/mod Initializes all registered plugins for the application. It requires an `AppHandle` and the application's plugin configuration. ```rust pub fn initialize_plugins(&self, app: &AppHandle) -> crate::Result<()> { self .plugins .lock() .expect("poisoned plugin store") .initialize_all(app, &self.config.plugins) } ``` -------------------------------- ### Get Application Resource Directory (Rust) Source: https://docs.rs/tauri/2.7.0/tauri/path/struct Returns the path to the application's resource directory. The resolution varies significantly by platform: Windows points to the executable's directory, Linux handles AppImage and standard installations differently, macOS points inside the .app bundle, and mobile platforms use special URIs. ```rust pub fn resource_dir(&self) -> Result ``` -------------------------------- ### Get Package Information API Source: https://docs.rs/tauri/2.7.0/src/tauri/app Gets the app's package information. ```APIDOC ## GET /package_info ### Description Gets the app's package information. ### Method GET ### Endpoint /package_info ### Response #### Success Response (200) - **packageInfo** (PackageInfo) - The application's package information. #### Response Example ```json { "packageInfo": { ... } } ``` ```