doc: update tauri documentations (#2446)

This commit is contained in:
Ngo Iok Ui (Wu Yu Wei)
2021-08-16 22:32:37 +08:00
committed by GitHub
parent 13003ec761
commit cd55d67149
32 changed files with 178 additions and 164 deletions

View File

@@ -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.

View File

@@ -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.

View File

@@ -97,7 +97,7 @@ pub fn context_codegen(data: ContextData) -> Result<TokenStream, EmbeddedAssetsE
quote!(env!("CARGO_PKG_VERSION").to_string())
};
let package_info = quote!(
#root::api::PackageInfo {
#root::PackageInfo {
name: #package_name,
version: #package_version,
}

View File

@@ -304,7 +304,7 @@ impl ToTokens for EmbeddedAssets {
// we expect phf related items to be in path when generating the path code
tokens.append_all(quote! {{
use ::tauri::api::assets::{EmbeddedAssets, phf, phf::phf_map};
use ::tauri::utils::assets::{EmbeddedAssets, phf, phf::phf_map};
EmbeddedAssets::from_zstd(phf_map! { #map })
}});
}

View File

@@ -3,7 +3,8 @@
// SPDX-License-Identifier: MIT
//! The Tauri configuration used at runtime.
//! It is pulled from a `tauri.conf.json` file and the [`config::Config`] struct is generated at compile time.
//!
//! It is pulled from a `tauri.conf.json` file and the [`Config`] struct is generated at compile time.
//!
//! # Stability
//! This is a core functionality that is not considered part of the stable API.
@@ -648,7 +649,7 @@ mod build {
macro_rules! literal_struct {
($tokens:ident, $struct:ident, $($field:ident),+) => {
$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) })
}
}

View File

@@ -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<Matches> {
let about = cli
.description()

View File

@@ -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)]

View File

@@ -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<String>,
/// 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<P: AsRef<Path>>(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<F: FnOnce(&tempfile::TempDir)>(callback: F) -> crate::api::Result<()> {
let dir = tempdir()?;
callback(&dir);

View File

@@ -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;

View File

@@ -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,

View File

@@ -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<usize>,
/// Connect timeout in seconds for the request
/// Connect timeout in seconds for the request.
pub connect_timeout: Option<u64>,
}
@@ -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<Response> {
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<Response> {
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<String, String>) -> Self {
self.query = Some(query);
self
@@ -390,7 +392,7 @@ pub struct RawResponse {
pub data: Vec<u8>,
}
/// The response type.
/// The response data.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]

View File

@@ -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<T> = std::result::Result<T, Error>;
// 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;
}
}

View File

@@ -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

View File

@@ -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<PathBuf> {
/// Returns the path to the resource directory of this app.
pub fn resource_dir(package_info: &PackageInfo) -> Option<PathBuf> {
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.

View File

@@ -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<PathBuf> {
let mut current_binary = None;
@@ -34,7 +36,7 @@ pub fn current_binary() -> Option<PathBuf> {
current_binary
}
/// Restart the process.
/// Restarts the process.
pub fn restart() {
if let Some(path) = current_binary() {
StdCommand::new(path)

View File

@@ -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<PathBuf>,
}
/// Child spawned.
/// Spawned child process.
#[derive(Debug)]
pub struct CommandChild {
inner: Arc<SharedChild>,
@@ -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<S: Into<String>>(program: S) -> crate::Result<Self> {
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<I, S>(mut self, args: I) -> Self
where
I: IntoIterator<Item = S>,

View File

@@ -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<T: Serialize, S: AsRef<str>>(
/// 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<T: Serialize, E: Serialize>(
result: Result<T, E>,
success_callback: impl AsRef<str>,

View File

@@ -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<String>) -> crate::api::Result<()> {
{
let exit_status = if let Some(with) = with {

View File

@@ -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;

View File

@@ -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,
};

View File

@@ -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<T> Future for JoinHandle<T> {
/// 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<F: Future>(&self, task: F) -> JoinHandle<F::Output>
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<F: Future>(&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<F: Future>(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<F>(task: F) -> JoinHandle<F::Output>
where
F: Future + Send + 'static,

View File

@@ -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;

View File

@@ -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;

View File

@@ -3,7 +3,7 @@
// SPDX-License-Identifier: MIT
use super::InvokeResponse;
use crate::api::PackageInfo;
use crate::PackageInfo;
use serde::Deserialize;
/// The API descriptor.

View File

@@ -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.

View File

@@ -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;

View File

@@ -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<A: Assets> {
pub(crate) assets: Arc<A>,
pub(crate) default_window_icon: Option<Vec<u8>>,
pub(crate) system_tray_icon: Option<Icon>,
pub(crate) package_info: crate::api::PackageInfo,
pub(crate) package_info: crate::PackageInfo,
pub(crate) _info_plist: (),
}
@@ -220,13 +218,13 @@ impl<A: Assets> Context<A> {
/// 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<A: Assets> Context<A> {
assets: Arc<A>,
default_window_icon: Option<Vec<u8>>,
system_tray_icon: Option<Icon>,
package_info: crate::api::PackageInfo,
package_info: crate::PackageInfo,
info_plist: (),
) -> Self {
Self {

View File

@@ -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,
};

View File

@@ -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<T> = std::result::Result<T, Box<dyn std::error::Error>>;
/// The plugin interface.
@@ -20,7 +20,7 @@ pub trait Plugin<R: Runtime>: 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<R>, config: JsonValue) -> Result<()> {
Ok(())
@@ -39,11 +39,11 @@ pub trait Plugin<R: Runtime>: Send {
#[allow(unused_variables)]
fn created(&mut self, window: Window<R>) {}
/// 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<R>, 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<R>) {}
}

View File

@@ -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<bool>,
}
/// 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<PathBuf> {
resolve_path(
config,

View File

@@ -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<R: Runtime>(
updater_config: UpdaterConfig,
package_info: crate::api::PackageInfo,
package_info: crate::PackageInfo,
window: Window<R>,
) {
if let Some(endpoints) = updater_config.endpoints.clone() {
@@ -418,7 +419,7 @@ pub(crate) async fn check_update_with_dialog<R: Runtime>(
/// This function should be run on the main thread once.
pub(crate) fn listener<R: Runtime>(
updater_config: UpdaterConfig,
package_info: crate::api::PackageInfo,
package_info: crate::PackageInfo,
window: &Window<R>,
) {
let isolated_window = window.clone();

View File

@@ -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,
};