### Rust Tauri Application IPC Setup Example with taurpc Source: https://docs.rs/taurpc/latest/taurpc/fn.create_ipc_handler This example demonstrates a complete setup for inter-process communication (IPC) in a Tauri application using the `taurpc` crate. It shows how to define RPC procedures using `#[taurpc::procedures]`, implement them, and integrate the `taurpc::create_ipc_handler` into the Tauri builder's `invoke_handler`. ```Rust #[taurpc::procedures] trait Api { async fn hello_world(); } #[derive(Clone)] struct ApiImpl; #[taurpc::resolvers] impl Api for ApiImpl { async fn hello_world(self) { println!("Hello world"); } } #[tokio::main] async fn main() { tauri::Builder::default() .invoke_handler( taurpc::create_ipc_handler(ApiImpl.into_handler()) ) .run(tauri::generate_context!()) .expect("error while running tauri application"); } ``` -------------------------------- ### Rust TauRPC Router Merging Example Source: https://docs.rs/taurpc/latest/src/taurpc/lib.rs Demonstrates how to initialize a TauRPC `Router` and merge multiple trait-based RPC handlers (`ApiImpl`, `EventsImpl`) into it. This example shows the typical setup for integrating TauRPC with a Tauri application's `invoke_handler` for handling frontend calls. ```Rust #[taurpc::procedures] trait Api { } #[derive(Clone)] struct ApiImpl; #[taurpc::resolveres] impl Api for ApiImpl { } #[taurpc::procedures(path = "events")] trait Events { } #[derive(Clone)] struct EventsImpl; #[taurpc::resolveres] impl Events for EventsImpl { } #[tokio::main] async fn main() { let router = Router::new() .merge(ApiImpl.into_handler()) .merge(EventsImpl.into_handler()); tauri::Builder::default() .invoke_handler(router.into_handler()) .run(tauri::generate_context!()) .expect("error while running tauri application"); } ``` -------------------------------- ### Example: Defining and Registering TauRPC Procedures Source: https://docs.rs/taurpc/latest/src/taurpc/lib.rs This example demonstrates the basic usage of TauRPC macros and functions to define an IPC API. It illustrates how to declare procedures using `#[taurpc::procedures]`, implement them with `#[taurpc::resolvers]`, and integrate the resulting handler into a Tauri application's `invoke_handler` for typesafe communication. ```Rust #[taurpc::procedures] trait Api { async fn hello_world(); } #[derive(Clone)] struct ApiImpl; #[taurpc::resolvers] impl Api for ApiImpl { async fn hello_world(self) { println!("Hello world"); } } #[tokio::main] async fn main() { tauri::Builder::default() .invoke_handler( taurpc::create_ipc_handler(ApiImpl.into_handler()); ) .run(tauri::generate_context!()) .expect("error while running tauri application"); } ``` -------------------------------- ### Rust TauRPC Router Handler Merging Example Source: https://docs.rs/taurpc/latest/src/taurpc/lib.rs A concise example demonstrating the use of the `merge` method on a TauRPC `Router` to combine multiple RPC handlers. This is a common pattern for structuring and organizing different API functionalities within a single router. ```Rust let router = Router::new() .merge(ApiImpl.into_handler()) .merge(EventsImpl.into_handler()); ``` -------------------------------- ### Integrate taurpc Router with Tauri Invoke Handler Source: https://docs.rs/taurpc/latest/taurpc/struct.Router This example demonstrates the final step of integrating the `taurpc` router into a Tauri application. The `into_handler()` method converts the router into a function suitable for Tauri's `invoke_handler()`, enabling the frontend to call the defined RPC procedures. ```Rust tauri::Builder::default() .invoke_handler(router.into_handler()) .run(tauri::generate_context!()) .expect("error while running tauri application"); ``` -------------------------------- ### Rust TauRPC Router Export Configuration Example Source: https://docs.rs/taurpc/latest/src/taurpc/lib.rs Illustrates how to customize the TypeScript export options for a TauRPC `Router` using the `export_config` method. This allows developers to control aspects like adding header comments or specifying how BigInt values are exported to TypeScript. ```Rust let router = Router::new() .export_config( specta_typescript::Typescript::default() .header("// My header\n") .bigint(specta_typescript::BigIntExportBehavior::String), ) .merge(...); ``` -------------------------------- ### Configure TypeScript Export Options for taurpc Router Source: https://docs.rs/taurpc/latest/taurpc/struct.Router This example shows how to customize the TypeScript export configuration for the `taurpc::Router`. It uses `specta_typescript::Typescript` to modify default options, such as adding a custom header or specifying how BigInt values should be exported (e.g., as strings). ```Rust let router = Router::new() .export_config( specta_typescript::Typescript::default() .header("// My header\n") .bigint(specta_typescript::BigIntExportBehavior::String), ) .merge(...); ``` -------------------------------- ### taurpc Router Struct API Reference Source: https://docs.rs/taurpc/latest/taurpc/struct.Router Comprehensive API documentation for the `taurpc::Router` struct, detailing its constructor, core methods, and various trait implementations. This includes methods for configuration export, handler conversion, merging other routers, and default initialization, along with auto and blanket trait implementations that define its behavior and capabilities within the Rust ecosystem. ```APIDOC Struct: Router Description: Used for merging nested trait implementations. This is used when you have multiple trait implementations, instead of `taurpc::create_ipc_handler()`. Use `.merge()` to add trait implementations to the router. The trait must have the `#[taurpc::procedures]` macro and the nested routes should have `#[taurpc::procedures(path = "path")]`. Methods: export_config() - Purpose: Exports the configuration of the router. into_handler() - Purpose: Converts the router into a handler. merge() - Purpose: Merges another router's trait implementations into this router. new() - Purpose: Creates a new instance of the Router. Trait Implementations: Default for Router - Purpose: Provides a default constructor for the Router. Auto Trait Implementations: !RefUnwindSafe for Router !UnwindSafe for Router Freeze for Router Send for Router - Purpose: Indicates that the Router can be safely sent between threads. Sync for Router - Purpose: Indicates that the Router can be safely shared between threads. Unpin for Router Blanket Implementations: Any for T Borrow for T BorrowMut for T ErasedDestructor for T From for T Into for T IntoEither for T TryFrom for T TryInto for T ``` -------------------------------- ### Define and Register taurpc Procedures with Tauri Source: https://docs.rs/taurpc/latest/taurpc/struct.Router This snippet demonstrates the core usage of `taurpc` by defining RPC procedures using `#[taurpc::procedures]`, implementing them with `#[taurpc::resolveres]`, merging these implementations into a `Router`, and finally integrating the router's handler with a Tauri application's `invoke_handler`. ```Rust #[taurpc::procedures] trait Api { } #[derive(Clone)] struct ApiImpl; #[taurpc::resolveres] impl Api for ApiImpl { } #[taurpc::procedures(path = "events")] trait Events { } #[derive(Clone)] struct EventsImpl; #[taurpc::resolveres] impl Events for EventsImpl { } #[tokio::main] async fn main() { let router = Router::new() .merge(ApiImpl.into_handler()) .merge(EventsImpl.into_handler()); tauri::Builder::default() .invoke_handler(router.into_handler()) .run(tauri::generate_context!()) .expect("error while running tauri application"); } ``` -------------------------------- ### Rust `Typescript` Struct Fields and Methods API Source: https://docs.rs/taurpc/latest/taurpc/struct.Typescript Comprehensive API documentation for the `Typescript` struct, detailing its public fields and associated methods for configuring TypeScript export behavior. This includes how to initialize the struct and customize its header, BigInt handling, comment rendering, and file formatting. ```APIDOC Struct: Typescript #[non_exhaustive] pub struct Typescript { pub header: Cow<'static, str>, pub framework_header: Cow<'static, str>, pub bigint: BigIntExportBehavior, pub comment_exporter: Option) -> String>, pub formatter: Option Result<(), Error>>, } Fields: header: Cow<'static, str> - Description: The user's file header. framework_header: Cow<'static, str> - Description: The framework’s header. bigint: BigIntExportBehavior - Description: How BigInts should be exported. comment_exporter: Option) -> String> - Description: How comments should be rendered. formatter: Option Result<(), Error>> - Description: How the resulting file should be formatted. Methods: pub fn new() -> Typescript - Description: Constructs a new Typescript exporter with the default options configured. pub fn header(self, header: impl Into>) -> Typescript - Description: Configures a header for the file. This is perfect for configuring lint ignore rules or other file-level comments. - Parameters: - self: The Typescript instance. - header: An object that can be converted into a Cow<'static, str>, representing the desired header content. - Returns: The modified Typescript instance for chaining. pub fn bigint(self, bigint: BigIntExportBehavior) -> Typescript - Description: Configure the BigInt handling behaviour. - Parameters: - self: The Typescript instance. - bigint: A BigIntExportBehavior enum value specifying how BigInts should be handled during export. - Returns: The modified Typescript instance for chaining. ``` -------------------------------- ### taurpc::Router Struct and Methods Source: https://docs.rs/taurpc/latest/taurpc/struct.Router Documentation for the `taurpc::Router` struct, which is used to manage and dispatch RPC procedures within a Tauri application. It allows merging multiple procedure implementations and generating a handler for Tauri's IPC system. This block includes its constructor, configuration, merging, and handler creation methods. ```APIDOC impl taurpc::Router pub fn new() -> Self - Description: Creates a new, empty `Router` instance. - Parameters: None - Returns: `Self` (a new `Router` instance) pub fn export_config(self, config: specta_typescript::Typescript) -> Self - Description: Overwrites `specta`’s default TypeScript export options. Refer to `specta_typescript::Typescript` for configuration details. - Parameters: - `self`: The `Router` instance. - `config`: A `specta_typescript::Typescript` struct containing the desired export configuration. - Returns: `Self` (the modified `Router` instance) pub fn merge>(self, handler: H) -> Self - Description: Adds routes to the router by merging a handler. Accepts a struct for which a `#[taurpc::procedures]` trait is implemented. - Parameters: - `self`: The `Router` instance. - `handler`: An instance of a struct that implements `TauRpcHandler`. - Returns: `Self` (the `Router` instance with merged handlers) pub fn into_handler(self) -> impl Fn(tauri::ipc::Invoke) -> bool - Description: Creates a handler function from the router that allows IPCs to be called from the frontend and generates corresponding types. This function should be used inside `tauri::Builder::invoke_handler()`. - Parameters: - `self`: The `Router` instance. - Returns: An `impl Fn(tauri::ipc::Invoke) -> bool` closure, suitable for Tauri's `invoke_handler`. ``` -------------------------------- ### Rust `Typescript` Struct Methods for Configuration and Export Source: https://docs.rs/taurpc/latest/taurpc/struct.Typescript This section provides the API documentation for the `Typescript` struct, which is used to configure and perform the export of Rust types into TypeScript definitions. It includes methods for customizing comment styles, applying code formatting to the output, and exporting the generated TypeScript code. ```APIDOC pub fn comment_style(self, exporter: fn(CommentFormatterArgs<'_>) -> String) -> Typescript - Description: Configures a function responsible for styling comments within the exported TypeScript definitions. - Parameters: - `exporter`: `fn(CommentFormatterArgs<'_>) -> String` - A function that takes `CommentFormatterArgs` and returns a `String` representing the styled comment. - Returns: `Typescript` - The modified `Typescript` instance for chaining. - Notes: Not calling this method defaults to `js_doc`. Passing `None` disables comment exporting. Passing `Some(exporter)` enables comment exporting using the provided function. pub fn formatter(self, formatter: fn(&Path) -> Result<(), Error>) -> Typescript - Description: Configures a function responsible for formatting the generated TypeScript file(s). - Parameters: - `formatter`: `fn(&Path) -> Result<(), Error>` - A function that takes a `Path` to the file to be formatted and returns a `Result` indicating success or an `Error`. - Returns: `Typescript` - The modified `Typescript` instance for chaining. - Notes: Built-in implementations include `prettier`, `ESLint`, and `Biome`. pub fn export(&self, types: &[TypeCollection]) -> Result - Description: Exports the given type collections into a single TypeScript string. - Parameters: - `types`: `&[TypeCollection]` - A slice of `TypeCollection` instances containing the types to be exported. - Returns: `Result` - A `Result` containing the exported TypeScript code as a `String` on success, or an `ExportError` on failure. pub fn export_to(&self, path: impl AsRef, types: &[TypeCollection]) -> Result<(), ExportError> - Description: Exports the given type collections to a specified file path. - Parameters: - `path`: `impl AsRef` - The path where the TypeScript definitions should be written. - `types`: `&[TypeCollection]` - A slice of `TypeCollection` instances containing the types to be exported. - Returns: `Result<(), ExportError>` - A `Result` indicating success or an `ExportError` on failure. pub fn format(&self, path: impl AsRef) -> Result<(), ExportError> - Description: Formats an existing file at the given path using the configured formatter. - Parameters: - `path`: `impl AsRef` - The path to the file that needs to be formatted. - Returns: `Result<(), ExportError>` - A `Result` indicating success or an `ExportError` on failure. ``` -------------------------------- ### Rust Tauri RPC Command Handler Initialization and Dispatch Source: https://docs.rs/taurpc/latest/src/taurpc/lib.rs This Rust snippet defines the core logic for handling remote procedure calls (RPC) in a Tauri application. The `into_handler` method sets up the main command handler, optionally exporting types for debug builds. The `on_command` method processes incoming `Invoke` messages, parsing the command name to dispatch it to the correct internal handler, specifically targeting commands prefixed with 'TauRPC__'. It includes logic for extracting the command path and resolving it to a registered handler, returning an error if the command is not found. ```Rust pub fn into_handler(self) -> impl Fn(Invoke) -> bool { #[cfg(debug_assertions)] // Only export in development builds export_types( self.export_path, self.args_map_json.clone(), self.export_config.clone(), self.fns_map.clone(), self.types.clone(), ) .unwrap(); move |invoke: Invoke| self.on_command(invoke) } fn on_command(&self, invoke: Invoke) -> bool { let cmd = invoke.message.command(); if !cmd.starts_with("TauRPC__") { return false; } // Remove `TauRPC__` let prefix = cmd[8..].to_string(); let mut prefix = prefix.split('.').collect::>(); // Remove the actual name of the command prefix.pop().unwrap(); match self.handlers.get(&prefix.join(".")) { Some(handler) => { let _ = handler.send(Arc::new(invoke)); } None => invoke .resolver .invoke_error(InvokeError::from(format!("`{cmd}` not found"))), }; true } ``` -------------------------------- ### Rust TryInto Trait Implementation Source: https://docs.rs/taurpc/latest/taurpc/struct.Router Documentation for the `TryInto` trait implementation, which is a reciprocal of `TryFrom`. This implementation allows converting `T` into `U` if `U` can be `TryFrom` `T`. ```APIDOC impl TryInto for T where U: TryFrom - Associated Type: - type Error = >::Error - Description: The type returned in the event of a conversion error, inherited from the `TryFrom` implementation for `U`. ``` -------------------------------- ### Rust TryFrom Trait Implementation Source: https://docs.rs/taurpc/latest/taurpc/struct.Router Documentation for the `TryFrom` trait implementation, allowing fallible conversions between types. This specific implementation handles conversions where the source type can be `Into` the target type, resulting in an `Infallible` error type. ```APIDOC impl TryFrom for T where U: Into - Associated Type: - type Error = Infallible - Description: The type returned in the event of a conversion error. For this implementation, conversion is infallible. - Method: - fn try_from(value: U) -> Result>::Error> - Description: Performs the conversion from `U` to `T`. Since `U` is `Into`, this conversion is guaranteed to succeed and returns `Ok(T)`. ``` -------------------------------- ### Rust TauRPC Router Integration with Tauri Builder Source: https://docs.rs/taurpc/latest/src/taurpc/lib.rs Shows how to integrate the TauRPC `Router` into a Tauri application by passing its `into_handler()` output to the `tauri::Builder::invoke_handler()` method. This is the final step to make the defined RPC procedures callable from the frontend. ```Rust tauri::Builder::default() .invoke_handler(router.into_handler()) .run(tauri::generate_context!()) ``` -------------------------------- ### Default Implementation for taurpc::Router Source: https://docs.rs/taurpc/latest/taurpc/struct.Router This section documents the `Default` trait implementation for `taurpc::Router`, providing a way to create a default instance of the router. ```APIDOC impl Default for taurpc::Router fn default() -> taurpc::Router - Description: Returns the “default value” for a `Router` type. - Parameters: None - Returns: A default `taurpc::Router` instance. ``` -------------------------------- ### TauRPC Crate Re-exports Source: https://docs.rs/taurpc/latest/taurpc/index The `taurpc` crate re-exports essential dependencies for convenience, allowing direct access to their functionalities within your project without needing to explicitly declare them. ```Rust pub extern crate serde; pub extern crate specta; pub extern crate specta_macros; ``` -------------------------------- ### Rust TauRPC Router Struct Methods Source: https://docs.rs/taurpc/latest/src/taurpc/lib.rs Provides methods for the `Router` struct in TauRPC, enabling the creation of a new router, configuration of TypeScript export options, and merging of multiple RPC handlers into a single router. This struct is central to defining and managing RPC endpoints in Tauri applications. ```Rust pub fn new() -> Self { Self { types: TypeCollection::default(), handlers: HashMap::new(), fns_map: BTreeMap::new(), export_path: None, args_map_json: BTreeMap::new(), export_config: specta_typescript::Typescript::default(), } } pub fn export_config(mut self, config: specta_typescript::Typescript) -> Self { self.export_config = config; self } pub fn merge>(mut self, handler: H) -> Self { if let Some(path) = H::EXPORT_PATH { self.export_path = Some(path) } self.args_map_json .insert(H::PATH_PREFIX.to_string(), H::args_map()); self.fns_map.insert( H::PATH_PREFIX.to_string(), H::collect_fn_types(&mut self.types), ); self.handlers .insert(H::PATH_PREFIX.to_string(), handler.spawn()); self } ``` -------------------------------- ### Rust From and Into Trait Implementations Source: https://docs.rs/taurpc/latest/taurpc/struct.Typescript Documents the `From` and `Into` traits, which are core to Rust's type conversion system. `From` allows converting one type into another, while `Into` is automatically implemented for any type that implements `From` for the target type, providing a convenient way to convert types. ```APIDOC From Trait: impl From for T fn from(t: T) -> T - Returns the argument unchanged. - Parameters: - t: T - The value to return. - Returns: T - The input value itself. Into Trait: impl Into for T where U: From fn into(self) -> U - Calls `U::from(self)`. This conversion is determined by the `From for U` implementation. - Parameters: - self: The value to convert. - Returns: U - The converted value. ``` -------------------------------- ### Rust Trait API: TryInto and ErasedDestructor Source: https://docs.rs/taurpc/latest/taurpc/struct.Router This section documents key Rust API elements related to type conversions via the `TryInto` trait and the `ErasedDestructor` trait. It includes the signature for `try_into` which performs fallible conversions, and the generic implementation signature for `ErasedDestructor` for types with a static lifetime. ```APIDOC fn try_into(self) -> Result>::Error> - Description: Performs a fallible conversion from `self` into type `U`. - Parameters: - self: The value to be converted. - Returns: A `Result` enum, which is `Ok(U)` on success or `Err(>::Error)` on failure. impl ErasedDestructor for T where T: 'static, - Description: Implements the `ErasedDestructor` trait for any type `T` that has a `'static` lifetime. This trait is typically used for managing destructors of types whose concrete type has been erased. ``` -------------------------------- ### EventTrigger Structure for Tauri Event Emission Source: https://docs.rs/taurpc/latest/src/taurpc/lib.rs Defines a structure for triggering Tauri events from the backend to the frontend. It encapsulates the `AppHandle`, path prefix, and event target, allowing events to be emitted to all windows by default or scoped to specific windows using `new_scoped` or `new_scoped_from_trigger`. ```APIDOC pub struct EventTrigger { app_handle: AppHandle, path_prefix: String, target: EventTarget, } impl Clone for EventTrigger { fn clone(&self) -> Self { Self { app_handle: self.app_handle.clone(), path_prefix: self.path_prefix.clone(), target: self.target.clone(), } } } impl EventTrigger { pub fn new(app_handle: AppHandle, path_prefix: String) -> Self { Self { app_handle, path_prefix, ``` -------------------------------- ### TauRPC Core Structs Source: https://docs.rs/taurpc/latest/taurpc/index Key structures provided by the `taurpc` crate for managing events, routing IPC calls, and exporting TypeScript types. These structs facilitate the core functionalities of the typesafe IPC layer. ```APIDOC EventTrigger: A structure used for triggering tauri events on the frontend. By default the events are send to all windows with `emit_all`, if you want to send to a specific window by label, use `new_scoped` or `new_scoped_from_trigger`. Router: Used for merging nested trait implementations. This is used when you have multiple trait implementations, instead of `taurpc::create_ipc_handler()`. Use `.merge()` to add trait implementations to the router. The trait must have the `#[taurpc::procedures]` macro and the nested routes should have `#[taurpc::procedures(path = "path")]`. Typescript: Typescript language exporter. ``` -------------------------------- ### Rust Core Conversion Traits: TryFrom and TryInto Source: https://docs.rs/taurpc/latest/taurpc/struct.Typescript Documents the `TryFrom` and `TryInto` traits from Rust's `core::convert` module, which provide fallible type conversion mechanisms. It includes the `try_from` and `try_into` methods, along with the associated `Error` type for handling conversion failures. ```APIDOC Trait: core::convert::TryFrom fn try_from(value: U) -> Result>::Error> - Description: Performs the conversion from `U` to `T`. - Parameters: - value: The value of type `U` to convert. - Returns: A `Result` containing `T` on success or `>::Error` on failure. Trait: core::convert::TryInto impl TryInto for T where U: TryFrom, - Description: A blanket implementation that allows any type `T` to be converted into `U` if `U` implements `TryFrom`. - Associated Type: - type Error = >::Error - Description: The type returned in the event of a conversion error. - Method: - fn try_into(self) -> Result>::Error> - Description: Performs the conversion from `self` (type `T`) to `U`. - Parameters: - self: The value of type `T` to convert. - Returns: A `Result` containing `U` on success or `>::Error` on failure. ``` -------------------------------- ### Into Trait Blanket Implementation Source: https://docs.rs/taurpc/latest/taurpc/struct.Router Explains the blanket implementation of the `Into` trait for any type `T` where `U` implements `From`. This trait provides a convenient way to convert one type into another, leveraging the `From` implementation for the target type. ```APIDOC impl Into for T where U: From fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From for U` chooses to do. ``` -------------------------------- ### Any Trait Blanket Implementation Source: https://docs.rs/taurpc/latest/taurpc/struct.Router Details the blanket implementation of the `Any` trait for all types `T` that are `'static` and optionally `Sized`. This trait allows querying a type's `TypeId` at runtime, which is fundamental for downcasting and dynamic type introspection. ```APIDOC impl Any for T where T: 'static + ?Sized fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. ``` -------------------------------- ### Rust IntoEither Trait Methods Source: https://docs.rs/taurpc/latest/taurpc/struct.Router Documentation for methods of the `IntoEither` trait, which provides functionality to convert a type into an `Either` enum variant based on a condition or a predicate closure. ```APIDOC fn into_either(self, into_left: bool) -> Either - Converts `self` into a `Left` variant of `Either` if `into_left` is `true`. - Converts `self` into a `Right` variant of `Either` otherwise. - Parameters: - self: The instance to convert. - into_left: A boolean indicating whether to convert to `Left` (true) or `Right` (false). - Returns: An `Either` enum. fn into_either_with(self, into_left: F) -> Either where F: FnOnce(&Self) -> bool - Converts `self` into a `Left` variant of `Either` if `into_left(&self)` returns `true`. - Converts `self` into a `Right` variant of `Either` otherwise. - Parameters: - self: The instance to convert. - into_left: A closure `F` that takes a reference to `self` and returns a boolean, determining the conversion. - Returns: An `Either` enum. ``` -------------------------------- ### Merge Handlers into taurpc Router Source: https://docs.rs/taurpc/latest/taurpc/struct.Router This snippet illustrates how to add multiple RPC handler implementations to a `taurpc::Router`. The `merge` method accepts any struct for which a `#[taurpc::procedures]` trait is implemented, allowing the router to combine different sets of RPC functionalities. ```Rust let router = Router::new() .merge(ApiImpl.into_handler()) .merge(EventsImpl.into_handler()); ``` -------------------------------- ### Taurpc Core Function API Reference Source: https://docs.rs/taurpc/latest/taurpc/trait.TauRpcHandler Detailed API specifications for the main functions in the `taurpc` library, including their signatures, parameters, return values, and a brief description of their functionality. These functions are crucial for managing IPC requests and integrating with frontend applications. ```APIDOC fn handle_incoming_request(self, invoke: Invoke) - Description: Handles a single incoming request received by the `taurpc` router. - Parameters: - invoke: `Invoke` (tauri::ipc::Invoke) - The incoming IPC invoke request containing method and arguments. - Returns: None fn spawn(self) -> Sender>> - Description: Spawns a new `tokio` thread dedicated to listening for and processing incoming requests via a `tokio::broadcast::channel`. This is particularly useful for scenarios where a router manages multiple handlers concurrently. - Returns: `Sender>>` (tokio::sync::broadcast::Sender) - A sender for broadcasting `Invoke` requests to the spawned thread. fn args_map() -> String - Description: Generates and returns a JSON object that describes the arguments expected by the methods. This mapping is essential for frontend applications to correctly serialize and send arguments with their corresponding identifiers to the backend. - Returns: `String` (alloc::string::String) - A JSON string representing the argument map. fn collect_fn_types(type_map: &mut TypeCollection) -> Vec - Description: Gathers all functions intended for export and adds any referenced types to the provided `type_map`. This function is critical for generating type-safe bindings or documentation for external consumers. - Parameters: - type_map: `&mut TypeCollection` (specta::type_collection::TypeCollection) - A mutable collection where all referenced types will be added. - Returns: `Vec` (specta::datatype::function::Function) - A vector containing metadata for all collected functions. ``` -------------------------------- ### From Trait Blanket Implementation Source: https://docs.rs/taurpc/latest/taurpc/struct.Router Documents the blanket implementation of the `From` trait for `T` itself. This trivial implementation signifies that any type can be converted into itself, primarily serving as a base case or identity conversion in generic contexts. ```APIDOC impl From for T fn from(t: T) -> T Returns the argument unchanged. ``` -------------------------------- ### Create TauRPC IPC Handler for Tauri Source: https://docs.rs/taurpc/latest/src/taurpc/lib.rs This function constructs the main IPC handler for Tauri applications using an implementation of the `TauRpcHandler` trait. It sets up argument mapping, collects function types, and conditionally exports TypeScript types during development, enabling typesafe communication between Rust and the frontend. ```Rust pub fn create_ipc_handler( procedures: H, ) -> impl Fn(Invoke) -> bool + Send + Sync + 'static where H: TauRpcHandler + Send + Sync + 'static + Clone, { let args_map = BTreeMap::from([(H::PATH_PREFIX.to_string(), H::args_map())]); let mut type_map = TypeCollection::default(); let functions = BTreeMap::from([ (H::PATH_PREFIX.to_string(), H::collect_fn_types(&mut type_map)), ]); #[cfg(debug_assertions)] // Only export in development builds export_types( H::EXPORT_PATH, args_map, specta_typescript::Typescript::default(), functions, type_map, ) .unwrap(); move |invoke: Invoke| { procedures.clone().handle_incoming_request(invoke); true } } ``` -------------------------------- ### Rust `#[resolvers]` Attribute Macro for Async Method Transformation Source: https://docs.rs/taurpc/latest/taurpc/attr.resolvers This attribute macro, part of the `taurpc` crate, is used to automatically transform method signatures. When applied, it causes methods to return `Pin>>`, which is necessary for handling asynchronous operations within the Tauri RPC framework. A notable limitation is that this macro does not support async traits. ```Rust #[resolvers] ``` -------------------------------- ### Rust `Default` Trait Implementation for `Typescript` Source: https://docs.rs/taurpc/latest/taurpc/struct.Typescript Describes the `Default` trait implementation for the `Typescript` struct, allowing for the creation of a default instance of the type. This is useful for initializing structs without providing all fields explicitly. ```APIDOC fn default() -> Typescript - Returns the "default value" for the `Typescript` type. - Parameters: None. - Returns: A new `Typescript` instance initialized with its default values. ``` -------------------------------- ### Rust CloneToUninit Trait Implementation Source: https://docs.rs/taurpc/latest/taurpc/struct.Typescript Documents the `CloneToUninit` trait, an experimental nightly-only API in Rust, which allows performing a copy-assignment from a value to an uninitialized memory destination. This is typically used in low-level memory manipulation scenarios. ```APIDOC CloneToUninit Trait: impl CloneToUninit for T where T: Clone unsafe fn clone_to_uninit(&self, dest: *mut u8) - Performs copy-assignment from `self` to `dest`. - Note: This is a nightly-only experimental API. - Parameters: - &self: The source value to copy from. - dest: *mut u8 - A raw mutable pointer to the uninitialized destination memory. - Returns: None (unsafe operation). ``` -------------------------------- ### TauRpcHandler Trait API Reference Source: https://docs.rs/taurpc/latest/taurpc/trait.TauRpcHandler Detailed API documentation for the `TauRpcHandler` trait, including its required associated constants and methods. This trait is crucial for defining how RPC procedures are handled and how their types are collected for bindings generation in `taurpc` applications. ```APIDOC TauRpcHandler Trait: A trait, which is automatically implemented by `#[taurpc::procedures]`, that is used for handling incoming requests and the type generation. Required Associated Constants: const TRAIT_NAME: &'static str - Description: The name of the trait. const PATH_PREFIX: &'static str - Description: This handler’s prefix in the TypeScript router. const EXPORT_PATH: Option<&'static str> - Description: Bindings export path optionally specified by the user. Required Methods: fn handle_incoming_request(self, invoke: Invoke) - Description: Handles an incoming RPC request. - Parameters: - self: The trait implementor instance. - invoke: The `Invoke` struct containing the request details. fn spawn(self) -> Sender>> - Description: Spawns a new task or thread for handling requests. - Parameters: - self: The trait implementor instance. - Returns: A `Sender` for sending `Invoke` requests. fn args_map() -> String - Description: Returns a string representation of the arguments map. - Parameters: None - Returns: A `String` representing the arguments map. fn collect_fn_types(type_map: &mut TypeCollection) -> Vec - Description: Collects function types into a type map for type generation. - Parameters: - type_map: A mutable reference to a `TypeCollection` to populate. - Returns: A `Vec` containing the collected function types. ``` -------------------------------- ### Rust taurpc `#[procedures]` Attribute Macro Usage Source: https://docs.rs/taurpc/latest/taurpc/attr.procedures This attribute macro, `#[procedures]`, is used in the `taurpc` crate to automatically generate the necessary Rust structs and enums for handling remote procedure calls (RPC). It also facilitates the generation of corresponding TypeScript types for frontend integration. This macro simplifies the boilerplate required for defining RPC interfaces. ```Rust #[procedures] ``` -------------------------------- ### Rust CloneToUninit Trait API Source: https://docs.rs/taurpc/latest/taurpc/struct.EventTrigger Documents the `CloneToUninit` trait, an experimental nightly-only API, which enables performing copy-assignment from a value to an uninitialized memory location. This is typically used for low-level memory manipulation. ```APIDOC impl CloneToUninit for T where T: Clone unsafe fn clone_to_uninit(&self, dest: *mut u8) - Description: Performs copy-assignment from `self` to the memory location pointed to by `dest`. - Parameters: - self: The source value to clone from. - dest: A mutable raw pointer to an uninitialized `u8` memory location where `self` will be copied. - Returns: None (void function). - Note: This is a nightly-only experimental API (`clone_to_uninit`). ``` -------------------------------- ### Rust `Debug` Trait Implementation for `Typescript` Source: https://docs.rs/taurpc/latest/taurpc/struct.Typescript Details the `Debug` trait implementation for the `Typescript` struct, which enables formatted debugging output. The `fmt` method allows the value to be represented in a human-readable format. ```APIDOC fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> - Formats the value using the given formatter for debugging purposes. - Parameters: - &self: A reference to the instance to be formatted. - f: &mut Formatter<'_>: A mutable reference to the formatter. - Returns: A `Result` indicating success or an `Error` if formatting fails. ``` -------------------------------- ### Rust taurpc::create_ipc_handler Function API Source: https://docs.rs/taurpc/latest/taurpc/fn.create_ipc_handler Defines the API signature for `create_ipc_handler`, a core function in the `taurpc` crate. This function is responsible for generating a handler that enables inter-process communication (IPC) between the frontend and backend in Tauri applications, allowing frontend calls to trigger Rust procedures. ```APIDOC Function: create_ipc_handler Signature: pub fn create_ipc_handler(procedures: H) -> impl Fn(Invoke) -> bool + Send + Sync + 'static Parameters: procedures: H Type: H (where H: TauRpcHandler + Send + Sync + 'static + Clone) Description: An instance of a struct that implements the `TauRpcHandler` trait. This struct should contain the definitions and implementations of your RPC procedures, typically marked with `#[taurpc::procedures]` and `#[taurpc::resolvers]`. Returns: impl Fn(Invoke) -> bool + Send + Sync + 'static Description: A closure suitable for use as an `invoke_handler` in a Tauri application. This closure processes incoming `Invoke` events from the frontend, dispatching them to the appropriate Rust RPC procedure. It returns `true` if the IPC call was handled, `false` otherwise. Constraints: H: Must implement `TauRpcHandler`, `Send`, `Sync`, `Clone`, and have a `'static` lifetime. R: Must implement `tauri::Runtime`. ``` -------------------------------- ### Rust From Trait API Source: https://docs.rs/taurpc/latest/taurpc/struct.EventTrigger Documents the `From` trait, a fundamental Rust trait for type conversion. It defines how a type can be converted from another type, providing a simple and explicit conversion mechanism. ```APIDOC impl From for T fn from(t: T) -> T - Description: Returns the argument unchanged. This is the identity conversion, meaning a type can be converted from itself. - Parameters: - t: The value of type `T`. - Returns: The input value `t` of type `T`. ``` -------------------------------- ### EventTrigger Clone Trait Implementation (Rust) Source: https://docs.rs/taurpc/latest/taurpc/struct.EventTrigger This section details the implementation of the `Clone` trait for the `EventTrigger` struct, allowing instances to be duplicated. It includes the `clone` method for creating a new identical instance and `clone_from` for copying state from another instance. ```APIDOC impl Clone for EventTrigger fn clone(&self) -> Self - Description: Returns a duplicate of the `EventTrigger` value. - Parameters: - &self: Reference to the `EventTrigger` instance to clone. - Returns: Self (a new, identical `EventTrigger` instance). fn clone_from(&mut self, source: &Self) - Description: Performs copy-assignment from a `source` `EventTrigger` to `self`. - Parameters: - &mut self: Mutable reference to the `EventTrigger` instance to be modified. - source: &Self - The `EventTrigger` instance to copy from. - Returns: None (modifies `self` in place). ``` -------------------------------- ### Rust TauRPC Trigger Struct Methods Source: https://docs.rs/taurpc/latest/src/taurpc/lib.rs Defines methods for the `Trigger` struct in TauRPC, used for creating scoped event triggers and making RPC calls with specified event names and data. These methods facilitate sending events to a target within the Tauri application. ```Rust pub fn new_scoped>( app_handle: AppHandle, path_prefix: String, target: I, ) -> Self { Self { app_handle, path_prefix, target: target.into(), } } pub fn new_scoped_from_trigger(trigger: Self, target: EventTarget) -> Self { Self { app_handle: trigger.app_handle, path_prefix: trigger.path_prefix, target, } } pub fn call(&self, proc_name: &str, event: S) -> tauri::Result<()> { let event_name = if self.path_prefix.is_empty() { proc_name.to_string() } else { format!("{}.{}", self.path_prefix, proc_name) }; let event = Event { event_name, event }; let _ = self .app_handle .emit_to(self.target.clone(), "TauRpc_event", event); Ok(()) } ```