From cd55d671498d48cf83ae603c4241031b9827119b Mon Sep 17 00:00:00 2001 From: "Ngo Iok Ui (Wu Yu Wei)" Date: Mon, 16 Aug 2021 22:32:37 +0800 Subject: [PATCH] doc: update tauri documentations (#2446) --- .changes/doc-tauri-utils.md | 4 +- ARCHITECTURE.md | 20 +------- core/tauri-codegen/src/context.rs | 2 +- core/tauri-codegen/src/embedded_assets.rs | 2 +- core/tauri-utils/src/config.rs | 11 +++-- core/tauri/src/api/cli.rs | 23 +++++----- core/tauri/src/api/dialog.rs | 3 ++ core/tauri/src/api/dir.rs | 13 +++--- core/tauri/src/api/file.rs | 2 + core/tauri/src/api/file/extract.rs | 2 +- core/tauri/src/api/http.rs | 24 +++++----- core/tauri/src/api/mod.rs | 24 ++-------- core/tauri/src/api/notification.rs | 5 +- core/tauri/src/api/path.rs | 18 +++++--- core/tauri/src/api/process.rs | 6 ++- core/tauri/src/api/process/command.rs | 19 ++++---- core/tauri/src/api/rpc.rs | 17 +++++-- core/tauri/src/api/shell.rs | 4 +- core/tauri/src/api/version.rs | 2 + core/tauri/src/app.rs | 4 +- core/tauri/src/async_runtime.rs | 21 +++++---- core/tauri/src/command.rs | 5 +- core/tauri/src/endpoints.rs | 3 +- core/tauri/src/endpoints/app.rs | 2 +- core/tauri/src/endpoints/cli.rs | 2 +- core/tauri/src/endpoints/window.rs | 2 +- core/tauri/src/lib.rs | 56 +++++++++++------------ core/tauri/src/manager.rs | 10 ++-- core/tauri/src/plugin.rs | 12 ++--- core/tauri/src/settings.rs | 11 +++-- core/tauri/src/updater/mod.rs | 9 ++-- core/tauri/src/window.rs | 4 +- 32 files changed, 178 insertions(+), 164 deletions(-) diff --git a/.changes/doc-tauri-utils.md b/.changes/doc-tauri-utils.md index d892be95b..73d4c438c 100644 --- a/.changes/doc-tauri-utils.md +++ b/.changes/doc-tauri-utils.md @@ -2,4 +2,6 @@ "tauri": minor --- -`tauri::api` no longer re-export items in `tauri-utils`. We already expose necessary items in the root of `tauri`. +Move items which `tauri::api` re-exports from `tauri-utils` to individual module `utils`. Because these items has their +own Error/Result types which are not related to api module at all. + diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 4e3478780..af52c47fb 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -15,7 +15,7 @@ Tauri apps can have custom menus and have tray-type interfaces. They can be upda The following section briefly describes the roles of the various parts of Tauri. ### Tauri Core [STABLE RUST] #### [tauri](https://github.com/tauri-apps/tauri/tree/dev/core/tauri) -This is the glue crate that holds everything together. It brings the runtimes, macros, utilities and API into one final product. It reads the `tauri.conf.json` file at compile time in order to bring in features and undertake actual configuration of the app (and even the `Cargo.toml` file in the project's folder). It handles script injection (for polyfills / prototype revision) at runtime, hosts the API for systems interaction, and even manages updating. +This is the major crate that holds everything together. It brings the runtimes, macros, utilities and API into one final product. It reads the `tauri.conf.json` file at compile time in order to bring in features and undertake actual configuration of the app (and even the `Cargo.toml` file in the project's folder). It handles script injection (for polyfills / prototype revision) at runtime, hosts the API for systems interaction, and even manages updating. #### [tauri-build](https://github.com/tauri-apps/tauri/tree/dev/core/tauri-build) Apply the macros at build-time in order to rig some special features needed by `cargo`. @@ -53,24 +53,6 @@ This rust executable provides the full interface to all of the required activiti #### [create-tauri-app](https://github.com/tauri-apps/tauri/tree/dev/tooling/create-tauri-app) [JS] This is a toolkit that will enable engineering teams to rapidly scaffold out a new tauri-apps project using the frontend framework of their choice (as long as it has been configured). -## TAURI RUST API -- **app** The App API module allows you to manage application processes. -- **assets** The Assets module allows you to read files that have been bundled by tauri Assets handled by Tauri during compile time and runtime. -- **config** The Tauri config definition. -- **dialog** The Dialog API module allows you to show messages and prompt for file paths. -- **dir** The Dir module is a helper for file system directory management. -- **file** The File API module contains helpers to perform file operations. -- **http** The HTTP request API. -- **notification** The desktop notifications API module. -- **path** The file system path operations API. -- **process** Process helpers including the management of child processes. -- **rpc** The RPC module includes utilities to send messages to the JS layer of the webview. -- **shell** The shell api. -- **shortcuts** Global shortcuts interface. -- **version** The semver API. - - - # External Crates The Tauri-Apps organisation maintains two "upstream" crates from Tauri, namely TAO for creating and managing application windows, and WRY for interfacing with the Webview that lives within the window. diff --git a/core/tauri-codegen/src/context.rs b/core/tauri-codegen/src/context.rs index 293dbf180..bd4307238 100644 --- a/core/tauri-codegen/src/context.rs +++ b/core/tauri-codegen/src/context.rs @@ -97,7 +97,7 @@ pub fn context_codegen(data: ContextData) -> Result { $tokens.append_all(quote! { - ::tauri::api::config::$struct { + ::tauri::utils::config::$struct { $($field: #$field),+ } }); @@ -657,7 +658,7 @@ mod build { impl ToTokens for WindowUrl { fn to_tokens(&self, tokens: &mut TokenStream) { - let prefix = quote! { ::tauri::api::config::WindowUrl }; + let prefix = quote! { ::tauri::utils::config::WindowUrl }; tokens.append_all(match self { Self::App(path) => { @@ -834,7 +835,7 @@ mod build { impl ToTokens for AppUrl { fn to_tokens(&self, tokens: &mut TokenStream) { - let prefix = quote! { ::tauri::api::config::AppUrl }; + let prefix = quote! { ::tauri::utils::config::AppUrl }; tokens.append_all(match self { Self::Url(url) => { @@ -915,7 +916,7 @@ mod build { str_lit, json_value_lit, ); - tokens.append_all(quote! { ::tauri::api::config::PluginConfig(#config) }) + tokens.append_all(quote! { ::tauri::utils::config::PluginConfig(#config) }) } } diff --git a/core/tauri/src/api/cli.rs b/core/tauri/src/api/cli.rs index 5d355d410..feda0e824 100644 --- a/core/tauri/src/api/cli.rs +++ b/core/tauri/src/api/cli.rs @@ -2,7 +2,9 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT -use crate::api::config::{CliArg, CliConfig}; +//! Types and functions related to CLI arguments. + +use crate::utils::config::{CliArg, CliConfig}; use clap::{ crate_authors, crate_description, crate_name, crate_version, App, Arg, ArgMatches, ErrorKind, @@ -14,17 +16,16 @@ use std::collections::HashMap; #[macro_use] mod macros; -/// The resolution of a arg match. +/// The resolution of a argument match. #[derive(Default, Debug, Serialize)] #[non_exhaustive] pub struct ArgData { - /// The value of the arg. - /// - Value::Bool if it's a flag, - /// - Value::Array if it's multiple, - /// - Value::String if it has value, - /// - Value::Null otherwise. + /// - [`Value::Bool`] if it's a flag, + /// - [`Value::Array`] if it's multiple, + /// - [`Value::String`] if it has value, + /// - [`Value::Null`] otherwise. pub value: Value, - /// The number of occurrences of the arg. + /// The number of occurrences of the argument. /// e.g. `./app --arg 1 --arg 2 --arg 2 3 4` results in three occurrences. pub occurrences: u64, } @@ -35,11 +36,11 @@ pub struct ArgData { pub struct SubcommandMatches { /// The subcommand name. pub name: String, - /// The subcommand arg matches. + /// The subcommand argument matches. pub matches: Matches, } -/// The arg matches of a command. +/// The argument matches of a command. #[derive(Default, Debug, Serialize)] #[non_exhaustive] pub struct Matches { @@ -61,7 +62,7 @@ impl Matches { } } -/// Gets the arg matches of the CLI definition. +/// Gets the argument matches of the CLI definition. pub fn get_matches(cli: &CliConfig) -> crate::api::Result { let about = cli .description() diff --git a/core/tauri/src/api/dialog.rs b/core/tauri/src/api/dialog.rs index d1e5c53b6..859e76e6a 100644 --- a/core/tauri/src/api/dialog.rs +++ b/core/tauri/src/api/dialog.rs @@ -2,6 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT +//! Types and functions related to display dialog. + #[cfg(any(dialog_open, dialog_save))] use std::path::{Path, PathBuf}; @@ -29,6 +31,7 @@ macro_rules! run_dialog { } /// The file dialog builder. +/// /// Constructs file picker dialogs that can select single/multiple files or directories. #[cfg(any(dialog_open, dialog_save))] #[derive(Debug, Default)] diff --git a/core/tauri/src/api/dir.rs b/core/tauri/src/api/dir.rs index 0fe101821..aa4deb278 100644 --- a/core/tauri/src/api/dir.rs +++ b/core/tauri/src/api/dir.rs @@ -2,6 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT +//! Types and functions related to file system directory management. + use serde::Serialize; use std::{ fs::{self, metadata}, @@ -9,16 +11,15 @@ use std::{ }; use tempfile::{self, tempdir}; -/// The result of the `read_dir` function. +/// A disk entry which is either a file or a directory. /// -/// A DiskEntry is either a file or a directory. -/// The `children` Vec is always `Some` if the entry is a directory. +/// This is the result of the [`read_dir`]. The `children` field is always `Some` if the entry is a directory. #[derive(Debug, Serialize)] #[non_exhaustive] pub struct DiskEntry { - /// The path to this entry. + /// The path to the entry. pub path: PathBuf, - /// The name of this entry (file name with extension or directory name) + /// The name of the entry (file name with extension or directory name). pub name: Option, /// The children of this entry if it's a directory. #[serde(skip_serializing_if = "Option::is_none")] @@ -59,7 +60,7 @@ pub fn read_dir>(path: P, recursive: bool) -> crate::api::Result< Result::Ok(files_and_dirs) } -/// Runs a closure with a temp dir argument. +/// Runs a closure with a temporary directory argument. pub fn with_temp_dir(callback: F) -> crate::api::Result<()> { let dir = tempdir()?; callback(&dir); diff --git a/core/tauri/src/api/file.rs b/core/tauri/src/api/file.rs index df403873f..5a85d857c 100644 --- a/core/tauri/src/api/file.rs +++ b/core/tauri/src/api/file.rs @@ -2,6 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT +//! Types and functions related to file operations. + mod extract; mod file_move; diff --git a/core/tauri/src/api/file/extract.rs b/core/tauri/src/api/file/extract.rs index 62f5c718b..54c8ee85b 100644 --- a/core/tauri/src/api/file/extract.rs +++ b/core/tauri/src/api/file/extract.rs @@ -26,7 +26,7 @@ pub enum Compression { Gz, } -/// The extract manager. +/// The extract manager to retrieve files from archives. #[derive(Debug)] pub struct Extract<'a> { source: &'a path::Path, diff --git a/core/tauri/src/api/http.rs b/core/tauri/src/api/http.rs index e7c91803a..2173b16f6 100644 --- a/core/tauri/src/api/http.rs +++ b/core/tauri/src/api/http.rs @@ -2,6 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT +//! Types and functions related to HTTP request. + use http::{header::HeaderName, Method}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -9,13 +11,13 @@ use serde_repr::{Deserialize_repr, Serialize_repr}; use std::{collections::HashMap, path::PathBuf, time::Duration}; -/// Client builder. +/// The builder of [`Client`]. #[derive(Debug, Clone, Default, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ClientBuilder { - /// Max number of redirections to follow + /// Max number of redirections to follow. pub max_redirections: Option, - /// Connect timeout in seconds for the request + /// Connect timeout in seconds for the request. pub connect_timeout: Option, } @@ -61,7 +63,7 @@ impl ClientBuilder { } } -/// The HTTP client. +/// The HTTP client based on [`reqwest`]. #[cfg(feature = "reqwest-client")] #[derive(Debug, Clone)] pub struct Client(reqwest::Client); @@ -75,8 +77,8 @@ pub struct Client(ClientBuilder); impl Client { /// Executes an HTTP request /// - /// The response will be transformed to String, - /// If reading the response as binary, the byte array will be serialized using serde_json. + /// The response will be transformed to String. + /// If reading the response as binary, the byte array will be serialized using [`serde_json`]. pub async fn send(&self, request: HttpRequestBuilder) -> crate::api::Result { let method = Method::from_bytes(request.method.to_uppercase().as_bytes())?; @@ -132,7 +134,7 @@ impl Client { impl Client { /// Executes an HTTP request /// - /// The response will be transformed to String, + /// The response will be transformed to String. /// If reading the response as binary, the byte array will be serialized using serde_json. pub async fn send(&self, request: HttpRequestBuilder) -> crate::api::Result { let method = Method::from_bytes(request.method.to_uppercase().as_bytes())?; @@ -188,7 +190,7 @@ impl Client { #[derive(Serialize_repr, Deserialize_repr, Clone, Debug)] #[repr(u16)] #[non_exhaustive] -/// The request's response type +/// The HTTP response type. pub enum ResponseType { /// Read the response as JSON Json = 1, @@ -198,7 +200,7 @@ pub enum ResponseType { Binary, } -/// FormBody data types. +/// [`FormBody`] data types. #[derive(Debug, Deserialize)] #[serde(untagged)] #[non_exhaustive] @@ -290,7 +292,7 @@ impl HttpRequestBuilder { } } - /// Sets the request params. + /// Sets the request parameters. pub fn query(mut self, query: HashMap) -> Self { self.query = Some(query); self @@ -390,7 +392,7 @@ pub struct RawResponse { pub data: Vec, } -/// The response type. +/// The response data. #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] #[non_exhaustive] diff --git a/core/tauri/src/api/mod.rs b/core/tauri/src/api/mod.rs index e507b81f9..732a15591 100644 --- a/core/tauri/src/api/mod.rs +++ b/core/tauri/src/api/mod.rs @@ -6,27 +6,17 @@ #![warn(missing_docs)] // #![feature(const_int_pow)] -/// A module for working with processes. pub mod dialog; -/// The Dir module is a helper for file system directory management. pub mod dir; -/// The File API module contains helpers to perform file operations. pub mod file; -/// The HTTP request API. pub mod http; -/// The file system path operations API. pub mod path; -/// The Command API module allows you to manage child processes. pub mod process; -/// The RPC module includes utilities to send messages to the JS layer of the webview. pub mod rpc; -/// The shell api. #[cfg(shell_open)] pub mod shell; -/// The semver API. pub mod version; -/// The CLI args interface. #[cfg(feature = "cli")] #[cfg_attr(doc_cfg, doc(cfg(feature = "cli")))] pub mod cli; @@ -35,18 +25,14 @@ pub mod cli; #[cfg_attr(doc_cfg, doc(cfg(feature = "cli")))] pub use clap; -/// The desktop notifications API module. #[cfg(notification_all)] pub mod notification; -#[doc(hidden)] -pub use tauri_utils::*; - mod error; -/// Tauri API error. +/// The error type of Tauri API module. pub use error::Error; -/// Tauri API result type. +/// The result type of Tauri API module. pub type Result = std::result::Result; // Not public API @@ -55,9 +41,9 @@ pub mod private { pub use once_cell::sync::OnceCell; pub trait AsTauriContext { - fn config() -> &'static crate::api::config::Config; - fn assets() -> &'static crate::api::assets::EmbeddedAssets; + fn config() -> &'static crate::Config; + fn assets() -> &'static crate::utils::assets::EmbeddedAssets; fn default_window_icon() -> Option<&'static [u8]>; - fn package_info() -> crate::api::PackageInfo; + fn package_info() -> crate::PackageInfo; } } diff --git a/core/tauri/src/api/notification.rs b/core/tauri/src/api/notification.rs index af1d020e4..75d23b310 100644 --- a/core/tauri/src/api/notification.rs +++ b/core/tauri/src/api/notification.rs @@ -2,10 +2,13 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT +//! Types and functions related to desktop notifications. + #[cfg(windows)] use std::path::MAIN_SEPARATOR; -/// The Notification definition. +/// The desktop notification definition. +/// /// Allows you to construct a Notification data and send it. /// /// # Example diff --git a/core/tauri/src/api/path.rs b/core/tauri/src/api/path.rs index 4188592e9..2fc007353 100644 --- a/core/tauri/src/api/path.rs +++ b/core/tauri/src/api/path.rs @@ -2,6 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT +//! Types and functions related to file system path operations. + use std::{ env, path::{Component, Path, PathBuf}, @@ -11,11 +13,12 @@ use crate::{Config, PackageInfo}; use serde_repr::{Deserialize_repr, Serialize_repr}; -/// A Base Directory to use. -/// The base directory is the optional root of a FS operation. +/// A base directory to be used in [`resolve_path`]. +/// +/// The base directory is the optional root of a file system operation. /// If informed by the API call, all paths will be relative to the path of the given directory. /// -/// For more information, check the [dirs_next documentation](https://docs.rs/dirs_next/). +/// For more information, check the [`dirs_next` documentation](https://docs.rs/dirs_next/). #[derive(Serialize_repr, Deserialize_repr, Clone, Debug)] #[repr(u16)] #[non_exhaustive] @@ -55,7 +58,7 @@ pub enum BaseDirectory { /// The Resource directory. Resource, /// The default App config directory. - /// Resolves to ${BaseDirectory::Config}/${config.tauri.bundle.identifier} + /// Resolves to [`BaseDirectory::Config`]. App, /// The current working directory. Current, @@ -65,8 +68,9 @@ pub enum BaseDirectory { /// /// # Example /// ``` -/// use tauri::api::{path::{resolve_path, BaseDirectory}, PackageInfo}; -/// // we use the default config and a mock PackageInfo, but in an actual app you should get the Config created from tauri.conf.json and the app's PackageInfo instance +/// use tauri::{api::path::{resolve_path, BaseDirectory}, PackageInfo}; +/// // we use the default config and a mock PackageInfo, but in an actual app you should get the +/// // Config created from `tauri.conf.json` and the app's PackageInfo instance. /// let path = resolve_path( /// &Default::default(), /// &PackageInfo { @@ -219,7 +223,7 @@ pub fn video_dir() -> Option { /// Returns the path to the resource directory of this app. pub fn resource_dir(package_info: &PackageInfo) -> Option { - crate::api::platform::resource_dir(package_info).ok() + crate::utils::platform::resource_dir(package_info).ok() } /// Returns the path to the suggested directory for your app config files. diff --git a/core/tauri/src/api/process.rs b/core/tauri/src/api/process.rs index bd7f6979c..fb3a55b47 100644 --- a/core/tauri/src/api/process.rs +++ b/core/tauri/src/api/process.rs @@ -2,6 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT +//! Types and functions related to child processes management. + use std::{ env, path::PathBuf, @@ -13,7 +15,7 @@ mod command; #[cfg(shell_execute)] pub use command::*; -/// Get the current binary +/// Gets the current binary. pub fn current_binary() -> Option { let mut current_binary = None; @@ -34,7 +36,7 @@ pub fn current_binary() -> Option { current_binary } -/// Restart the process. +/// Restarts the process. pub fn restart() { if let Some(path) = current_binary() { StdCommand::new(path) diff --git a/core/tauri/src/api/process/command.rs b/core/tauri/src/api/process/command.rs index 607ca9673..01a8f55f9 100644 --- a/core/tauri/src/api/process/command.rs +++ b/core/tauri/src/api/process/command.rs @@ -33,7 +33,7 @@ fn commands() -> &'static ChildStore { &STORE } -/// Kill all child process created with [`Command`]. +/// Kills all child processes created with [`Command`]. /// By default it's called before the [`crate::App`] exits. pub fn kill_children() { for child in commands().lock().unwrap().values() { @@ -41,7 +41,7 @@ pub fn kill_children() { } } -/// Payload for the `Terminated` command event. +/// Payload for the [`CommandEvent::Terminated`] command event. #[derive(Debug, Clone, Serialize)] pub struct TerminatedPayload { /// Exit code of the process. @@ -85,7 +85,7 @@ macro_rules! get_std_command { }}; } -/// API to spawn commands. +/// The type to spawn commands. #[derive(Debug)] pub struct Command { program: String, @@ -95,7 +95,7 @@ pub struct Command { current_dir: Option, } -/// Child spawned. +/// Spawned child process. #[derive(Debug)] pub struct CommandChild { inner: Arc, @@ -103,13 +103,13 @@ pub struct CommandChild { } impl CommandChild { - /// Write to process stdin. + /// Writes to process stdin. pub fn write(&mut self, buf: &[u8]) -> crate::api::Result<()> { self.stdin_writer.write_all(buf)?; Ok(()) } - /// Send a kill signal to the child. + /// Sends a kill signal to the child. pub fn kill(self) -> crate::api::Result<()> { self.inner.kill()?; Ok(()) @@ -133,7 +133,7 @@ impl ExitStatus { self.code } - /// Was termination successful? Signal termination is not considered a success, and success is defined as a zero exit status. + /// Returns true if exit status is zero. Signal termination is not considered a success, and success is defined as a zero exit status. pub fn success(&self) -> bool { self.code == Some(0) } @@ -187,6 +187,9 @@ impl Command { } /// Creates a new Command for launching the given sidecar program. + /// + /// A sidecar program is a embedded external binary in order to make your application work + /// or to prevent users having to install additional dependencies (e.g. Node.js, Python, etc). pub fn new_sidecar>(program: S) -> crate::Result { let program = format!( "{}-{}", @@ -196,7 +199,7 @@ impl Command { Ok(Self::new(relative_command_path(program)?)) } - /// Append args to the command. + /// Appends arguments to the command. pub fn args(mut self, args: I) -> Self where I: IntoIterator, diff --git a/core/tauri/src/api/rpc.rs b/core/tauri/src/api/rpc.rs index 15d6362cc..42fc2914b 100644 --- a/core/tauri/src/api/rpc.rs +++ b/core/tauri/src/api/rpc.rs @@ -2,6 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT +//! Types and functions related to Remote Procedure Call(RPC). +//! +//! This module includes utilities to send messages to the JS layer of the webview. + use serde::Serialize; use serde_json::value::RawValue; @@ -15,7 +19,7 @@ use serde_json::value::RawValue; const MAX_JSON_STR_LEN: usize = usize::pow(2, 30) - 2; /// Minimum size JSON needs to be in order to convert it to JSON.parse with [`escape_json_parse`]. -// todo: this number should be benchmarked and checked for optimal range, I set 10 KiB arbitrarily +// TODO: this number should be benchmarked and checked for optimal range, I set 10 KiB arbitrarily // we don't want to lose the gained object parsing time to extra allocations preparing it const MIN_JSON_PARSE_LEN: usize = 10_240; @@ -62,13 +66,15 @@ fn escape_json_parse(json: &RawValue) -> String { /// See [json-parse-benchmark](https://github.com/GoogleChromeLabs/json-parse-benchmark). /// /// # Examples +/// - With string literals: /// ``` /// use tauri::api::rpc::format_callback; /// // callback with a string argument -/// let cb = format_callback("callback-function-name", &"the string response").expect("failed to serialize"); +/// let cb = format_callback("callback-function-name", &"the string response").unwrap(); /// assert!(cb.contains(r#"window["callback-function-name"]("the string response")"#)); /// ``` /// +/// - With types implement [`serde::Serialize`]: /// ``` /// use tauri::api::rpc::format_callback; /// use serde::Serialize; @@ -79,8 +85,10 @@ fn escape_json_parse(json: &RawValue) -> String { /// value: String /// } /// -/// let cb = format_callback("callback-function-name", &MyResponse { value: String::from_utf8(vec![b'X'; 10_240]).unwrap()}) -/// .expect("failed to serialize"); +/// let cb = format_callback( +/// "callback-function-name", +/// &MyResponse { value: String::from_utf8(vec![b'X'; 10_240]).unwrap() +/// }).expect("failed to serialize"); /// /// assert!(cb.contains(r#"window["callback-function-name"](JSON.parse('{"value":"XXXXXXXXX"#)); /// ``` @@ -158,6 +166,7 @@ pub fn format_callback>( /// let cb = format_callback_result(res, "success_cb", "error_cb").expect("failed to format"); /// assert!(cb.contains(r#"window["error_cb"]("error message here")"#)); /// ``` +// TODO: better example to explain pub fn format_callback_result( result: Result, success_callback: impl AsRef, diff --git a/core/tauri/src/api/shell.rs b/core/tauri/src/api/shell.rs index 19204d87c..c6a6bcafd 100644 --- a/core/tauri/src/api/shell.rs +++ b/core/tauri/src/api/shell.rs @@ -2,7 +2,9 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT -/// Open path or URL with `with`, or system default +//! Types and functions related to shell. + +/// Opens path or URL with program specified in `with`, or system default if `None`. pub fn open(path: String, with: Option) -> crate::api::Result<()> { { let exit_status = if let Some(with) = with { diff --git a/core/tauri/src/api/version.rs b/core/tauri/src/api/version.rs index 80634c284..e36fc4eb0 100644 --- a/core/tauri/src/api/version.rs +++ b/core/tauri/src/api/version.rs @@ -2,6 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT +//! Types and functions related to semantics versioning. + use semver::Version; use std::cmp::Ordering; diff --git a/core/tauri/src/app.rs b/core/tauri/src/app.rs index fad113978..21acb09b3 100644 --- a/core/tauri/src/app.rs +++ b/core/tauri/src/app.rs @@ -6,8 +6,6 @@ pub(crate) mod tray; use crate::{ - api::assets::Assets, - api::config::{Config, WindowUrl}, command::{CommandArg, CommandItem}, hooks::{InvokeHandler, OnPageLoad, PageLoadPayload, SetupHook}, manager::WindowManager, @@ -18,6 +16,8 @@ use crate::{ Dispatch, ExitRequestedEventAction, RunEvent, Runtime, }, sealed::{ManagerBase, RuntimeOrDispatch}, + utils::assets::Assets, + utils::config::{Config, WindowUrl}, Context, Invoke, InvokeError, Manager, StateManager, Window, }; diff --git a/core/tauri/src/async_runtime.rs b/core/tauri/src/async_runtime.rs index 756af59d7..e63de1ef6 100644 --- a/core/tauri/src/async_runtime.rs +++ b/core/tauri/src/async_runtime.rs @@ -2,10 +2,13 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT -//! The singleton async runtime used by Tauri and exposed to consumers. -//! Wraps a `tokio` Runtime and is meant to be used by initialization code, such as plugins `initialization` and app `setup` hooks. -//! Fox more complex use cases, consider creating your own runtime. -//! For command handlers, it's recommended to use a plain `async fn` command. +//! The singleton async runtime used by Tauri and exposed to users. +//! +//! Tauri uses [`tokio`] Runtime to initialize code, such as +//! [`Plugin::initialize`](../plugin/trait.Plugin.html#method.initialize) and [`crate::Builder::setup`] hooks. +//! This module also re-export some common items most developers need from [`tokio`]. If there's +//! one you need isn't here, you could use types in [`tokio`] dierectly. +//! For custom command handlers, it's recommended to use a plain `async fn` command. use futures_lite::future::FutureExt; use once_cell::sync::OnceCell; @@ -44,13 +47,13 @@ impl Future for JoinHandle { /// Runtime handle definition. pub trait RuntimeHandle: fmt::Debug + Clone + Sync + Sync { - /// Spawn a future onto the runtime. + /// Spawns a future onto the runtime. fn spawn(&self, task: F) -> JoinHandle where F: Future + Send + 'static, F::Output: Send + 'static; - /// Run a future to completion on runtime. + /// Runs a future to completion on runtime. fn block_on(&self, task: F) -> F::Output; } @@ -68,19 +71,19 @@ impl RuntimeHandle for Handle { } } -/// Returns a handle to the async runtime. +/// Returns a handle of the async runtime. pub fn handle() -> impl RuntimeHandle { let runtime = RUNTIME.get_or_init(|| Runtime::new().unwrap()); runtime.handle().clone() } -/// Run a future to completion on runtime. +/// Runs a future to completion on runtime. pub fn block_on(task: F) -> F::Output { let runtime = RUNTIME.get_or_init(|| Runtime::new().unwrap()); runtime.block_on(task) } -/// Spawn a future onto the runtime. +/// Spawns a future onto the runtime. pub fn spawn(task: F) -> JoinHandle where F: Future + Send + 'static, diff --git a/core/tauri/src/command.rs b/core/tauri/src/command.rs index f5a3f2bf2..b5122a19f 100644 --- a/core/tauri/src/command.rs +++ b/core/tauri/src/command.rs @@ -2,7 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT -//! Useful items for custom commands. +//! The Tauri custom commands types and traits. +//! +//! You usually don't need to create these items yourself. These are created from [command](../attr.command.html) +//! attribute macro along the way and used by [`crate::generate_handler`] macro. use crate::hooks::InvokeError; use crate::runtime::Runtime; diff --git a/core/tauri/src/endpoints.rs b/core/tauri/src/endpoints.rs index 2069a9392..8844e4828 100644 --- a/core/tauri/src/endpoints.rs +++ b/core/tauri/src/endpoints.rs @@ -3,10 +3,9 @@ // SPDX-License-Identifier: MIT use crate::{ - api::{config::Config, PackageInfo}, hooks::{InvokeError, InvokeMessage, InvokeResolver}, runtime::Runtime, - Invoke, Window, + Config, Invoke, PackageInfo, Window, }; use serde::{Deserialize, Serialize}; use serde_json::Value as JsonValue; diff --git a/core/tauri/src/endpoints/app.rs b/core/tauri/src/endpoints/app.rs index df4f48eb9..9c39d9d3b 100644 --- a/core/tauri/src/endpoints/app.rs +++ b/core/tauri/src/endpoints/app.rs @@ -3,7 +3,7 @@ // SPDX-License-Identifier: MIT use super::InvokeResponse; -use crate::api::PackageInfo; +use crate::PackageInfo; use serde::Deserialize; /// The API descriptor. diff --git a/core/tauri/src/endpoints/cli.rs b/core/tauri/src/endpoints/cli.rs index e9d17f986..b5f34eb05 100644 --- a/core/tauri/src/endpoints/cli.rs +++ b/core/tauri/src/endpoints/cli.rs @@ -3,7 +3,7 @@ // SPDX-License-Identifier: MIT use super::InvokeResponse; -use crate::api::config::CliConfig; +use crate::utils::config::CliConfig; use serde::Deserialize; /// The API descriptor. diff --git a/core/tauri/src/endpoints/window.rs b/core/tauri/src/endpoints/window.rs index 98f1ca051..3e886092e 100644 --- a/core/tauri/src/endpoints/window.rs +++ b/core/tauri/src/endpoints/window.rs @@ -5,12 +5,12 @@ #[cfg(window_create)] use crate::runtime::{webview::WindowBuilder, Dispatch}; use crate::{ - api::config::WindowConfig, endpoints::InvokeResponse, runtime::{ window::dpi::{Position, Size}, Runtime, UserAttentionType, }, + utils::config::WindowConfig, Manager, Window, }; use serde::Deserialize; diff --git a/core/tauri/src/lib.rs b/core/tauri/src/lib.rs index 8a27937af..fb2226303 100644 --- a/core/tauri/src/lib.rs +++ b/core/tauri/src/lib.rs @@ -28,7 +28,6 @@ pub use tauri_macros::{command, generate_handler}; pub mod api; pub(crate) mod app; -/// Async runtime. pub mod async_runtime; pub mod command; /// The Tauri API endpoints. @@ -38,16 +37,16 @@ mod event; mod hooks; mod manager; pub mod plugin; -/// Tauri window. pub mod window; use tauri_runtime as runtime; -/// The Tauri-specific settings for your runtime e.g. notification permission status. pub mod settings; mod state; #[cfg(feature = "updater")] #[cfg_attr(doc_cfg, doc(cfg(feature = "updater")))] pub mod updater; +pub use tauri_utils as utils; + #[cfg(feature = "wry")] #[cfg_attr(doc_cfg, doc(cfg(feature = "wry")))] pub use tauri_runtime_wry::Wry; @@ -72,24 +71,6 @@ pub use runtime::menu::CustomMenuItem; #[cfg_attr(doc_cfg, doc(cfg(target_os = "macos")))] pub use runtime::{menu::NativeImage, ActivationPolicy}; -pub use { - self::api::assets::Assets, - self::app::{App, AppHandle, Builder, CloseRequestApi, Event, GlobalWindowEvent, PathResolver}, - self::hooks::{ - Invoke, InvokeError, InvokeHandler, InvokeMessage, InvokeResolver, InvokeResponse, OnPageLoad, - PageLoadPayload, SetupHook, - }, - self::runtime::{ - webview::{WebviewAttributes, WindowBuilder}, - window::{ - dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize, Pixel, Position, Size}, - WindowEvent, - }, - ClipboardManager, GlobalShortcutManager, Icon, RunIteration, Runtime, UserAttentionType, - }, - self::state::{State, StateManager}, - self::window::{Monitor, Window}, -}; #[cfg(feature = "system-tray")] #[cfg_attr(doc_cfg, doc(cfg(feature = "system-tray")))] pub use { @@ -104,10 +85,27 @@ pub use { self::runtime::menu::{Menu, MenuItem, Submenu}, self::window::menu::MenuEvent, }; - -pub use tauri_utils::{ - config::{Config, WindowUrl}, - PackageInfo, +pub use { + self::app::{App, AppHandle, Builder, CloseRequestApi, Event, GlobalWindowEvent, PathResolver}, + self::hooks::{ + Invoke, InvokeError, InvokeHandler, InvokeMessage, InvokeResolver, InvokeResponse, OnPageLoad, + PageLoadPayload, SetupHook, + }, + self::runtime::{ + webview::{WebviewAttributes, WindowBuilder}, + window::{ + dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize, Pixel, Position, Size}, + WindowEvent, + }, + ClipboardManager, GlobalShortcutManager, Icon, RunIteration, Runtime, UserAttentionType, + }, + self::state::{State, StateManager}, + self::utils::{ + assets::Assets, + config::{Config, WindowUrl}, + PackageInfo, + }, + self::window::{Monitor, Window}, }; /// Reads the config file at compile time and generates a [`Context`] based on its content. @@ -154,7 +152,7 @@ pub struct Context { pub(crate) assets: Arc, pub(crate) default_window_icon: Option>, pub(crate) system_tray_icon: Option, - pub(crate) package_info: crate::api::PackageInfo, + pub(crate) package_info: crate::PackageInfo, pub(crate) _info_plist: (), } @@ -220,13 +218,13 @@ impl Context { /// Package information. #[inline(always)] - pub fn package_info(&self) -> &crate::api::PackageInfo { + pub fn package_info(&self) -> &crate::PackageInfo { &self.package_info } /// A mutable reference to the package information. #[inline(always)] - pub fn package_info_mut(&mut self) -> &mut crate::api::PackageInfo { + pub fn package_info_mut(&mut self) -> &mut crate::PackageInfo { &mut self.package_info } @@ -237,7 +235,7 @@ impl Context { assets: Arc, default_window_icon: Option>, system_tray_icon: Option, - package_info: crate::api::PackageInfo, + package_info: crate::PackageInfo, info_plist: (), ) -> Self { Self { diff --git a/core/tauri/src/manager.rs b/core/tauri/src/manager.rs index 33d5ff601..672014d12 100644 --- a/core/tauri/src/manager.rs +++ b/core/tauri/src/manager.rs @@ -3,11 +3,6 @@ // SPDX-License-Identifier: MIT use crate::{ - api::{ - assets::Assets, - config::{AppUrl, Config, WindowUrl}, - PackageInfo, - }, app::{AppHandle, GlobalWindowEvent, GlobalWindowEventListener}, event::{Event, EventHandler, Listeners}, hooks::{InvokeHandler, OnPageLoad, PageLoadPayload}, @@ -20,6 +15,11 @@ use crate::{ window::{dpi::PhysicalSize, DetachedWindow, PendingWindow, WindowEvent}, Icon, Runtime, }, + utils::{ + assets::Assets, + config::{AppUrl, Config, WindowUrl}, + PackageInfo, + }, Context, Invoke, StateManager, Window, }; diff --git a/core/tauri/src/plugin.rs b/core/tauri/src/plugin.rs index 9d23ee141..26f12156d 100644 --- a/core/tauri/src/plugin.rs +++ b/core/tauri/src/plugin.rs @@ -2,17 +2,17 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT -//! Extend Tauri functionality. +//! The Tauri plugin extension to expand Tauri functionality. use crate::{ - api::config::PluginConfig, runtime::Runtime, AppHandle, Invoke, PageLoadPayload, Window, + runtime::Runtime, utils::config::PluginConfig, AppHandle, Invoke, PageLoadPayload, Window, }; use serde_json::Value as JsonValue; use tauri_macros::default_runtime; use std::{collections::HashMap, fmt}; -/// The plugin result type. +/// The result type of Tauri plugin module. pub type Result = std::result::Result>; /// The plugin interface. @@ -20,7 +20,7 @@ pub trait Plugin: Send { /// The plugin name. Used as key on the plugin config object. fn name(&self) -> &'static str; - /// Initialize the plugin. + /// Initializes the plugin. #[allow(unused_variables)] fn initialize(&mut self, app: &AppHandle, config: JsonValue) -> Result<()> { Ok(()) @@ -39,11 +39,11 @@ pub trait Plugin: Send { #[allow(unused_variables)] fn created(&mut self, window: Window) {} - /// Callback invoked when the webview performs a navigation. + /// Callback invoked when the webview performs a navigation to a page. #[allow(unused_variables)] fn on_page_load(&mut self, window: Window, payload: PageLoadPayload) {} - /// Add invoke_handler API extension commands. + /// Extend commands to [`crate::Builder::invoke_handler`]. #[allow(unused_variables)] fn extend_api(&mut self, invoke: Invoke) {} } diff --git a/core/tauri/src/settings.rs b/core/tauri/src/settings.rs index 239399c16..82017e4c6 100644 --- a/core/tauri/src/settings.rs +++ b/core/tauri/src/settings.rs @@ -2,13 +2,16 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT +//! The Tauri-specific settings for your application. +//! +//! This only contains notification permission status for now, but is able to expand in the future. + use crate::{ api::{ file::read_binary, path::{resolve_path, BaseDirectory}, - PackageInfo, }, - Config, + Config, PackageInfo, }; use serde::{Deserialize, Serialize}; use std::{ @@ -17,7 +20,7 @@ use std::{ path::{Path, PathBuf}, }; -/// Tauri Settings. +/// The Tauri Settings. #[derive(Debug, Clone, Default, Deserialize, Serialize)] #[non_exhaustive] pub struct Settings { @@ -26,7 +29,7 @@ pub struct Settings { pub allow_notification: Option, } -/// Gets the path to the settings file +/// Gets the path to the settings file. fn get_settings_path(config: &Config, package_info: &PackageInfo) -> crate::api::Result { resolve_path( config, diff --git a/core/tauri/src/updater/mod.rs b/core/tauri/src/updater/mod.rs index 11bd1de37..31f48bc12 100644 --- a/core/tauri/src/updater/mod.rs +++ b/core/tauri/src/updater/mod.rs @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT -//! # Tauri Updater +//! The Tauri updater. //! //! The updater is focused on making Tauri's application updates **as safe and transparent as updates to a website**. //! @@ -333,8 +333,9 @@ mod error; pub use self::error::Error; use crate::{ - api::{config::UpdaterConfig, dialog::ask, process::restart}, + api::{dialog::ask, process::restart}, runtime::Runtime, + utils::config::UpdaterConfig, Window, }; @@ -376,7 +377,7 @@ struct UpdateManifest { /// Check if there is any new update with builtin dialog. pub(crate) async fn check_update_with_dialog( updater_config: UpdaterConfig, - package_info: crate::api::PackageInfo, + package_info: crate::PackageInfo, window: Window, ) { if let Some(endpoints) = updater_config.endpoints.clone() { @@ -418,7 +419,7 @@ pub(crate) async fn check_update_with_dialog( /// This function should be run on the main thread once. pub(crate) fn listener( updater_config: UpdaterConfig, - package_info: crate::api::PackageInfo, + package_info: crate::PackageInfo, window: &Window, ) { let isolated_window = window.clone(); diff --git a/core/tauri/src/window.rs b/core/tauri/src/window.rs index fc12afde0..90fb29bf1 100644 --- a/core/tauri/src/window.rs +++ b/core/tauri/src/window.rs @@ -2,12 +2,13 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT +//! The Tauri window types and functions. + pub(crate) mod menu; pub use menu::{MenuEvent, MenuHandle}; use crate::{ - api::config::WindowUrl, app::AppHandle, command::{CommandArg, CommandItem}, event::{Event, EventHandler}, @@ -23,6 +24,7 @@ use crate::{ }, sealed::ManagerBase, sealed::RuntimeOrDispatch, + utils::config::WindowUrl, Invoke, InvokeError, InvokeMessage, InvokeResolver, Manager, PageLoadPayload, };