repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-utils/src/config/parse.rs | crates/tauri-utils/src/config/parse.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::config::Config;
use crate::platform::Target;
use json_patch::merge;
use serde::de::DeserializeOwned;
use serde_json::Value;
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use thiserror::Error;
/// All extensions that are possibly supported, but perhaps not enabled.
pub const EXTENSIONS_SUPPORTED: &[&str] = &["json", "json5", "toml"];
/// All configuration formats that are possibly supported, but perhaps not enabled.
pub const SUPPORTED_FORMATS: &[ConfigFormat] =
&[ConfigFormat::Json, ConfigFormat::Json5, ConfigFormat::Toml];
/// All configuration formats that are currently enabled.
pub const ENABLED_FORMATS: &[ConfigFormat] = &[
ConfigFormat::Json,
#[cfg(feature = "config-json5")]
ConfigFormat::Json5,
#[cfg(feature = "config-toml")]
ConfigFormat::Toml,
];
/// The available configuration formats.
#[derive(Debug, Copy, Clone)]
pub enum ConfigFormat {
/// The default JSON (tauri.conf.json) format.
Json,
/// The JSON5 (tauri.conf.json5) format.
Json5,
/// The TOML (Tauri.toml file) format.
Toml,
}
impl ConfigFormat {
/// Maps the config format to its file name.
pub fn into_file_name(self) -> &'static str {
match self {
Self::Json => "tauri.conf.json",
Self::Json5 => "tauri.conf.json5",
Self::Toml => "Tauri.toml",
}
}
fn into_platform_file_name(self, target: Target) -> &'static str {
match self {
Self::Json => match target {
Target::MacOS => "tauri.macos.conf.json",
Target::Windows => "tauri.windows.conf.json",
Target::Linux => "tauri.linux.conf.json",
Target::Android => "tauri.android.conf.json",
Target::Ios => "tauri.ios.conf.json",
},
Self::Json5 => match target {
Target::MacOS => "tauri.macos.conf.json5",
Target::Windows => "tauri.windows.conf.json5",
Target::Linux => "tauri.linux.conf.json5",
Target::Android => "tauri.android.conf.json5",
Target::Ios => "tauri.ios.conf.json5",
},
Self::Toml => match target {
Target::MacOS => "Tauri.macos.toml",
Target::Windows => "Tauri.windows.toml",
Target::Linux => "Tauri.linux.toml",
Target::Android => "Tauri.android.toml",
Target::Ios => "Tauri.ios.toml",
},
}
}
}
/// Represents all the errors that can happen while reading the config.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ConfigError {
/// Failed to parse from JSON.
#[error("unable to parse JSON Tauri config file at {path} because {error}")]
FormatJson {
/// The path that failed to parse into JSON.
path: PathBuf,
/// The parsing [`serde_json::Error`].
error: serde_json::Error,
},
/// Failed to parse from JSON5.
#[cfg(feature = "config-json5")]
#[error("unable to parse JSON5 Tauri config file at {path} because {error}")]
FormatJson5 {
/// The path that failed to parse into JSON5.
path: PathBuf,
/// The parsing [`json5::Error`].
error: ::json5::Error,
},
/// Failed to parse from TOML.
#[cfg(feature = "config-toml")]
#[error("unable to parse toml Tauri config file at {path} because {error}")]
FormatToml {
/// The path that failed to parse into TOML.
path: PathBuf,
/// The parsing [`toml::Error`].
error: Box<::toml::de::Error>,
},
/// Unknown config file name encountered.
#[error("unsupported format encountered {0}")]
UnsupportedFormat(String),
/// Known file extension encountered, but corresponding parser is not enabled (cargo features).
#[error("supported (but disabled) format encountered {extension} - try enabling `{feature}` ")]
DisabledFormat {
/// The extension encountered.
extension: String,
/// The cargo feature to enable it.
feature: String,
},
/// A generic IO error with context of what caused it.
#[error("unable to read Tauri config file at {path} because {error}")]
Io {
/// The path the IO error occurred on.
path: PathBuf,
/// The [`std::io::Error`].
error: std::io::Error,
},
}
/// Determines if the given folder has a configuration file.
pub fn folder_has_configuration_file(target: Target, folder: &Path) -> bool {
folder.join(ConfigFormat::Json.into_file_name()).exists()
|| folder.join(ConfigFormat::Json5.into_file_name()).exists()
|| folder.join(ConfigFormat::Toml.into_file_name()).exists()
// platform file names
|| folder.join(ConfigFormat::Json.into_platform_file_name(target)).exists()
|| folder.join(ConfigFormat::Json5.into_platform_file_name(target)).exists()
|| folder.join(ConfigFormat::Toml.into_platform_file_name(target)).exists()
}
/// Determines if the given file path represents a Tauri configuration file.
pub fn is_configuration_file(target: Target, path: &Path) -> bool {
path
.file_name()
.map(|file_name| {
file_name == OsStr::new(ConfigFormat::Json.into_file_name())
|| file_name == OsStr::new(ConfigFormat::Json5.into_file_name())
|| file_name == OsStr::new(ConfigFormat::Toml.into_file_name())
// platform file names
|| file_name == OsStr::new(ConfigFormat::Json.into_platform_file_name(target))
|| file_name == OsStr::new(ConfigFormat::Json5.into_platform_file_name(target))
|| file_name == OsStr::new(ConfigFormat::Toml.into_platform_file_name(target))
})
.unwrap_or_default()
}
/// Reads the configuration from the given root directory.
///
/// It first looks for a `tauri.conf.json[5]` or `Tauri.toml` file on the given directory. The file must exist.
/// Then it looks for a platform-specific configuration file:
/// - `tauri.macos.conf.json[5]` or `Tauri.macos.toml` on macOS
/// - `tauri.linux.conf.json[5]` or `Tauri.linux.toml` on Linux
/// - `tauri.windows.conf.json[5]` or `Tauri.windows.toml` on Windows
/// - `tauri.android.conf.json[5]` or `Tauri.android.toml` on Android
/// - `tauri.ios.conf.json[5]` or `Tauri.ios.toml` on iOS
/// Merging the configurations using [JSON Merge Patch (RFC 7396)].
///
/// Returns the raw configuration and used config paths.
///
/// [JSON Merge Patch (RFC 7396)]: https://datatracker.ietf.org/doc/html/rfc7396.
pub fn read_from(target: Target, root_dir: &Path) -> Result<(Value, Vec<PathBuf>), ConfigError> {
let (mut config, config_file_path) = parse_value(target, root_dir.join("tauri.conf.json"))?;
let mut config_paths = vec![config_file_path];
if let Some((platform_config, path)) = read_platform(target, root_dir)? {
config_paths.push(path);
merge(&mut config, &platform_config);
}
Ok((config, config_paths))
}
/// Reads the platform-specific configuration file from the given root directory if it exists.
///
/// Check [`read_from`] for more information.
pub fn read_platform(
target: Target,
root_dir: &Path,
) -> Result<Option<(Value, PathBuf)>, ConfigError> {
let platform_config_path = root_dir.join(ConfigFormat::Json.into_platform_file_name(target));
if does_supported_file_name_exist(target, &platform_config_path) {
let (platform_config, path): (Value, PathBuf) = parse_value(target, platform_config_path)?;
Ok(Some((platform_config, path)))
} else {
Ok(None)
}
}
/// Check if a supported config file exists at path.
///
/// The passed path is expected to be the path to the "default" configuration format, in this case
/// JSON with `.json`.
pub fn does_supported_file_name_exist(target: Target, path: impl Into<PathBuf>) -> bool {
let path = path.into();
let source_file_name = path.file_name().unwrap();
let lookup_platform_config = ENABLED_FORMATS
.iter()
.any(|format| source_file_name == format.into_platform_file_name(target));
ENABLED_FORMATS.iter().any(|format| {
path
.with_file_name(if lookup_platform_config {
format.into_platform_file_name(target)
} else {
format.into_file_name()
})
.exists()
})
}
/// Parse the config from path, including alternative formats.
///
/// Hierarchy:
/// 1. Check if `tauri.conf.json` exists
/// a. Parse it with `serde_json`
/// b. Parse it with `json5` if `serde_json` fails
/// c. Return original `serde_json` error if all above steps failed
/// 2. Check if `tauri.conf.json5` exists
/// a. Parse it with `json5`
/// b. Return error if all above steps failed
/// 3. Check if `Tauri.json` exists
/// a. Parse it with `toml`
/// b. Return error if all above steps failed
/// 4. Return error if all above steps failed
pub fn parse(target: Target, path: impl Into<PathBuf>) -> Result<(Config, PathBuf), ConfigError> {
do_parse(target, path.into())
}
/// See [`parse`] for specifics, returns a JSON [`Value`] instead of [`Config`].
pub fn parse_value(
target: Target,
path: impl Into<PathBuf>,
) -> Result<(Value, PathBuf), ConfigError> {
do_parse(target, path.into())
}
fn do_parse<D: DeserializeOwned>(
target: Target,
path: PathBuf,
) -> Result<(D, PathBuf), ConfigError> {
let file_name = path
.file_name()
.map(OsStr::to_string_lossy)
.unwrap_or_default();
let lookup_platform_config = ENABLED_FORMATS
.iter()
.any(|format| file_name == format.into_platform_file_name(target));
let json5 = path.with_file_name(if lookup_platform_config {
ConfigFormat::Json5.into_platform_file_name(target)
} else {
ConfigFormat::Json5.into_file_name()
});
let toml = path.with_file_name(if lookup_platform_config {
ConfigFormat::Toml.into_platform_file_name(target)
} else {
ConfigFormat::Toml.into_file_name()
});
let path_ext = path
.extension()
.map(OsStr::to_string_lossy)
.unwrap_or_default();
if path.exists() {
let raw = read_to_string(&path)?;
// to allow us to easily use the compile-time #[cfg], we always bind
#[allow(clippy::let_and_return)]
let json = do_parse_json(&raw, &path);
// we also want to support **valid** json5 in the .json extension if the feature is enabled.
// if the json5 is not valid the serde_json error for regular json will be returned.
// this could be a bit confusing, so we may want to encourage users using json5 to use the
// .json5 extension instead of .json
#[cfg(feature = "config-json5")]
let json = {
match do_parse_json5(&raw, &path) {
json5 @ Ok(_) => json5,
// assume any errors from json5 in a .json file is because it's not json5
Err(_) => json,
}
};
json.map(|j| (j, path))
} else if json5.exists() {
#[cfg(feature = "config-json5")]
{
let raw = read_to_string(&json5)?;
do_parse_json5(&raw, &json5).map(|config| (config, json5))
}
#[cfg(not(feature = "config-json5"))]
Err(ConfigError::DisabledFormat {
extension: ".json5".into(),
feature: "config-json5".into(),
})
} else if toml.exists() {
#[cfg(feature = "config-toml")]
{
let raw = read_to_string(&toml)?;
do_parse_toml(&raw, &toml).map(|config| (config, toml))
}
#[cfg(not(feature = "config-toml"))]
Err(ConfigError::DisabledFormat {
extension: ".toml".into(),
feature: "config-toml".into(),
})
} else if !EXTENSIONS_SUPPORTED.contains(&path_ext.as_ref()) {
Err(ConfigError::UnsupportedFormat(path_ext.to_string()))
} else {
Err(ConfigError::Io {
path,
error: std::io::ErrorKind::NotFound.into(),
})
}
}
/// "Low-level" helper to parse JSON into a [`Config`].
///
/// `raw` should be the contents of the file that is represented by `path`.
pub fn parse_json(raw: &str, path: &Path) -> Result<Config, ConfigError> {
do_parse_json(raw, path)
}
/// "Low-level" helper to parse JSON into a JSON [`Value`].
///
/// `raw` should be the contents of the file that is represented by `path`.
pub fn parse_json_value(raw: &str, path: &Path) -> Result<Value, ConfigError> {
do_parse_json(raw, path)
}
fn do_parse_json<D: DeserializeOwned>(raw: &str, path: &Path) -> Result<D, ConfigError> {
serde_json::from_str(raw).map_err(|error| ConfigError::FormatJson {
path: path.into(),
error,
})
}
/// "Low-level" helper to parse JSON5 into a [`Config`].
///
/// `raw` should be the contents of the file that is represented by `path`. This function requires
/// the `config-json5` feature to be enabled.
#[cfg(feature = "config-json5")]
pub fn parse_json5(raw: &str, path: &Path) -> Result<Config, ConfigError> {
do_parse_json5(raw, path)
}
/// "Low-level" helper to parse JSON5 into a JSON [`Value`].
///
/// `raw` should be the contents of the file that is represented by `path`. This function requires
/// the `config-json5` feature to be enabled.
#[cfg(feature = "config-json5")]
pub fn parse_json5_value(raw: &str, path: &Path) -> Result<Value, ConfigError> {
do_parse_json5(raw, path)
}
#[cfg(feature = "config-json5")]
fn do_parse_json5<D: DeserializeOwned>(raw: &str, path: &Path) -> Result<D, ConfigError> {
::json5::from_str(raw).map_err(|error| ConfigError::FormatJson5 {
path: path.into(),
error,
})
}
#[cfg(feature = "config-toml")]
fn do_parse_toml<D: DeserializeOwned>(raw: &str, path: &Path) -> Result<D, ConfigError> {
::toml::from_str(raw).map_err(|error| ConfigError::FormatToml {
path: path.into(),
error: Box::new(error),
})
}
/// Helper function to wrap IO errors from [`std::fs::read_to_string`] into a [`ConfigError`].
fn read_to_string(path: &Path) -> Result<String, ConfigError> {
std::fs::read_to_string(path).map_err(|error| ConfigError::Io {
path: path.into(),
error,
})
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-utils/src/pattern/mod.rs | crates/tauri-utils/src/pattern/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
/// Handling the Tauri "Isolation" Pattern.
#[cfg(feature = "isolation")]
pub mod isolation;
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-utils/src/pattern/isolation.rs | crates/tauri-utils/src/pattern/isolation.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::array::TryFromSliceError;
use std::borrow::Cow;
use std::fmt::{Debug, Formatter};
use std::string::FromUtf8Error;
use aes_gcm::aead::Aead;
use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
use getrandom::Error as CsprngError;
use serialize_to_javascript::{default_template, Template};
/// The style for the isolation iframe.
pub const IFRAME_STYLE: &str = "#__tauri_isolation__ { display: none !important }";
/// Errors that can occur during Isolation keys generation.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
/// Something went wrong with the CSPRNG.
#[error("CSPRNG error")]
Csprng(#[from] CsprngError),
/// Something went wrong with decrypting an AES-GCM payload
#[error("AES-GCM")]
Aes,
/// Nonce was not 96 bits
#[error("Nonce: {0}")]
NonceSize(#[from] TryFromSliceError),
/// Payload was not valid utf8
#[error("{0}")]
Utf8(#[from] FromUtf8Error),
/// Invalid json format
#[error("{0}")]
Json(#[from] serde_json::Error),
}
/// A formatted AES-GCM cipher instance along with the key used to initialize it.
#[derive(Clone)]
pub struct AesGcmPair {
raw: [u8; 32],
key: Aes256Gcm,
}
impl Debug for AesGcmPair {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "AesGcmPair(...)")
}
}
impl AesGcmPair {
fn new() -> Result<Self, Error> {
let mut raw = [0u8; 32];
getrandom::fill(&mut raw)?;
let key = aes_gcm::Key::<Aes256Gcm>::from_slice(&raw);
Ok(Self {
raw,
key: Aes256Gcm::new(key),
})
}
/// The raw value used to create the AES-GCM key
pub fn raw(&self) -> &[u8; 32] {
&self.raw
}
/// The formatted AES-GCM key
pub fn key(&self) -> &Aes256Gcm {
&self.key
}
#[doc(hidden)]
pub fn encrypt(&self, nonce: &[u8; 12], payload: &[u8]) -> Result<Vec<u8>, Error> {
self
.key
.encrypt(nonce.into(), payload)
.map_err(|_| self::Error::Aes)
}
}
/// All cryptographic keys required for Isolation encryption
#[derive(Debug, Clone)]
pub struct Keys {
/// AES-GCM key
aes_gcm: AesGcmPair,
}
impl Keys {
/// Securely generate required keys for Isolation encryption.
pub fn new() -> Result<Self, Error> {
AesGcmPair::new().map(|aes_gcm| Self { aes_gcm })
}
/// The AES-GCM data (and raw data).
pub fn aes_gcm(&self) -> &AesGcmPair {
&self.aes_gcm
}
/// Decrypts a message using the generated keys.
pub fn decrypt(&self, raw: RawIsolationPayload<'_>) -> Result<Vec<u8>, Error> {
let RawIsolationPayload { nonce, payload, .. } = raw;
let nonce: [u8; 12] = nonce.as_ref().try_into()?;
self
.aes_gcm
.key
.decrypt(Nonce::from_slice(&nonce), payload.as_ref())
.map_err(|_| self::Error::Aes)
}
}
/// Raw representation of
#[derive(Debug, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RawIsolationPayload<'a> {
nonce: Cow<'a, [u8]>,
payload: Cow<'a, [u8]>,
content_type: Cow<'a, str>,
}
impl<'a> RawIsolationPayload<'a> {
/// Content type of this payload.
pub fn content_type(&self) -> &Cow<'a, str> {
&self.content_type
}
}
impl<'a> TryFrom<&'a Vec<u8>> for RawIsolationPayload<'a> {
type Error = Error;
fn try_from(value: &'a Vec<u8>) -> Result<Self, Self::Error> {
serde_json::from_slice(value).map_err(Into::into)
}
}
/// The Isolation JavaScript template meant to be injected during codegen.
///
/// Note: This struct is not considered part of the stable API
#[derive(Template)]
#[default_template("isolation.js")]
pub struct IsolationJavascriptCodegen {
// this template intentionally does not include the runtime field
}
/// The Isolation JavaScript template meant to be injected during runtime.
///
/// Note: This struct is not considered part of the stable API
#[derive(Template)]
#[default_template("isolation.js")]
pub struct IsolationJavascriptRuntime<'a> {
/// The key used on the Rust backend and the Isolation Javascript
pub runtime_aes_gcm_key: &'a [u8; 32],
/// The origin the isolation application is expecting messages from.
pub origin: String,
/// The function that processes the IPC message.
#[raw]
pub process_ipc_message_fn: &'a str,
}
#[cfg(test)]
mod test {
#[test]
fn create_keys() -> Result<(), Box<dyn std::error::Error>> {
let _ = super::Keys::new()?;
Ok(())
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-utils/src/platform/starting_binary.rs | crates/tauri-utils/src/platform/starting_binary.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use ctor::ctor;
use std::{
io::{Error, ErrorKind, Result},
path::{Path, PathBuf},
};
/// A cached version of the current binary using [`ctor`] to cache it before even `main` runs.
#[ctor]
#[used]
pub(super) static STARTING_BINARY: StartingBinary = StartingBinary::new();
/// Represents a binary path that was cached when the program was loaded.
pub(super) struct StartingBinary(std::io::Result<PathBuf>);
impl StartingBinary {
/// Find the starting executable as safely as possible.
fn new() -> Self {
// see notes on current_exe() for security implications
let dangerous_path = match std::env::current_exe() {
Ok(dangerous_path) => dangerous_path,
error @ Err(_) => return Self(error),
};
// note: this only checks symlinks on problematic platforms, see implementation below
if let Some(symlink) = Self::has_symlink(&dangerous_path) {
return Self(Err(Error::new(
ErrorKind::InvalidData,
format!("StartingBinary found current_exe() that contains a symlink on a non-allowed platform: {}", symlink.display()),
)));
}
// we canonicalize the path to resolve any symlinks to the real exe path
Self(dangerous_path.canonicalize())
}
/// A clone of the [`PathBuf`] found to be the starting path.
///
/// Because [`Error`] is not clone-able, it is recreated instead.
pub(super) fn cloned(&self) -> Result<PathBuf> {
// false positive
#[allow(clippy::useless_asref)]
self
.0
.as_ref()
.map(Clone::clone)
.map_err(|e| Error::new(e.kind(), e.to_string()))
}
/// We only care about checking this on macOS currently, as it has the least symlink protections.
#[cfg(any(
not(target_os = "macos"),
feature = "process-relaunch-dangerous-allow-symlink-macos"
))]
fn has_symlink(_: &Path) -> Option<&Path> {
None
}
/// We only care about checking this on macOS currently, as it has the least symlink protections.
#[cfg(all(
target_os = "macos",
not(feature = "process-relaunch-dangerous-allow-symlink-macos")
))]
fn has_symlink(path: &Path) -> Option<&Path> {
path.ancestors().find(|ancestor| {
matches!(
ancestor
.symlink_metadata()
.as_ref()
.map(std::fs::Metadata::file_type)
.as_ref()
.map(std::fs::FileType::is_symlink),
Ok(true)
)
})
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-schema-worker/src/config.rs | crates/tauri-schema-worker/src/config.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use anyhow::Context;
use axum::{
extract::Path,
http::{header, StatusCode},
response::Result,
routing::get,
Router,
};
use semver::{Version, VersionReq};
use serde::Deserialize;
use worker::*;
#[derive(Deserialize)]
pub struct CrateReleases {
pub versions: Vec<CrateRelease>,
}
#[derive(Debug, Deserialize)]
pub struct CrateRelease {
#[serde(alias = "num")]
pub version: Version,
pub yanked: Option<bool>,
}
#[derive(Deserialize)]
pub struct CrateMetadataFull {
#[serde(rename = "crate")]
pub crate_: CrateMetadata,
}
#[derive(Deserialize)]
pub struct CrateMetadata {
pub max_stable_version: Version,
}
const USERAGENT: &str = "tauri-schema-worker (contact@tauri.app)";
pub fn router() -> Router {
Router::new()
.route("/config", get(stable_schema))
.route("/config/latest", get(stable_schema))
.route("/config/stable", get(stable_schema))
.route("/config/next", get(next_schema)) // pre-releases versions, (rc, alpha and beta)
.route("/config/{version}", get(schema_for_version))
}
async fn schema_for_version(Path(version): Path<String>) -> Result<String> {
try_schema_for_version(version)
.await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
.map_err(Into::into)
}
async fn stable_schema() -> Result<String> {
try_stable_schema()
.await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
.map_err(Into::into)
}
async fn next_schema() -> Result<String> {
try_next_schema()
.await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
.map_err(Into::into)
}
#[worker::send]
async fn try_schema_for_version(version: String) -> anyhow::Result<String> {
let version = version.parse::<VersionReq>()?;
let releases = crate_releases("tauri").await?;
if releases.is_empty() {
return try_stable_schema().await;
}
let Some(version) = releases.into_iter().find(|r| version.matches(&r.version)) else {
return try_stable_schema().await;
};
schema_file_for_version(version.version).await
}
#[worker::send]
async fn try_stable_schema() -> anyhow::Result<String> {
let max = stable_version("tauri").await?;
schema_file_for_version(max).await
}
#[worker::send]
async fn try_next_schema() -> anyhow::Result<String> {
let releases = crate_releases("tauri").await?;
let version = releases
.into_iter()
.filter(|r| !r.version.pre.is_empty())
.map(|r| r.version)
.max()
.context("Couldn't find latest pre-release")?;
schema_file_for_version(version).await
}
async fn schema_file_for_version(version: Version) -> anyhow::Result<String> {
let cache = Cache::open("schema".to_string()).await;
let cache_key = format!("https://schema.tauri.app/config/{version}");
if let Some(mut cached) = cache.get(cache_key.clone(), true).await? {
console_log!("Serving schema for {version} from cache");
return cached.text().await.map_err(Into::into);
}
console_log!("Fetching schema for {version} from remote");
let path = if version.major >= 2 {
"crates/tauri-schema-generator/schemas/config.schema.json"
} else {
"core/tauri-config-schema/schema.json"
};
let url = format!("https://raw.githubusercontent.com/tauri-apps/tauri/tauri-v{version}/{path}");
let mut res = Fetch::Request(fetch_req(&url)?).send().await?;
cache.put(cache_key, res.cloned()?).await?;
res.text().await.map_err(Into::into)
}
async fn crate_releases(crate_: &str) -> anyhow::Result<Vec<CrateRelease>> {
let url = format!("https://crates.io/api/v1/crates/{crate_}/versions");
let mut res = Fetch::Request(fetch_req(&url)?).send().await?;
let versions: CrateReleases = res.json().await?;
let versions = versions.versions;
let flt = |r: &CrateRelease| r.yanked == Some(false);
Ok(versions.into_iter().filter(flt).collect())
}
async fn stable_version(crate_: &str) -> anyhow::Result<Version> {
let url = format!("https://crates.io/api/v1/crates/{crate_}");
let mut res = Fetch::Request(fetch_req(&url)?).send().await?;
let metadata: CrateMetadataFull = res.json().await?;
Ok(metadata.crate_.max_stable_version)
}
fn fetch_req(url: &str) -> anyhow::Result<worker::Request> {
let headers = Headers::new();
headers.append(header::USER_AGENT.as_str(), USERAGENT)?;
worker::Request::new_with_init(
url,
&RequestInit {
method: Method::Get,
headers,
cf: CfProperties {
cache_ttl: Some(86400),
cache_everything: Some(true),
cache_ttl_by_status: Some(
[
("200-299".to_string(), 86400),
("404".to_string(), 1),
("500-599".to_string(), 0),
]
.into(),
),
..Default::default()
},
..Default::default()
},
)
.map_err(Into::into)
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-schema-worker/src/lib.rs | crates/tauri-schema-worker/src/lib.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use axum::{routing::get, Router};
use tower_service::Service;
use worker::*;
mod config;
#[worker::event(fetch)]
async fn main(
req: HttpRequest,
_env: Env,
_ctx: Context,
) -> worker::Result<axum::http::Response<axum::body::Body>> {
console_error_panic_hook::set_once();
Ok(router().call(req).await?)
}
fn router() -> Router {
Router::new().route("/", get(root)).merge(config::router())
}
async fn root() -> &'static str {
"tauri schema worker"
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-macros/src/mobile.rs | crates/tauri-macros/src/mobile.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use std::env::var;
use syn::{parse_macro_input, spanned::Spanned, ItemFn};
fn get_env_var(name: &str, error: &mut Option<TokenStream2>, function: &ItemFn) -> TokenStream2 {
match var(name) {
Ok(value) => {
let ident = format_ident!("{value}");
quote!(#ident)
}
Err(_) => {
error.replace(
syn::Error::new(
function.span(),
format!("`{name}` env var not set, do you have a build script with tauri-build?",),
)
.into_compile_error(),
);
quote!()
}
}
}
pub fn entry_point(_attributes: TokenStream, item: TokenStream) -> TokenStream {
let function = parse_macro_input!(item as ItemFn);
let function_name = function.sig.ident.clone();
let mut error = None;
let domain = get_env_var("TAURI_ANDROID_PACKAGE_NAME_PREFIX", &mut error, &function);
let app_name = get_env_var("TAURI_ANDROID_PACKAGE_NAME_APP_NAME", &mut error, &function);
let (wrapper, wrapper_name) = if function.sig.asyncness.is_some() {
let wrapper_name = syn::Ident::new(&format!("{function_name}_wrapper"), function_name.span());
(
quote! {
#function
fn #wrapper_name() {
::tauri::async_runtime::block_on(#function_name());
}
},
wrapper_name,
)
} else {
(
quote! {
#function
},
function_name,
)
};
if let Some(e) = error {
quote!(#e).into()
} else {
quote!(
fn stop_unwind<F: FnOnce() -> T, T>(f: F) -> T {
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
Ok(t) => t,
Err(err) => {
eprintln!("attempt to unwind out of `rust` with err: {:?}", err);
std::process::abort()
}
}
}
#wrapper
fn _start_app() {
#[cfg(target_os = "ios")]
::tauri::log_stdout();
#[cfg(target_os = "android")]
{
::tauri::android_binding!(#domain, #app_name, _start_app, ::tauri::wry);
}
stop_unwind(#wrapper_name);
}
// be careful when renaming this, the `start_app` symbol is checked by the CLI
#[cfg(not(target_os = "android"))]
#[no_mangle]
#[inline(never)]
pub extern "C" fn start_app() {
_start_app()
}
)
.into()
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-macros/src/lib.rs | crates/tauri-macros/src/lib.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Create macros for `tauri::Context`, invoke handler and commands leveraging the `tauri-codegen` crate.
#![doc(
html_logo_url = "https://github.com/tauri-apps/tauri/raw/dev/.github/icon.png",
html_favicon_url = "https://github.com/tauri-apps/tauri/raw/dev/.github/icon.png"
)]
use std::path::PathBuf;
use crate::context::ContextItems;
use proc_macro::TokenStream;
use quote::{quote, ToTokens};
use syn::{parse2, parse_macro_input, LitStr};
use tauri_codegen::image::CachedIcon;
mod command;
mod menu;
mod mobile;
mod runtime;
#[macro_use]
mod context;
/// Mark a function as a command handler. It creates a wrapper function with the necessary glue code.
///
/// # Stability
/// The output of this macro is managed internally by Tauri,
/// and should not be accessed directly on normal applications.
/// It may have breaking changes in the future.
#[proc_macro_attribute]
pub fn command(attributes: TokenStream, item: TokenStream) -> TokenStream {
command::wrapper(attributes, item)
}
#[proc_macro_attribute]
pub fn mobile_entry_point(attributes: TokenStream, item: TokenStream) -> TokenStream {
mobile::entry_point(attributes, item)
}
/// Accepts a list of command functions. Creates a handler that allows commands to be called from JS with invoke().
///
/// You can optionally annotate the commands with a inner attribute tag `#![plugin(your_plugin_name)]`
/// for `build > removeUnusedCommands` to work for plugins not defined in a standalone crate like `tauri-plugin-fs`
///
/// # Examples
///
/// ```rust,ignore
/// use tauri_macros::{command, generate_handler};
/// #[command]
/// fn command_one() {
/// println!("command one called");
/// }
/// #[command]
/// fn command_two() {
/// println!("command two called");
/// }
/// fn main() {
/// let _handler = generate_handler![command_one, command_two];
/// }
/// ```
///
/// # Stability
///
/// The output of this macro is managed internally by Tauri,
/// and should not be accessed directly on normal applications.
/// It may have breaking changes in the future.
#[proc_macro]
pub fn generate_handler(item: TokenStream) -> TokenStream {
parse_macro_input!(item as command::Handler).into()
}
/// Reads a Tauri config file and generates a `::tauri::Context` based on the content.
///
/// # Stability
/// The output of this macro is managed internally by Tauri,
/// and should not be accessed directly on normal applications.
/// It may have breaking changes in the future.
#[proc_macro]
pub fn generate_context(items: TokenStream) -> TokenStream {
// this macro is exported from the context module
let path = parse_macro_input!(items as ContextItems);
context::generate_context(path).into()
}
/// Adds the default type for the last parameter (assumed to be runtime) for a specific feature.
///
/// e.g. To default the runtime generic to type `crate::Wry` when the `wry` feature is enabled, the
/// syntax would look like `#[default_runtime(crate::Wry, wry)`. This is **always** set for the last
/// generic, so make sure the last generic is the runtime when using this macro.
#[doc(hidden)]
#[proc_macro_attribute]
pub fn default_runtime(attributes: TokenStream, input: TokenStream) -> TokenStream {
let attributes = parse_macro_input!(attributes as runtime::Attributes);
let input = parse_macro_input!(input as runtime::Input);
runtime::default_runtime(attributes, input).into()
}
/// Accepts a closure-like syntax to call arbitrary code on a menu item
/// after matching against `kind` and retrieving it from `resources_table` using `rid`.
///
/// You can optionally pass a 5th parameter to select which item kinds
/// to match against, by providing a `|` separated list of item kinds
/// ```ignore
/// do_menu_item!(resources_table, rid, kind, |i| i.set_text(text), Check | Submenu);
/// ```
/// You could also provide a negated list
/// ```ignore
/// do_menu_item!(resources_table, rid, kind, |i| i.set_text(text), !Check);
/// do_menu_item!(resources_table, rid, kind, |i| i.set_text(text), !Check | !Submenu);
/// ```
/// but you can't have mixed negations and positive kinds.
/// ```ignore
/// do_menu_item!(resources_table, rid, kind, |i| i.set_text(text), !Check | Submenu);
/// ```
///
/// #### Example
///
/// ```ignore
/// let rid = 23;
/// let kind = ItemKind::Check;
/// let resources_table = app.resources_table();
/// do_menu_item!(resources_table, rid, kind, |i| i.set_text(text))
/// ```
/// which will expand into:
/// ```ignore
/// let rid = 23;
/// let kind = ItemKind::Check;
/// let resources_table = app.resources_table();
/// match kind {
/// ItemKind::Submenu => {
/// let i = resources_table.get::<Submenu<R>>(rid)?;
/// i.set_text(text)
/// }
/// ItemKind::MenuItem => {
/// let i = resources_table.get::<MenuItem<R>>(rid)?;
/// i.set_text(text)
/// }
/// ItemKind::Predefined => {
/// let i = resources_table.get::<PredefinedMenuItem<R>>(rid)?;
/// i.set_text(text)
/// }
/// ItemKind::Check => {
/// let i = resources_table.get::<CheckMenuItem<R>>(rid)?;
/// i.set_text(text)
/// }
/// ItemKind::Icon => {
/// let i = resources_table.get::<IconMenuItem<R>>(rid)?;
/// i.set_text(text)
/// }
/// _ => unreachable!(),
/// }
/// ```
#[proc_macro]
pub fn do_menu_item(input: TokenStream) -> TokenStream {
let tokens = parse_macro_input!(input as menu::DoMenuItemInput);
menu::do_menu_item(tokens).into()
}
/// Convert a .png or .ico icon to an Image
/// for things like `tauri::tray::TrayIconBuilder` to consume,
/// relative paths are resolved from `CARGO_MANIFEST_DIR`, not current file
///
/// ### Examples
///
/// ```ignore
/// const APP_ICON: Image<'_> = include_image!("./icons/32x32.png");
///
/// // then use it with tray
/// TrayIconBuilder::new().icon(APP_ICON).build().unwrap();
///
/// // or with window
/// WebviewWindowBuilder::new(app, "main", WebviewUrl::default())
/// .icon(APP_ICON)
/// .unwrap()
/// .build()
/// .unwrap();
///
/// // or with any other functions that takes `Image` struct
/// ```
///
/// Note: this stores the image in raw pixels to the final binary,
/// so keep the icon size (width and height) small
/// or else it's going to bloat your final executable
#[proc_macro]
pub fn include_image(tokens: TokenStream) -> TokenStream {
let path = match parse2::<LitStr>(tokens.into()) {
Ok(path) => path,
Err(err) => return err.into_compile_error().into(),
};
let path = PathBuf::from(path.value());
let resolved_path = if path.is_relative() {
if let Ok(base_dir) = std::env::var("CARGO_MANIFEST_DIR").map(PathBuf::from) {
base_dir.join(path)
} else {
return quote!(compile_error!("$CARGO_MANIFEST_DIR is not defined")).into();
}
} else {
path
};
if !resolved_path.exists() {
let error_string = format!(
"Provided Image path \"{}\" doesn't exists",
resolved_path.display()
);
return quote!(compile_error!(#error_string)).into();
}
match CachedIcon::new("e!(::tauri), &resolved_path).map_err(|error| error.to_string()) {
Ok(icon) => icon.into_token_stream(),
Err(error) => quote!(compile_error!(#error)),
}
.into()
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-macros/src/menu.rs | crates/tauri-macros/src/menu.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use proc_macro2::{Ident, Span, TokenStream};
use quote::quote;
use syn::{
parse::{Parse, ParseStream},
punctuated::Punctuated,
Expr, Token,
};
pub struct DoMenuItemInput {
resources_table: Ident,
rid: Ident,
kind: Ident,
var: Ident,
expr: Expr,
kinds: Vec<NegatedIdent>,
}
#[derive(Clone)]
struct NegatedIdent {
negated: bool,
ident: Ident,
}
impl NegatedIdent {
fn new(ident: &str) -> Self {
Self {
negated: false,
ident: Ident::new(ident, Span::call_site()),
}
}
fn is_negated(&self) -> bool {
self.negated
}
}
impl Parse for NegatedIdent {
fn parse(input: ParseStream) -> syn::Result<Self> {
let negated_token = input.parse::<Token![!]>();
let ident: Ident = input.parse()?;
Ok(NegatedIdent {
negated: negated_token.is_ok(),
ident,
})
}
}
impl Parse for DoMenuItemInput {
fn parse(input: ParseStream) -> syn::Result<Self> {
let resources_table: Ident = input.parse()?;
let _: Token![,] = input.parse()?;
let rid: Ident = input.parse()?;
let _: Token![,] = input.parse()?;
let kind: Ident = input.parse()?;
let _: Token![,] = input.parse()?;
let _: Token![|] = input.parse()?;
let var: Ident = input.parse()?;
let _: Token![|] = input.parse()?;
let expr: Expr = input.parse()?;
let _: syn::Result<Token![,]> = input.parse();
let kinds = Punctuated::<NegatedIdent, Token![|]>::parse_terminated(input)?;
Ok(Self {
resources_table,
rid,
kind,
var,
expr,
kinds: kinds.into_iter().collect(),
})
}
}
pub fn do_menu_item(input: DoMenuItemInput) -> TokenStream {
let DoMenuItemInput {
rid,
resources_table,
kind,
expr,
var,
mut kinds,
} = input;
let defaults = vec![
NegatedIdent::new("Submenu"),
NegatedIdent::new("MenuItem"),
NegatedIdent::new("Predefined"),
NegatedIdent::new("Check"),
NegatedIdent::new("Icon"),
];
if kinds.is_empty() {
kinds.extend(defaults.clone());
}
let has_negated = kinds.iter().any(|n| n.is_negated());
if has_negated {
kinds.extend(defaults);
kinds.sort_by(|a, b| a.ident.cmp(&b.ident));
kinds.dedup_by(|a, b| a.ident == b.ident);
}
let (kinds, types): (Vec<Ident>, Vec<Ident>) = kinds
.into_iter()
.filter_map(|nident| {
if nident.is_negated() {
None
} else {
match nident.ident {
i if i == "MenuItem" => Some((i, Ident::new("MenuItem", Span::call_site()))),
i if i == "Submenu" => Some((i, Ident::new("Submenu", Span::call_site()))),
i if i == "Predefined" => Some((i, Ident::new("PredefinedMenuItem", Span::call_site()))),
i if i == "Check" => Some((i, Ident::new("CheckMenuItem", Span::call_site()))),
i if i == "Icon" => Some((i, Ident::new("IconMenuItem", Span::call_site()))),
_ => None,
}
}
})
.unzip();
quote! {
match #kind {
#(
ItemKind::#kinds => {
let #var = #resources_table.get::<#types<R>>(#rid)?;
#expr
}
)*
_ => unreachable!(),
}
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-macros/src/runtime.rs | crates/tauri-macros/src/runtime.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use syn::parse::{Parse, ParseStream};
use syn::{
parse_quote, DeriveInput, Error, GenericParam, Ident, ItemTrait, ItemType, Token, Type, TypeParam,
};
#[derive(Clone)]
pub(crate) enum Input {
Derive(DeriveInput),
Trait(ItemTrait),
Type(ItemType),
}
impl Parse for Input {
fn parse(input: ParseStream) -> syn::Result<Self> {
input
.parse::<DeriveInput>()
.map(Self::Derive)
.or_else(|_| input.parse().map(Self::Trait))
.or_else(|_| input.parse().map(Self::Type))
.map_err(|_| {
Error::new(
input.span(),
"default_runtime only supports `struct`, `enum`, `type`, or `trait` definitions",
)
})
}
}
impl Input {
fn last_param_mut(&mut self) -> Option<&mut GenericParam> {
match self {
Input::Derive(d) => d.generics.params.last_mut(),
Input::Trait(t) => t.generics.params.last_mut(),
Input::Type(t) => t.generics.params.last_mut(),
}
}
}
impl ToTokens for Input {
fn to_tokens(&self, tokens: &mut TokenStream) {
match self {
Input::Derive(d) => d.to_tokens(tokens),
Input::Trait(t) => t.to_tokens(tokens),
Input::Type(t) => t.to_tokens(tokens),
}
}
}
/// The default runtime type to enable when the provided feature is enabled.
pub(crate) struct Attributes {
default_type: Type,
feature: Ident,
}
impl Parse for Attributes {
fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
let default_type = input.parse()?;
input.parse::<Token![,]>()?;
Ok(Attributes {
default_type,
feature: input.parse()?,
})
}
}
pub(crate) fn default_runtime(attributes: Attributes, input: Input) -> TokenStream {
// create a new copy to manipulate for the wry feature flag
let mut wry = input.clone();
let wry_runtime = wry
.last_param_mut()
.expect("default_runtime requires the item to have at least 1 generic parameter");
// set the default value of the last generic parameter to the provided runtime type
match wry_runtime {
GenericParam::Type(
param @ TypeParam {
eq_token: None,
default: None,
..
},
) => {
param.eq_token = Some(parse_quote!(=));
param.default = Some(attributes.default_type);
}
_ => {
panic!("DefaultRuntime requires the last parameter to not have a default value")
}
};
let feature = attributes.feature.to_string();
quote!(
#[cfg(feature = #feature)]
#wry
#[cfg(not(feature = #feature))]
#input
)
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-macros/src/context.rs | crates/tauri-macros/src/context.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use proc_macro2::{Ident, Span, TokenStream};
use quote::{quote, ToTokens};
use std::path::PathBuf;
use syn::{
parse::{Parse, ParseBuffer},
punctuated::Punctuated,
Expr, ExprLit, Lit, LitBool, LitStr, Meta, PathArguments, PathSegment, Token,
};
use tauri_codegen::{context_codegen, get_config, ContextData};
use tauri_utils::{config::parse::does_supported_file_name_exist, platform::Target};
pub(crate) struct ContextItems {
config_file: PathBuf,
root: syn::Path,
capabilities: Option<Vec<PathBuf>>,
assets: Option<Expr>,
test: bool,
}
impl Parse for ContextItems {
fn parse(input: &ParseBuffer<'_>) -> syn::parse::Result<Self> {
let target = std::env::var("TARGET")
.or_else(|_| std::env::var("TAURI_ENV_TARGET_TRIPLE"))
.as_deref()
.map(Target::from_triple)
.unwrap_or_else(|_| Target::current());
let mut root = None;
let mut capabilities = None;
let mut assets = None;
let mut test = false;
let config_file = input.parse::<LitStr>().ok().map(|raw| {
let _ = input.parse::<Token![,]>();
let path = PathBuf::from(raw.value());
if path.is_relative() {
std::env::var("CARGO_MANIFEST_DIR")
.map(|m| PathBuf::from(m).join(path))
.map_err(|e| e.to_string())
} else {
Ok(path)
}
.and_then(|path| {
if does_supported_file_name_exist(target, &path) {
Ok(path)
} else {
Err(format!(
"no file at path {} exists, expected tauri config file",
path.display()
))
}
})
});
while let Ok(meta) = input.parse::<Meta>() {
match meta {
Meta::Path(p) => {
root.replace(p);
}
Meta::NameValue(v) => {
let ident = v.path.require_ident()?;
match ident.to_string().as_str() {
"capabilities" => {
if let Expr::Array(array) = v.value {
capabilities.replace(
array
.elems
.into_iter()
.map(|e| {
if let Expr::Lit(ExprLit {
attrs: _,
lit: Lit::Str(s),
}) = e
{
Ok(s.value().into())
} else {
Err(syn::Error::new(
input.span(),
"unexpected expression for capability",
))
}
})
.collect::<Result<Vec<_>, syn::Error>>()?,
);
} else {
return Err(syn::Error::new(
input.span(),
"unexpected value for capabilities",
));
}
}
"assets" => {
assets.replace(v.value);
}
"test" => {
if let Expr::Lit(ExprLit {
lit: Lit::Bool(LitBool { value, .. }),
..
}) = v.value
{
test = value;
} else {
return Err(syn::Error::new(input.span(), "unexpected value for test"));
}
}
name => {
return Err(syn::Error::new(
input.span(),
format!("unknown attribute {name}"),
));
}
}
}
Meta::List(_) => {
return Err(syn::Error::new(input.span(), "unexpected list input"));
}
}
let _ = input.parse::<Token![,]>();
}
Ok(Self {
config_file: config_file
.unwrap_or_else(|| {
std::env::var("CARGO_MANIFEST_DIR")
.map(|m| PathBuf::from(m).join("tauri.conf.json"))
.map_err(|e| e.to_string())
})
.map_err(|e| input.error(e))?,
root: root.unwrap_or_else(|| {
let mut segments = Punctuated::new();
segments.push(PathSegment {
ident: Ident::new("tauri", Span::call_site()),
arguments: PathArguments::None,
});
syn::Path {
leading_colon: Some(Token)),
segments,
}
}),
capabilities,
assets,
test,
})
}
}
pub(crate) fn generate_context(context: ContextItems) -> TokenStream {
let context = get_config(&context.config_file)
.map_err(|e| e.to_string())
.map(|(config, config_parent)| ContextData {
dev: cfg!(not(feature = "custom-protocol")),
config,
config_parent,
root: context.root.to_token_stream(),
capabilities: context.capabilities,
assets: context.assets,
test: context.test,
})
.and_then(|data| context_codegen(data).map_err(|e| e.to_string()));
match context {
Ok(code) => code,
Err(error) => quote!(compile_error!(#error)),
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-macros/src/command/wrapper.rs | crates/tauri-macros/src/command/wrapper.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{env::var, sync::OnceLock};
use heck::{ToLowerCamelCase, ToSnakeCase};
use proc_macro::TokenStream;
use proc_macro2::{Ident, Span, TokenStream as TokenStream2};
use quote::{format_ident, quote, quote_spanned};
use syn::{
ext::IdentExt,
parse::{Parse, ParseStream},
parse_macro_input,
punctuated::Punctuated,
spanned::Spanned,
Expr, ExprLit, FnArg, ItemFn, Lit, Meta, Pat, Token, Visibility,
};
use tauri_utils::acl::REMOVE_UNUSED_COMMANDS_ENV_VAR;
#[allow(clippy::large_enum_variant)]
enum WrapperAttributeKind {
Meta(Meta),
Async,
}
impl Parse for WrapperAttributeKind {
fn parse(input: ParseStream) -> syn::Result<Self> {
match input.parse::<Meta>() {
Ok(m) => Ok(Self::Meta(m)),
Err(e) => match input.parse::<Token![async]>() {
Ok(_) => Ok(Self::Async),
Err(_) => Err(e),
},
}
}
}
struct WrapperAttributes {
root: TokenStream2,
execution_context: ExecutionContext,
argument_case: ArgumentCase,
}
impl Parse for WrapperAttributes {
fn parse(input: ParseStream) -> syn::Result<Self> {
let mut wrapper_attributes = WrapperAttributes {
root: quote!(::tauri),
execution_context: ExecutionContext::Blocking,
argument_case: ArgumentCase::Camel,
};
let attrs = Punctuated::<WrapperAttributeKind, Token![,]>::parse_terminated(input)?;
for attr in attrs {
match attr {
WrapperAttributeKind::Meta(Meta::List(_)) => {
return Err(syn::Error::new(input.span(), "unexpected list input"));
}
WrapperAttributeKind::Meta(Meta::NameValue(v)) => {
if v.path.is_ident("rename_all") {
if let Expr::Lit(ExprLit {
lit: Lit::Str(s),
attrs: _,
}) = v.value
{
wrapper_attributes.argument_case = match s.value().as_str() {
"snake_case" => ArgumentCase::Snake,
"camelCase" => ArgumentCase::Camel,
_ => {
return Err(syn::Error::new(
s.span(),
"expected \"camelCase\" or \"snake_case\"",
))
}
};
}
} else if v.path.is_ident("root") {
if let Expr::Lit(ExprLit {
lit: Lit::Str(s),
attrs: _,
}) = v.value
{
let lit = s.value();
wrapper_attributes.root = if lit == "crate" {
quote!($crate)
} else {
let ident = Ident::new(&lit, Span::call_site());
quote!(#ident)
};
}
}
}
WrapperAttributeKind::Meta(Meta::Path(_)) => {
return Err(syn::Error::new(
input.span(),
"unexpected input, expected one of `rename_all`, `root`, `async`",
));
}
WrapperAttributeKind::Async => {
wrapper_attributes.execution_context = ExecutionContext::Async;
}
}
}
Ok(wrapper_attributes)
}
}
/// The execution context of the command.
enum ExecutionContext {
Async,
Blocking,
}
/// The case of each argument name.
#[derive(Copy, Clone)]
enum ArgumentCase {
Snake,
Camel,
}
/// The bindings we attach to `tauri::Invoke`.
struct Invoke {
message: Ident,
resolver: Ident,
acl: Ident,
}
/// Create a new [`Wrapper`] from the function and the generated code parsed from the function.
pub fn wrapper(attributes: TokenStream, item: TokenStream) -> TokenStream {
let mut attrs = parse_macro_input!(attributes as WrapperAttributes);
let function = parse_macro_input!(item as ItemFn);
let wrapper = super::format_command_wrapper(&function.sig.ident);
let visibility = &function.vis;
if function.sig.asyncness.is_some() {
attrs.execution_context = ExecutionContext::Async;
}
// macros used with `pub use my_macro;` need to be exported with `#[macro_export]`
let maybe_macro_export = match &function.vis {
Visibility::Public(_) | Visibility::Restricted(_) => quote!(#[macro_export]),
_ => TokenStream2::default(),
};
let invoke = Invoke {
message: format_ident!("__tauri_message__"),
resolver: format_ident!("__tauri_resolver__"),
acl: format_ident!("__tauri_acl__"),
};
// Tauri currently doesn't support async commands that take a reference as input and don't return
// a result. See: https://github.com/tauri-apps/tauri/issues/2533
//
// For now, we provide an informative error message to the user in that case. Once #2533 is
// resolved, this check can be removed.
let mut async_command_check = TokenStream2::new();
if function.sig.asyncness.is_some() {
// This check won't catch all possible problems but it should catch the most common ones.
let mut ref_argument_span = None;
for arg in &function.sig.inputs {
if let syn::FnArg::Typed(pat) = arg {
match &*pat.ty {
syn::Type::Reference(_) => {
ref_argument_span = Some(pat.span());
}
syn::Type::Path(path) => {
// Check if the type contains a lifetime argument
let last = path.path.segments.last().unwrap();
if let syn::PathArguments::AngleBracketed(args) = &last.arguments {
if args
.args
.iter()
.any(|arg| matches!(arg, syn::GenericArgument::Lifetime(_)))
{
ref_argument_span = Some(pat.span());
}
}
}
_ => {}
}
if let Some(span) = ref_argument_span {
if let syn::ReturnType::Type(_, return_type) = &function.sig.output {
// To check if the return type is `Result` we require it to check a trait that is
// only implemented by `Result`. That way we don't exclude renamed result types
// which we wouldn't otherwise be able to detect purely from the token stream.
// The "error message" displayed to the user is simply the trait name.
//
// TODO: remove this check once our MSRV is high enough
let diagnostic = if is_rustc_at_least(1, 78) {
quote!(#[diagnostic::on_unimplemented(message = "async commands that contain references as inputs must return a `Result`")])
} else {
quote!()
};
async_command_check = quote_spanned! {return_type.span() =>
#[allow(unreachable_code, clippy::diverging_sub_expression, clippy::used_underscore_binding)]
const _: () = if false {
#diagnostic
trait AsyncCommandMustReturnResult {}
impl<A, B> AsyncCommandMustReturnResult for ::std::result::Result<A, B> {}
let _check: #return_type = unreachable!();
let _: &dyn AsyncCommandMustReturnResult = &_check;
};
};
} else {
return quote_spanned! {
span => compile_error!("async commands that contain references as inputs must return a `Result`");
}.into();
}
}
}
}
}
let plugin_name = var("CARGO_PKG_NAME")
.expect("missing `CARGO_PKG_NAME` environment variable")
.strip_prefix("tauri-plugin-")
.map(|name| quote!(::core::option::Option::Some(#name)))
.unwrap_or_else(|| quote!(::core::option::Option::None));
let body = match attrs.execution_context {
ExecutionContext::Async => body_async(&plugin_name, &function, &invoke, &attrs)
.unwrap_or_else(syn::Error::into_compile_error),
ExecutionContext::Blocking => body_blocking(&plugin_name, &function, &invoke, &attrs)
.unwrap_or_else(syn::Error::into_compile_error),
};
let Invoke {
message,
resolver,
acl,
} = invoke;
let root = attrs.root;
let kind = match attrs.execution_context {
ExecutionContext::Async if function.sig.asyncness.is_none() => "sync_threadpool",
ExecutionContext::Async => "async",
ExecutionContext::Blocking => "sync",
};
let loc = function.span().start();
let line = loc.line;
let col = loc.column;
let maybe_span = if cfg!(feature = "tracing") {
quote!({
let _span = tracing::debug_span!(
"ipc::request::handler",
cmd = #message.command(),
kind = #kind,
loc.line = #line,
loc.col = #col,
is_internal = false,
)
.entered();
})
} else {
quote!()
};
// Allow this to be unused when we're building with `build > removeUnusedCommands` for dead code elimination
let maybe_allow_unused = if var(REMOVE_UNUSED_COMMANDS_ENV_VAR).is_ok() {
quote!(#[allow(unused)])
} else {
TokenStream2::default()
};
// Rely on rust 2018 edition to allow importing a macro from a path.
quote!(
#async_command_check
#maybe_allow_unused
#function
#maybe_allow_unused
#maybe_macro_export
#[doc(hidden)]
macro_rules! #wrapper {
// double braces because the item is expected to be a block expression
($path:path, $invoke:ident) => {
// The IIFE here is for preventing stack overflow on Windows,
// see https://github.com/tauri-apps/tauri/issues/12488
{
move || {
#[allow(unused_imports)]
use #root::ipc::private::*;
// prevent warnings when the body is a `compile_error!` or if the command has no arguments
#[allow(unused_variables)]
let #root::ipc::Invoke { message: #message, resolver: #resolver, acl: #acl } = $invoke;
#maybe_span
#body
}
}()
};
}
// allow the macro to be resolved with the same path as the command function
#[allow(unused_imports)]
#visibility use #wrapper;
)
.into()
}
/// Generates an asynchronous command response from the arguments and return value of a function.
///
/// See the [`tauri::command`] module for all the items and traits that make this possible.
///
/// [`tauri::command`]: https://docs.rs/tauri/*/tauri/runtime/index.html
fn body_async(
plugin_name: &TokenStream2,
function: &ItemFn,
invoke: &Invoke,
attributes: &WrapperAttributes,
) -> syn::Result<TokenStream2> {
let Invoke {
message,
resolver,
acl,
} = invoke;
parse_args(plugin_name, function, message, acl, attributes).map(|args| {
#[cfg(feature = "tracing")]
quote! {
use tracing::Instrument;
let span = tracing::debug_span!("ipc::request::run");
#resolver.respond_async_serialized(async move {
let result = $path(#(#args?),*);
let kind = (&result).async_kind();
kind.future(result).await
}
.instrument(span));
return true;
}
#[cfg(not(feature = "tracing"))]
quote! {
#resolver.respond_async_serialized(async move {
let result = $path(#(#args?),*);
let kind = (&result).async_kind();
kind.future(result).await
});
return true;
}
})
}
/// Generates a blocking command response from the arguments and return value of a function.
///
/// See the [`tauri::command`] module for all the items and traits that make this possible.
///
/// [`tauri::command`]: https://docs.rs/tauri/*/tauri/runtime/index.html
fn body_blocking(
plugin_name: &TokenStream2,
function: &ItemFn,
invoke: &Invoke,
attributes: &WrapperAttributes,
) -> syn::Result<TokenStream2> {
let Invoke {
message,
resolver,
acl,
} = invoke;
let args = parse_args(plugin_name, function, message, acl, attributes)?;
// the body of a `match` to early return any argument that wasn't successful in parsing.
let match_body = quote!({
Ok(arg) => arg,
Err(err) => { #resolver.invoke_error(err); return true },
});
let maybe_span = if cfg!(feature = "tracing") {
quote!(let _span = tracing::debug_span!("ipc::request::run").entered();)
} else {
quote!()
};
Ok(quote! {
#maybe_span
let result = $path(#(match #args #match_body),*);
let kind = (&result).blocking_kind();
kind.block(result, #resolver);
return true;
})
}
/// Parse all arguments for the command wrapper to use from the signature of the command function.
fn parse_args(
plugin_name: &TokenStream2,
function: &ItemFn,
message: &Ident,
acl: &Ident,
attributes: &WrapperAttributes,
) -> syn::Result<Vec<TokenStream2>> {
function
.sig
.inputs
.iter()
.map(|arg| {
parse_arg(
plugin_name,
&function.sig.ident,
arg,
message,
acl,
attributes,
)
})
.collect()
}
/// Transform a [`FnArg`] into a command argument.
fn parse_arg(
plugin_name: &TokenStream2,
command: &Ident,
arg: &FnArg,
message: &Ident,
acl: &Ident,
attributes: &WrapperAttributes,
) -> syn::Result<TokenStream2> {
// we have no use for self arguments
let mut arg = match arg {
FnArg::Typed(arg) => arg.pat.as_ref().clone(),
FnArg::Receiver(arg) => {
return Err(syn::Error::new(
arg.span(),
"unable to use self as a command function parameter",
))
}
};
// we only support patterns that allow us to extract some sort of keyed identifier
let mut key = match &mut arg {
Pat::Ident(arg) => arg.ident.unraw().to_string(),
Pat::Wild(_) => "".into(), // we always convert to camelCase, so "_" will end up empty anyways
Pat::Struct(s) => super::path_to_command(&mut s.path).ident.to_string(),
Pat::TupleStruct(s) => super::path_to_command(&mut s.path).ident.to_string(),
err => {
return Err(syn::Error::new(
err.span(),
"only named, wildcard, struct, and tuple struct arguments allowed",
))
}
};
// also catch self arguments that use FnArg::Typed syntax
if key == "self" {
return Err(syn::Error::new(
key.span(),
"unable to use self as a command function parameter",
));
}
match attributes.argument_case {
ArgumentCase::Camel => {
key = key.to_lower_camel_case();
}
ArgumentCase::Snake => {
key = key.to_snake_case();
}
}
let root = &attributes.root;
Ok(quote!(#root::ipc::CommandArg::from_command(
#root::ipc::CommandItem {
plugin: #plugin_name,
name: stringify!(#command),
key: #key,
message: &#message,
acl: &#acl,
}
)))
}
fn is_rustc_at_least(major: u32, minor: u32) -> bool {
let version = rustc_version();
version.0 >= major && version.1 >= minor
}
fn rustc_version() -> &'static (u32, u32) {
static RUSTC_VERSION: OnceLock<(u32, u32)> = OnceLock::new();
RUSTC_VERSION.get_or_init(|| {
cross_command("rustc")
.arg("-V")
.output()
.ok()
.and_then(|o| {
let version = String::from_utf8_lossy(&o.stdout)
.trim()
.split(' ')
.nth(1)
.unwrap_or_default()
.split('.')
.take(2)
.flat_map(|p| p.parse::<u32>().ok())
.collect::<Vec<_>>();
version
.first()
.and_then(|major| version.get(1).map(|minor| (*major, *minor)))
})
.unwrap_or((1, 0))
})
}
fn cross_command(bin: &str) -> std::process::Command {
#[cfg(target_os = "windows")]
let cmd = {
let mut cmd = std::process::Command::new("cmd");
cmd.arg("/c").arg(bin);
cmd
};
#[cfg(not(target_os = "windows"))]
let cmd = std::process::Command::new(bin);
cmd
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-macros/src/command/mod.rs | crates/tauri-macros/src/command/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use proc_macro2::Ident;
use syn::{Path, PathSegment};
pub use self::{handler::Handler, wrapper::wrapper};
mod handler;
mod wrapper;
/// The autogenerated wrapper ident.
fn format_command_wrapper(function: &Ident) -> Ident {
quote::format_ident!("__cmd__{}", function)
}
/// This function will panic if the passed [`syn::Path`] does not have any segments.
fn path_to_command(path: &mut Path) -> &mut PathSegment {
path
.segments
.last_mut()
.expect("parsed syn::Path has no segment")
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-macros/src/command/handler.rs | crates/tauri-macros/src/command/handler.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use quote::format_ident;
use syn::{
parse::{Parse, ParseBuffer, ParseStream},
Attribute, Ident, Path, Token,
};
struct CommandDef {
path: Path,
attrs: Vec<Attribute>,
}
impl Parse for CommandDef {
fn parse(input: ParseStream) -> syn::Result<Self> {
let attrs = input.call(Attribute::parse_outer)?;
let path = input.parse()?;
Ok(CommandDef { path, attrs })
}
}
/// The items parsed from [`generate_handle!`](crate::generate_handle).
pub struct Handler {
command_defs: Vec<CommandDef>,
commands: Vec<Ident>,
wrappers: Vec<Path>,
}
impl Parse for Handler {
fn parse(input: &ParseBuffer<'_>) -> syn::Result<Self> {
let plugin_name = try_get_plugin_name(input)?;
let mut command_defs = input
.parse_terminated(CommandDef::parse, Token![,])?
.into_iter()
.collect();
filter_unused_commands(plugin_name, &mut command_defs);
let mut commands = Vec::new();
let mut wrappers = Vec::new();
// parse the command names and wrappers from the passed paths
for command_def in &command_defs {
let mut wrapper = command_def.path.clone();
let last = super::path_to_command(&mut wrapper);
// the name of the actual command function
let command = last.ident.clone();
// set the path to the command function wrapper
last.ident = super::format_command_wrapper(&command);
commands.push(command);
wrappers.push(wrapper);
}
Ok(Self {
command_defs,
commands,
wrappers,
})
}
}
/// Try to get the plugin name by parsing the input for a `#![plugin(...)]` attribute,
/// if it's not present, try getting it from `CARGO_PKG_NAME` environment variable
fn try_get_plugin_name(input: &ParseBuffer<'_>) -> Result<Option<String>, syn::Error> {
if let Ok(attrs) = input.call(Attribute::parse_inner) {
for attr in attrs {
if attr.path().is_ident("plugin") {
// Parse the content inside #![plugin(...)]
let plugin_name = attr.parse_args::<Ident>()?.to_string();
return Ok(Some(if plugin_name == "__TAURI_CHANNEL__" {
// TODO: Remove this in v3
plugin_name
} else {
plugin_name.replace("_", "-")
}));
}
}
}
Ok(
std::env::var("CARGO_PKG_NAME")
.ok()
.and_then(|var| var.strip_prefix("tauri-plugin-").map(String::from)),
)
}
fn filter_unused_commands(plugin_name: Option<String>, command_defs: &mut Vec<CommandDef>) {
let allowed_commands = tauri_utils::acl::read_allowed_commands();
let Some(allowed_commands) = allowed_commands else {
return;
};
// TODO: Remove this in v3
if plugin_name.as_deref() == Some("__TAURI_CHANNEL__") {
// Always allowed
return;
}
if plugin_name.is_none() && !allowed_commands.has_app_acl {
// All application commands are allowed if we don't have an application ACL
//
// note that inline plugins without the #![plugin()] attribute would also get to this check
// which means inline plugins must have an app manifest to get proper unused command removal
return;
}
let mut unused_commands = Vec::new();
let command_prefix = if let Some(plugin_name) = &plugin_name {
format!("plugin:{plugin_name}|")
} else {
"".into()
};
command_defs.retain(|command_def| {
let mut wrapper = command_def.path.clone();
let last = super::path_to_command(&mut wrapper);
// the name of the actual command function
let command_name = &last.ident;
let command = format!("{command_prefix}{command_name}");
let is_allowed = allowed_commands.commands.contains(&command);
if !is_allowed {
unused_commands.push(command_name.to_string());
}
is_allowed
});
if !unused_commands.is_empty() {
let plugin_display_name = plugin_name.as_deref().unwrap_or("application");
let unused_commands_display = unused_commands.join(", ");
println!("Removed unused commands from {plugin_display_name}: {unused_commands_display}",);
}
}
impl From<Handler> for proc_macro::TokenStream {
fn from(
Handler {
command_defs,
commands,
wrappers,
}: Handler,
) -> Self {
let cmd = format_ident!("__tauri_cmd__");
let invoke = format_ident!("__tauri_invoke__");
let (paths, attrs): (Vec<Path>, Vec<Vec<Attribute>>) = command_defs
.into_iter()
.map(|def| (def.path, def.attrs))
.unzip();
quote::quote!(move |#invoke| {
let #cmd = #invoke.message.command();
match #cmd {
#(#(#attrs)* stringify!(#commands) => #wrappers!(#paths, #invoke),)*
_ => {
return false;
},
}
})
.into()
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/build.rs | crates/tauri/build.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use heck::AsShoutySnakeCase;
use tauri_utils::write_if_changed;
use std::{
collections::BTreeMap,
env, fs,
path::{Path, PathBuf},
sync::{Mutex, OnceLock},
};
static CHECKED_FEATURES: OnceLock<Mutex<Vec<String>>> = OnceLock::new();
const PLUGINS: &[(&str, &[(&str, bool)])] = &[
// (plugin_name, &[(command, enabled-by_default)])
// TODO: Enable this in v3
// ("core:channel", &[("fetch", true)]),
(
"core:path",
&[
("resolve_directory", true),
("resolve", true),
("normalize", true),
("join", true),
("dirname", true),
("extname", true),
("basename", true),
("is_absolute", true),
],
),
(
"core:event",
&[
("listen", true),
("unlisten", true),
("emit", true),
("emit_to", true),
],
),
(
"core:window",
&[
("create", false),
// getters
("get_all_windows", true),
("scale_factor", true),
("inner_position", true),
("outer_position", true),
("inner_size", true),
("outer_size", true),
("is_fullscreen", true),
("is_minimized", true),
("is_maximized", true),
("is_focused", true),
("is_decorated", true),
("is_resizable", true),
("is_maximizable", true),
("is_minimizable", true),
("is_closable", true),
("is_visible", true),
("is_enabled", true),
("title", true),
("current_monitor", true),
("primary_monitor", true),
("monitor_from_point", true),
("available_monitors", true),
("cursor_position", true),
("theme", true),
("is_always_on_top", true),
// setters
("center", false),
("request_user_attention", false),
("set_enabled", false),
("set_resizable", false),
("set_maximizable", false),
("set_minimizable", false),
("set_closable", false),
("set_title", false),
("maximize", false),
("unmaximize", false),
("minimize", false),
("unminimize", false),
("show", false),
("hide", false),
("close", false),
("destroy", false),
("set_decorations", false),
("set_shadow", false),
("set_effects", false),
("set_always_on_top", false),
("set_always_on_bottom", false),
("set_visible_on_all_workspaces", false),
("set_content_protected", false),
("set_size", false),
("set_min_size", false),
("set_size_constraints", false),
("set_max_size", false),
("set_position", false),
("set_fullscreen", false),
("set_simple_fullscreen", false),
("set_focus", false),
("set_focusable", false),
("set_skip_taskbar", false),
("set_cursor_grab", false),
("set_cursor_visible", false),
("set_cursor_icon", false),
("set_cursor_position", false),
("set_ignore_cursor_events", false),
("start_dragging", false),
("start_resize_dragging", false),
("set_progress_bar", false),
("set_badge_count", false),
("set_overlay_icon", false),
("set_badge_label", false),
("set_icon", false),
("set_title_bar_style", false),
("set_theme", false),
("toggle_maximize", false),
("set_background_color", false),
// internal
("internal_toggle_maximize", true),
],
),
(
"core:webview",
&[
("create_webview", false),
("create_webview_window", false),
// getters
("get_all_webviews", true),
("webview_position", true),
("webview_size", true),
// setters
("webview_close", false),
("set_webview_size", false),
("set_webview_position", false),
("set_webview_focus", false),
("set_webview_auto_resize", false),
("set_webview_zoom", false),
("webview_hide", false),
("webview_show", false),
("print", false),
("reparent", false),
("clear_all_browsing_data", false),
("set_webview_background_color", false),
// internal
("internal_toggle_devtools", true),
],
),
(
"core:app",
&[
("version", true),
("name", true),
("tauri_version", true),
("identifier", true),
("app_show", false),
("app_hide", false),
("fetch_data_store_identifiers", false),
("remove_data_store", false),
("default_window_icon", false),
("set_app_theme", false),
("set_dock_visibility", false),
("bundle_type", true),
("register_listener", true),
("remove_listener", true),
],
),
(
"core:image",
&[
("new", true),
("from_bytes", true),
("from_path", true),
("rgba", true),
("size", true),
],
),
("core:resources", &[("close", true)]),
(
"core:menu",
&[
("new", true),
("append", true),
("prepend", true),
("insert", true),
("remove", true),
("remove_at", true),
("items", true),
("get", true),
("popup", true),
("create_default", true),
("set_as_app_menu", true),
("set_as_window_menu", true),
("text", true),
("set_text", true),
("is_enabled", true),
("set_enabled", true),
("set_accelerator", true),
("set_as_windows_menu_for_nsapp", true),
("set_as_help_menu_for_nsapp", true),
("is_checked", true),
("set_checked", true),
("set_icon", true),
],
),
(
"core:tray",
&[
("new", true),
("get_by_id", true),
("remove_by_id", true),
("set_icon", true),
("set_menu", true),
("set_tooltip", true),
("set_title", true),
("set_visible", true),
("set_temp_dir_path", true),
("set_icon_as_template", true),
("set_show_menu_on_left_click", true),
],
),
];
// checks if the given Cargo feature is enabled.
fn has_feature(feature: &str) -> bool {
CHECKED_FEATURES
.get_or_init(Default::default)
.lock()
.unwrap()
.push(feature.to_string());
// when a feature is enabled, Cargo sets the `CARGO_FEATURE_<name>` env var to 1
// <https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts>
std::env::var(format!("CARGO_FEATURE_{}", AsShoutySnakeCase(feature)))
.map(|x| x == "1")
.unwrap_or(false)
}
// creates a cfg alias if `has_feature` is true.
// `alias` must be a snake case string.
fn alias(alias: &str, has_feature: bool) {
println!("cargo:rustc-check-cfg=cfg({alias})");
if has_feature {
println!("cargo:rustc-cfg={alias}");
}
}
fn main() {
let custom_protocol = has_feature("custom-protocol");
let dev = !custom_protocol;
alias("custom_protocol", custom_protocol);
alias("dev", dev);
println!("cargo:dev={dev}");
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
let mobile = target_os == "ios" || target_os == "android";
alias("desktop", !mobile);
alias("mobile", mobile);
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
let checked_features_out_path = out_dir.join("checked_features");
std::fs::write(
checked_features_out_path,
CHECKED_FEATURES.get().unwrap().lock().unwrap().join(","),
)
.expect("failed to write checked_features file");
// workaround needed to prevent `STATUS_ENTRYPOINT_NOT_FOUND` error in tests
// see https://github.com/tauri-apps/tauri/pull/4383#issuecomment-1212221864
let target_env = std::env::var("CARGO_CFG_TARGET_ENV");
let is_tauri_workspace = std::env::var("__TAURI_WORKSPACE__").is_ok_and(|v| v == "true");
if is_tauri_workspace && target_os == "windows" && Ok("msvc") == target_env.as_deref() {
embed_manifest_for_tests();
}
if target_os == "android" {
fn env_var(var: &str) -> String {
std::env::var(var).unwrap_or_else(|_| {
panic!("`{var}` is not set, which is needed to generate the kotlin files for android.")
})
}
if let Ok(kotlin_out_dir) = std::env::var("WRY_ANDROID_KOTLIN_FILES_OUT_DIR") {
let package = env_var("WRY_ANDROID_PACKAGE");
let library = env_var("WRY_ANDROID_LIBRARY");
let kotlin_out_dir = PathBuf::from(&kotlin_out_dir)
.canonicalize()
.unwrap_or_else(move |_| {
panic!("Failed to canonicalize `WRY_ANDROID_KOTLIN_FILES_OUT_DIR` path {kotlin_out_dir}")
});
let kotlin_files_path =
PathBuf::from(env_var("CARGO_MANIFEST_DIR")).join("mobile/android-codegen");
println!("cargo:rerun-if-changed={}", kotlin_files_path.display());
let kotlin_files =
fs::read_dir(kotlin_files_path).expect("failed to read Android codegen directory");
for file in kotlin_files {
let file = file.unwrap();
let content = fs::read_to_string(file.path())
.expect("failed to read kotlin file as string")
.replace("{{package}}", &package)
.replace("{{library}}", &library);
let out_path = kotlin_out_dir.join(file.file_name());
// Overwrite only if changed to not trigger rebuilds
write_if_changed(&out_path, &content).expect("Failed to write kotlin file");
println!("cargo:rerun-if-changed={}", out_path.display());
}
}
if let Some(project_dir) = env::var_os("TAURI_ANDROID_PROJECT_PATH").map(PathBuf::from) {
let package_unescaped = env::var("TAURI_ANDROID_PACKAGE_UNESCAPED")
.unwrap_or_else(|_| env_var("WRY_ANDROID_PACKAGE").replace('`', ""));
let tauri_proguard =
include_str!("./mobile/proguard-tauri.pro").replace("$PACKAGE", &package_unescaped);
std::fs::write(
project_dir.join("app").join("proguard-tauri.pro"),
tauri_proguard,
)
.expect("failed to write proguard-tauri.pro");
}
let lib_path =
PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap()).join("mobile/android");
println!("cargo:android_library_path={}", lib_path.display());
}
#[cfg(target_os = "macos")]
{
if target_os == "ios" {
let lib_path =
PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap()).join("mobile/ios-api");
tauri_utils::build::link_apple_library("Tauri", &lib_path);
println!("cargo:ios_library_path={}", lib_path.display());
}
}
let tauri_global_scripts = PathBuf::from("./scripts/bundle.global.js")
.canonicalize()
.expect("failed to canonicalize tauri global API script path");
tauri_utils::plugin::define_global_api_script_path(&tauri_global_scripts);
// This should usually be done in `tauri-build`,
// but we need to do this here for the examples in this workspace to work as they don't have build scripts
if is_tauri_workspace {
tauri_utils::plugin::save_global_api_scripts_paths(&out_dir, Some(tauri_global_scripts));
}
let permissions = define_permissions(&out_dir);
tauri_utils::acl::build::generate_allowed_commands(&out_dir, None, permissions).unwrap();
}
const LICENSE_HEADER: &str = r"# Copyright 2019-2024 Tauri Programme within The Commons Conservancy
# SPDX-License-Identifier: Apache-2.0
# SPDX-License-Identifier: MIT
";
fn define_permissions(
out_dir: &Path,
) -> BTreeMap<String, Vec<tauri_utils::acl::manifest::PermissionFile>> {
let mut all_permissions = BTreeMap::new();
for (plugin, commands) in PLUGINS {
let plugin_directory_name = plugin.strip_prefix("core:").unwrap_or(plugin);
let permissions_out_dir = out_dir.join("permissions").join(plugin_directory_name);
let autogenerated =
permissions_out_dir.join(tauri_utils::acl::build::AUTOGENERATED_FOLDER_NAME);
let commands_dir = autogenerated.join("commands");
tauri_utils::acl::build::autogenerate_command_permissions(
&commands_dir,
&commands.iter().map(|(cmd, _)| *cmd).collect::<Vec<_>>(),
LICENSE_HEADER,
false,
);
let default_permissions: Vec<_> = commands.iter().filter(|(_cmd, default)| *default).collect();
let all_commands_enabled_by_default = commands.len() == default_permissions.len();
let default_permissions = default_permissions
.into_iter()
.map(|(cmd, _)| {
let slugified_command = cmd.replace('_', "-");
format!("\"allow-{slugified_command}\"")
})
.collect::<Vec<_>>()
.join(", ");
let all_enable_by_default = if all_commands_enabled_by_default {
", which enables all commands"
} else {
""
};
let default_toml = format!(
r#"{LICENSE_HEADER}# Automatically generated - DO NOT EDIT!
[default]
description = "Default permissions for the plugin{all_enable_by_default}."
permissions = [{default_permissions}]
"#,
);
let out_path = autogenerated.join("default.toml");
write_if_changed(out_path, default_toml)
.unwrap_or_else(|_| panic!("unable to autogenerate default permissions"));
let permissions = tauri_utils::acl::build::define_permissions(
&PathBuf::from(glob::Pattern::escape(
&permissions_out_dir.to_string_lossy(),
))
.join("**")
.join("*.toml")
.to_string_lossy(),
&format!("tauri:{plugin}"),
out_dir,
|_| true,
)
.unwrap_or_else(|e| panic!("failed to define permissions for {plugin}: {e}"));
let docs_out_dir = Path::new("permissions")
.join(plugin_directory_name)
.join("autogenerated");
fs::create_dir_all(&docs_out_dir).expect("failed to create plugin documentation directory");
tauri_utils::acl::build::generate_docs(
&permissions,
&docs_out_dir,
plugin.strip_prefix("tauri-plugin-").unwrap_or(plugin),
)
.expect("failed to generate plugin documentation page");
all_permissions.insert(plugin.to_string(), permissions);
}
let default_permissions = define_default_permission_set(out_dir);
all_permissions.insert("core".to_string(), default_permissions);
all_permissions
}
fn define_default_permission_set(
out_dir: &Path,
) -> Vec<tauri_utils::acl::manifest::PermissionFile> {
let permissions_out_dir = out_dir.join("permissions");
fs::create_dir_all(&permissions_out_dir)
.expect("failed to create core:default permissions directory");
let default_toml = permissions_out_dir.join("default.toml");
let toml_content = format!(
r#"{LICENSE_HEADER}
[default]
description = "Default core plugins set."
permissions = [{}]
"#,
PLUGINS
.iter()
.map(|(k, _)| format!("\"{k}:default\""))
.collect::<Vec<_>>()
.join(",")
);
write_if_changed(default_toml, toml_content)
.unwrap_or_else(|_| panic!("unable to autogenerate core:default set"));
tauri_utils::acl::build::define_permissions(
&PathBuf::from(glob::Pattern::escape(
&permissions_out_dir.to_string_lossy(),
))
.join("*.toml")
.to_string_lossy(),
"tauri:core",
out_dir,
|_| true,
)
.unwrap_or_else(|e| panic!("failed to define permissions for `core:default` : {e}"))
}
fn embed_manifest_for_tests() {
static WINDOWS_MANIFEST_FILE: &str = "windows-app-manifest.xml";
let manifest = std::env::current_dir()
.unwrap()
.join("../tauri-build/src")
.join(WINDOWS_MANIFEST_FILE);
println!("cargo:rerun-if-changed={}", manifest.display());
// Embed the Windows application manifest file.
println!("cargo:rustc-link-arg=/MANIFEST:EMBED");
println!(
"cargo:rustc-link-arg=/MANIFESTINPUT:{}",
manifest.to_str().unwrap()
);
// Turn linker warnings into errors.
println!("cargo:rustc-link-arg=/WX");
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/ios.rs | crates/tauri/src/ios.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use swift_rs::{swift, SRString, SwiftArg};
use std::{
ffi::c_void,
os::raw::{c_char, c_int, c_ulonglong},
};
type PluginMessageCallbackFn = unsafe extern "C" fn(c_int, c_int, *const c_char);
pub struct PluginMessageCallback(pub PluginMessageCallbackFn);
impl<'a> SwiftArg<'a> for PluginMessageCallback {
type ArgType = PluginMessageCallbackFn;
unsafe fn as_arg(&'a self) -> Self::ArgType {
self.0
}
}
type ChannelSendDataCallbackFn = unsafe extern "C" fn(c_ulonglong, *const c_char);
pub struct ChannelSendDataCallback(pub ChannelSendDataCallbackFn);
impl<'a> SwiftArg<'a> for ChannelSendDataCallback {
type ArgType = ChannelSendDataCallbackFn;
unsafe fn as_arg(&'a self) -> Self::ArgType {
self.0
}
}
swift!(pub fn run_plugin_command(
id: i32,
name: &SRString,
method: &SRString,
data: &SRString,
callback: PluginMessageCallback,
send_channel_data_callback: ChannelSendDataCallback
));
swift!(pub fn register_plugin(
name: &SRString,
plugin: *const c_void,
config: &SRString,
webview: *const c_void
));
swift!(pub fn on_webview_created(webview: *const c_void, controller: *const c_void));
swift!(pub fn log_stdout());
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/app.rs | crates/tauri/src/app.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{
image::Image,
ipc::{
channel::ChannelDataIpcQueue, CallbackFn, CommandArg, CommandItem, Invoke, InvokeError,
InvokeHandler, InvokeResponseBody,
},
manager::{webview::UriSchemeProtocol, AppManager, Asset},
plugin::{Plugin, PluginStore},
resources::ResourceTable,
runtime::{
window::{WebviewEvent as RuntimeWebviewEvent, WindowEvent as RuntimeWindowEvent},
ExitRequestedEventAction, RunEvent as RuntimeRunEvent,
},
sealed::{ManagerBase, RuntimeOrDispatch},
utils::{config::Config, Env},
webview::PageLoadPayload,
Context, DeviceEventFilter, Emitter, EventLoopMessage, EventName, Listener, Manager, Monitor,
Runtime, Scopes, StateManager, Theme, Webview, WebviewWindowBuilder, Window,
};
#[cfg(desktop)]
use crate::menu::{Menu, MenuEvent};
#[cfg(all(desktop, feature = "tray-icon"))]
use crate::tray::{TrayIcon, TrayIconBuilder, TrayIconEvent, TrayIconId};
use raw_window_handle::HasDisplayHandle;
use serialize_to_javascript::{default_template, DefaultTemplate, Template};
use tauri_macros::default_runtime;
#[cfg(desktop)]
use tauri_runtime::EventLoopProxy;
use tauri_runtime::{
dpi::{PhysicalPosition, PhysicalSize},
window::DragDropEvent,
RuntimeInitArgs,
};
use tauri_utils::{assets::AssetsIter, PackageInfo};
use std::{
borrow::Cow,
collections::HashMap,
fmt,
sync::{atomic, mpsc::Sender, Arc, Mutex, MutexGuard},
thread::ThreadId,
time::Duration,
};
use crate::{event::EventId, runtime::RuntimeHandle, Event, EventTarget};
#[cfg(target_os = "macos")]
use crate::ActivationPolicy;
pub(crate) mod plugin;
#[cfg(desktop)]
pub(crate) type GlobalMenuEventListener<T> = Box<dyn Fn(&T, crate::menu::MenuEvent) + Send + Sync>;
#[cfg(all(desktop, feature = "tray-icon"))]
pub(crate) type GlobalTrayIconEventListener<T> =
Box<dyn Fn(&T, crate::tray::TrayIconEvent) + Send + Sync>;
pub(crate) type GlobalWindowEventListener<R> = Box<dyn Fn(&Window<R>, &WindowEvent) + Send + Sync>;
pub(crate) type GlobalWebviewEventListener<R> =
Box<dyn Fn(&Webview<R>, &WebviewEvent) + Send + Sync>;
/// A closure that is run when the Tauri application is setting up.
pub type SetupHook<R> =
Box<dyn FnOnce(&mut App<R>) -> std::result::Result<(), Box<dyn std::error::Error>> + Send>;
/// A closure that is run every time a page starts or finishes loading.
pub type OnPageLoad<R> = dyn Fn(&Webview<R>, &PageLoadPayload<'_>) + Send + Sync + 'static;
pub type ChannelInterceptor<R> =
Box<dyn Fn(&Webview<R>, CallbackFn, usize, &InvokeResponseBody) -> bool + Send + Sync + 'static>;
/// The exit code on [`RunEvent::ExitRequested`] when [`AppHandle#method.restart`] is called.
pub const RESTART_EXIT_CODE: i32 = i32::MAX;
/// Api exposed on the `ExitRequested` event.
#[derive(Debug, Clone)]
pub struct ExitRequestApi {
tx: Sender<ExitRequestedEventAction>,
code: Option<i32>,
}
impl ExitRequestApi {
/// Prevents the app from exiting.
///
/// **Note:** This is ignored when using [`AppHandle#method.restart`].
pub fn prevent_exit(&self) {
if self.code != Some(RESTART_EXIT_CODE) {
self.tx.send(ExitRequestedEventAction::Prevent).unwrap();
}
}
}
/// Api exposed on the `CloseRequested` event.
#[derive(Debug, Clone)]
pub struct CloseRequestApi(Sender<bool>);
impl CloseRequestApi {
/// Prevents the window from being closed.
pub fn prevent_close(&self) {
self.0.send(true).unwrap();
}
}
/// An event from a window.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum WindowEvent {
/// The size of the window has changed. Contains the client area's new dimensions.
Resized(PhysicalSize<u32>),
/// The position of the window has changed. Contains the window's new position.
Moved(PhysicalPosition<i32>),
/// The window has been requested to close.
#[non_exhaustive]
CloseRequested {
/// An API modify the behavior of the close requested event.
api: CloseRequestApi,
},
/// The window has been destroyed.
Destroyed,
/// The window gained or lost focus.
///
/// The parameter is true if the window has gained focus, and false if it has lost focus.
Focused(bool),
/// The window's scale factor has changed.
///
/// The following user actions can cause DPI changes:
///
/// - Changing the display's resolution.
/// - Changing the display's scale factor (e.g. in Control Panel on Windows).
/// - Moving the window to a display with a different scale factor.
#[non_exhaustive]
ScaleFactorChanged {
/// The new scale factor.
scale_factor: f64,
/// The window inner size.
new_inner_size: PhysicalSize<u32>,
},
/// An event associated with the drag and drop action.
DragDrop(DragDropEvent),
/// The system window theme has changed. Only delivered if the window [`theme`](`crate::window::WindowBuilder#method.theme`) is `None`.
///
/// Applications might wish to react to this to change the theme of the content of the window when the system changes the window theme.
///
/// ## Platform-specific
///
/// - **Linux**: Not supported.
ThemeChanged(Theme),
}
impl From<RuntimeWindowEvent> for WindowEvent {
fn from(event: RuntimeWindowEvent) -> Self {
match event {
RuntimeWindowEvent::Resized(size) => Self::Resized(size),
RuntimeWindowEvent::Moved(position) => Self::Moved(position),
RuntimeWindowEvent::CloseRequested { signal_tx } => Self::CloseRequested {
api: CloseRequestApi(signal_tx),
},
RuntimeWindowEvent::Destroyed => Self::Destroyed,
RuntimeWindowEvent::Focused(flag) => Self::Focused(flag),
RuntimeWindowEvent::ScaleFactorChanged {
scale_factor,
new_inner_size,
} => Self::ScaleFactorChanged {
scale_factor,
new_inner_size,
},
RuntimeWindowEvent::DragDrop(event) => Self::DragDrop(event),
RuntimeWindowEvent::ThemeChanged(theme) => Self::ThemeChanged(theme),
}
}
}
/// An event from a window.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum WebviewEvent {
/// An event associated with the drag and drop action.
DragDrop(DragDropEvent),
}
impl From<RuntimeWebviewEvent> for WebviewEvent {
fn from(event: RuntimeWebviewEvent) -> Self {
match event {
RuntimeWebviewEvent::DragDrop(e) => Self::DragDrop(e),
}
}
}
/// An application event, triggered from the event loop.
///
/// See [`App::run`](crate::App#method.run) for usage examples.
#[derive(Debug)]
#[non_exhaustive]
pub enum RunEvent {
/// Event loop is exiting.
Exit,
/// The app is about to exit
#[non_exhaustive]
ExitRequested {
/// Exit code.
/// [`Option::None`] when the exit is requested by user interaction,
/// [`Option::Some`] when requested programmatically via [`AppHandle#method.exit`] and [`AppHandle#method.restart`].
code: Option<i32>,
/// Event API
api: ExitRequestApi,
},
/// An event associated with a window.
#[non_exhaustive]
WindowEvent {
/// The window label.
label: String,
/// The detailed event.
event: WindowEvent,
},
/// An event associated with a webview.
#[non_exhaustive]
WebviewEvent {
/// The window label.
label: String,
/// The detailed event.
event: WebviewEvent,
},
/// Application ready.
Ready,
/// Sent if the event loop is being resumed.
Resumed,
/// Emitted when all of the event loop's input events have been processed and redraw processing is about to begin.
///
/// This event is useful as a place to put your code that should be run after all state-changing events have been handled and you want to do stuff (updating state, performing calculations, etc) that happens as the "main body" of your event loop.
MainEventsCleared,
/// Emitted when the user wants to open the specified resource with the app.
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[cfg_attr(docsrs, doc(cfg(any(target_os = "macos", feature = "ios"))))]
Opened {
/// The URL of the resources that is being open.
urls: Vec<url::Url>,
},
/// An event from a menu item, could be on the window menu bar, application menu bar (on macOS) or tray icon menu.
#[cfg(desktop)]
#[cfg_attr(docsrs, doc(cfg(desktop)))]
MenuEvent(crate::menu::MenuEvent),
/// An event from a tray icon.
#[cfg(all(desktop, feature = "tray-icon"))]
#[cfg_attr(docsrs, doc(cfg(all(desktop, feature = "tray-icon"))))]
TrayIconEvent(crate::tray::TrayIconEvent),
/// Emitted when the NSApplicationDelegate's applicationShouldHandleReopen gets called
#[non_exhaustive]
#[cfg(target_os = "macos")]
#[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
Reopen {
/// Indicates whether the NSApplication object found any visible windows in your application.
has_visible_windows: bool,
},
}
impl From<EventLoopMessage> for RunEvent {
fn from(event: EventLoopMessage) -> Self {
match event {
#[cfg(desktop)]
EventLoopMessage::MenuEvent(e) => Self::MenuEvent(e),
#[cfg(all(desktop, feature = "tray-icon"))]
EventLoopMessage::TrayIconEvent(e) => Self::TrayIconEvent(e),
}
}
}
/// The asset resolver is a helper to access the [`tauri_utils::assets::Assets`] interface.
#[derive(Debug, Clone)]
pub struct AssetResolver<R: Runtime> {
manager: Arc<AppManager<R>>,
}
impl<R: Runtime> AssetResolver<R> {
/// Gets the app asset associated with the given path.
///
/// By default it tries to infer your application's URL scheme in production by checking if all webviews
/// were configured with [`crate::webview::WebviewBuilder::use_https_scheme`] or `tauri.conf.json > app > windows > useHttpsScheme`.
/// If you are resolving an asset for a webview with a more dynamic configuration, see [`AssetResolver::get_for_scheme`].
///
/// In production, this resolves to the embedded asset bundled in the app executable
/// which contains your frontend assets in [`frontendDist`](https://v2.tauri.app/reference/config/#frontenddist) during build time.
///
/// In dev mode, if [`devUrl`](https://v2.tauri.app/reference/config/#devurl) is set, we don't bundle the assets to reduce re-builds,
/// and this will fall back to read from `frontendDist` directly.
/// Note that the dist directory must exist so you might need to build your frontend assets first.
pub fn get(&self, path: String) -> Option<Asset> {
let use_https_scheme = self
.manager
.webviews()
.values()
.all(|webview| webview.use_https_scheme());
self.get_for_scheme(path, use_https_scheme)
}
/// Same as [`AssetResolver::get`] but resolves the custom protocol scheme based on a parameter.
///
/// - `use_https_scheme`: If `true` when using [`Pattern::Isolation`](crate::Pattern::Isolation),
/// the csp header will contain `https://tauri.localhost` instead of `http://tauri.localhost`
pub fn get_for_scheme(&self, path: String, use_https_scheme: bool) -> Option<Asset> {
#[cfg(dev)]
{
// We don't bundle the assets when in dev mode and `devUrl` is set, so fall back to read from `frontendDist` directly
// TODO: Maybe handle `FrontendDist::Files` as well
if let (Some(_), Some(crate::utils::config::FrontendDist::Directory(dist_path))) = (
&self.manager.config().build.dev_url,
&self.manager.config().build.frontend_dist,
) {
let asset_path = std::path::PathBuf::from(&path)
.components()
.filter(|c| !matches!(c, std::path::Component::RootDir))
.collect::<std::path::PathBuf>();
let asset_path = self
.manager
.config_parent()
.map(|p| p.join(dist_path).join(&asset_path))
.unwrap_or_else(|| dist_path.join(&asset_path));
return std::fs::read(asset_path).ok().map(|bytes| {
let mime_type = crate::utils::mime_type::MimeType::parse(&bytes, &path);
Asset {
bytes,
mime_type,
csp_header: None,
}
});
}
}
self.manager.get_asset(path, use_https_scheme).ok()
}
/// Iterate on all assets.
pub fn iter(&self) -> Box<AssetsIter<'_>> {
self.manager.assets.iter()
}
}
/// A handle to the currently running application.
///
/// This type implements [`Manager`] which allows for manipulation of global application items.
#[default_runtime(crate::Wry, wry)]
#[derive(Debug)]
pub struct AppHandle<R: Runtime> {
pub(crate) runtime_handle: R::Handle,
pub(crate) manager: Arc<AppManager<R>>,
event_loop: Arc<Mutex<EventLoop>>,
}
/// Not the real event loop, only contains the main thread id of the event loop
#[derive(Debug)]
struct EventLoop {
main_thread_id: ThreadId,
}
/// APIs specific to the wry runtime.
#[cfg(feature = "wry")]
impl AppHandle<crate::Wry> {
/// Create a new tao window using a callback. The event loop must be running at this point.
pub fn create_tao_window<
F: FnOnce() -> (String, tauri_runtime_wry::TaoWindowBuilder) + Send + 'static,
>(
&self,
f: F,
) -> crate::Result<std::sync::Weak<tauri_runtime_wry::Window>> {
self.runtime_handle.create_tao_window(f).map_err(Into::into)
}
/// Sends a window message to the event loop.
pub fn send_tao_window_event(
&self,
window_id: tauri_runtime_wry::TaoWindowId,
message: tauri_runtime_wry::WindowMessage,
) -> crate::Result<()> {
self
.runtime_handle
.send_event(tauri_runtime_wry::Message::Window(
self.runtime_handle.window_id(window_id),
message,
))
.map_err(Into::into)
}
}
#[cfg(target_vendor = "apple")]
impl<R: Runtime> AppHandle<R> {
/// Fetches all Data Store Identifiers by this app
///
/// Needs to be called from Main Thread
pub async fn fetch_data_store_identifiers(&self) -> crate::Result<Vec<[u8; 16]>> {
let (tx, rx) = tokio::sync::oneshot::channel::<Result<Vec<[u8; 16]>, tauri_runtime::Error>>();
let lock: Arc<Mutex<Option<_>>> = Arc::new(Mutex::new(Some(tx)));
let runtime_handle = self.runtime_handle.clone();
self.run_on_main_thread(move || {
let cloned_lock = lock.clone();
if let Err(err) = runtime_handle.fetch_data_store_identifiers(move |ids| {
if let Some(tx) = cloned_lock.lock().unwrap().take() {
let _ = tx.send(Ok(ids));
}
}) {
if let Some(tx) = lock.lock().unwrap().take() {
let _ = tx.send(Err(err));
}
}
})?;
rx.await?.map_err(Into::into)
}
/// Deletes a Data Store of this app
///
/// Needs to be called from Main Thread
pub async fn remove_data_store(&self, uuid: [u8; 16]) -> crate::Result<()> {
let (tx, rx) = tokio::sync::oneshot::channel::<Result<(), tauri_runtime::Error>>();
let lock: Arc<Mutex<Option<_>>> = Arc::new(Mutex::new(Some(tx)));
let runtime_handle = self.runtime_handle.clone();
self.run_on_main_thread(move || {
let cloned_lock = lock.clone();
if let Err(err) = runtime_handle.remove_data_store(uuid, move |result| {
if let Some(tx) = cloned_lock.lock().unwrap().take() {
let _ = tx.send(result);
}
}) {
if let Some(tx) = lock.lock().unwrap().take() {
let _ = tx.send(Err(err));
}
}
})?;
rx.await?.map_err(Into::into)
}
}
impl<R: Runtime> Clone for AppHandle<R> {
fn clone(&self) -> Self {
Self {
runtime_handle: self.runtime_handle.clone(),
manager: self.manager.clone(),
event_loop: self.event_loop.clone(),
}
}
}
impl<'de, R: Runtime> CommandArg<'de, R> for AppHandle<R> {
/// Grabs the [`Window`] from the [`CommandItem`] and returns the associated [`AppHandle`]. This will never fail.
fn from_command(command: CommandItem<'de, R>) -> std::result::Result<Self, InvokeError> {
Ok(command.message.webview().app_handle)
}
}
impl<R: Runtime> AppHandle<R> {
/// Runs the given closure on the main thread.
pub fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> crate::Result<()> {
self
.runtime_handle
.run_on_main_thread(f)
.map_err(Into::into)
}
/// Adds a Tauri application plugin.
/// This function can be used to register a plugin that is loaded dynamically e.g. after login.
/// For plugins that are created when the app is started, prefer [`Builder::plugin`].
///
/// See [`Builder::plugin`] for more information.
///
/// # Examples
///
/// ```
/// use tauri::{plugin::{Builder as PluginBuilder, TauriPlugin}, Runtime};
///
/// fn init_plugin<R: Runtime>() -> TauriPlugin<R> {
/// PluginBuilder::new("dummy").build()
/// }
///
/// tauri::Builder::default()
/// .setup(move |app| {
/// let handle = app.handle().clone();
/// std::thread::spawn(move || {
/// handle.plugin(init_plugin());
/// });
///
/// Ok(())
/// });
/// ```
pub fn plugin<P: Plugin<R> + 'static>(&self, plugin: P) -> crate::Result<()> {
self.plugin_boxed(Box::new(plugin))
}
/// Adds a Tauri application plugin.
///
/// This method is similar to [`Self::plugin`],
/// but accepts a boxed trait object instead of a generic type.
#[cfg_attr(feature = "tracing", tracing::instrument(name = "app::plugin::register", skip(plugin), fields(name = plugin.name())))]
pub fn plugin_boxed(&self, mut plugin: Box<dyn Plugin<R>>) -> crate::Result<()> {
let mut store = self.manager().plugins.lock().unwrap();
store.initialize(&mut plugin, self, &self.config().plugins)?;
store.register(plugin);
Ok(())
}
/// Removes the plugin with the given name.
///
/// # Examples
///
/// ```
/// use tauri::{plugin::{Builder as PluginBuilder, TauriPlugin, Plugin}, Runtime};
///
/// fn init_plugin<R: Runtime>() -> TauriPlugin<R> {
/// PluginBuilder::new("dummy").build()
/// }
///
/// let plugin = init_plugin();
/// // `.name()` requires the `Plugin` trait import
/// let plugin_name = plugin.name();
/// tauri::Builder::default()
/// .plugin(plugin)
/// .setup(move |app| {
/// let handle = app.handle().clone();
/// std::thread::spawn(move || {
/// handle.remove_plugin(plugin_name);
/// });
///
/// Ok(())
/// });
/// ```
pub fn remove_plugin(&self, plugin: &str) -> bool {
self.manager().plugins.lock().unwrap().unregister(plugin)
}
/// Exits the app by triggering [`RunEvent::ExitRequested`] and [`RunEvent::Exit`].
pub fn exit(&self, exit_code: i32) {
if let Err(e) = self.runtime_handle.request_exit(exit_code) {
log::error!("failed to exit: {}", e);
self.cleanup_before_exit();
std::process::exit(exit_code);
}
}
/// Restarts the app by triggering [`RunEvent::ExitRequested`] with code [`RESTART_EXIT_CODE`](crate::RESTART_EXIT_CODE) and [`RunEvent::Exit`].
///
/// When this function is called on the main thread, we cannot guarantee the delivery of those events,
/// so we skip them and directly restart the process.
///
/// If you want to trigger them reliably, use [`Self::request_restart`] instead
pub fn restart(&self) -> ! {
if self.event_loop.lock().unwrap().main_thread_id == std::thread::current().id() {
log::debug!("restart triggered on the main thread");
self.cleanup_before_exit();
crate::process::restart(&self.env());
} else {
log::debug!("restart triggered from a separate thread");
// we're running on a separate thread, so we must trigger the exit request and wait for it to finish
self
.manager
.restart_on_exit
.store(true, atomic::Ordering::Relaxed);
// We'll be restarting when we receive the next `RuntimeRunEvent::Exit` event in `App::run` if this call succeed
match self.runtime_handle.request_exit(RESTART_EXIT_CODE) {
Ok(()) => loop {
std::thread::sleep(Duration::MAX);
},
Err(e) => {
log::error!("failed to request exit: {e}");
self.cleanup_before_exit();
crate::process::restart(&self.env());
}
}
}
}
/// Restarts the app by triggering [`RunEvent::ExitRequested`] with code [`RESTART_EXIT_CODE`] and [`RunEvent::Exit`].
pub fn request_restart(&self) {
self
.manager
.restart_on_exit
.store(true, atomic::Ordering::Relaxed);
// We'll be restarting when we receive the next `RuntimeRunEvent::Exit` event in `App::run` if this call succeed
if self.runtime_handle.request_exit(RESTART_EXIT_CODE).is_err() {
self.cleanup_before_exit();
crate::process::restart(&self.env());
}
}
/// Sets the activation policy for the application. It is set to `NSApplicationActivationPolicyRegular` by default.
///
/// # Examples
/// ```,no_run
/// tauri::Builder::default()
/// .setup(move |app| {
/// #[cfg(target_os = "macos")]
/// app.handle().set_activation_policy(tauri::ActivationPolicy::Accessory);
/// Ok(())
/// });
/// ```
#[cfg(target_os = "macos")]
#[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
pub fn set_activation_policy(&self, activation_policy: ActivationPolicy) -> crate::Result<()> {
self
.runtime_handle
.set_activation_policy(activation_policy)
.map_err(Into::into)
}
/// Sets the dock visibility for the application.
///
/// # Examples
/// ```,no_run
/// tauri::Builder::default()
/// .setup(move |app| {
/// #[cfg(target_os = "macos")]
/// app.handle().set_dock_visibility(false);
/// Ok(())
/// });
/// ```
#[cfg(target_os = "macos")]
#[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
pub fn set_dock_visibility(&self, visible: bool) -> crate::Result<()> {
self
.runtime_handle
.set_dock_visibility(visible)
.map_err(Into::into)
}
/// Change the device event filter mode.
///
/// See [App::set_device_event_filter] for details.
///
/// ## Platform-specific
///
/// See [App::set_device_event_filter] for details.
pub fn set_device_event_filter(&self, filter: DeviceEventFilter) {
self.runtime_handle.set_device_event_filter(filter);
}
}
impl<R: Runtime> Manager<R> for AppHandle<R> {
fn resources_table(&self) -> MutexGuard<'_, ResourceTable> {
self.manager.resources_table()
}
}
impl<R: Runtime> ManagerBase<R> for AppHandle<R> {
fn manager(&self) -> &AppManager<R> {
&self.manager
}
fn manager_owned(&self) -> Arc<AppManager<R>> {
self.manager.clone()
}
fn runtime(&self) -> RuntimeOrDispatch<'_, R> {
RuntimeOrDispatch::RuntimeHandle(self.runtime_handle.clone())
}
fn managed_app_handle(&self) -> &AppHandle<R> {
self
}
}
/// The instance of the currently running application.
///
/// This type implements [`Manager`] which allows for manipulation of global application items.
#[default_runtime(crate::Wry, wry)]
pub struct App<R: Runtime> {
runtime: Option<R>,
setup: Option<SetupHook<R>>,
manager: Arc<AppManager<R>>,
handle: AppHandle<R>,
ran_setup: bool,
}
impl<R: Runtime> fmt::Debug for App<R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("App")
.field("runtime", &self.runtime)
.field("manager", &self.manager)
.field("handle", &self.handle)
.finish()
}
}
impl<R: Runtime> Manager<R> for App<R> {
fn resources_table(&self) -> MutexGuard<'_, ResourceTable> {
self.manager.resources_table()
}
}
impl<R: Runtime> ManagerBase<R> for App<R> {
fn manager(&self) -> &AppManager<R> {
&self.manager
}
fn manager_owned(&self) -> Arc<AppManager<R>> {
self.manager.clone()
}
fn runtime(&self) -> RuntimeOrDispatch<'_, R> {
if let Some(runtime) = self.runtime.as_ref() {
RuntimeOrDispatch::Runtime(runtime)
} else {
self.handle.runtime()
}
}
fn managed_app_handle(&self) -> &AppHandle<R> {
self.handle()
}
}
/// APIs specific to the wry runtime.
#[cfg(feature = "wry")]
impl App<crate::Wry> {
/// Adds a [`tauri_runtime_wry::Plugin`] using its [`tauri_runtime_wry::PluginBuilder`].
///
/// # Stability
///
/// This API is unstable.
pub fn wry_plugin<P: tauri_runtime_wry::PluginBuilder<EventLoopMessage> + Send + 'static>(
&mut self,
plugin: P,
) where
<P as tauri_runtime_wry::PluginBuilder<EventLoopMessage>>::Plugin: Send,
{
self.handle.runtime_handle.plugin(plugin);
}
}
macro_rules! shared_app_impl {
($app: ty) => {
impl<R: Runtime> $app {
/// Registers a global menu event listener.
#[cfg(desktop)]
pub fn on_menu_event<F: Fn(&AppHandle<R>, MenuEvent) + Send + Sync + 'static>(
&self,
handler: F,
) {
self.manager.menu.on_menu_event(handler)
}
/// Registers a global tray icon menu event listener.
#[cfg(all(desktop, feature = "tray-icon"))]
#[cfg_attr(docsrs, doc(cfg(all(desktop, feature = "tray-icon"))))]
pub fn on_tray_icon_event<F: Fn(&AppHandle<R>, TrayIconEvent) + Send + Sync + 'static>(
&self,
handler: F,
) {
self.manager.tray.on_tray_icon_event(handler)
}
/// Gets a tray icon using the provided id.
#[cfg(all(desktop, feature = "tray-icon"))]
#[cfg_attr(docsrs, doc(cfg(all(desktop, feature = "tray-icon"))))]
pub fn tray_by_id<'a, I>(&self, id: &'a I) -> Option<TrayIcon<R>>
where
I: ?Sized,
TrayIconId: PartialEq<&'a I>,
{
self.manager.tray.tray_by_id(self.app_handle(), id)
}
/// Removes a tray icon using the provided id from tauri's internal state and returns it.
///
/// Note that dropping the returned icon, may cause the tray icon to disappear
/// if it wasn't cloned somewhere else or referenced by JS.
#[cfg(all(desktop, feature = "tray-icon"))]
#[cfg_attr(docsrs, doc(cfg(all(desktop, feature = "tray-icon"))))]
pub fn remove_tray_by_id<'a, I>(&self, id: &'a I) -> Option<TrayIcon<R>>
where
I: ?Sized,
TrayIconId: PartialEq<&'a I>,
{
self.manager.tray.remove_tray_by_id(self.app_handle(), id)
}
/// Gets the app's configuration, defined on the `tauri.conf.json` file.
pub fn config(&self) -> &Config {
self.manager.config()
}
/// Gets the app's package information.
pub fn package_info(&self) -> &PackageInfo {
self.manager.package_info()
}
/// The application's asset resolver.
pub fn asset_resolver(&self) -> AssetResolver<R> {
AssetResolver {
manager: self.manager.clone(),
}
}
/// Returns the primary monitor of the system.
///
/// Returns None if it can't identify any monitor as a primary one.
pub fn primary_monitor(&self) -> crate::Result<Option<Monitor>> {
Ok(match self.runtime() {
RuntimeOrDispatch::Runtime(h) => h.primary_monitor().map(Into::into),
RuntimeOrDispatch::RuntimeHandle(h) => h.primary_monitor().map(Into::into),
_ => unreachable!(),
})
}
/// Returns the monitor that contains the given point.
pub fn monitor_from_point(&self, x: f64, y: f64) -> crate::Result<Option<Monitor>> {
Ok(match self.runtime() {
RuntimeOrDispatch::Runtime(h) => h.monitor_from_point(x, y).map(Into::into),
RuntimeOrDispatch::RuntimeHandle(h) => h.monitor_from_point(x, y).map(Into::into),
_ => unreachable!(),
})
}
/// Returns the list of all the monitors available on the system.
pub fn available_monitors(&self) -> crate::Result<Vec<Monitor>> {
Ok(match self.runtime() {
RuntimeOrDispatch::Runtime(h) => {
h.available_monitors().into_iter().map(Into::into).collect()
}
RuntimeOrDispatch::RuntimeHandle(h) => {
h.available_monitors().into_iter().map(Into::into).collect()
}
_ => unreachable!(),
})
}
/// Get the cursor position relative to the top-left hand corner of the desktop.
///
/// Note that the top-left hand corner of the desktop is not necessarily the same as the screen.
/// If the user uses a desktop with multiple monitors,
/// the top-left hand corner of the desktop is the top-left hand corner of the main monitor on Windows and macOS
/// or the top-left of the leftmost monitor on X11.
///
/// The coordinates can be negative if the top-left hand corner of the window is outside of the visible screen region.
pub fn cursor_position(&self) -> crate::Result<PhysicalPosition<f64>> {
Ok(match self.runtime() {
RuntimeOrDispatch::Runtime(h) => h.cursor_position()?,
RuntimeOrDispatch::RuntimeHandle(h) => h.cursor_position()?,
_ => unreachable!(),
})
}
/// Sets the app theme.
///
/// ## Platform-specific
///
/// - **iOS / Android:** Unsupported.
pub fn set_theme(&self, theme: Option<Theme>) {
#[cfg(windows)]
for window in self.manager.windows().values() {
if let (Some(menu), Ok(hwnd)) = (window.menu(), window.hwnd()) {
let raw_hwnd = hwnd.0 as isize;
let _ = self.run_on_main_thread(move || {
let _ = unsafe {
menu.inner().set_theme_for_hwnd(
raw_hwnd,
theme
.map(crate::menu::map_to_menu_theme)
.unwrap_or(muda::MenuTheme::Auto),
)
};
});
};
}
match self.runtime() {
RuntimeOrDispatch::Runtime(h) => h.set_theme(theme),
RuntimeOrDispatch::RuntimeHandle(h) => h.set_theme(theme),
_ => unreachable!(),
}
}
/// Returns the default window icon.
pub fn default_window_icon(&self) -> Option<&Image<'_>> {
self.manager.window.default_icon.as_ref()
}
/// Returns the app-wide menu.
#[cfg(desktop)]
pub fn menu(&self) -> Option<Menu<R>> {
self.manager.menu.menu_lock().clone()
}
/// Sets the app-wide menu and returns the previous one.
///
/// If a window was not created with an explicit menu or had one set explicitly,
/// this menu will be assigned to it.
#[cfg(desktop)]
pub fn set_menu(&self, menu: Menu<R>) -> crate::Result<Option<Menu<R>>> {
let prev_menu = self.remove_menu()?;
self.manager.menu.insert_menu_into_stash(&menu);
self.manager.menu.menu_lock().replace(menu.clone());
// set it on all windows that don't have one or previously had the app-wide menu
#[cfg(not(target_os = "macos"))]
{
for window in self.manager.windows().values() {
let has_app_wide_menu = window.has_app_wide_menu() || window.menu().is_none();
if has_app_wide_menu {
window.set_menu(menu.clone())?;
window.menu_lock().replace(crate::window::WindowMenu {
is_app_wide: true,
menu: menu.clone(),
});
}
}
}
// set it app-wide for macos
#[cfg(target_os = "macos")]
{
let menu_ = menu.clone();
self.run_on_main_thread(move || {
let _ = init_app_menu(&menu_);
})?;
}
Ok(prev_menu)
}
/// Remove the app-wide menu and returns it.
///
/// If a window was not created with an explicit menu or had one set explicitly,
/// this will remove the menu from it.
#[cfg(desktop)]
pub fn remove_menu(&self) -> crate::Result<Option<Menu<R>>> {
let menu = self.manager.menu.menu_lock().as_ref().cloned();
#[allow(unused_variables)]
if let Some(menu) = menu {
// remove from windows that have the app-wide menu
#[cfg(not(target_os = "macos"))]
{
for window in self.manager.windows().values() {
let has_app_wide_menu = window.has_app_wide_menu();
if has_app_wide_menu {
window.remove_menu()?;
*window.menu_lock() = None;
}
}
}
// remove app-wide for macos
#[cfg(target_os = "macos")]
{
self.run_on_main_thread(move || {
menu.inner().remove_for_nsapp();
})?;
}
}
let prev_menu = self.manager.menu.menu_lock().take();
self
.manager
.remove_menu_from_stash_by_id(prev_menu.as_ref().map(|m| m.id()));
Ok(prev_menu)
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | true |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/lib.rs | crates/tauri/src/lib.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Tauri is a framework for building tiny, blazing fast binaries for all major desktop platforms.
//! Developers can integrate any front-end framework that compiles to HTML, JS and CSS for building their user interface.
//! The backend of the application is a rust-sourced binary with an API that the front-end can interact with.
//!
//! # Cargo features
//!
//! The following are a list of [Cargo features](https://doc.rust-lang.org/stable/cargo/reference/manifest.html#the-features-section) that can be enabled or disabled:
//!
//! - **wry** *(enabled by default)*: Enables the [wry](https://github.com/tauri-apps/wry) runtime. Only disable it if you want a custom runtime.
//! - **common-controls-v6** *(enabled by default)*: Enables [Common Controls v6](https://learn.microsoft.com/en-us/windows/win32/controls/common-control-versions) support on Windows, mainly for the predefined `about` menu item.
//! - **x11** *(enabled by default)*: Enables X11 support. Disable this if you only target Wayland.
//! - **unstable**: Enables unstable features. Be careful, it might introduce breaking changes in future minor releases.
//! - **tracing**: Enables [`tracing`](https://docs.rs/tracing/latest/tracing) for window startup, plugins, `Window::eval`, events, IPC, updater and custom protocol request handlers.
//! - **test**: Enables the [`mod@test`] module exposing unit test helpers.
//! - **objc-exception**: This feature flag is no-op since 2.3.0.
//! - **linux-libxdo**: Enables linking to libxdo which enables Cut, Copy, Paste and SelectAll menu items to work on Linux.
//! - **isolation**: Enables the isolation pattern. Enabled by default if the `app > security > pattern > use` config option is set to `isolation` on the `tauri.conf.json` file.
//! - **custom-protocol**: Feature managed by the Tauri CLI. When enabled, Tauri assumes a production environment instead of a development one.
//! - **devtools**: Enables the developer tools (Web inspector) and [`window::Window#method.open_devtools`]. Enabled by default on debug builds.
//! On macOS it uses private APIs, so you can't enable it if your app will be published to the App Store.
//! - **native-tls**: Provides TLS support to connect over HTTPS.
//! - **native-tls-vendored**: Compile and statically link to a vendored copy of OpenSSL.
//! - **rustls-tls**: Provides TLS support to connect over HTTPS using rustls.
//! - **process-relaunch-dangerous-allow-symlink-macos**: Allows the [`process::current_binary`] function to allow symlinks on macOS (this is dangerous, see the Security section in the documentation website).
//! - **tray-icon**: Enables application tray icon APIs. Enabled by default if the `trayIcon` config is defined on the `tauri.conf.json` file.
//! - **macos-private-api**: Enables features only available in **macOS**'s private APIs, currently the `transparent` window functionality and the `fullScreenEnabled` preference setting to `true`. Enabled by default if the `tauri > macosPrivateApi` config flag is set to `true` on the `tauri.conf.json` file.
//! - **webview-data-url**: Enables usage of data URLs on the webview.
//! - **compression** *(enabled by default): Enables asset compression. You should only disable this if you want faster compile times in release builds - it produces larger binaries.
//! - **config-json5**: Adds support to JSON5 format for `tauri.conf.json`.
//! - **config-toml**: Adds support to TOML format for the configuration `Tauri.toml`.
//! - **image-ico**: Adds support to parse `.ico` image, see [`Image`].
//! - **image-png**: Adds support to parse `.png` image, see [`Image`].
//! - **macos-proxy**: Adds support for [`WebviewBuilder::proxy_url`] on macOS. Requires macOS 14+.
//! - **specta**: Add support for [`specta::specta`](https://docs.rs/specta/%5E2.0.0-rc.9/specta/attr.specta.html) with Tauri arguments such as [`State`](crate::State), [`Window`](crate::Window) and [`AppHandle`](crate::AppHandle)
//! - **dynamic-acl** *(enabled by default)*: Enables you to add ACLs at runtime, notably it enables the [`Manager::add_capability`] function.
//!
//! ## Cargo allowlist features
//!
//! The following are a list of [Cargo features](https://doc.rust-lang.org/stable/cargo/reference/manifest.html#the-features-section) that enables commands for Tauri's API package.
//! These features are automatically enabled by the Tauri CLI based on the `allowlist` configuration under `tauri.conf.json`.
//!
//! ### Protocol allowlist
//!
//! - **protocol-asset**: Enables the `asset` custom protocol.
#![doc(
html_logo_url = "https://github.com/tauri-apps/tauri/raw/dev/.github/icon.png",
html_favicon_url = "https://github.com/tauri-apps/tauri/raw/dev/.github/icon.png"
)]
#![warn(missing_docs, rust_2018_idioms)]
#![cfg_attr(docsrs, feature(doc_cfg))]
/// Setups the binding that initializes an iOS plugin.
#[cfg(target_os = "ios")]
#[macro_export]
macro_rules! ios_plugin_binding {
($fn_name: ident) => {
tauri::swift_rs::swift!(fn $fn_name() -> *const ::std::ffi::c_void);
}
}
#[cfg(target_os = "macos")]
#[doc(hidden)]
pub use embed_plist;
pub use error::{Error, Result};
use ipc::RuntimeAuthority;
#[cfg(feature = "dynamic-acl")]
use ipc::RuntimeCapability;
pub use resources::{Resource, ResourceId, ResourceTable};
#[cfg(target_os = "ios")]
#[doc(hidden)]
pub use swift_rs;
pub use tauri_macros::include_image;
#[cfg(mobile)]
pub use tauri_macros::mobile_entry_point;
pub use tauri_macros::{command, generate_handler};
use tauri_utils::assets::AssetsIter;
pub use url::Url;
pub(crate) mod app;
pub mod async_runtime;
mod error;
mod event;
pub mod ipc;
mod manager;
mod pattern;
pub mod plugin;
pub(crate) mod protocol;
mod resources;
mod vibrancy;
pub mod webview;
pub mod window;
use tauri_runtime as runtime;
pub mod image;
#[cfg(target_os = "ios")]
mod ios;
#[cfg(desktop)]
#[cfg_attr(docsrs, doc(cfg(desktop)))]
pub mod menu;
/// Path APIs.
pub mod path;
pub mod process;
/// The allowlist scopes.
pub mod scope;
mod state;
#[cfg(all(desktop, feature = "tray-icon"))]
#[cfg_attr(docsrs, doc(cfg(all(desktop, feature = "tray-icon"))))]
pub mod tray;
pub use tauri_utils as utils;
pub use http;
/// A Tauri [`Runtime`] wrapper around wry.
#[cfg(feature = "wry")]
#[cfg_attr(docsrs, doc(cfg(feature = "wry")))]
pub type Wry = tauri_runtime_wry::Wry<EventLoopMessage>;
/// A Tauri [`RuntimeHandle`] wrapper around wry.
#[cfg(feature = "wry")]
#[cfg_attr(docsrs, doc(cfg(feature = "wry")))]
pub type WryHandle = tauri_runtime_wry::WryHandle<EventLoopMessage>;
#[cfg(all(feature = "wry", target_os = "android"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "wry", target_os = "android"))))]
#[doc(hidden)]
#[macro_export]
macro_rules! android_binding {
($domain:ident, $app_name:ident, $main:ident, $wry:path) => {
use $wry::{
android_setup,
prelude::{JClass, JNIEnv, JString},
};
::tauri::wry::android_binding!($domain, $app_name, $wry);
::tauri::tao::android_binding!(
$domain,
$app_name,
WryActivity,
android_setup,
$main,
::tauri::tao
);
// be careful when renaming this, the `Java_app_tauri_plugin_PluginManager_handlePluginResponse` symbol is checked by the CLI
::tauri::tao::platform::android::prelude::android_fn!(
app_tauri,
plugin,
PluginManager,
handlePluginResponse,
[i32, JString, JString],
);
::tauri::tao::platform::android::prelude::android_fn!(
app_tauri,
plugin,
PluginManager,
sendChannelData,
[i64, JString],
);
// this function is a glue between PluginManager.kt > handlePluginResponse and Rust
#[allow(non_snake_case)]
pub fn handlePluginResponse(
mut env: JNIEnv,
_: JClass,
id: i32,
success: JString,
error: JString,
) {
::tauri::handle_android_plugin_response(&mut env, id, success, error);
}
// this function is a glue between PluginManager.kt > sendChannelData and Rust
#[allow(non_snake_case)]
pub fn sendChannelData(mut env: JNIEnv, _: JClass, id: i64, data: JString) {
::tauri::send_channel_data(&mut env, id, data);
}
};
}
#[cfg(all(feature = "wry", target_os = "android"))]
#[doc(hidden)]
pub use plugin::mobile::{handle_android_plugin_response, send_channel_data};
#[cfg(all(feature = "wry", target_os = "android"))]
#[doc(hidden)]
pub use tauri_runtime_wry::{tao, wry};
/// A task to run on the main thread.
pub type SyncTask = Box<dyn FnOnce() + Send>;
use serde::Serialize;
use std::{
borrow::Cow,
collections::HashMap,
fmt::{self, Debug},
sync::MutexGuard,
};
use utils::assets::{AssetKey, CspHash, EmbeddedAssets};
#[cfg(feature = "wry")]
#[cfg_attr(docsrs, doc(cfg(feature = "wry")))]
pub use tauri_runtime_wry::webview_version;
#[cfg(target_os = "macos")]
#[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
pub use runtime::ActivationPolicy;
pub use self::utils::TitleBarStyle;
use self::event::EventName;
pub use self::event::{Event, EventId, EventTarget};
use self::manager::EmitPayload;
pub use {
self::app::{
App, AppHandle, AssetResolver, Builder, CloseRequestApi, ExitRequestApi, RunEvent,
UriSchemeContext, UriSchemeResponder, WebviewEvent, WindowEvent, RESTART_EXIT_CODE,
},
self::manager::Asset,
self::runtime::{
dpi::{
LogicalPosition, LogicalRect, LogicalSize, LogicalUnit, PhysicalPosition, PhysicalRect,
PhysicalSize, PhysicalUnit, Pixel, PixelUnit, Position, Rect, Size,
},
window::{CursorIcon, DragDropEvent, WindowSizeConstraints},
DeviceEventFilter, UserAttentionType,
},
self::state::{State, StateManager},
self::utils::{
config::{Config, WebviewUrl},
Env, PackageInfo, Theme,
},
self::webview::{Webview, WebviewWindow, WebviewWindowBuilder},
self::window::{Monitor, Window},
scope::*,
};
#[cfg(feature = "unstable")]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
pub use {self::webview::WebviewBuilder, self::window::WindowBuilder};
/// The Tauri version.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
#[cfg(target_os = "ios")]
#[doc(hidden)]
pub fn log_stdout() {
#[cfg(target_os = "ios")]
unsafe {
crate::ios::log_stdout();
}
}
/// The user event type.
#[derive(Debug, Clone)]
pub enum EventLoopMessage {
/// An event from a menu item, could be on the window menu bar, application menu bar (on macOS) or tray icon menu.
#[cfg(desktop)]
MenuEvent(menu::MenuEvent),
/// An event from a menu item, could be on the window menu bar, application menu bar (on macOS) or tray icon menu.
#[cfg(all(desktop, feature = "tray-icon"))]
#[cfg_attr(docsrs, doc(cfg(all(desktop, feature = "tray-icon"))))]
TrayIconEvent(tray::TrayIconEvent),
}
/// The webview runtime interface. A wrapper around [`runtime::Runtime`] with the proper user event type associated.
pub trait Runtime: runtime::Runtime<EventLoopMessage> {}
/// The webview runtime handle. A wrapper around [`runtime::RuntimeHandle`] with the proper user event type associated.
pub trait RuntimeHandle: runtime::RuntimeHandle<EventLoopMessage> {}
impl<W: runtime::Runtime<EventLoopMessage>> Runtime for W {}
impl<R: runtime::RuntimeHandle<EventLoopMessage>> RuntimeHandle for R {}
/// Reads the config file at compile time and generates a [`Context`] based on its content.
///
/// The default config file path is a `tauri.conf.json` file inside the Cargo manifest directory of
/// the crate being built.
///
/// # Custom Config Path
///
/// You may pass a string literal to this macro to specify a custom path for the Tauri config file.
/// If the path is relative, it will be search for relative to the Cargo manifest of the compiling
/// crate.
///
/// # Note
///
/// This macro should not be called if you are using [`tauri-build`] to generate the context from
/// inside your build script as it will just cause excess computations that will be discarded. Use
/// either the [`tauri-build`] method or this macro - not both.
///
/// [`tauri-build`]: https://docs.rs/tauri-build
pub use tauri_macros::generate_context;
/// Include a [`Context`] that was generated by [`tauri-build`] inside your build script.
///
/// You should either use [`tauri-build`] and this macro to include the compile time generated code,
/// or [`generate_context!`]. Do not use both at the same time, as they generate the same code and
/// will cause excess computations that will be discarded.
///
/// [`tauri-build`]: https://docs.rs/tauri-build
#[macro_export]
macro_rules! tauri_build_context {
() => {
include!(concat!(env!("OUT_DIR"), "/tauri-build-context.rs"))
};
}
pub use pattern::Pattern;
/// Whether we are running in development mode or not.
pub const fn is_dev() -> bool {
!cfg!(feature = "custom-protocol")
}
/// Represents a container of file assets that are retrievable during runtime.
pub trait Assets<R: Runtime>: Send + Sync + 'static {
/// Initialize the asset provider.
fn setup(&self, app: &App<R>) {
let _ = app;
}
/// Get the content of the passed [`AssetKey`].
fn get(&self, key: &AssetKey) -> Option<Cow<'_, [u8]>>;
/// Iterator for the assets.
fn iter(&self) -> Box<tauri_utils::assets::AssetsIter<'_>>;
/// Gets the hashes for the CSP tag of the HTML on the given path.
fn csp_hashes(&self, html_path: &AssetKey) -> Box<dyn Iterator<Item = CspHash<'_>> + '_>;
}
impl<R: Runtime> Assets<R> for EmbeddedAssets {
fn get(&self, key: &AssetKey) -> Option<Cow<'_, [u8]>> {
EmbeddedAssets::get(self, key)
}
fn iter(&self) -> Box<AssetsIter<'_>> {
EmbeddedAssets::iter(self)
}
fn csp_hashes(&self, html_path: &AssetKey) -> Box<dyn Iterator<Item = CspHash<'_>> + '_> {
EmbeddedAssets::csp_hashes(self, html_path)
}
}
/// User supplied data required inside of a Tauri application.
///
/// # Stability
/// This is the output of the [`generate_context`] macro, and is not considered part of the stable API.
/// Unless you know what you are doing and are prepared for this type to have breaking changes, do not create it yourself.
#[tauri_macros::default_runtime(Wry, wry)]
pub struct Context<R: Runtime> {
pub(crate) config: Config,
#[cfg(dev)]
pub(crate) config_parent: Option<std::path::PathBuf>,
/// Asset provider.
pub assets: Box<dyn Assets<R>>,
pub(crate) default_window_icon: Option<image::Image<'static>>,
pub(crate) app_icon: Option<Vec<u8>>,
#[cfg(all(desktop, feature = "tray-icon"))]
pub(crate) tray_icon: Option<image::Image<'static>>,
pub(crate) package_info: PackageInfo,
pub(crate) pattern: Pattern,
pub(crate) runtime_authority: RuntimeAuthority,
pub(crate) plugin_global_api_scripts: Option<&'static [&'static str]>,
}
/// Temporary struct that overrides the Debug formatting for the `app_icon` field.
///
/// It reduces the output size compared to the default, as that would format the binary
/// data as a slice of numbers `[65, 66, 67]`. This instead shows the length of the Vec.
///
/// For example: `Some([u8; 493])`
pub(crate) struct DebugAppIcon<'a>(&'a Option<Vec<u8>>);
impl std::fmt::Debug for DebugAppIcon<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0 {
Option::None => f.write_str("None"),
Option::Some(icon) => f
.debug_tuple("Some")
.field(&format_args!("[u8; {}]", icon.len()))
.finish(),
}
}
}
impl<R: Runtime> fmt::Debug for Context<R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut d = f.debug_struct("Context");
d.field("config", &self.config)
.field("default_window_icon", &self.default_window_icon)
.field("app_icon", &DebugAppIcon(&self.app_icon))
.field("package_info", &self.package_info)
.field("pattern", &self.pattern)
.field("plugin_global_api_scripts", &self.plugin_global_api_scripts);
#[cfg(all(desktop, feature = "tray-icon"))]
d.field("tray_icon", &self.tray_icon);
d.finish()
}
}
impl<R: Runtime> Context<R> {
/// The config the application was prepared with.
#[inline(always)]
pub fn config(&self) -> &Config {
&self.config
}
/// A mutable reference to the config the application was prepared with.
#[inline(always)]
pub fn config_mut(&mut self) -> &mut Config {
&mut self.config
}
/// The assets to be served directly by Tauri.
#[inline(always)]
pub fn assets(&self) -> &dyn Assets<R> {
self.assets.as_ref()
}
/// Replace the [`Assets`] implementation and returns the previous value so you can use it as a fallback if desired.
#[inline(always)]
pub fn set_assets(&mut self, assets: Box<dyn Assets<R>>) -> Box<dyn Assets<R>> {
std::mem::replace(&mut self.assets, assets)
}
/// The default window icon Tauri should use when creating windows.
#[inline(always)]
pub fn default_window_icon(&self) -> Option<&image::Image<'_>> {
self.default_window_icon.as_ref()
}
/// Set the default window icon Tauri should use when creating windows.
#[inline(always)]
pub fn set_default_window_icon(&mut self, icon: Option<image::Image<'static>>) {
self.default_window_icon = icon;
}
/// The icon to use on the tray icon.
#[cfg(all(desktop, feature = "tray-icon"))]
#[cfg_attr(docsrs, doc(cfg(all(desktop, feature = "tray-icon"))))]
#[inline(always)]
pub fn tray_icon(&self) -> Option<&image::Image<'_>> {
self.tray_icon.as_ref()
}
/// Set the icon to use on the tray icon.
#[cfg(all(desktop, feature = "tray-icon"))]
#[cfg_attr(docsrs, doc(cfg(all(desktop, feature = "tray-icon"))))]
#[inline(always)]
pub fn set_tray_icon(&mut self, icon: Option<image::Image<'static>>) {
self.tray_icon = icon;
}
/// Package information.
#[inline(always)]
pub fn package_info(&self) -> &PackageInfo {
&self.package_info
}
/// A mutable reference to the package information.
#[inline(always)]
pub fn package_info_mut(&mut self) -> &mut PackageInfo {
&mut self.package_info
}
/// The application pattern.
#[inline(always)]
pub fn pattern(&self) -> &Pattern {
&self.pattern
}
/// A mutable reference to the resolved ACL.
///
/// # Stability
///
/// This API is unstable.
#[doc(hidden)]
#[inline(always)]
pub fn runtime_authority_mut(&mut self) -> &mut RuntimeAuthority {
&mut self.runtime_authority
}
/// Create a new [`Context`] from the minimal required items.
#[inline(always)]
#[allow(clippy::too_many_arguments)]
pub fn new(
config: Config,
assets: Box<dyn Assets<R>>,
default_window_icon: Option<image::Image<'static>>,
app_icon: Option<Vec<u8>>,
package_info: PackageInfo,
pattern: Pattern,
runtime_authority: RuntimeAuthority,
plugin_global_api_scripts: Option<&'static [&'static str]>,
) -> Self {
Self {
config,
#[cfg(dev)]
config_parent: None,
assets,
default_window_icon,
app_icon,
#[cfg(all(desktop, feature = "tray-icon"))]
tray_icon: None,
package_info,
pattern,
runtime_authority,
plugin_global_api_scripts,
}
}
#[cfg(dev)]
#[doc(hidden)]
pub fn with_config_parent(&mut self, config_parent: impl AsRef<std::path::Path>) {
self
.config_parent
.replace(config_parent.as_ref().to_owned());
}
}
// TODO: expand these docs
/// Manages a running application.
pub trait Manager<R: Runtime>: sealed::ManagerBase<R> {
/// The application handle associated with this manager.
fn app_handle(&self) -> &AppHandle<R> {
self.managed_app_handle()
}
/// The [`Config`] the manager was created with.
fn config(&self) -> &Config {
self.manager().config()
}
/// The [`PackageInfo`] the manager was created with.
fn package_info(&self) -> &PackageInfo {
self.manager().package_info()
}
/// Fetch a single window from the manager.
#[cfg(feature = "unstable")]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
fn get_window(&self, label: &str) -> Option<Window<R>> {
self.manager().get_window(label)
}
/// Fetch the focused window. Returns `None` if there is not any focused window.
#[cfg(feature = "unstable")]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
fn get_focused_window(&self) -> Option<Window<R>> {
self.manager().get_focused_window()
}
/// Fetch all managed windows.
#[cfg(feature = "unstable")]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
fn windows(&self) -> HashMap<String, Window<R>> {
self.manager().windows()
}
/// Fetch a single webview from the manager.
#[cfg(feature = "unstable")]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
fn get_webview(&self, label: &str) -> Option<Webview<R>> {
self.manager().get_webview(label)
}
/// Fetch all managed webviews.
#[cfg(feature = "unstable")]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
fn webviews(&self) -> HashMap<String, Webview<R>> {
self.manager().webviews()
}
/// Fetch a single webview window from the manager.
fn get_webview_window(&self, label: &str) -> Option<WebviewWindow<R>> {
self.manager().get_webview(label).and_then(|webview| {
let window = webview.window();
if window.is_webview_window() {
Some(WebviewWindow { window, webview })
} else {
None
}
})
}
/// Fetch all managed webview windows.
fn webview_windows(&self) -> HashMap<String, WebviewWindow<R>> {
self
.manager()
.webviews()
.into_iter()
.filter_map(|(label, webview)| {
let window = webview.window();
if window.is_webview_window() {
Some((label, WebviewWindow { window, webview }))
} else {
None
}
})
.collect::<HashMap<_, _>>()
}
/// Add `state` to the state managed by the application.
///
/// If the state for the `T` type has previously been set, the state is unchanged and false is returned. Otherwise true is returned.
///
/// Managed state can be retrieved by any command handler via the
/// [`State`] guard. In particular, if a value of type `T`
/// is managed by Tauri, adding `State<T>` to the list of arguments in a
/// command handler instructs Tauri to retrieve the managed value.
/// Additionally, [`state`](Self#method.state) can be used to retrieve the value manually.
///
/// # Mutability
///
/// Since the managed state is global and must be [`Send`] + [`Sync`], mutations can only happen through interior mutability:
///
/// ```rust,no_run
/// use std::{collections::HashMap, sync::Mutex};
/// use tauri::State;
/// // here we use Mutex to achieve interior mutability
/// struct Storage {
/// store: Mutex<HashMap<u64, String>>,
/// }
/// struct Connection;
/// struct DbConnection {
/// db: Mutex<Option<Connection>>,
/// }
///
/// #[tauri::command]
/// fn connect(connection: State<DbConnection>) {
/// // initialize the connection, mutating the state with interior mutability
/// *connection.db.lock().unwrap() = Some(Connection {});
/// }
///
/// #[tauri::command]
/// fn storage_insert(key: u64, value: String, storage: State<Storage>) {
/// // mutate the storage behind the Mutex
/// storage.store.lock().unwrap().insert(key, value);
/// }
///
/// tauri::Builder::default()
/// .manage(Storage { store: Default::default() })
/// .manage(DbConnection { db: Default::default() })
/// .invoke_handler(tauri::generate_handler![connect, storage_insert])
/// // on an actual app, remove the string argument
/// .run(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
/// .expect("error while running tauri application");
/// ```
///
/// # Examples
///
/// ```rust,no_run
/// use tauri::{Manager, State};
///
/// struct MyInt(isize);
/// struct MyString(String);
///
/// #[tauri::command]
/// fn int_command(state: State<MyInt>) -> String {
/// format!("The stateful int is: {}", state.0)
/// }
///
/// #[tauri::command]
/// fn string_command<'r>(state: State<'r, MyString>) {
/// println!("state: {}", state.inner().0);
/// }
///
/// tauri::Builder::default()
/// .setup(|app| {
/// app.manage(MyInt(0));
/// app.manage(MyString("tauri".into()));
/// // `MyInt` is already managed, so `manage()` returns false
/// assert!(!app.manage(MyInt(1)));
/// // read the `MyInt` managed state with the turbofish syntax
/// let int = app.state::<MyInt>();
/// assert_eq!(int.0, 0);
/// // read the `MyString` managed state with the `State` guard
/// let val: State<MyString> = app.state();
/// assert_eq!(val.0, "tauri");
/// Ok(())
/// })
/// .invoke_handler(tauri::generate_handler![int_command, string_command])
/// // on an actual app, remove the string argument
/// .run(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
/// .expect("error while running tauri application");
/// ```
fn manage<T>(&self, state: T) -> bool
where
T: Send + Sync + 'static,
{
self.manager().state().set(state)
}
/// Removes the state managed by the application for T. Returns the state if it was actually removed.
///
/// <div class="warning">
///
/// This method is *UNSAFE* and calling it will cause previously obtained references through
/// [Manager::state] and [State::inner] to become dangling references.
///
/// It is currently deprecated and may be removed in the future.
///
/// If you really want to unmanage a state, use [std::sync::Mutex] and [Option::take] to wrap the state instead.
///
/// See [tauri-apps/tauri#12721] for more information.
///
/// [tauri-apps/tauri#12721]: https://github.com/tauri-apps/tauri/issues/12721
///
/// </div>
#[deprecated(
since = "2.3.0",
note = "This method is unsafe, since it can cause dangling references."
)]
fn unmanage<T>(&self) -> Option<T>
where
T: Send + Sync + 'static,
{
// The caller decides to break the safety here, then OK, just let it go.
unsafe { self.manager().state().unmanage() }
}
/// Retrieves the managed state for the type `T`.
///
/// # Panics
///
/// Panics if the state for the type `T` has not been previously [managed](Self::manage).
/// Use [try_state](Self::try_state) for a non-panicking version.
fn state<T>(&self) -> State<'_, T>
where
T: Send + Sync + 'static,
{
self.manager().state.try_get().unwrap_or_else(|| {
panic!(
"state() called before manage() for {}",
std::any::type_name::<T>()
)
})
}
/// Attempts to retrieve the managed state for the type `T`.
///
/// Returns `Some` if the state has previously been [managed](Self::manage). Otherwise returns `None`.
fn try_state<T>(&self) -> Option<State<'_, T>>
where
T: Send + Sync + 'static,
{
self.manager().state.try_get()
}
/// Get a reference to the resources table of this manager.
fn resources_table(&self) -> MutexGuard<'_, ResourceTable>;
/// Gets the managed [`Env`].
fn env(&self) -> Env {
self.state::<Env>().inner().clone()
}
/// Gets the scope for the asset protocol.
#[cfg(feature = "protocol-asset")]
fn asset_protocol_scope(&self) -> scope::fs::Scope {
self.state::<Scopes>().inner().asset_protocol.clone()
}
/// The path resolver.
fn path(&self) -> &crate::path::PathResolver<R> {
self.state::<crate::path::PathResolver<R>>().inner()
}
/// Adds a capability to the app.
///
/// Note that by default every capability file in the `src-tauri/capabilities` folder
/// are automatically enabled unless specific capabilities are configured in [`tauri.conf.json > app > security > capabilities`],
/// so you should use a different director for the runtime-added capabilities or use [tauri_build::Attributes::capabilities_path_pattern].
///
/// # Examples
/// ```
/// use tauri::Manager;
///
/// tauri::Builder::default()
/// .setup(|app| {
/// #[cfg(feature = "beta")]
/// app.add_capability(include_str!("../capabilities/beta/cap.json"));
///
/// #[cfg(feature = "stable")]
/// app.add_capability(include_str!("../capabilities/stable/cap.json"));
/// Ok(())
/// });
/// ```
///
/// The above example assumes the following directory layout:
/// ```md
/// ├── capabilities
/// │ ├── app (default capabilities used by any app flavor)
/// | | |-- cap.json
/// │ ├── beta (capabilities only added to a `beta` flavor)
/// | | |-- cap.json
/// │ ├── stable (capabilities only added to a `stable` flavor)
/// | |-- cap.json
/// ```
///
/// For this layout to be properly parsed by Tauri, we need to change the build script to
///
/// ```skip
/// // only pick up capabilities in the capabilities/app folder by default
/// let attributes = tauri_build::Attributes::new().capabilities_path_pattern("./capabilities/app/*.json");
/// tauri_build::try_build(attributes).unwrap();
/// ```
///
/// [`tauri.conf.json > app > security > capabilities`]: https://tauri.app/reference/config/#capabilities
/// [tauri_build::Attributes::capabilities_path_pattern]: https://docs.rs/tauri-build/2/tauri_build/struct.Attributes.html#method.capabilities_path_pattern
#[cfg(feature = "dynamic-acl")]
fn add_capability(&self, capability: impl RuntimeCapability) -> Result<()> {
self
.manager()
.runtime_authority
.lock()
.unwrap()
.add_capability(capability)
}
}
/// Listen to events.
pub trait Listener<R: Runtime>: sealed::ManagerBase<R> {
/// Listen to an emitted event on this manager.
///
/// # Examples
/// ```
/// use tauri::{Manager, Listener, Emitter};
///
/// #[tauri::command]
/// fn synchronize(window: tauri::Window) {
/// // emits the synchronized event to all windows
/// window.emit("synchronized", ());
/// }
///
/// tauri::Builder::default()
/// .setup(|app| {
/// app.listen("synchronized", |event| {
/// println!("app is in sync");
/// });
/// Ok(())
/// })
/// .invoke_handler(tauri::generate_handler![synchronize]);
/// ```
/// # Panics
/// Will panic if `event` contains characters other than alphanumeric, `-`, `/`, `:` and `_`
fn listen<F>(&self, event: impl Into<String>, handler: F) -> EventId
where
F: Fn(Event) + Send + 'static;
/// Listen to an event on this manager only once.
///
/// See [`Self::listen`] for more information.
/// # Panics
/// Will panic if `event` contains characters other than alphanumeric, `-`, `/`, `:` and `_`
fn once<F>(&self, event: impl Into<String>, handler: F) -> EventId
where
F: FnOnce(Event) + Send + 'static;
/// Remove an event listener.
///
/// # Examples
/// ```
/// use tauri::{Manager, Listener};
///
/// tauri::Builder::default()
/// .setup(|app| {
/// let handle = app.handle().clone();
/// let handler = app.listen_any("ready", move |event| {
/// println!("app is ready");
///
/// // we no longer need to listen to the event
/// // we also could have used `app.once_global` instead
/// handle.unlisten(event.id());
/// });
///
/// // stop listening to the event when you do not need it anymore
/// app.unlisten(handler);
///
///
/// Ok(())
/// });
/// ```
fn unlisten(&self, id: EventId);
/// Listen to an emitted event to any [target](EventTarget).
///
/// # Examples
/// ```
/// use tauri::{Manager, Emitter, Listener};
///
/// #[tauri::command]
/// fn synchronize(window: tauri::Window) {
/// // emits the synchronized event to all windows
/// window.emit("synchronized", ());
/// }
///
/// tauri::Builder::default()
/// .setup(|app| {
/// app.listen_any("synchronized", |event| {
/// println!("app is in sync");
/// });
/// Ok(())
/// })
/// .invoke_handler(tauri::generate_handler![synchronize]);
/// ```
/// # Panics
/// Will panic if `event` contains characters other than alphanumeric, `-`, `/`, `:` and `_`
fn listen_any<F>(&self, event: impl Into<String>, handler: F) -> EventId
where
F: Fn(Event) + Send + 'static,
{
let event = EventName::new(event.into()).unwrap();
self.manager().listen(event, EventTarget::Any, handler)
}
/// Listens once to an emitted event to any [target](EventTarget) .
///
/// See [`Self::listen_any`] for more information.
/// # Panics
/// Will panic if `event` contains characters other than alphanumeric, `-`, `/`, `:` and `_`
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | true |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/process.rs | crates/tauri/src/process.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Types and functions related to child processes management.
use crate::Env;
use std::path::PathBuf;
/// Finds the current running binary's path.
///
/// With exception to any following platform-specific behavior, the path is cached as soon as
/// possible, and then used repeatedly instead of querying for a new path every time this function
/// is called.
///
/// # Platform-specific behavior
///
/// ## Linux
///
/// On Linux, this function will **attempt** to detect if it's currently running from a
/// valid [AppImage] and use that path instead.
///
/// ## macOS
///
/// On `macOS`, this function will return an error if the original path contained any symlinks
/// due to less protection on macOS regarding symlinks. This behavior can be disabled by setting the
/// `process-relaunch-dangerous-allow-symlink-macos` feature, although it is *highly discouraged*.
///
/// # Security
///
/// See [`tauri_utils::platform::current_exe`] for possible security implications.
///
/// # Examples
///
/// ```rust,no_run
/// use tauri::{process::current_binary, Env, Manager};
/// let current_binary_path = current_binary(&Env::default()).unwrap();
///
/// tauri::Builder::default()
/// .setup(|app| {
/// let current_binary_path = current_binary(&app.env())?;
/// Ok(())
/// });
/// ```
///
/// [AppImage]: https://appimage.org/
pub fn current_binary(_env: &Env) -> std::io::Result<PathBuf> {
// if we are running from an AppImage, we ONLY want the set AppImage path
#[cfg(target_os = "linux")]
if let Some(app_image_path) = &_env.appimage {
return Ok(PathBuf::from(app_image_path));
}
tauri_utils::platform::current_exe()
}
/// Restarts the currently running binary.
///
/// See [`current_binary`] for platform specific behavior, and
/// [`tauri_utils::platform::current_exe`] for possible security implications.
///
/// # Examples
///
/// ```rust,no_run
/// use tauri::{process::restart, Env, Manager};
///
/// tauri::Builder::default()
/// .setup(|app| {
/// restart(&app.env());
/// Ok(())
/// });
/// ```
pub fn restart(env: &Env) -> ! {
use std::process::{exit, Command};
if let Ok(path) = current_binary(env) {
// on macOS on updates the binary name might have changed
// so we'll read the Contents/Info.plist file to determine the binary path
#[cfg(target_os = "macos")]
restart_macos_app(&path, env);
if let Err(e) = Command::new(path).args(env.args_os.iter().skip(1)).spawn() {
log::error!("failed to restart app: {e}");
}
}
exit(0);
}
#[cfg(target_os = "macos")]
fn restart_macos_app(current_binary: &std::path::Path, env: &Env) {
use std::process::{exit, Command};
if let Some(macos_directory) = current_binary.parent() {
if macos_directory.components().next_back()
!= Some(std::path::Component::Normal(std::ffi::OsStr::new("MacOS")))
{
return;
}
if let Some(contents_directory) = macos_directory.parent() {
if contents_directory.components().next_back()
!= Some(std::path::Component::Normal(std::ffi::OsStr::new(
"Contents",
)))
{
return;
}
if let Ok(info_plist) =
plist::from_file::<_, plist::Dictionary>(contents_directory.join("Info.plist"))
{
if let Some(binary_name) = info_plist
.get("CFBundleExecutable")
.and_then(|v| v.as_string())
{
if let Err(e) = Command::new(macos_directory.join(binary_name))
.args(env.args_os.iter().skip(1))
.spawn()
{
log::error!("failed to restart app: {e}");
}
exit(0);
}
}
}
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/pattern.rs | crates/tauri/src/pattern.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
#[cfg(feature = "isolation")]
use std::sync::Arc;
use serde::Serialize;
use serialize_to_javascript::{default_template, Template};
/// The domain of the isolation iframe source.
#[cfg(feature = "isolation")]
pub const ISOLATION_IFRAME_SRC_DOMAIN: &str = "localhost";
/// An application pattern.
#[derive(Debug)]
pub enum Pattern {
/// The brownfield pattern.
Brownfield,
/// Isolation pattern. Recommended for security purposes.
#[cfg(feature = "isolation")]
Isolation {
/// The HTML served on `isolation://index.html`.
assets: Arc<tauri_utils::assets::EmbeddedAssets>,
/// The schema used for the isolation frames.
schema: String,
/// A random string used to ensure that the message went through the isolation frame.
///
/// This should be regenerated at runtime.
key: String,
/// Cryptographically secure keys
crypto_keys: Box<tauri_utils::pattern::isolation::Keys>,
},
}
/// The shape of the JavaScript Pattern config
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase", tag = "pattern")]
pub(crate) enum PatternObject {
/// Brownfield pattern.
Brownfield,
/// Isolation pattern. Recommended for security purposes.
#[cfg(feature = "isolation")]
Isolation {
/// Which `IsolationSide` this `PatternObject` is getting injected into
side: IsolationSide,
},
}
impl From<&Pattern> for PatternObject {
fn from(pattern: &Pattern) -> Self {
match pattern {
Pattern::Brownfield => Self::Brownfield,
#[cfg(feature = "isolation")]
Pattern::Isolation { .. } => Self::Isolation {
side: IsolationSide::default(),
},
}
}
}
/// Where the JavaScript is injected to
#[cfg(feature = "isolation")]
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum IsolationSide {
/// Original frame, the Brownfield application
#[default]
Original,
/// Secure frame, the isolation security application
#[allow(dead_code)]
Secure,
}
#[derive(Template)]
#[default_template("../scripts/pattern.js")]
pub(crate) struct PatternJavascript {
pub(crate) pattern: PatternObject,
}
#[cfg(feature = "isolation")]
pub(crate) fn format_real_schema(schema: &str, https: bool) -> String {
if cfg!(windows) || cfg!(target_os = "android") {
let scheme = if https { "https" } else { "http" };
format!("{scheme}://{schema}.{ISOLATION_IFRAME_SRC_DOMAIN}/")
} else {
format!("{schema}://{ISOLATION_IFRAME_SRC_DOMAIN}/")
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/state.rs | crates/tauri/src/state.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{
any::{Any, TypeId},
collections::HashMap,
hash::BuildHasherDefault,
pin::Pin,
sync::Mutex,
};
use crate::{
ipc::{CommandArg, CommandItem, InvokeError},
Runtime,
};
/// A guard for a state value.
///
/// See [`Manager::manage`](`crate::Manager::manage`) for usage examples.
pub struct State<'r, T: Send + Sync + 'static>(&'r T);
impl<'r, T: Send + Sync + 'static> State<'r, T> {
/// Retrieve a borrow to the underlying value with a lifetime of `'r`.
/// Using this method is typically unnecessary as `State` implements
/// [`std::ops::Deref`] with a [`std::ops::Deref::Target`] of `T`.
#[inline(always)]
pub fn inner(&self) -> &'r T {
self.0
}
}
impl<T: Send + Sync + 'static> std::ops::Deref for State<'_, T> {
type Target = T;
#[inline(always)]
fn deref(&self) -> &T {
self.0
}
}
impl<T: Send + Sync + 'static> Clone for State<'_, T> {
fn clone(&self) -> Self {
State(self.0)
}
}
impl<T: Send + Sync + 'static + PartialEq> PartialEq for State<'_, T> {
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
impl<T: Send + Sync + std::fmt::Debug> std::fmt::Debug for State<'_, T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("State").field(&self.0).finish()
}
}
impl<'r, 'de: 'r, T: Send + Sync + 'static, R: Runtime> CommandArg<'de, R> for State<'r, T> {
/// Grabs the [`State`] from the [`CommandItem`]. This will never fail.
fn from_command(command: CommandItem<'de, R>) -> Result<Self, InvokeError> {
command.message.state_ref().try_get().ok_or_else(|| {
InvokeError::from_anyhow(anyhow::anyhow!(
"state not managed for field `{}` on command `{}`. You must call `.manage()` before using this command",
command.key, command.name
))
})
}
}
// Taken from: https://github.com/SergioBenitez/state/blob/556c1b94db8ce8427a0e72de7983ab5a9af4cc41/src/ident_hash.rs
// This is a _super_ stupid hash. It just uses its input as the hash value. This
// hash is meant to be used _only_ for "prehashed" values. In particular, we use
// this so that hashing a TypeId is essentially a noop. This is because TypeIds
// are already unique integers.
#[derive(Default)]
struct IdentHash(u64);
impl std::hash::Hasher for IdentHash {
fn finish(&self) -> u64 {
self.0
}
fn write(&mut self, bytes: &[u8]) {
for byte in bytes {
self.write_u8(*byte);
}
}
fn write_u8(&mut self, i: u8) {
self.0 = (self.0 << 8) | (i as u64);
}
fn write_u64(&mut self, i: u64) {
self.0 = i;
}
}
/// Safety:
/// - The `key` must equal to `(*value).type_id()`, see the safety doc in methods of [StateManager] for details.
/// - Once you insert a value, you can't remove/mutated/move it anymore, see [StateManager::try_get] for details.
type TypeIdMap = HashMap<TypeId, Pin<Box<dyn Any + Sync + Send>>, BuildHasherDefault<IdentHash>>;
/// The Tauri state manager.
#[derive(Debug)]
pub struct StateManager {
map: Mutex<TypeIdMap>,
}
impl StateManager {
pub(crate) fn new() -> Self {
Self {
map: Default::default(),
}
}
pub(crate) fn set<T: Send + Sync + 'static>(&self, state: T) -> bool {
let mut map = self.map.lock().unwrap();
let type_id = TypeId::of::<T>();
let already_set = map.contains_key(&type_id);
if !already_set {
let ptr = Box::new(state) as Box<dyn Any + Sync + Send>;
let pinned_ptr = Box::into_pin(ptr);
map.insert(
type_id,
// SAFETY: keep the type of the key is the same as the type of the value,
// see [try_get] methods for details.
pinned_ptr,
);
}
!already_set
}
/// SAFETY: Calling this method will move the `value`,
/// which will cause references obtained through [Self::try_get] to dangle.
pub(crate) unsafe fn unmanage<T: Send + Sync + 'static>(&self) -> Option<T> {
let mut map = self.map.lock().unwrap();
let type_id = TypeId::of::<T>();
let pinned_ptr = map.remove(&type_id)?;
// SAFETY: The caller decides to break the immovability/safety here, then OK, just let it go.
let ptr = unsafe { Pin::into_inner_unchecked(pinned_ptr) };
let value = unsafe {
ptr
.downcast::<T>()
// SAFETY: the type of the key is the same as the type of the value
.unwrap_unchecked()
};
Some(*value)
}
/// Gets the state associated with the specified type.
pub fn get<T: Send + Sync + 'static>(&self) -> State<'_, T> {
self
.try_get()
.unwrap_or_else(|| panic!("state not found for type {}", std::any::type_name::<T>()))
}
/// Gets the state associated with the specified type.
pub fn try_get<T: Send + Sync + 'static>(&self) -> Option<State<'_, T>> {
let map = self.map.lock().unwrap();
let type_id = TypeId::of::<T>();
let ptr = map.get(&type_id)?;
let value = unsafe {
ptr
.downcast_ref::<T>()
// SAFETY: the type of the key is the same as the type of the value
.unwrap_unchecked()
};
// SAFETY: We ensure the lifetime of `value` is the same as [StateManager] and `value` will not be mutated/moved.
let v_ref = unsafe { &*(value as *const T) };
Some(State(v_ref))
}
}
// Ported from https://github.com/SergioBenitez/state/blob/556c1b94db8ce8427a0e72de7983ab5a9af4cc41/tests/main.rs
#[cfg(test)]
mod tests {
use super::StateManager;
use std::sync::{Arc, RwLock};
use std::thread;
// Tiny structures to test that dropping works as expected.
struct DroppingStruct(Arc<RwLock<bool>>);
struct DroppingStructWrap(#[allow(dead_code)] DroppingStruct);
impl Drop for DroppingStruct {
fn drop(&mut self) {
*self.0.write().unwrap() = true;
}
}
#[test]
#[should_panic(expected = "state not found for type core::option::Option<alloc::string::String>")]
fn get_panics() {
let state = StateManager::new();
state.get::<Option<String>>();
}
#[test]
fn simple_set_get() {
let state = StateManager::new();
assert!(state.set(1u32));
assert_eq!(*state.get::<u32>(), 1);
}
#[test]
fn simple_set_get_unmanage() {
let state = StateManager::new();
assert!(state.set(1u32));
assert_eq!(*state.get::<u32>(), 1);
// safety: the reference returned by `try_get` is already dropped.
assert!(unsafe { state.unmanage::<u32>() }.is_some());
assert!(unsafe { state.unmanage::<u32>() }.is_none());
assert_eq!(state.try_get::<u32>(), None);
assert!(state.set(2u32));
assert_eq!(*state.get::<u32>(), 2);
}
#[test]
fn dst_set_get() {
let state = StateManager::new();
assert!(state.set::<[u32; 4]>([1, 2, 3, 4u32]));
assert_eq!(*state.get::<[u32; 4]>(), [1, 2, 3, 4]);
}
#[test]
fn set_get_remote() {
let state = Arc::new(StateManager::new());
let sate_ = Arc::clone(&state);
thread::spawn(move || {
sate_.set(10isize);
})
.join()
.unwrap();
assert_eq!(*state.get::<isize>(), 10);
}
#[test]
fn two_put_get() {
let state = StateManager::new();
assert!(state.set("Hello, world!".to_string()));
let s_old = state.get::<String>();
assert_eq!(*s_old, "Hello, world!");
assert!(!state.set::<String>("Bye bye!".into()));
assert_eq!(*state.get::<String>(), "Hello, world!");
assert_eq!(state.get::<String>(), s_old);
}
#[test]
fn many_puts_only_one_succeeds() {
let state = Arc::new(StateManager::new());
let mut threads = vec![];
for _ in 0..1000 {
let state_ = Arc::clone(&state);
threads.push(thread::spawn(move || state_.set(10i64)))
}
let results: Vec<bool> = threads.into_iter().map(|t| t.join().unwrap()).collect();
assert_eq!(results.into_iter().filter(|&b| b).count(), 1);
assert_eq!(*state.get::<i64>(), 10);
}
// Ensure setting when already set doesn't cause a drop.
#[test]
fn test_no_drop_on_set() {
let state = StateManager::new();
let drop_flag = Arc::new(RwLock::new(false));
let dropping_struct = DroppingStruct(drop_flag.clone());
let _drop_flag_ignore = Arc::new(RwLock::new(false));
let _dropping_struct_ignore = DroppingStruct(_drop_flag_ignore);
state.set::<DroppingStruct>(dropping_struct);
assert!(!state.set::<DroppingStruct>(_dropping_struct_ignore));
assert!(!*drop_flag.read().unwrap());
}
// Ensure dropping a type_map drops its contents.
#[test]
fn drop_inners_on_drop() {
let drop_flag_a = Arc::new(RwLock::new(false));
let dropping_struct_a = DroppingStruct(drop_flag_a.clone());
let drop_flag_b = Arc::new(RwLock::new(false));
let dropping_struct_b = DroppingStructWrap(DroppingStruct(drop_flag_b.clone()));
{
let state = StateManager::new();
state.set(dropping_struct_a);
assert!(!*drop_flag_a.read().unwrap());
state.set(dropping_struct_b);
assert!(!*drop_flag_a.read().unwrap());
assert!(!*drop_flag_b.read().unwrap());
}
assert!(*drop_flag_a.read().unwrap());
assert!(*drop_flag_b.read().unwrap());
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/error.rs | crates/tauri/src/error.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::fmt;
/// A generic boxed error.
#[derive(Debug)]
pub struct SetupError(Box<dyn std::error::Error>);
impl From<Box<dyn std::error::Error>> for SetupError {
fn from(error: Box<dyn std::error::Error>) -> Self {
Self(error)
}
}
// safety: the setup error is only used on the main thread
// and we exit the process immediately.
unsafe impl Send for SetupError {}
unsafe impl Sync for SetupError {}
impl fmt::Display for SetupError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl std::error::Error for SetupError {}
/// Runtime errors that can happen inside a Tauri application.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
/// Runtime error.
#[error("runtime error: {0}")]
Runtime(#[from] tauri_runtime::Error),
/// Window label must be unique.
#[error("a window with label `{0}` already exists")]
WindowLabelAlreadyExists(String),
/// Webview label must be unique.
#[error("a webview with label `{0}` already exists")]
WebviewLabelAlreadyExists(String),
/// Cannot use the webview reparent function on webview windows.
#[error("cannot reparent when using a WebviewWindow")]
CannotReparentWebviewWindow,
/// Embedded asset not found.
#[error("asset not found: {0}")]
AssetNotFound(String),
/// Failed to serialize/deserialize.
#[error("JSON error: {0}")]
Json(#[from] serde_json::Error),
/// IO error.
#[error("{0}")]
Io(#[from] std::io::Error),
/// Failed to load window icon.
#[error("invalid icon: {0}")]
InvalidIcon(std::io::Error),
/// Invalid args when running a command.
#[error("invalid args `{1}` for command `{0}`: {2}")]
InvalidArgs(&'static str, &'static str, serde_json::Error),
/// Encountered an error in the setup hook,
#[error("error encountered during setup hook: {0}")]
Setup(SetupError),
/// Error initializing plugin.
#[error("failed to initialize plugin `{0}`: {1}")]
PluginInitialization(String, String),
/// A part of the URL is malformed or invalid. This may occur when parsing and combining
/// user-provided URLs and paths.
#[error("invalid url: {0}")]
InvalidUrl(url::ParseError),
/// Task join error.
#[error(transparent)]
JoinError(#[from] tokio::task::JoinError),
/// An error happened inside the isolation pattern.
#[cfg(feature = "isolation")]
#[error("isolation pattern error: {0}")]
IsolationPattern(#[from] tauri_utils::pattern::isolation::Error),
/// An invalid window URL was provided. Includes details about the error.
#[error("invalid window url: {0}")]
InvalidWebviewUrl(&'static str),
/// Invalid glob pattern.
#[error("invalid glob pattern: {0}")]
GlobPattern(#[from] glob::PatternError),
/// Image error.
#[cfg(any(feature = "image-png", feature = "image-ico"))]
#[error("failed to process image: {0}")]
Image(#[from] image::error::ImageError),
/// The Window's raw handle is invalid for the platform.
#[error("Unexpected `raw_window_handle` for the current platform")]
InvalidWindowHandle,
/// JNI error.
#[cfg(target_os = "android")]
#[error("jni error: {0}")]
Jni(#[from] jni::errors::Error),
/// Failed to receive message .
#[error("failed to receive message")]
FailedToReceiveMessage,
/// Menu error.
#[error("menu error: {0}")]
#[cfg(desktop)]
Menu(#[from] muda::Error),
/// Bad menu icon error.
#[error(transparent)]
#[cfg(desktop)]
BadMenuIcon(#[from] muda::BadIcon),
/// Tray icon error.
#[error("tray icon error: {0}")]
#[cfg(all(desktop, feature = "tray-icon"))]
#[cfg_attr(docsrs, doc(cfg(all(desktop, feature = "tray-icon"))))]
Tray(#[from] tray_icon::Error),
/// Bad tray icon error.
#[error(transparent)]
#[cfg(all(desktop, feature = "tray-icon"))]
#[cfg_attr(docsrs, doc(cfg(all(desktop, feature = "tray-icon"))))]
BadTrayIcon(#[from] tray_icon::BadIcon),
/// Path does not have a parent.
#[error("path does not have a parent")]
NoParent,
/// Path does not have an extension.
#[error("path does not have an extension")]
NoExtension,
/// Path does not have a basename.
#[error("path does not have a basename")]
NoBasename,
/// Cannot resolve current directory.
#[error("failed to read current dir: {0}")]
CurrentDir(std::io::Error),
/// Unknown path.
#[cfg(not(target_os = "android"))]
#[error("unknown path")]
UnknownPath,
/// Failed to invoke mobile plugin.
#[cfg(target_os = "android")]
#[error(transparent)]
PluginInvoke(#[from] crate::plugin::mobile::PluginInvokeError),
/// window not found.
#[error("window not found")]
WindowNotFound,
/// The resource id is invalid.
#[error("The resource id {0} is invalid.")]
BadResourceId(crate::resources::ResourceId),
/// The anyhow crate error.
#[error(transparent)]
Anyhow(#[from] anyhow::Error),
/// webview not found.
#[error("webview not found")]
WebviewNotFound,
/// API requires the unstable feature flag.
#[error("this feature requires the `unstable` flag on Cargo.toml")]
UnstableFeatureNotSupported,
/// Failed to deserialize scope object.
#[error("error deserializing scope: {0}")]
CannotDeserializeScope(Box<dyn std::error::Error + Send + Sync>),
/// Failed to get a raw handle.
#[error(transparent)]
RawHandleError(#[from] raw_window_handle::HandleError),
/// Something went wrong with the CSPRNG.
#[error("unable to generate random bytes from the operating system: {0}")]
Csprng(getrandom::Error),
/// Bad `__TAURI_INVOKE_KEY__` value received in ipc message.
#[error("bad __TAURI_INVOKE_KEY__ value received in ipc message")]
InvokeKey,
/// Illegal event name.
#[error("only alphanumeric, '-', '/', ':', '_' permitted for event names: {0:?}")]
IllegalEventName(String),
/// tokio oneshot channel failed to receive message
#[error(transparent)]
TokioOneshotRecv(#[from] tokio::sync::oneshot::error::RecvError),
}
impl From<getrandom::Error> for Error {
fn from(value: getrandom::Error) -> Self {
Self::Csprng(value)
}
}
/// `Result<T, ::tauri::Error>`
pub type Result<T> = std::result::Result<T, Error>;
#[cfg(test)]
mod tests {
#[test]
fn error_is_send_sync() {
crate::test_utils::assert_send::<super::Error>();
crate::test_utils::assert_sync::<super::Error>();
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/async_runtime.rs | crates/tauri/src/async_runtime.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! 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`] directly.
//! For custom command handlers, it's recommended to use a plain `async fn` command.
pub use tokio::{
runtime::{Handle as TokioHandle, Runtime as TokioRuntime},
sync::{
mpsc::{channel, Receiver, Sender},
Mutex, RwLock,
},
task::JoinHandle as TokioJoinHandle,
};
use std::{
future::Future,
pin::Pin,
sync::OnceLock,
task::{Context, Poll},
};
static RUNTIME: OnceLock<GlobalRuntime> = OnceLock::new();
struct GlobalRuntime {
runtime: Option<Runtime>,
handle: RuntimeHandle,
}
impl GlobalRuntime {
fn handle(&self) -> RuntimeHandle {
if let Some(r) = &self.runtime {
r.handle()
} else {
self.handle.clone()
}
}
fn spawn<F>(&self, task: F) -> JoinHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
if let Some(r) = &self.runtime {
r.spawn(task)
} else {
self.handle.spawn(task)
}
}
pub fn spawn_blocking<F, R>(&self, func: F) -> JoinHandle<R>
where
F: FnOnce() -> R + Send + 'static,
R: Send + 'static,
{
if let Some(r) = &self.runtime {
r.spawn_blocking(func)
} else {
self.handle.spawn_blocking(func)
}
}
fn block_on<F: Future>(&self, task: F) -> F::Output {
if let Some(r) = &self.runtime {
r.block_on(task)
} else {
self.handle.block_on(task)
}
}
}
/// A runtime used to execute asynchronous tasks.
pub enum Runtime {
/// The tokio runtime.
Tokio(TokioRuntime),
}
impl Runtime {
/// Gets a reference to the [`TokioRuntime`].
pub fn inner(&self) -> &TokioRuntime {
let Self::Tokio(r) = self;
r
}
/// Returns a handle of the async runtime.
pub fn handle(&self) -> RuntimeHandle {
match self {
Self::Tokio(r) => RuntimeHandle::Tokio(r.handle().clone()),
}
}
/// Spawns a future onto the runtime.
pub fn spawn<F>(&self, task: F) -> JoinHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
match self {
Self::Tokio(r) => {
let _guard = r.enter();
JoinHandle::Tokio(tokio::spawn(task))
}
}
}
/// Runs the provided function on an executor dedicated to blocking operations.
pub fn spawn_blocking<F, R>(&self, func: F) -> JoinHandle<R>
where
F: FnOnce() -> R + Send + 'static,
R: Send + 'static,
{
match self {
Self::Tokio(r) => JoinHandle::Tokio(r.spawn_blocking(func)),
}
}
/// Runs a future to completion on runtime.
pub fn block_on<F: Future>(&self, task: F) -> F::Output {
match self {
Self::Tokio(r) => r.block_on(task),
}
}
}
/// An owned permission to join on a task (await its termination).
#[derive(Debug)]
pub enum JoinHandle<T> {
/// The tokio JoinHandle.
Tokio(TokioJoinHandle<T>),
}
impl<T> JoinHandle<T> {
/// Gets a reference to the [`TokioJoinHandle`].
pub fn inner(&self) -> &TokioJoinHandle<T> {
let Self::Tokio(t) = self;
t
}
/// Abort the task associated with the handle.
///
/// Awaiting a cancelled task might complete as usual if the task was
/// already completed at the time it was cancelled, but most likely it
/// will fail with a cancelled `JoinError`.
pub fn abort(&self) {
match self {
Self::Tokio(t) => t.abort(),
}
}
}
impl<T> Future for JoinHandle<T> {
type Output = crate::Result<T>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match self.get_mut() {
Self::Tokio(t) => Pin::new(t).poll(cx).map_err(Into::into),
}
}
}
/// A handle to the async runtime
#[derive(Clone)]
pub enum RuntimeHandle {
/// The tokio handle.
Tokio(TokioHandle),
}
impl RuntimeHandle {
/// Gets a reference to the [`TokioHandle`].
pub fn inner(&self) -> &TokioHandle {
let Self::Tokio(h) = self;
h
}
/// Runs the provided function on an executor dedicated to blocking operations.
pub fn spawn_blocking<F, R>(&self, func: F) -> JoinHandle<R>
where
F: FnOnce() -> R + Send + 'static,
R: Send + 'static,
{
match self {
Self::Tokio(h) => JoinHandle::Tokio(h.spawn_blocking(func)),
}
}
/// Spawns a future onto the runtime.
pub fn spawn<F>(&self, task: F) -> JoinHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
match self {
Self::Tokio(h) => {
let _guard = h.enter();
JoinHandle::Tokio(tokio::spawn(task))
}
}
}
/// Runs a future to completion on runtime.
pub fn block_on<F: Future>(&self, task: F) -> F::Output {
match self {
Self::Tokio(h) => h.block_on(task),
}
}
}
fn default_runtime() -> GlobalRuntime {
let runtime = Runtime::Tokio(TokioRuntime::new().unwrap());
let handle = runtime.handle();
GlobalRuntime {
runtime: Some(runtime),
handle,
}
}
/// Sets the runtime to use to execute asynchronous tasks.
/// For convenience, this method takes a [`TokioHandle`].
/// Note that you cannot drop the underlying [`TokioRuntime`].
///
/// # Examples
///
/// ```rust
/// #[tokio::main]
/// async fn main() {
/// // perform some async task before initializing the app
/// do_something().await;
/// // share the current runtime with Tauri
/// tauri::async_runtime::set(tokio::runtime::Handle::current());
///
/// // bootstrap the tauri app...
/// // tauri::Builder::default().run().unwrap();
/// }
///
/// async fn do_something() {}
/// ```
///
/// # Panics
///
/// Panics if the runtime is already set.
pub fn set(handle: TokioHandle) {
RUNTIME
.set(GlobalRuntime {
runtime: None,
handle: RuntimeHandle::Tokio(handle),
})
.unwrap_or_else(|_| panic!("runtime already initialized"))
}
/// Returns a handle of the async runtime.
pub fn handle() -> RuntimeHandle {
let runtime = RUNTIME.get_or_init(default_runtime);
runtime.handle()
}
/// Runs a future to completion on runtime.
pub fn block_on<F: Future>(task: F) -> F::Output {
let runtime = RUNTIME.get_or_init(default_runtime);
runtime.block_on(task)
}
/// Spawns a future onto the runtime.
pub fn spawn<F>(task: F) -> JoinHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
let runtime = RUNTIME.get_or_init(default_runtime);
runtime.spawn(task)
}
/// Runs the provided function on an executor dedicated to blocking operations.
pub fn spawn_blocking<F, R>(func: F) -> JoinHandle<R>
where
F: FnOnce() -> R + Send + 'static,
R: Send + 'static,
{
let runtime = RUNTIME.get_or_init(default_runtime);
runtime.spawn_blocking(func)
}
#[allow(dead_code)]
pub(crate) fn safe_block_on<F>(task: F) -> F::Output
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
if let Ok(handle) = tokio::runtime::Handle::try_current() {
let (tx, rx) = std::sync::mpsc::sync_channel(1);
let handle_ = handle.clone();
handle.spawn_blocking(move || {
tx.send(handle_.block_on(task)).unwrap();
});
rx.recv().unwrap()
} else {
block_on(task)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn runtime_spawn() {
let join = spawn(async { 5 });
assert_eq!(join.await.unwrap(), 5);
}
#[test]
fn runtime_block_on() {
assert_eq!(block_on(async { 0 }), 0);
}
#[tokio::test]
async fn handle_spawn() {
let handle = handle();
let join = handle.spawn(async { 5 });
assert_eq!(join.await.unwrap(), 5);
}
#[test]
fn handle_block_on() {
let handle = handle();
assert_eq!(handle.block_on(async { 0 }), 0);
}
#[tokio::test]
async fn handle_abort() {
let handle = handle();
let join = handle.spawn(async {
// Here we sleep 1 second to ensure this task to be uncompleted when abort() invoked.
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
5
});
join.abort();
if let crate::Error::JoinError(raw_error) = join.await.unwrap_err() {
assert!(raw_error.is_cancelled());
} else {
panic!("Abort did not result in the expected `JoinError`");
}
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/plugin.rs | crates/tauri/src/plugin.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! The Tauri plugin extension to expand Tauri functionality.
use crate::{
app::UriSchemeResponder,
ipc::{Invoke, InvokeHandler, ScopeObject, ScopeValue},
manager::webview::UriSchemeProtocol,
utils::config::PluginConfig,
webview::PageLoadPayload,
AppHandle, Error, RunEvent, Runtime, UriSchemeContext, Webview, Window,
};
use serde::{
de::{Deserialize, DeserializeOwned, Deserializer, Error as DeError},
Serialize, Serializer,
};
use serde_json::Value as JsonValue;
use tauri_macros::default_runtime;
use tauri_runtime::webview::InitializationScript;
use thiserror::Error;
use url::Url;
use std::{
borrow::Cow,
collections::HashMap,
fmt::{self, Debug},
sync::Arc,
};
/// Mobile APIs.
#[cfg(mobile)]
pub mod mobile;
/// The plugin interface.
pub trait Plugin<R: Runtime>: Send {
/// The plugin name. Used as key on the plugin config object.
fn name(&self) -> &'static str;
/// Initializes the plugin.
#[allow(unused_variables)]
fn initialize(
&mut self,
app: &AppHandle<R>,
config: JsonValue,
) -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
/// Add the provided JavaScript to a list of scripts that should be run after the global object has been created,
/// but before the HTML document has been parsed and before any other script included by the HTML document is run.
///
/// The script is wrapped into its own context with `(function () { /* your script here */ })();`,
/// so global variables must be assigned to `window` instead of implicitly declared.
///
/// This is executed only on the main frame.
/// If you only want to run it in all frames, use [`Plugin::initialization_script_2`] to set that to false.
///
/// ## Platform-specific
///
/// - **Windows:** scripts are always added to subframes.
/// - **Android:** When [addDocumentStartJavaScript] is not supported,
/// we prepend initialization scripts to each HTML head (implementation only supported on custom protocol URLs).
/// For remote URLs, we use [onPageStarted] which is not guaranteed to run before other scripts.
///
/// [addDocumentStartJavaScript]: https://developer.android.com/reference/androidx/webkit/WebViewCompat#addDocumentStartJavaScript(android.webkit.WebView,java.lang.String,java.util.Set%3Cjava.lang.String%3E)
/// [onPageStarted]: https://developer.android.com/reference/android/webkit/WebViewClient#onPageStarted(android.webkit.WebView,%20java.lang.String,%20android.graphics.Bitmap)
fn initialization_script(&self) -> Option<String> {
None
}
// TODO: Change `initialization_script` to this in v3
/// Same as [`Plugin::initialization_script`] but returns an [`InitializationScript`] instead
/// We plan to replace [`Plugin::initialization_script`] with this signature in v3
fn initialization_script_2(&self) -> Option<InitializationScript> {
self
.initialization_script()
.map(|script| InitializationScript {
script,
for_main_frame_only: true,
})
}
/// Callback invoked when the window is created.
#[allow(unused_variables)]
fn window_created(&mut self, window: Window<R>) {}
/// Callback invoked when the webview is created.
#[allow(unused_variables)]
fn webview_created(&mut self, webview: Webview<R>) {}
/// Callback invoked when webview tries to navigate to the given Url. Returning false cancels navigation.
#[allow(unused_variables)]
fn on_navigation(&mut self, webview: &Webview<R>, url: &Url) -> bool {
true
}
/// Callback invoked when the webview performs a navigation to a page.
#[allow(unused_variables)]
fn on_page_load(&mut self, webview: &Webview<R>, payload: &PageLoadPayload<'_>) {}
/// Callback invoked when the event loop receives a new event.
#[allow(unused_variables)]
fn on_event(&mut self, app: &AppHandle<R>, event: &RunEvent) {}
/// Extend commands to [`crate::Builder::invoke_handler`].
#[allow(unused_variables)]
fn extend_api(&mut self, invoke: Invoke<R>) -> bool {
false
}
}
type SetupHook<R, C> =
dyn FnOnce(&AppHandle<R>, PluginApi<R, C>) -> Result<(), Box<dyn std::error::Error>> + Send;
type OnWindowReady<R> = dyn FnMut(Window<R>) + Send;
type OnWebviewReady<R> = dyn FnMut(Webview<R>) + Send;
type OnEvent<R> = dyn FnMut(&AppHandle<R>, &RunEvent) + Send;
type OnNavigation<R> = dyn Fn(&Webview<R>, &Url) -> bool + Send;
type OnPageLoad<R> = dyn FnMut(&Webview<R>, &PageLoadPayload<'_>) + Send;
type OnDrop<R> = dyn FnOnce(AppHandle<R>) + Send;
/// A handle to a plugin.
#[derive(Debug)]
#[allow(dead_code)]
pub struct PluginHandle<R: Runtime> {
name: &'static str,
handle: AppHandle<R>,
}
impl<R: Runtime> Clone for PluginHandle<R> {
fn clone(&self) -> Self {
Self {
name: self.name,
handle: self.handle.clone(),
}
}
}
impl<R: Runtime> PluginHandle<R> {
/// Returns the application handle.
pub fn app(&self) -> &AppHandle<R> {
&self.handle
}
}
/// Api exposed to the plugin setup hook.
#[derive(Clone)]
#[allow(dead_code)]
pub struct PluginApi<R: Runtime, C: DeserializeOwned> {
handle: AppHandle<R>,
name: &'static str,
raw_config: Arc<JsonValue>,
config: C,
}
impl<R: Runtime, C: DeserializeOwned> PluginApi<R, C> {
/// Returns the plugin configuration.
pub fn config(&self) -> &C {
&self.config
}
/// Returns the application handle.
pub fn app(&self) -> &AppHandle<R> {
&self.handle
}
/// Gets the global scope defined on the permissions that are part of the app ACL.
pub fn scope<T: ScopeObject>(&self) -> crate::Result<ScopeValue<T>> {
self
.handle
.manager
.runtime_authority
.lock()
.unwrap()
.scope_manager
.get_global_scope_typed(&self.handle, self.name)
}
}
/// Errors that can happen during [`Builder`].
#[derive(Debug, Clone, Hash, PartialEq, Error)]
#[non_exhaustive]
pub enum BuilderError {
/// Plugin attempted to use a reserved name.
#[error("plugin uses reserved name: {0}")]
ReservedName(String),
}
const RESERVED_PLUGIN_NAMES: &[&str] = &["core", "tauri"];
/// Builds a [`TauriPlugin`].
///
/// This Builder offers a more concise way to construct Tauri plugins than implementing the Plugin trait directly.
///
/// # Conventions
///
/// When using the Builder Pattern it is encouraged to export a function called `init` that constructs and returns the plugin.
/// While plugin authors can provide every possible way to construct a plugin,
/// sticking to the `init` function convention helps users to quickly identify the correct function to call.
///
/// ```rust
/// use tauri::{plugin::{Builder, TauriPlugin}, Runtime};
///
/// pub fn init<R: Runtime>() -> TauriPlugin<R> {
/// Builder::new("example")
/// .build()
/// }
/// ```
///
/// When plugins expose more complex configuration options, it can be helpful to provide a Builder instead:
///
/// ```rust
/// use tauri::{plugin::{Builder as PluginBuilder, TauriPlugin}, Runtime};
///
/// pub struct Builder {
/// option_a: String,
/// option_b: String,
/// option_c: bool
/// }
///
/// impl Default for Builder {
/// fn default() -> Self {
/// Self {
/// option_a: "foo".to_string(),
/// option_b: "bar".to_string(),
/// option_c: false
/// }
/// }
/// }
///
/// impl Builder {
/// pub fn new() -> Self {
/// Default::default()
/// }
///
/// pub fn option_a(mut self, option_a: String) -> Self {
/// self.option_a = option_a;
/// self
/// }
///
/// pub fn option_b(mut self, option_b: String) -> Self {
/// self.option_b = option_b;
/// self
/// }
///
/// pub fn option_c(mut self, option_c: bool) -> Self {
/// self.option_c = option_c;
/// self
/// }
///
/// pub fn build<R: Runtime>(self) -> TauriPlugin<R> {
/// PluginBuilder::new("example")
/// .setup(move |app_handle, api| {
/// // use the options here to do stuff
/// println!("a: {}, b: {}, c: {}", self.option_a, self.option_b, self.option_c);
///
/// Ok(())
/// })
/// .build()
/// }
/// }
/// ```
pub struct Builder<R: Runtime, C: DeserializeOwned = ()> {
name: &'static str,
invoke_handler: Box<InvokeHandler<R>>,
setup: Option<Box<SetupHook<R, C>>>,
js_init_script: Option<InitializationScript>,
on_navigation: Box<OnNavigation<R>>,
on_page_load: Box<OnPageLoad<R>>,
on_window_ready: Box<OnWindowReady<R>>,
on_webview_ready: Box<OnWebviewReady<R>>,
on_event: Box<OnEvent<R>>,
on_drop: Option<Box<OnDrop<R>>>,
uri_scheme_protocols: HashMap<String, Arc<UriSchemeProtocol<R>>>,
}
impl<R: Runtime, C: DeserializeOwned> Builder<R, C> {
/// Creates a new Plugin builder.
pub fn new(name: &'static str) -> Self {
Self {
name,
setup: None,
js_init_script: None,
invoke_handler: Box::new(|_| false),
on_navigation: Box::new(|_, _| true),
on_page_load: Box::new(|_, _| ()),
on_window_ready: Box::new(|_| ()),
on_webview_ready: Box::new(|_| ()),
on_event: Box::new(|_, _| ()),
on_drop: None,
uri_scheme_protocols: Default::default(),
}
}
/// Defines the JS message handler callback.
/// It is recommended you use the [tauri::generate_handler] to generate the input to this method, as the input type is not considered stable yet.
///
/// # Examples
///
/// ```rust
/// use tauri::{plugin::{Builder, TauriPlugin}, Runtime};
///
/// #[tauri::command]
/// async fn foobar<R: Runtime>(app: tauri::AppHandle<R>, window: tauri::Window<R>) -> Result<(), String> {
/// println!("foobar");
///
/// Ok(())
/// }
///
/// fn init<R: Runtime>() -> TauriPlugin<R> {
/// Builder::new("example")
/// .invoke_handler(tauri::generate_handler![foobar])
/// .build()
/// }
///
/// ```
/// [tauri::generate_handler]: ../macro.generate_handler.html
#[must_use]
pub fn invoke_handler<F>(mut self, invoke_handler: F) -> Self
where
F: Fn(Invoke<R>) -> bool + Send + Sync + 'static,
{
self.invoke_handler = Box::new(invoke_handler);
self
}
/// Sets the provided JavaScript to be run after the global object has been created,
/// but before the HTML document has been parsed and before any other script included by the HTML document is run.
///
/// The script is wrapped into its own context with `(function () { /* your script here */ })();`,
/// so global variables must be assigned to `window` instead of implicitly declared.
///
/// Note that calling this function multiple times overrides previous values.
///
/// This is executed only on the main frame.
/// If you only want to run it in all frames, use [`Self::js_init_script_on_all_frames`] instead.
///
/// ## Platform-specific
///
/// - **Windows:** scripts are always added to subframes.
/// - **Android:** When [addDocumentStartJavaScript] is not supported,
/// we prepend initialization scripts to each HTML head (implementation only supported on custom protocol URLs).
/// For remote URLs, we use [onPageStarted] which is not guaranteed to run before other scripts.
///
/// [addDocumentStartJavaScript]: https://developer.android.com/reference/androidx/webkit/WebViewCompat#addDocumentStartJavaScript(android.webkit.WebView,java.lang.String,java.util.Set%3Cjava.lang.String%3E)
/// [onPageStarted]: https://developer.android.com/reference/android/webkit/WebViewClient#onPageStarted(android.webkit.WebView,%20java.lang.String,%20android.graphics.Bitmap)
///
/// # Examples
///
/// ```rust
/// use tauri::{plugin::{Builder, TauriPlugin}, Runtime};
///
/// const INIT_SCRIPT: &str = r#"
/// if (window.location.origin === 'https://tauri.app') {
/// console.log("hello world from js init script");
///
/// window.__MY_CUSTOM_PROPERTY__ = { foo: 'bar' };
/// }
/// "#;
///
/// fn init<R: Runtime>() -> TauriPlugin<R> {
/// Builder::new("example")
/// .js_init_script(INIT_SCRIPT)
/// .build()
/// }
/// ```
#[must_use]
// TODO: Rename to `initialization_script` in v3
pub fn js_init_script(mut self, js_init_script: impl Into<String>) -> Self {
self.js_init_script = Some(InitializationScript {
script: js_init_script.into(),
for_main_frame_only: true,
});
self
}
/// Sets the provided JavaScript to be run after the global object has been created,
/// but before the HTML document has been parsed and before any other script included by the HTML document is run.
///
/// Since it runs on all top-level document and child frame page navigations,
/// it's recommended to check the `window.location` to guard your script from running on unexpected origins.
///
/// Note that calling this function multiple times overrides previous values.
///
/// This is executed on all frames, main frame and also sub frames.
/// If you only want to run it in the main frame, use [`Self::js_init_script`] instead.
///
/// ## Platform-specific
///
/// - **Windows:** scripts are always added to subframes.
/// - **Android:** When [addDocumentStartJavaScript] is not supported,
/// we prepend initialization scripts to each HTML head (implementation only supported on custom protocol URLs).
/// For remote URLs, we use [onPageStarted] which is not guaranteed to run before other scripts.
///
/// [addDocumentStartJavaScript]: https://developer.android.com/reference/androidx/webkit/WebViewCompat#addDocumentStartJavaScript(android.webkit.WebView,java.lang.String,java.util.Set%3Cjava.lang.String%3E)
/// [onPageStarted]: https://developer.android.com/reference/android/webkit/WebViewClient#onPageStarted(android.webkit.WebView,%20java.lang.String,%20android.graphics.Bitmap)
#[must_use]
pub fn js_init_script_on_all_frames(mut self, js_init_script: impl Into<String>) -> Self {
self.js_init_script = Some(InitializationScript {
script: js_init_script.into(),
for_main_frame_only: false,
});
self
}
/// Define a closure that runs when the plugin is registered.
///
/// # Examples
///
/// ```rust
/// use tauri::{plugin::{Builder, TauriPlugin}, Runtime, Manager};
/// use std::path::PathBuf;
///
/// #[derive(Debug, Default)]
/// struct PluginState {
/// dir: Option<PathBuf>
/// }
///
/// fn init<R: Runtime>() -> TauriPlugin<R> {
/// Builder::new("example")
/// .setup(|app, api| {
/// app.manage(PluginState::default());
///
/// Ok(())
/// })
/// .build()
/// }
/// ```
#[must_use]
pub fn setup<F>(mut self, setup: F) -> Self
where
F: FnOnce(&AppHandle<R>, PluginApi<R, C>) -> Result<(), Box<dyn std::error::Error>>
+ Send
+ 'static,
{
self.setup.replace(Box::new(setup));
self
}
/// Callback invoked when the webview tries to navigate to a URL. Returning false cancels the navigation.
///
/// #Example
///
/// ```
/// use tauri::{plugin::{Builder, TauriPlugin}, Runtime};
///
/// fn init<R: Runtime>() -> TauriPlugin<R> {
/// Builder::new("example")
/// .on_navigation(|webview, url| {
/// // allow the production URL or localhost on dev
/// url.scheme() == "tauri" || (cfg!(dev) && url.host_str() == Some("localhost"))
/// })
/// .build()
/// }
/// ```
#[must_use]
pub fn on_navigation<F>(mut self, on_navigation: F) -> Self
where
F: Fn(&Webview<R>, &Url) -> bool + Send + 'static,
{
self.on_navigation = Box::new(on_navigation);
self
}
/// Callback invoked when the webview performs a navigation to a page.
///
/// # Examples
///
/// ```rust
/// use tauri::{plugin::{Builder, TauriPlugin}, Runtime};
///
/// fn init<R: Runtime>() -> TauriPlugin<R> {
/// Builder::new("example")
/// .on_page_load(|webview, payload| {
/// println!("{:?} URL {} in webview {}", payload.event(), payload.url(), webview.label());
/// })
/// .build()
/// }
/// ```
#[must_use]
pub fn on_page_load<F>(mut self, on_page_load: F) -> Self
where
F: FnMut(&Webview<R>, &PageLoadPayload<'_>) + Send + 'static,
{
self.on_page_load = Box::new(on_page_load);
self
}
/// Callback invoked when the window is created.
///
/// # Examples
///
/// ```rust
/// use tauri::{plugin::{Builder, TauriPlugin}, Runtime};
///
/// fn init<R: Runtime>() -> TauriPlugin<R> {
/// Builder::new("example")
/// .on_window_ready(|window| {
/// println!("created window {}", window.label());
/// })
/// .build()
/// }
/// ```
#[must_use]
pub fn on_window_ready<F>(mut self, on_window_ready: F) -> Self
where
F: FnMut(Window<R>) + Send + 'static,
{
self.on_window_ready = Box::new(on_window_ready);
self
}
/// Callback invoked when the webview is created.
///
/// # Examples
///
/// ```rust
/// use tauri::{plugin::{Builder, TauriPlugin}, Runtime};
///
/// fn init<R: Runtime>() -> TauriPlugin<R> {
/// Builder::new("example")
/// .on_webview_ready(|webview| {
/// println!("created webview {}", webview.label());
/// })
/// .build()
/// }
/// ```
#[must_use]
pub fn on_webview_ready<F>(mut self, on_webview_ready: F) -> Self
where
F: FnMut(Webview<R>) + Send + 'static,
{
self.on_webview_ready = Box::new(on_webview_ready);
self
}
/// Callback invoked when the event loop receives a new event.
///
/// # Examples
///
/// ```rust
/// use tauri::{plugin::{Builder, TauriPlugin}, RunEvent, Runtime};
///
/// fn init<R: Runtime>() -> TauriPlugin<R> {
/// Builder::new("example")
/// .on_event(|app_handle, event| {
/// match event {
/// RunEvent::ExitRequested { api, .. } => {
/// // Prevents the app from exiting.
/// // This will cause the core thread to continue running in the background even without any open windows.
/// api.prevent_exit();
/// }
/// // Ignore all other cases.
/// _ => {}
/// }
/// })
/// .build()
/// }
/// ```
#[must_use]
pub fn on_event<F>(mut self, on_event: F) -> Self
where
F: FnMut(&AppHandle<R>, &RunEvent) + Send + 'static,
{
self.on_event = Box::new(on_event);
self
}
/// Callback invoked when the plugin is dropped.
///
/// # Examples
///
/// ```rust
/// use tauri::{plugin::{Builder, TauriPlugin}, Runtime};
///
/// fn init<R: Runtime>() -> TauriPlugin<R> {
/// Builder::new("example")
/// .on_drop(|app| {
/// println!("plugin has been dropped and is no longer running");
/// // you can run cleanup logic here
/// })
/// .build()
/// }
/// ```
#[must_use]
pub fn on_drop<F>(mut self, on_drop: F) -> Self
where
F: FnOnce(AppHandle<R>) + Send + 'static,
{
self.on_drop.replace(Box::new(on_drop));
self
}
/// Registers a URI scheme protocol available to all webviews.
///
/// Leverages [setURLSchemeHandler](https://developer.apple.com/documentation/webkit/wkwebviewconfiguration/2875766-seturlschemehandler) on macOS,
/// [AddWebResourceRequestedFilter](https://docs.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2.addwebresourcerequestedfilter?view=webview2-dotnet-1.0.774.44) on Windows
/// and [webkit-web-context-register-uri-scheme](https://webkitgtk.org/reference/webkit2gtk/stable/WebKitWebContext.html#webkit-web-context-register-uri-scheme) on Linux.
///
/// # Known limitations
///
/// URI scheme protocols are registered when the webview is created. Due to this limitation, if the plugin is registered after a webview has been created, this protocol won't be available.
///
/// # Arguments
///
/// * `uri_scheme` The URI scheme to register, such as `example`.
/// * `protocol` the protocol associated with the given URI scheme. It's a function that takes an URL such as `example://localhost/asset.css`.
///
/// # Examples
///
/// ```rust
/// use tauri::{plugin::{Builder, TauriPlugin}, Runtime};
///
/// fn init<R: Runtime>() -> TauriPlugin<R> {
/// Builder::new("myplugin")
/// .register_uri_scheme_protocol("myscheme", |_ctx, req| {
/// http::Response::builder().body(Vec::new()).unwrap()
/// })
/// .build()
/// }
/// ```
///
/// # Warning
///
/// Pages loaded from a custom protocol will have a different Origin on different platforms.
/// Servers which enforce CORS will need to add the exact same Origin header (or `*`) in `Access-Control-Allow-Origin`
/// if you wish to send requests with native `fetch` and `XmlHttpRequest` APIs. Here are the
/// different Origin headers across platforms:
///
/// - macOS, iOS and Linux: `<scheme_name>://localhost/<path>` (so it will be `my-scheme://localhost/path/to/page).
/// - Windows and Android: `http://<scheme_name>.localhost/<path>` by default (so it will be `http://my-scheme.localhost/path/to/page`).
/// To use `https` instead of `http`, use [`super::webview::WebviewBuilder::use_https_scheme`].
#[must_use]
pub fn register_uri_scheme_protocol<
N: Into<String>,
T: Into<Cow<'static, [u8]>>,
H: Fn(UriSchemeContext<'_, R>, http::Request<Vec<u8>>) -> http::Response<T>
+ Send
+ Sync
+ 'static,
>(
mut self,
uri_scheme: N,
protocol_handler: H,
) -> Self {
self.uri_scheme_protocols.insert(
uri_scheme.into(),
Arc::new(UriSchemeProtocol {
handler: Box::new(move |ctx, request, responder| {
responder.respond(protocol_handler(ctx, request))
}),
}),
);
self
}
/// Similar to [`Self::register_uri_scheme_protocol`] but with an asynchronous responder that allows you
/// to process the request in a separate thread and respond asynchronously.
///
/// # Arguments
///
/// * `uri_scheme` The URI scheme to register, such as `example`.
/// * `protocol` the protocol associated with the given URI scheme. It's a function that takes an URL such as `example://localhost/asset.css`.
///
/// # Examples
///
/// ```rust
/// use tauri::{plugin::{Builder, TauriPlugin}, Runtime};
///
/// fn init<R: Runtime>() -> TauriPlugin<R> {
/// Builder::new("myplugin")
/// .register_asynchronous_uri_scheme_protocol("app-files", |_ctx, request, responder| {
/// // skip leading `/`
/// let path = request.uri().path()[1..].to_string();
/// std::thread::spawn(move || {
/// if let Ok(data) = std::fs::read(path) {
/// responder.respond(
/// http::Response::builder()
/// .body(data)
/// .unwrap()
/// );
/// } else {
/// responder.respond(
/// http::Response::builder()
/// .status(http::StatusCode::BAD_REQUEST)
/// .header(http::header::CONTENT_TYPE, mime::TEXT_PLAIN.essence_str())
/// .body("failed to read file".as_bytes().to_vec())
/// .unwrap()
/// );
/// }
/// });
/// })
/// .build()
/// }
/// ```
///
/// # Warning
///
/// Pages loaded from a custom protocol will have a different Origin on different platforms.
/// Servers which enforce CORS will need to add the exact same Origin header (or `*`) in `Access-Control-Allow-Origin`
/// if you wish to send requests with native `fetch` and `XmlHttpRequest` APIs. Here are the
/// different Origin headers across platforms:
///
/// - macOS, iOS and Linux: `<scheme_name>://localhost/<path>` (so it will be `my-scheme://localhost/path/to/page).
/// - Windows and Android: `http://<scheme_name>.localhost/<path>` by default (so it will be `http://my-scheme.localhost/path/to/page`).
/// To use `https` instead of `http`, use [`super::webview::WebviewBuilder::use_https_scheme`].
#[must_use]
pub fn register_asynchronous_uri_scheme_protocol<
N: Into<String>,
H: Fn(UriSchemeContext<'_, R>, http::Request<Vec<u8>>, UriSchemeResponder) + Send + Sync + 'static,
>(
mut self,
uri_scheme: N,
protocol_handler: H,
) -> Self {
self.uri_scheme_protocols.insert(
uri_scheme.into(),
Arc::new(UriSchemeProtocol {
handler: Box::new(protocol_handler),
}),
);
self
}
/// Builds the [`TauriPlugin`].
pub fn try_build(self) -> Result<TauriPlugin<R, C>, BuilderError> {
if let Some(&reserved) = RESERVED_PLUGIN_NAMES.iter().find(|&r| r == &self.name) {
return Err(BuilderError::ReservedName(reserved.into()));
}
Ok(TauriPlugin {
name: self.name,
app: None,
invoke_handler: self.invoke_handler,
setup: self.setup,
js_init_script: self.js_init_script,
on_navigation: self.on_navigation,
on_page_load: self.on_page_load,
on_window_ready: self.on_window_ready,
on_webview_ready: self.on_webview_ready,
on_event: self.on_event,
on_drop: self.on_drop,
uri_scheme_protocols: self.uri_scheme_protocols,
})
}
/// Builds the [`TauriPlugin`].
///
/// # Panics
///
/// If the builder returns an error during [`Self::try_build`], then this method will panic.
pub fn build(self) -> TauriPlugin<R, C> {
self.try_build().expect("valid plugin")
}
}
/// Plugin struct that is returned by the [`Builder`]. Should only be constructed through the builder.
pub struct TauriPlugin<R: Runtime, C: DeserializeOwned = ()> {
name: &'static str,
app: Option<AppHandle<R>>,
invoke_handler: Box<InvokeHandler<R>>,
setup: Option<Box<SetupHook<R, C>>>,
js_init_script: Option<InitializationScript>,
on_navigation: Box<OnNavigation<R>>,
on_page_load: Box<OnPageLoad<R>>,
on_window_ready: Box<OnWindowReady<R>>,
on_webview_ready: Box<OnWebviewReady<R>>,
on_event: Box<OnEvent<R>>,
on_drop: Option<Box<OnDrop<R>>>,
uri_scheme_protocols: HashMap<String, Arc<UriSchemeProtocol<R>>>,
}
impl<R: Runtime, C: DeserializeOwned> Drop for TauriPlugin<R, C> {
fn drop(&mut self) {
if let (Some(on_drop), Some(app)) = (self.on_drop.take(), self.app.take()) {
on_drop(app);
}
}
}
impl<R: Runtime, C: DeserializeOwned> Plugin<R> for TauriPlugin<R, C> {
fn name(&self) -> &'static str {
self.name
}
fn initialize(
&mut self,
app: &AppHandle<R>,
config: JsonValue,
) -> Result<(), Box<dyn std::error::Error>> {
self.app.replace(app.clone());
if let Some(s) = self.setup.take() {
(s)(
app,
PluginApi {
name: self.name,
handle: app.clone(),
raw_config: Arc::new(config.clone()),
config: serde_json::from_value(config).map_err(|err| {
format!(
"Error deserializing 'plugins.{}' within your Tauri configuration: {err}",
self.name
)
})?,
},
)?;
}
for (uri_scheme, protocol) in &self.uri_scheme_protocols {
app
.manager
.webview
.register_uri_scheme_protocol(uri_scheme, protocol.clone())
}
Ok(())
}
fn initialization_script(&self) -> Option<String> {
self
.js_init_script
.clone()
.map(|initialization_script| initialization_script.script)
}
fn initialization_script_2(&self) -> Option<InitializationScript> {
self.js_init_script.clone()
}
fn window_created(&mut self, window: Window<R>) {
(self.on_window_ready)(window)
}
fn webview_created(&mut self, webview: Webview<R>) {
(self.on_webview_ready)(webview)
}
fn on_navigation(&mut self, webview: &Webview<R>, url: &Url) -> bool {
(self.on_navigation)(webview, url)
}
fn on_page_load(&mut self, webview: &Webview<R>, payload: &PageLoadPayload<'_>) {
(self.on_page_load)(webview, payload)
}
fn on_event(&mut self, app: &AppHandle<R>, event: &RunEvent) {
(self.on_event)(app, event)
}
fn extend_api(&mut self, invoke: Invoke<R>) -> bool {
(self.invoke_handler)(invoke)
}
}
/// Plugin collection type.
#[default_runtime(crate::Wry, wry)]
pub(crate) struct PluginStore<R: Runtime> {
store: Vec<Box<dyn Plugin<R>>>,
}
impl<R: Runtime> fmt::Debug for PluginStore<R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let plugins: Vec<&str> = self.store.iter().map(|plugins| plugins.name()).collect();
f.debug_struct("PluginStore")
.field("plugins", &plugins)
.finish()
}
}
impl<R: Runtime> Default for PluginStore<R> {
fn default() -> Self {
Self { store: Vec::new() }
}
}
impl<R: Runtime> PluginStore<R> {
/// Adds a plugin to the store.
///
/// Returns `true` if a plugin with the same name is already in the store.
pub fn register(&mut self, plugin: Box<dyn Plugin<R>>) -> bool {
let len = self.store.len();
self.store.retain(|p| p.name() != plugin.name());
let result = len != self.store.len();
self.store.push(plugin);
result
}
/// Removes the plugin with the given name from the store.
pub fn unregister(&mut self, plugin: &str) -> bool {
let len = self.store.len();
self.store.retain(|p| p.name() != plugin);
len != self.store.len()
}
/// Initializes the given plugin.
pub(crate) fn initialize(
&self,
plugin: &mut Box<dyn Plugin<R>>,
app: &AppHandle<R>,
config: &PluginConfig,
) -> crate::Result<()> {
initialize(plugin, app, config)
}
/// Initializes all plugins in the store.
pub(crate) fn initialize_all(
&mut self,
app: &AppHandle<R>,
config: &PluginConfig,
) -> crate::Result<()> {
self
.store
.iter_mut()
.try_for_each(|plugin| initialize(plugin, app, config))
}
/// Generates an initialization script from all plugins in the store.
pub(crate) fn initialization_script(&self) -> Vec<InitializationScript> {
self
.store
.iter()
.filter_map(|p| p.initialization_script_2())
.map(
|InitializationScript {
script,
for_main_frame_only,
}| InitializationScript {
script: format!("(function () {{ {script} }})();"),
for_main_frame_only,
},
)
.collect()
}
/// Runs the created hook for all plugins in the store.
pub(crate) fn window_created(&mut self, window: Window<R>) {
self.store.iter_mut().for_each(|plugin| {
#[cfg(feature = "tracing")]
let _span = tracing::trace_span!("plugin::hooks::created", name = plugin.name()).entered();
plugin.window_created(window.clone())
})
}
/// Runs the webview created hook for all plugins in the store.
pub(crate) fn webview_created(&mut self, webview: Webview<R>) {
self
.store
.iter_mut()
.for_each(|plugin| plugin.webview_created(webview.clone()))
}
pub(crate) fn on_navigation(&mut self, webview: &Webview<R>, url: &Url) -> bool {
for plugin in self.store.iter_mut() {
#[cfg(feature = "tracing")]
let _span =
tracing::trace_span!("plugin::hooks::on_navigation", name = plugin.name()).entered();
if !plugin.on_navigation(webview, url) {
return false;
}
}
true
}
/// Runs the on_page_load hook for all plugins in the store.
pub(crate) fn on_page_load(&mut self, webview: &Webview<R>, payload: &PageLoadPayload<'_>) {
self.store.iter_mut().for_each(|plugin| {
#[cfg(feature = "tracing")]
let _span =
tracing::trace_span!("plugin::hooks::on_page_load", name = plugin.name()).entered();
plugin.on_page_load(webview, payload)
})
}
/// Runs the on_event hook for all plugins in the store.
pub(crate) fn on_event(&mut self, app: &AppHandle<R>, event: &RunEvent) {
self
.store
.iter_mut()
.for_each(|plugin| plugin.on_event(app, event))
}
/// Runs the plugin `extend_api` hook if it exists. Returns whether the invoke message was handled or not.
///
/// The message is not handled when the plugin exists **and** the command does not.
pub(crate) fn extend_api(&mut self, plugin: &str, invoke: Invoke<R>) -> bool {
for p in self.store.iter_mut() {
if p.name() == plugin {
#[cfg(feature = "tracing")]
let _span = tracing::trace_span!("plugin::hooks::ipc", name = plugin).entered();
return p.extend_api(invoke);
}
}
invoke.resolver.reject(format!("plugin {plugin} not found"));
true
}
}
#[cfg_attr(feature = "tracing", tracing::instrument(name = "plugin::hooks::initialize", skip(plugin, app), fields(name = plugin.name())))]
fn initialize<R: Runtime>(
plugin: &mut Box<dyn Plugin<R>>,
app: &AppHandle<R>,
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | true |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/scope/fs.rs | crates/tauri/src/scope/fs.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{
collections::{HashMap, HashSet},
fmt,
path::{Path, PathBuf, MAIN_SEPARATOR},
sync::{
atomic::{AtomicU32, Ordering},
Arc, Mutex,
},
};
use tauri_utils::config::FsScope;
use crate::ScopeEventId;
pub use glob::Pattern;
/// Scope change event.
#[derive(Debug, Clone)]
pub enum Event {
/// A path has been allowed.
PathAllowed(PathBuf),
/// A path has been forbidden.
PathForbidden(PathBuf),
}
type EventListener = Box<dyn Fn(&Event) + Send>;
/// Scope for filesystem access.
#[derive(Clone)]
pub struct Scope {
allowed_patterns: Arc<Mutex<HashSet<Pattern>>>,
forbidden_patterns: Arc<Mutex<HashSet<Pattern>>>,
event_listeners: Arc<Mutex<HashMap<ScopeEventId, EventListener>>>,
match_options: glob::MatchOptions,
next_event_id: Arc<AtomicU32>,
}
impl Scope {
fn next_event_id(&self) -> u32 {
self.next_event_id.fetch_add(1, Ordering::Relaxed)
}
}
impl fmt::Debug for Scope {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Scope")
.field(
"allowed_patterns",
&self
.allowed_patterns
.lock()
.unwrap()
.iter()
.map(|p| p.as_str())
.collect::<Vec<&str>>(),
)
.field(
"forbidden_patterns",
&self
.forbidden_patterns
.lock()
.unwrap()
.iter()
.map(|p| p.as_str())
.collect::<Vec<&str>>(),
)
.finish()
}
}
fn push_pattern<P: AsRef<Path>, F: Fn(&str) -> Result<Pattern, glob::PatternError>>(
list: &mut HashSet<Pattern>,
pattern: P,
f: F,
) -> crate::Result<()> {
// Reconstruct pattern path components with appropraite separator
// so `some\path/to/dir/**\*` would be `some/path/to/dir/**/*` on Unix
// and `some\path\to\dir\**\*` on Windows.
let path: PathBuf = pattern.as_ref().components().collect();
// Add pattern as is to be matched with paths as is
let path_str = path.to_string_lossy();
list.insert(f(&path_str)?);
// On Windows, if path starts with a Prefix, try to strip it if possible
// so `\\?\C:\\SomeDir` would result in a scope of:
// - `\\?\C:\\SomeDir`
// - `C:\\SomeDir`
#[cfg(windows)]
{
use std::path::{Component, Prefix};
let mut components = path.components();
let is_unc = match components.next() {
Some(Component::Prefix(p)) => match p.kind() {
Prefix::VerbatimDisk(..) => true,
_ => false, // Other kinds of UNC paths
},
_ => false, // relative or empty
};
if is_unc {
// we remove UNC manually, instead of `dunce::simplified` because
// `path` could have `*` in it and that's not allowed on Windows and
// `dunce::simplified` will check that and return `path` as is without simplification
let simplified = path
.to_str()
.and_then(|s| s.get(4..))
.map_or(path.as_path(), Path::new);
let simplified_str = simplified.to_string_lossy();
if simplified_str != path_str {
list.insert(f(&simplified_str)?);
}
}
}
// Add canonicalized version of the pattern or canonicalized version of its parents
// so `/data/user/0/appid/assets/*` would be canonicalized to `/data/data/appid/assets/*`
// and can then be matched against any of them.
if let Some(p) = canonicalize_parent(path) {
list.insert(f(&p.to_string_lossy())?);
}
Ok(())
}
/// Attempt to canonicalize path or its parents in case we have a path like `/data/user/0/appid/**`
/// where `**` obviously does not exist but we need to canonicalize the parent.
///
/// example: given the `/data/user/0/appid/assets/*` path,
/// it's a glob pattern so it won't exist (std::fs::canonicalize() fails);
///
/// the second iteration needs to check `/data/user/0/appid/assets` and save the `*` component to append later.
///
/// if it also does not exist, a third iteration is required to check `/data/user/0/appid`
/// with `assets/*` as the cached value (`checked_path` variable)
/// on Android that gets canonicalized to `/data/data/appid` so the final value will be `/data/data/appid/assets/*`
/// which is the value we want to check when we execute the `Scope::is_allowed` function
fn canonicalize_parent(mut path: PathBuf) -> Option<PathBuf> {
let mut failed_components = None;
loop {
if let Ok(path) = path.canonicalize() {
break Some(if let Some(p) = failed_components {
path.join(p)
} else {
path
});
}
// grap the last component of the path
if let Some(mut last) = path.iter().next_back().map(PathBuf::from) {
// remove the last component of the path so the next iteration checks its parent
// if there is no more parent components, we failed to canonicalize
if !path.pop() {
break None;
}
// append the already checked path to the last component
// to construct `<last>/<checked_path>` and saved it for next iteration
if let Some(failed_components) = &failed_components {
last.push(failed_components);
}
failed_components.replace(last);
} else {
break None;
}
}
}
impl Scope {
/// Creates a new scope from a [`FsScope`] configuration.
pub fn new<R: crate::Runtime, M: crate::Manager<R>>(
manager: &M,
scope: &FsScope,
) -> crate::Result<Self> {
let mut allowed_patterns = HashSet::new();
for path in scope.allowed_paths() {
if let Ok(path) = manager.path().parse(path) {
push_pattern(&mut allowed_patterns, path, Pattern::new)?;
}
}
let mut forbidden_patterns = HashSet::new();
if let Some(forbidden_paths) = scope.forbidden_paths() {
for path in forbidden_paths {
if let Ok(path) = manager.path().parse(path) {
push_pattern(&mut forbidden_patterns, path, Pattern::new)?;
}
}
}
let require_literal_leading_dot = match scope {
FsScope::Scope {
require_literal_leading_dot: Some(require),
..
} => *require,
// dotfiles are not supposed to be exposed by default on unix
#[cfg(unix)]
_ => true,
#[cfg(windows)]
_ => false,
};
Ok(Self {
allowed_patterns: Arc::new(Mutex::new(allowed_patterns)),
forbidden_patterns: Arc::new(Mutex::new(forbidden_patterns)),
event_listeners: Default::default(),
next_event_id: Default::default(),
match_options: glob::MatchOptions {
// this is needed so `/dir/*` doesn't match files within subdirectories such as `/dir/subdir/file.txt`
// see: <https://github.com/tauri-apps/tauri/security/advisories/GHSA-6mv3-wm7j-h4w5>
require_literal_separator: true,
require_literal_leading_dot,
..Default::default()
},
})
}
/// The list of allowed patterns.
pub fn allowed_patterns(&self) -> HashSet<Pattern> {
self.allowed_patterns.lock().unwrap().clone()
}
/// The list of forbidden patterns.
pub fn forbidden_patterns(&self) -> HashSet<Pattern> {
self.forbidden_patterns.lock().unwrap().clone()
}
/// Listen to an event on this scope.
pub fn listen<F: Fn(&Event) + Send + 'static>(&self, f: F) -> ScopeEventId {
let id = self.next_event_id();
self.listen_with_id(id, f);
id
}
fn listen_with_id<F: Fn(&Event) + Send + 'static>(&self, id: ScopeEventId, f: F) {
self.event_listeners.lock().unwrap().insert(id, Box::new(f));
}
/// Listen to an event on this scope and immediately unlisten.
pub fn once<F: FnOnce(&Event) + Send + 'static>(&self, f: F) -> ScopeEventId {
let listerners = self.event_listeners.clone();
let handler = std::cell::Cell::new(Some(f));
let id = self.next_event_id();
self.listen_with_id(id, move |event| {
listerners.lock().unwrap().remove(&id);
let handler = handler
.take()
.expect("attempted to call handler more than once");
handler(event)
});
id
}
/// Removes an event listener on this scope.
pub fn unlisten(&self, id: ScopeEventId) {
self.event_listeners.lock().unwrap().remove(&id);
}
fn emit(&self, event: Event) {
let listeners = self.event_listeners.lock().unwrap();
let handlers = listeners.values();
for listener in handlers {
listener(&event);
}
}
/// Extend the allowed patterns with the given directory.
///
/// After this function has been called, the frontend will be able to use the Tauri API to read
/// the directory and all of its files. If `recursive` is `true`, subdirectories will be accessible too.
pub fn allow_directory<P: AsRef<Path>>(&self, path: P, recursive: bool) -> crate::Result<()> {
let path = path.as_ref();
{
let mut list = self.allowed_patterns.lock().unwrap();
// allow the directory to be read
push_pattern(&mut list, path, escaped_pattern)?;
// allow its files and subdirectories to be read
push_pattern(&mut list, path, |p| {
escaped_pattern_with(p, if recursive { "**" } else { "*" })
})?;
}
self.emit(Event::PathAllowed(path.to_path_buf()));
Ok(())
}
/// Extend the allowed patterns with the given file path.
///
/// After this function has been called, the frontend will be able to use the Tauri API to read the contents of this file.
pub fn allow_file<P: AsRef<Path>>(&self, path: P) -> crate::Result<()> {
let path = path.as_ref();
push_pattern(
&mut self.allowed_patterns.lock().unwrap(),
path,
escaped_pattern,
)?;
self.emit(Event::PathAllowed(path.to_path_buf()));
Ok(())
}
/// Set the given directory path to be forbidden by this scope.
///
/// **Note:** this takes precedence over allowed paths, so its access gets denied **always**.
pub fn forbid_directory<P: AsRef<Path>>(&self, path: P, recursive: bool) -> crate::Result<()> {
let path = path.as_ref();
{
let mut list = self.forbidden_patterns.lock().unwrap();
// allow the directory to be read
push_pattern(&mut list, path, escaped_pattern)?;
// allow its files and subdirectories to be read
push_pattern(&mut list, path, |p| {
escaped_pattern_with(p, if recursive { "**" } else { "*" })
})?;
}
self.emit(Event::PathForbidden(path.to_path_buf()));
Ok(())
}
/// Set the given file path to be forbidden by this scope.
///
/// **Note:** this takes precedence over allowed paths, so its access gets denied **always**.
pub fn forbid_file<P: AsRef<Path>>(&self, path: P) -> crate::Result<()> {
let path = path.as_ref();
push_pattern(
&mut self.forbidden_patterns.lock().unwrap(),
path,
escaped_pattern,
)?;
self.emit(Event::PathForbidden(path.to_path_buf()));
Ok(())
}
/// Determines if the given path is allowed on this scope.
///
/// Returns `false` if the path was explicitly forbidden or neither allowed nor forbidden.
///
/// May return `false` if the path points to a broken symlink.
pub fn is_allowed<P: AsRef<Path>>(&self, path: P) -> bool {
let path = try_resolve_symlink_and_canonicalize(path);
if let Ok(path) = path {
let path: PathBuf = path.components().collect();
let forbidden = self
.forbidden_patterns
.lock()
.unwrap()
.iter()
.any(|p| p.matches_path_with(&path, self.match_options));
if forbidden {
false
} else {
let allowed = self
.allowed_patterns
.lock()
.unwrap()
.iter()
.any(|p| p.matches_path_with(&path, self.match_options));
allowed
}
} else {
false
}
}
/// Determines if the given path is explicitly forbidden on this scope.
///
/// May return `true` if the path points to a broken symlink.
pub fn is_forbidden<P: AsRef<Path>>(&self, path: P) -> bool {
let path = try_resolve_symlink_and_canonicalize(path);
if let Ok(path) = path {
let path: PathBuf = path.components().collect();
self
.forbidden_patterns
.lock()
.unwrap()
.iter()
.any(|p| p.matches_path_with(&path, self.match_options))
} else {
true
}
}
}
fn try_resolve_symlink_and_canonicalize<P: AsRef<Path>>(path: P) -> crate::Result<PathBuf> {
let path = path.as_ref();
let path = if path.is_symlink() {
std::fs::read_link(path)?
} else {
path.to_path_buf()
};
if !path.exists() {
crate::Result::Ok(path)
} else {
std::fs::canonicalize(path).map_err(Into::into)
}
}
fn escaped_pattern(p: &str) -> Result<Pattern, glob::PatternError> {
Pattern::new(&glob::Pattern::escape(p))
}
fn escaped_pattern_with(p: &str, append: &str) -> Result<Pattern, glob::PatternError> {
if p.ends_with(MAIN_SEPARATOR) {
Pattern::new(&format!("{}{append}", glob::Pattern::escape(p)))
} else {
Pattern::new(&format!(
"{}{}{append}",
glob::Pattern::escape(p),
MAIN_SEPARATOR
))
}
}
#[cfg(test)]
mod tests {
use std::collections::HashSet;
use glob::Pattern;
use super::{push_pattern, Scope};
fn new_scope() -> Scope {
Scope {
allowed_patterns: Default::default(),
forbidden_patterns: Default::default(),
event_listeners: Default::default(),
next_event_id: Default::default(),
match_options: glob::MatchOptions {
// this is needed so `/dir/*` doesn't match files within subdirectories such as `/dir/subdir/file.txt`
// see: <https://github.com/tauri-apps/tauri/security/advisories/GHSA-6mv3-wm7j-h4w5>
require_literal_separator: true,
// dotfiles are not supposed to be exposed by default on unix
#[cfg(unix)]
require_literal_leading_dot: true,
#[cfg(windows)]
require_literal_leading_dot: false,
..Default::default()
},
}
}
#[test]
fn path_is_escaped() {
let scope = new_scope();
#[cfg(unix)]
{
scope.allow_directory("/home/tauri/**", false).unwrap();
assert!(scope.is_allowed("/home/tauri/**"));
assert!(scope.is_allowed("/home/tauri/**/file"));
assert!(!scope.is_allowed("/home/tauri/anyfile"));
}
#[cfg(windows)]
{
scope.allow_directory("C:\\home\\tauri\\**", false).unwrap();
assert!(scope.is_allowed("C:\\home\\tauri\\**"));
assert!(scope.is_allowed("C:\\home\\tauri\\**\\file"));
assert!(!scope.is_allowed("C:\\home\\tauri\\anyfile"));
}
let scope = new_scope();
#[cfg(unix)]
{
scope.allow_file("/home/tauri/**").unwrap();
assert!(scope.is_allowed("/home/tauri/**"));
assert!(!scope.is_allowed("/home/tauri/**/file"));
assert!(!scope.is_allowed("/home/tauri/anyfile"));
}
#[cfg(windows)]
{
scope.allow_file("C:\\home\\tauri\\**").unwrap();
assert!(scope.is_allowed("C:\\home\\tauri\\**"));
assert!(!scope.is_allowed("C:\\home\\tauri\\**\\file"));
assert!(!scope.is_allowed("C:\\home\\tauri\\anyfile"));
}
let scope = new_scope();
#[cfg(unix)]
{
scope.allow_directory("/home/tauri", true).unwrap();
scope.forbid_directory("/home/tauri/**", false).unwrap();
assert!(!scope.is_allowed("/home/tauri/**"));
assert!(!scope.is_allowed("/home/tauri/**/file"));
assert!(scope.is_allowed("/home/tauri/**/inner/file"));
assert!(scope.is_allowed("/home/tauri/inner/folder/anyfile"));
assert!(scope.is_allowed("/home/tauri/anyfile"));
}
#[cfg(windows)]
{
scope.allow_directory("C:\\home\\tauri", true).unwrap();
scope
.forbid_directory("C:\\home\\tauri\\**", false)
.unwrap();
assert!(!scope.is_allowed("C:\\home\\tauri\\**"));
assert!(!scope.is_allowed("C:\\home\\tauri\\**\\file"));
assert!(scope.is_allowed("C:\\home\\tauri\\**\\inner\\file"));
assert!(scope.is_allowed("C:\\home\\tauri\\inner\\folder\\anyfile"));
assert!(scope.is_allowed("C:\\home\\tauri\\anyfile"));
}
let scope = new_scope();
#[cfg(unix)]
{
scope.allow_directory("/home/tauri", true).unwrap();
scope.forbid_file("/home/tauri/**").unwrap();
assert!(!scope.is_allowed("/home/tauri/**"));
assert!(scope.is_allowed("/home/tauri/**/file"));
assert!(scope.is_allowed("/home/tauri/**/inner/file"));
assert!(scope.is_allowed("/home/tauri/anyfile"));
}
#[cfg(windows)]
{
scope.allow_directory("C:\\home\\tauri", true).unwrap();
scope.forbid_file("C:\\home\\tauri\\**").unwrap();
assert!(!scope.is_allowed("C:\\home\\tauri\\**"));
assert!(scope.is_allowed("C:\\home\\tauri\\**\\file"));
assert!(scope.is_allowed("C:\\home\\tauri\\**\\inner\\file"));
assert!(scope.is_allowed("C:\\home\\tauri\\anyfile"));
}
let scope = new_scope();
#[cfg(unix)]
{
scope.allow_directory("/home/tauri", false).unwrap();
assert!(scope.is_allowed("/home/tauri/**"));
assert!(!scope.is_allowed("/home/tauri/**/file"));
assert!(!scope.is_allowed("/home/tauri/**/inner/file"));
assert!(scope.is_allowed("/home/tauri/anyfile"));
}
#[cfg(windows)]
{
scope.allow_directory("C:\\home\\tauri", false).unwrap();
assert!(scope.is_allowed("C:\\home\\tauri\\**"));
assert!(!scope.is_allowed("C:\\home\\tauri\\**\\file"));
assert!(!scope.is_allowed("C:\\home\\tauri\\**\\inner\\file"));
assert!(scope.is_allowed("C:\\home\\tauri\\anyfile"));
}
}
#[cfg(windows)]
#[test]
fn windows_root_paths() {
let scope = new_scope();
{
// UNC network path
scope.allow_directory("\\\\localhost\\c$", true).unwrap();
assert!(scope.is_allowed("\\\\localhost\\c$"));
assert!(scope.is_allowed("\\\\localhost\\c$\\Windows"));
assert!(scope.is_allowed("\\\\localhost\\c$\\NonExistentFile"));
assert!(!scope.is_allowed("\\\\localhost\\d$"));
assert!(!scope.is_allowed("\\\\OtherServer\\Share"));
}
let scope = new_scope();
{
// Verbatim UNC network path
scope
.allow_directory("\\\\?\\UNC\\localhost\\c$", true)
.unwrap();
assert!(scope.is_allowed("\\\\localhost\\c$"));
assert!(scope.is_allowed("\\\\localhost\\c$\\Windows"));
assert!(scope.is_allowed("\\\\?\\UNC\\localhost\\c$\\Windows\\NonExistentFile"));
// A non-existent file cannot be canonicalized to a verbatim UNC path, so this will fail to match
assert!(!scope.is_allowed("\\\\localhost\\c$\\Windows\\NonExistentFile"));
assert!(!scope.is_allowed("\\\\localhost\\d$"));
assert!(!scope.is_allowed("\\\\OtherServer\\Share"));
}
let scope = new_scope();
{
// Device namespace
scope.allow_file("\\\\.\\COM1").unwrap();
assert!(scope.is_allowed("\\\\.\\COM1"));
assert!(!scope.is_allowed("\\\\.\\COM2"));
}
let scope = new_scope();
{
// Disk root
scope.allow_directory("C:\\", true).unwrap();
assert!(scope.is_allowed("C:\\Windows"));
assert!(scope.is_allowed("C:\\Windows\\system.ini"));
assert!(scope.is_allowed("C:\\NonExistentFile"));
assert!(!scope.is_allowed("D:\\home"));
}
let scope = new_scope();
{
// Verbatim disk root
scope.allow_directory("\\\\?\\C:\\", true).unwrap();
assert!(scope.is_allowed("C:\\Windows"));
assert!(scope.is_allowed("C:\\Windows\\system.ini"));
assert!(scope.is_allowed("C:\\NonExistentFile"));
assert!(!scope.is_allowed("D:\\home"));
}
let scope = new_scope();
{
// Verbatim path
scope.allow_file("\\\\?\\anyfile").unwrap();
assert!(scope.is_allowed("\\\\?\\anyfile"));
assert!(!scope.is_allowed("\\\\?\\otherfile"));
}
}
#[test]
fn push_pattern_generated_paths() {
macro_rules! assert_pattern {
($patterns:ident, $pattern:literal) => {
assert!($patterns.contains(&Pattern::new($pattern).unwrap()))
};
}
let mut patterns = HashSet::new();
#[cfg(not(windows))]
{
push_pattern(&mut patterns, "/path/to/dir/", Pattern::new).expect("failed to push pattern");
push_pattern(&mut patterns, "/path/to/dir/**", Pattern::new).expect("failed to push pattern");
assert_pattern!(patterns, "/path/to/dir");
assert_pattern!(patterns, "/path/to/dir/**");
}
#[cfg(windows)]
{
push_pattern(&mut patterns, "C:\\path\\to\\dir", Pattern::new)
.expect("failed to push pattern");
push_pattern(&mut patterns, "C:\\path\\to\\dir\\**", Pattern::new)
.expect("failed to push pattern");
assert_pattern!(patterns, "C:\\path\\to\\dir");
assert_pattern!(patterns, "C:\\path\\to\\dir\\**");
assert_pattern!(patterns, "\\\\?\\C:\\path\\to\\dir");
assert_pattern!(patterns, "\\\\?\\C:\\path\\to\\dir\\**");
}
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/scope/mod.rs | crates/tauri/src/scope/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
/// FS scope.
pub mod fs;
use std::path::Path;
/// Unique id of a scope event.
pub type ScopeEventId = u32;
/// Managed state for all the core scopes in a tauri application.
pub struct Scopes {
#[cfg(feature = "protocol-asset")]
pub(crate) asset_protocol: fs::Scope,
}
#[allow(unused)]
impl Scopes {
/// Allows a directory on the scopes.
pub fn allow_directory<P: AsRef<Path>>(&self, path: P, recursive: bool) -> crate::Result<()> {
#[cfg(feature = "protocol-asset")]
self.asset_protocol.allow_directory(path, recursive)?;
Ok(())
}
/// Allows a file on the scopes.
pub fn allow_file<P: AsRef<Path>>(&self, path: P) -> crate::Result<()> {
#[cfg(feature = "protocol-asset")]
self.asset_protocol.allow_file(path)?;
Ok(())
}
/// Forbids a file on the scopes.
pub fn forbid_file<P: AsRef<Path>>(&self, path: P) -> crate::Result<()> {
#[cfg(feature = "protocol-asset")]
self.asset_protocol.forbid_file(path)?;
Ok(())
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/plugin/mobile.rs | crates/tauri/src/plugin/mobile.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use super::{PluginApi, PluginHandle};
use crate::{ipc::Channel, AppHandle, Runtime};
#[cfg(target_os = "android")]
use crate::{
runtime::RuntimeHandle,
sealed::{ManagerBase, RuntimeOrDispatch},
};
#[cfg(mobile)]
use std::sync::atomic::{AtomicI32, Ordering};
#[cfg(mobile)]
use tokio::sync::oneshot;
use serde::{de::DeserializeOwned, Serialize};
use std::{
collections::HashMap,
fmt,
sync::{mpsc::channel, Mutex, OnceLock},
};
type PluginResponse = Result<serde_json::Value, serde_json::Value>;
type PendingPluginCallHandler = Box<dyn FnOnce(PluginResponse) + Send + 'static>;
#[cfg(mobile)]
static PENDING_PLUGIN_CALLS_ID: AtomicI32 = AtomicI32::new(0);
static PENDING_PLUGIN_CALLS: OnceLock<Mutex<HashMap<i32, PendingPluginCallHandler>>> =
OnceLock::new();
static CHANNELS: OnceLock<Mutex<HashMap<u32, Channel<serde_json::Value>>>> = OnceLock::new();
/// Possible errors when invoking a plugin.
#[derive(Debug, thiserror::Error)]
pub enum PluginInvokeError {
/// Failed to reach platform webview handle.
#[error("the webview is unreachable")]
UnreachableWebview,
/// JNI error.
#[cfg(target_os = "android")]
#[error("jni error: {0}")]
Jni(#[from] jni::errors::Error),
/// Error returned from direct mobile plugin invoke.
#[error(transparent)]
InvokeRejected(#[from] ErrorResponse),
/// Failed to deserialize response.
#[error("failed to deserialize response: {0}")]
CannotDeserializeResponse(serde_json::Error),
/// Failed to serialize request payload.
#[error("failed to serialize payload: {0}")]
CannotSerializePayload(serde_json::Error),
}
pub(crate) fn register_channel(channel: Channel<serde_json::Value>) {
CHANNELS
.get_or_init(Default::default)
.lock()
.unwrap()
.insert(channel.id(), channel);
}
/// Glue between Rust and the Kotlin code that sends the plugin response back.
#[cfg(target_os = "android")]
pub fn handle_android_plugin_response(
env: &mut jni::JNIEnv<'_>,
id: i32,
success: jni::objects::JString<'_>,
error: jni::objects::JString<'_>,
) {
let (payload, is_ok): (serde_json::Value, bool) = match (
env
.is_same_object(&success, jni::objects::JObject::default())
.unwrap_or_default(),
env
.is_same_object(&error, jni::objects::JObject::default())
.unwrap_or_default(),
) {
// both null
(true, true) => (serde_json::Value::Null, true),
// error null
(false, true) => (
serde_json::from_str(env.get_string(&success).unwrap().to_str().unwrap()).unwrap(),
true,
),
// success null
(true, false) => (
serde_json::from_str(env.get_string(&error).unwrap().to_str().unwrap()).unwrap(),
false,
),
// both are set - impossible in the Kotlin code
(false, false) => unreachable!(),
};
if let Some(handler) = PENDING_PLUGIN_CALLS
.get_or_init(Default::default)
.lock()
.unwrap()
.remove(&id)
{
handler(if is_ok { Ok(payload) } else { Err(payload) });
}
}
/// Glue between Rust and the Kotlin code that sends the channel data.
#[cfg(target_os = "android")]
pub fn send_channel_data(
env: &mut jni::JNIEnv<'_>,
channel_id: i64,
data_str: jni::objects::JString<'_>,
) {
let data: serde_json::Value =
serde_json::from_str(env.get_string(&data_str).unwrap().to_str().unwrap()).unwrap();
if let Some(channel) = CHANNELS
.get_or_init(Default::default)
.lock()
.unwrap()
.get(&(channel_id as u32))
{
let _ = channel.send(data);
}
}
/// Error response from the Kotlin and Swift backends.
#[derive(Debug, thiserror::Error, Clone, serde::Deserialize)]
pub struct ErrorResponse<T = ()> {
/// Error code.
pub code: Option<String>,
/// Error message.
pub message: Option<String>,
/// Optional error data.
#[serde(flatten)]
pub data: T,
}
impl<T> fmt::Display for ErrorResponse<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(code) = &self.code {
write!(f, "[{code}]")?;
if self.message.is_some() {
write!(f, " - ")?;
}
}
if let Some(message) = &self.message {
write!(f, "{message}")?;
}
Ok(())
}
}
impl<R: Runtime, C: DeserializeOwned> PluginApi<R, C> {
/// Registers an iOS plugin.
#[cfg(all(target_os = "ios", feature = "wry"))]
pub fn register_ios_plugin(
&self,
init_fn: unsafe fn() -> *const std::ffi::c_void,
) -> Result<PluginHandle<R>, PluginInvokeError> {
if let Some(webview) = self.handle.manager.webviews().values().next() {
let (tx, rx) = channel();
let name = self.name;
let config = self.raw_config.clone();
webview
.with_webview(move |w| {
unsafe {
crate::ios::register_plugin(
&name.into(),
init_fn(),
&serde_json::to_string(&config).unwrap().as_str().into(),
w.inner() as _,
)
};
tx.send(()).unwrap();
})
.map_err(|_| PluginInvokeError::UnreachableWebview)?;
rx.recv().unwrap();
} else {
unsafe {
crate::ios::register_plugin(
&self.name.into(),
init_fn(),
&serde_json::to_string(&self.raw_config)
.unwrap()
.as_str()
.into(),
std::ptr::null(),
)
};
}
Ok(PluginHandle {
name: self.name,
handle: self.handle.clone(),
})
}
/// Registers an Android plugin.
#[cfg(target_os = "android")]
pub fn register_android_plugin(
&self,
plugin_identifier: &str,
class_name: &str,
) -> Result<PluginHandle<R>, PluginInvokeError> {
use jni::{errors::Error as JniError, objects::JObject, JNIEnv};
fn initialize_plugin<R: Runtime>(
env: &mut JNIEnv<'_>,
activity: &JObject<'_>,
webview: &JObject<'_>,
runtime_handle: &R::Handle,
plugin_name: &'static str,
plugin_class: String,
plugin_config: &serde_json::Value,
) -> Result<(), JniError> {
// instantiate plugin
let plugin_class = runtime_handle.find_class(env, activity, plugin_class)?;
let plugin = env.new_object(
plugin_class,
"(Landroid/app/Activity;)V",
&[activity.into()],
)?;
// load plugin
let plugin_manager = env
.call_method(
activity,
"getPluginManager",
"()Lapp/tauri/plugin/PluginManager;",
&[],
)?
.l()?;
let plugin_name = env.new_string(plugin_name)?;
let config = env.new_string(&serde_json::to_string(plugin_config).unwrap())?;
env.call_method(
plugin_manager,
"load",
"(Landroid/webkit/WebView;Ljava/lang/String;Lapp/tauri/plugin/Plugin;Ljava/lang/String;)V",
&[
webview.into(),
(&plugin_name).into(),
(&plugin).into(),
(&config).into(),
],
)?;
Ok(())
}
let plugin_class = format!("{}/{}", plugin_identifier.replace('.', "/"), class_name);
let plugin_name = self.name;
let plugin_config = self.raw_config.clone();
let runtime_handle = self.handle.runtime_handle.clone();
let (tx, rx) = channel();
self
.handle
.runtime_handle
.run_on_android_context(move |env, activity, webview| {
let result = initialize_plugin::<R>(
env,
activity,
webview,
&runtime_handle,
plugin_name,
plugin_class,
&plugin_config,
);
tx.send(result).unwrap();
});
rx.recv().unwrap()?;
Ok(PluginHandle {
name: self.name,
handle: self.handle.clone(),
})
}
}
impl<R: Runtime> PluginHandle<R> {
/// Executes the given mobile command.
/// This is an async optimized variant of run_mobile_plugin
pub async fn run_mobile_plugin_async<T: DeserializeOwned>(
&self,
command: impl AsRef<str>,
payload: impl Serialize,
) -> Result<T, PluginInvokeError> {
let (tx, rx) = oneshot::channel();
// the closure is an FnOnce but on Android we need to clone it (error handling)
let tx = std::sync::Arc::new(std::sync::Mutex::new(Some(tx)));
run_command(
self.name,
&self.handle,
command,
serde_json::to_value(payload).map_err(PluginInvokeError::CannotSerializePayload)?,
move |response| {
tx.lock().unwrap().take().unwrap().send(response).unwrap();
},
)?;
let response = rx.await.unwrap();
match response {
Ok(r) => serde_json::from_value(r).map_err(PluginInvokeError::CannotDeserializeResponse),
Err(r) => Err(
serde_json::from_value::<ErrorResponse>(r)
.map(Into::into)
.map_err(PluginInvokeError::CannotDeserializeResponse)?,
),
}
}
/// Executes the given mobile command.
pub fn run_mobile_plugin<T: DeserializeOwned>(
&self,
command: impl AsRef<str>,
payload: impl Serialize,
) -> Result<T, PluginInvokeError> {
let (tx, rx) = channel();
run_command(
self.name,
&self.handle,
command,
serde_json::to_value(payload).map_err(PluginInvokeError::CannotSerializePayload)?,
move |response| {
tx.send(response).unwrap();
},
)?;
let response = rx.recv().unwrap();
match response {
Ok(r) => serde_json::from_value(r).map_err(PluginInvokeError::CannotDeserializeResponse),
Err(r) => Err(
serde_json::from_value::<ErrorResponse>(r)
.map(Into::into)
.map_err(PluginInvokeError::CannotDeserializeResponse)?,
),
}
}
}
#[cfg(target_os = "ios")]
pub(crate) fn run_command<R: Runtime, C: AsRef<str>, F: FnOnce(PluginResponse) + Send + 'static>(
name: &str,
_handle: &AppHandle<R>,
command: C,
payload: serde_json::Value,
handler: F,
) -> Result<(), PluginInvokeError> {
use std::{
ffi::CStr,
os::raw::{c_char, c_int, c_ulonglong},
};
let id: i32 = PENDING_PLUGIN_CALLS_ID.fetch_add(1, Ordering::Relaxed);
PENDING_PLUGIN_CALLS
.get_or_init(Default::default)
.lock()
.unwrap()
.insert(id, Box::new(handler));
unsafe {
extern "C" fn plugin_command_response_handler(
id: c_int,
success: c_int,
payload: *const c_char,
) {
let payload = unsafe {
assert!(!payload.is_null());
CStr::from_ptr(payload)
};
if let Some(handler) = PENDING_PLUGIN_CALLS
.get_or_init(Default::default)
.lock()
.unwrap()
.remove(&id)
{
let json = payload.to_str().unwrap();
match serde_json::from_str(json) {
Ok(payload) => {
handler(if success == 1 {
Ok(payload)
} else {
Err(payload)
});
}
Err(err) => {
handler(Err(format!("{err}, data: {}", json).into()));
}
}
}
}
extern "C" fn send_channel_data_handler(id: c_ulonglong, payload: *const c_char) {
let payload = unsafe {
assert!(!payload.is_null());
CStr::from_ptr(payload)
};
if let Some(channel) = CHANNELS
.get_or_init(Default::default)
.lock()
.unwrap()
.get(&(id as u32))
{
let payload: serde_json::Value = serde_json::from_str(payload.to_str().unwrap()).unwrap();
let _ = channel.send(payload);
}
}
crate::ios::run_plugin_command(
id,
&name.into(),
&command.as_ref().into(),
&serde_json::to_string(&payload).unwrap().as_str().into(),
crate::ios::PluginMessageCallback(plugin_command_response_handler),
crate::ios::ChannelSendDataCallback(send_channel_data_handler),
);
}
Ok(())
}
#[cfg(target_os = "android")]
pub(crate) fn run_command<
R: Runtime,
C: AsRef<str>,
F: FnOnce(PluginResponse) + Send + Clone + 'static,
>(
name: &str,
handle: &AppHandle<R>,
command: C,
payload: serde_json::Value,
handler: F,
) -> Result<(), PluginInvokeError> {
use jni::{errors::Error as JniError, objects::JObject, JNIEnv};
fn run<R: Runtime>(
id: i32,
plugin: &str,
command: String,
payload: &serde_json::Value,
env: &mut JNIEnv<'_>,
activity: &JObject<'_>,
) -> Result<(), JniError> {
let plugin = env.new_string(plugin)?;
let command = env.new_string(&command)?;
let data = env.new_string(&serde_json::to_string(payload).unwrap())?;
let plugin_manager = env
.call_method(
activity,
"getPluginManager",
"()Lapp/tauri/plugin/PluginManager;",
&[],
)?
.l()?;
env.call_method(
plugin_manager,
"runCommand",
"(ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;)V",
&[
id.into(),
(&plugin).into(),
(&command).into(),
(&data).into(),
],
)?;
Ok(())
}
let handle = match handle.runtime() {
RuntimeOrDispatch::Runtime(r) => r.handle(),
RuntimeOrDispatch::RuntimeHandle(h) => h,
_ => unreachable!(),
};
let id: i32 = PENDING_PLUGIN_CALLS_ID.fetch_add(1, Ordering::Relaxed);
let plugin_name = name.to_string();
let command = command.as_ref().to_string();
PENDING_PLUGIN_CALLS
.get_or_init(Default::default)
.lock()
.unwrap()
.insert(id, Box::new(handler.clone()));
handle.run_on_android_context(move |env, activity, _webview| {
if let Err(e) = run::<R>(id, &plugin_name, command, &payload, env, activity) {
handler(Err(e.to_string().into()));
}
});
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/tray/mod.rs | crates/tauri/src/tray/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Tray icon types and utilities.
pub(crate) mod plugin;
use crate::app::{GlobalMenuEventListener, GlobalTrayIconEventListener};
use crate::menu::ContextMenu;
use crate::menu::MenuEvent;
use crate::resources::Resource;
use crate::{
image::Image, menu::run_item_main_thread, AppHandle, Manager, PhysicalPosition, Rect, Runtime,
};
use crate::{ResourceId, UnsafeSend};
use serde::Serialize;
use std::path::Path;
pub use tray_icon::TrayIconId;
/// Describes the mouse button state.
#[derive(Default, Clone, Copy, PartialEq, Eq, Debug, Serialize)]
pub enum MouseButtonState {
/// Mouse button pressed.
#[default]
Up,
/// Mouse button released.
Down,
}
impl From<tray_icon::MouseButtonState> for MouseButtonState {
fn from(value: tray_icon::MouseButtonState) -> Self {
match value {
tray_icon::MouseButtonState::Up => MouseButtonState::Up,
tray_icon::MouseButtonState::Down => MouseButtonState::Down,
}
}
}
/// Describes which mouse button triggered the event..
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Default)]
pub enum MouseButton {
/// Left mouse button.
#[default]
Left,
/// Right mouse button.
Right,
/// Middle mouse button.
Middle,
}
impl From<tray_icon::MouseButton> for MouseButton {
fn from(value: tray_icon::MouseButton) -> Self {
match value {
tray_icon::MouseButton::Left => MouseButton::Left,
tray_icon::MouseButton::Right => MouseButton::Right,
tray_icon::MouseButton::Middle => MouseButton::Middle,
}
}
}
/// Describes a tray icon event.
///
/// ## Platform-specific:
///
/// - **Linux**: Unsupported. The event is not emitted even though the icon is shown
/// and will still show a context menu on right click.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type")]
#[non_exhaustive]
pub enum TrayIconEvent {
/// A click happened on the tray icon.
#[serde(rename_all = "camelCase")]
Click {
/// Id of the tray icon which triggered this event.
id: TrayIconId,
/// Physical Position of this event.
position: PhysicalPosition<f64>,
/// Position and size of the tray icon.
rect: Rect,
/// Mouse button that triggered this event.
button: MouseButton,
/// Mouse button state when this event was triggered.
button_state: MouseButtonState,
},
/// A double click happened on the tray icon. **Windows Only**
DoubleClick {
/// Id of the tray icon which triggered this event.
id: TrayIconId,
/// Physical Position of this event.
position: PhysicalPosition<f64>,
/// Position and size of the tray icon.
rect: Rect,
/// Mouse button that triggered this event.
button: MouseButton,
},
/// The mouse entered the tray icon region.
Enter {
/// Id of the tray icon which triggered this event.
id: TrayIconId,
/// Physical Position of this event.
position: PhysicalPosition<f64>,
/// Position and size of the tray icon.
rect: Rect,
},
/// The mouse moved over the tray icon region.
Move {
/// Id of the tray icon which triggered this event.
id: TrayIconId,
/// Physical Position of this event.
position: PhysicalPosition<f64>,
/// Position and size of the tray icon.
rect: Rect,
},
/// The mouse left the tray icon region.
Leave {
/// Id of the tray icon which triggered this event.
id: TrayIconId,
/// Physical Position of this event.
position: PhysicalPosition<f64>,
/// Position and size of the tray icon.
rect: Rect,
},
}
impl TrayIconEvent {
/// Get the id of the tray icon that triggered this event.
pub fn id(&self) -> &TrayIconId {
match self {
TrayIconEvent::Click { id, .. } => id,
TrayIconEvent::DoubleClick { id, .. } => id,
TrayIconEvent::Enter { id, .. } => id,
TrayIconEvent::Move { id, .. } => id,
TrayIconEvent::Leave { id, .. } => id,
}
}
}
impl From<tray_icon::TrayIconEvent> for TrayIconEvent {
fn from(value: tray_icon::TrayIconEvent) -> Self {
match value {
tray_icon::TrayIconEvent::Click {
id,
position,
rect,
button,
button_state,
} => TrayIconEvent::Click {
id,
position,
rect: Rect {
position: rect.position.into(),
size: rect.size.into(),
},
button: button.into(),
button_state: button_state.into(),
},
tray_icon::TrayIconEvent::DoubleClick {
id,
position,
rect,
button,
} => TrayIconEvent::DoubleClick {
id,
position,
rect: Rect {
position: rect.position.into(),
size: rect.size.into(),
},
button: button.into(),
},
tray_icon::TrayIconEvent::Enter { id, position, rect } => TrayIconEvent::Enter {
id,
position,
rect: Rect {
position: rect.position.into(),
size: rect.size.into(),
},
},
tray_icon::TrayIconEvent::Move { id, position, rect } => TrayIconEvent::Move {
id,
position,
rect: Rect {
position: rect.position.into(),
size: rect.size.into(),
},
},
tray_icon::TrayIconEvent::Leave { id, position, rect } => TrayIconEvent::Leave {
id,
position,
rect: Rect {
position: rect.position.into(),
size: rect.size.into(),
},
},
_ => todo!(),
}
}
}
/// [`TrayIcon`] builder struct and associated methods.
#[derive(Default)]
pub struct TrayIconBuilder<R: Runtime> {
on_menu_event: Option<GlobalMenuEventListener<AppHandle<R>>>,
on_tray_icon_event: Option<GlobalTrayIconEventListener<TrayIcon<R>>>,
inner: tray_icon::TrayIconBuilder,
}
impl<R: Runtime> TrayIconBuilder<R> {
/// Creates a new tray icon builder.
///
/// ## Platform-specific:
///
/// - **Linux:** Sometimes the icon won't be visible unless a menu is set.
/// Setting an empty [`Menu`](crate::menu::Menu) is enough.
pub fn new() -> Self {
Self {
inner: tray_icon::TrayIconBuilder::new(),
on_menu_event: None,
on_tray_icon_event: None,
}
}
/// Creates a new tray icon builder with the specified id.
///
/// ## Platform-specific:
///
/// - **Linux:** Sometimes the icon won't be visible unless a menu is set.
/// Setting an empty [`Menu`](crate::menu::Menu) is enough.
pub fn with_id<I: Into<TrayIconId>>(id: I) -> Self {
let mut builder = Self::new();
builder.inner = builder.inner.with_id(id);
builder
}
/// Set the a menu for this tray icon.
///
/// ## Platform-specific:
///
/// - **Linux**: once a menu is set, it cannot be removed or replaced but you can change its content.
pub fn menu<M: ContextMenu>(mut self, menu: &M) -> Self {
self.inner = self.inner.with_menu(menu.inner_context_owned());
self
}
/// Set an icon for this tray icon.
///
/// ## Platform-specific:
///
/// - **Linux:** Sometimes the icon won't be visible unless a menu is set.
/// Setting an empty [`Menu`](crate::menu::Menu) is enough.
pub fn icon(mut self, icon: Image<'_>) -> Self {
let icon = icon.try_into().ok();
if let Some(icon) = icon {
self.inner = self.inner.with_icon(icon);
}
self
}
/// Set a tooltip for this tray icon.
///
/// ## Platform-specific:
///
/// - **Linux:** Unsupported.
pub fn tooltip<S: AsRef<str>>(mut self, s: S) -> Self {
self.inner = self.inner.with_tooltip(s);
self
}
/// Set the tray icon title.
///
/// ## Platform-specific
///
/// - **Linux:** The title will not be shown unless there is an icon
/// as well. The title is useful for numerical and other frequently
/// updated information. In general, it shouldn't be shown unless a
/// user requests it as it can take up a significant amount of space
/// on the user's panel. This may not be shown in all visualizations.
/// - **Windows:** Unsupported.
pub fn title<S: AsRef<str>>(mut self, title: S) -> Self {
self.inner = self.inner.with_title(title);
self
}
/// Set tray icon temp dir path. **Linux only**.
///
/// On Linux, we need to write the icon to the disk and usually it will
/// be `$XDG_RUNTIME_DIR/tray-icon` or `$TEMP/tray-icon`.
pub fn temp_dir_path<P: AsRef<Path>>(mut self, s: P) -> Self {
self.inner = self.inner.with_temp_dir_path(s);
self
}
/// Use the icon as a [template](https://developer.apple.com/documentation/appkit/nsimage/1520017-template?language=objc). **macOS only**.
pub fn icon_as_template(mut self, is_template: bool) -> Self {
self.inner = self.inner.with_icon_as_template(is_template);
self
}
/// Whether to show the tray menu on left click or not, default is `true`.
///
/// ## Platform-specific:
///
/// - **Linux:** Unsupported.
#[deprecated(
since = "2.2.0",
note = "Use `TrayIconBuilder::show_menu_on_left_click` instead."
)]
pub fn menu_on_left_click(mut self, enable: bool) -> Self {
self.inner = self.inner.with_menu_on_left_click(enable);
self
}
/// Whether to show the tray menu on left click or not, default is `true`.
///
/// ## Platform-specific:
///
/// - **Linux:** Unsupported.
pub fn show_menu_on_left_click(mut self, enable: bool) -> Self {
self.inner = self.inner.with_menu_on_left_click(enable);
self
}
/// Set a handler for menu events.
///
/// Note that this handler is called for any menu event,
/// whether it is coming from this window, another window or from the tray icon menu.
pub fn on_menu_event<F: Fn(&AppHandle<R>, MenuEvent) + Sync + Send + 'static>(
mut self,
f: F,
) -> Self {
self.on_menu_event.replace(Box::new(f));
self
}
/// Set a handler for this tray icon events.
pub fn on_tray_icon_event<F: Fn(&TrayIcon<R>, TrayIconEvent) + Sync + Send + 'static>(
mut self,
f: F,
) -> Self {
self.on_tray_icon_event.replace(Box::new(f));
self
}
/// Access the unique id that will be assigned to the tray icon
/// this builder will create.
pub fn id(&self) -> &TrayIconId {
self.inner.id()
}
pub(crate) fn build_inner(
self,
app_handle: &AppHandle<R>,
) -> crate::Result<(TrayIcon<R>, ResourceId)> {
let id = self.id().clone();
// SAFETY:
// the menu within this builder was created on main thread
// and will be accessed on the main thread
let unsafe_builder = UnsafeSend(self.inner);
let (tx, rx) = std::sync::mpsc::channel();
let unsafe_tray = app_handle
.run_on_main_thread(move || {
// SAFETY: will only be accessed on main thread
let _ = tx.send(unsafe_builder.take().build().map(UnsafeSend));
})
.and_then(|_| rx.recv().map_err(|_| crate::Error::FailedToReceiveMessage))??;
let icon = TrayIcon {
id,
inner: unsafe_tray.take(),
app_handle: app_handle.clone(),
};
let rid = icon.register(
&icon.app_handle,
self.on_menu_event,
self.on_tray_icon_event,
);
Ok((icon, rid))
}
/// Builds and adds a new [`TrayIcon`] to the system tray.
pub fn build<M: Manager<R>>(self, manager: &M) -> crate::Result<TrayIcon<R>> {
let (icon, _rid) = self.build_inner(manager.app_handle())?;
Ok(icon)
}
}
/// Tray icon struct and associated methods.
///
/// This type is reference-counted and the icon is removed when the last instance is dropped.
///
/// See [TrayIconBuilder] to construct this type.
#[tauri_macros::default_runtime(crate::Wry, wry)]
pub struct TrayIcon<R: Runtime> {
id: TrayIconId,
inner: tray_icon::TrayIcon,
app_handle: AppHandle<R>,
}
impl<R: Runtime> Clone for TrayIcon<R> {
fn clone(&self) -> Self {
Self {
id: self.id.clone(),
inner: self.inner.clone(),
app_handle: self.app_handle.clone(),
}
}
}
/// # Safety
///
/// We make sure it always runs on the main thread.
unsafe impl<R: Runtime> Sync for TrayIcon<R> {}
unsafe impl<R: Runtime> Send for TrayIcon<R> {}
impl<R: Runtime> TrayIcon<R> {
fn register(
&self,
app_handle: &AppHandle<R>,
on_menu_event: Option<GlobalMenuEventListener<AppHandle<R>>>,
on_tray_icon_event: Option<GlobalTrayIconEventListener<TrayIcon<R>>>,
) -> ResourceId {
if let Some(handler) = on_menu_event {
app_handle
.manager
.menu
.global_event_listeners
.lock()
.unwrap()
.push(handler);
}
if let Some(handler) = on_tray_icon_event {
app_handle
.manager
.tray
.event_listeners
.lock()
.unwrap()
.insert(self.id.clone(), handler);
}
let rid = app_handle.resources_table().add(self.clone());
app_handle
.manager
.tray
.icons
.lock()
.unwrap()
.push((self.id().clone(), rid));
rid
}
/// The application handle associated with this type.
pub fn app_handle(&self) -> &AppHandle<R> {
&self.app_handle
}
/// Register a handler for menu events.
///
/// Note that this handler is called for any menu event,
/// whether it is coming from this window, another window or from the tray icon menu.
pub fn on_menu_event<F: Fn(&AppHandle<R>, MenuEvent) + Sync + Send + 'static>(&self, f: F) {
self
.app_handle
.manager
.menu
.global_event_listeners
.lock()
.unwrap()
.push(Box::new(f));
}
/// Register a handler for this tray icon events.
pub fn on_tray_icon_event<F: Fn(&TrayIcon<R>, TrayIconEvent) + Sync + Send + 'static>(
&self,
f: F,
) {
self
.app_handle
.manager
.tray
.event_listeners
.lock()
.unwrap()
.insert(self.id.clone(), Box::new(f));
}
/// Returns the id associated with this tray icon.
pub fn id(&self) -> &TrayIconId {
&self.id
}
/// Sets a new tray icon. If `None` is provided, it will remove the icon.
pub fn set_icon(&self, icon: Option<Image<'_>>) -> crate::Result<()> {
let icon = match icon {
Some(i) => Some(i.try_into()?),
None => None,
};
run_item_main_thread!(self, |self_: Self| self_.inner.set_icon(icon))?.map_err(Into::into)
}
/// Sets a new tray menu.
///
/// ## Platform-specific:
///
/// - **Linux**: once a menu is set it cannot be removed so `None` has no effect
pub fn set_menu<M: ContextMenu + 'static>(&self, menu: Option<M>) -> crate::Result<()> {
run_item_main_thread!(self, |self_: Self| {
self_.inner.set_menu(menu.map(|m| m.inner_context_owned()))
})
}
/// Sets the tooltip for this tray icon.
///
/// ## Platform-specific:
///
/// - **Linux:** Unsupported
pub fn set_tooltip<S: AsRef<str>>(&self, tooltip: Option<S>) -> crate::Result<()> {
let s = tooltip.map(|s| s.as_ref().to_string());
run_item_main_thread!(self, |self_: Self| self_.inner.set_tooltip(s))?.map_err(Into::into)
}
/// Sets the title for this tray icon.
///
/// ## Platform-specific:
///
/// - **Linux:** The title will not be shown unless there is an icon
/// as well. The title is useful for numerical and other frequently
/// updated information. In general, it shouldn't be shown unless a
/// user requests it as it can take up a significant amount of space
/// on the user's panel. This may not be shown in all visualizations.
/// - **Windows:** Unsupported
pub fn set_title<S: AsRef<str>>(&self, title: Option<S>) -> crate::Result<()> {
let s = title.map(|s| s.as_ref().to_string());
run_item_main_thread!(self, |self_: Self| self_.inner.set_title(s))
}
/// Show or hide this tray icon.
pub fn set_visible(&self, visible: bool) -> crate::Result<()> {
run_item_main_thread!(self, |self_: Self| self_.inner.set_visible(visible))?.map_err(Into::into)
}
/// Sets the tray icon temp dir path. **Linux only**.
///
/// On Linux, we need to write the icon to the disk and usually it will
/// be `$XDG_RUNTIME_DIR/tray-icon` or `$TEMP/tray-icon`.
pub fn set_temp_dir_path<P: AsRef<Path>>(&self, path: Option<P>) -> crate::Result<()> {
#[allow(unused)]
let p = path.map(|p| p.as_ref().to_path_buf());
#[cfg(target_os = "linux")]
run_item_main_thread!(self, |self_: Self| self_.inner.set_temp_dir_path(p))?;
Ok(())
}
/// Sets the current icon as a [template](https://developer.apple.com/documentation/appkit/nsimage/1520017-template?language=objc). **macOS only**.
pub fn set_icon_as_template(&self, #[allow(unused)] is_template: bool) -> crate::Result<()> {
#[cfg(target_os = "macos")]
run_item_main_thread!(self, |self_: Self| {
self_.inner.set_icon_as_template(is_template)
})?;
Ok(())
}
/// Disable or enable showing the tray menu on left click.
///
///
/// ## Platform-specific:
///
/// - **Linux**: Unsupported.
pub fn set_show_menu_on_left_click(&self, #[allow(unused)] enable: bool) -> crate::Result<()> {
#[cfg(any(target_os = "macos", windows))]
run_item_main_thread!(self, |self_: Self| {
self_.inner.set_show_menu_on_left_click(enable)
})?;
Ok(())
}
/// Get tray icon rect.
///
/// ## Platform-specific:
///
/// - **Linux**: Unsupported, always returns `None`.
pub fn rect(&self) -> crate::Result<Option<crate::Rect>> {
run_item_main_thread!(self, |self_: Self| {
self_.inner.rect().map(|rect| Rect {
position: rect.position.into(),
size: rect.size.into(),
})
})
}
/// Do something with the inner [`tray_icon::TrayIcon`] on main thread
///
/// Note that `tray-icon` crate may be updated in minor releases of Tauri.
/// Therefore, it’s recommended to pin Tauri to at least a minor version when you’re using `with_inner_tray_icon`.
pub fn with_inner_tray_icon<F, T>(&self, f: F) -> crate::Result<T>
where
F: FnOnce(&tray_icon::TrayIcon) -> T + Send + 'static,
T: Send + 'static,
{
run_item_main_thread!(self, |self_: Self| { f(&self_.inner) })
}
}
impl<R: Runtime> Resource for TrayIcon<R> {
fn close(self: std::sync::Arc<Self>) {
let mut icons = self.app_handle.manager.tray.icons.lock().unwrap();
for (i, (tray_icon_id, _rid)) in icons.iter_mut().enumerate() {
if tray_icon_id == &self.id {
icons.swap_remove(i);
return;
}
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn tray_event_json_serialization() {
// NOTE: if this test is ever changed, you probably need to change `TrayIconEvent` in JS as well
use super::*;
let event = TrayIconEvent::Click {
button: MouseButton::Left,
button_state: MouseButtonState::Down,
id: TrayIconId::new("id"),
position: crate::PhysicalPosition::default(),
rect: crate::Rect {
position: tray_icon::Rect::default().position.into(),
size: tray_icon::Rect::default().size.into(),
},
};
let value = serde_json::to_value(&event).unwrap();
assert_eq!(
value,
serde_json::json!({
"type": "Click",
"button": "Left",
"buttonState": "Down",
"id": "id",
"position": {
"x": 0.0,
"y": 0.0,
},
"rect": {
"size": {
"Physical": {
"width": 0,
"height": 0,
}
},
"position": {
"Physical": {
"x": 0,
"y": 0,
}
},
}
})
);
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/tray/plugin.rs | crates/tauri/src/tray/plugin.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::path::PathBuf;
use anyhow::Context;
use serde::Deserialize;
use crate::{
command,
image::JsImage,
ipc::Channel,
menu::{plugin::ItemKind, Menu, Submenu},
plugin::{Builder, TauriPlugin},
resources::ResourceId,
tray::TrayIconBuilder,
AppHandle, Manager, Runtime, Webview,
};
use super::{TrayIcon, TrayIconEvent};
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct TrayIconOptions {
id: Option<String>,
menu: Option<(ResourceId, ItemKind)>,
icon: Option<JsImage>,
tooltip: Option<String>,
title: Option<String>,
temp_dir_path: Option<PathBuf>,
icon_as_template: Option<bool>,
menu_on_left_click: Option<bool>,
show_menu_on_left_click: Option<bool>,
}
#[command(root = "crate")]
fn new<R: Runtime>(
webview: Webview<R>,
options: TrayIconOptions,
handler: Channel<TrayIconEvent>,
) -> crate::Result<(ResourceId, String)> {
let mut builder = if let Some(id) = options.id {
TrayIconBuilder::<R>::with_id(id)
} else {
TrayIconBuilder::<R>::new()
};
builder = builder.on_tray_icon_event(move |_tray, e| {
let _ = handler.send(e);
});
let resources_table = webview.resources_table();
if let Some((rid, kind)) = options.menu {
match kind {
ItemKind::Menu => {
let menu = resources_table.get::<Menu<R>>(rid)?;
builder = builder.menu(&*menu);
}
ItemKind::Submenu => {
let submenu = resources_table.get::<Submenu<R>>(rid)?;
builder = builder.menu(&*submenu);
}
_ => return Err(anyhow::anyhow!("unexpected menu item kind").into()),
};
}
if let Some(icon) = options.icon {
builder = builder.icon(icon.into_img(&resources_table)?.as_ref().clone());
}
if let Some(tooltip) = options.tooltip {
builder = builder.tooltip(tooltip);
}
if let Some(title) = options.title {
builder = builder.title(title);
}
if let Some(temp_dir_path) = options.temp_dir_path {
builder = builder.temp_dir_path(temp_dir_path);
}
if let Some(icon_as_template) = options.icon_as_template {
builder = builder.icon_as_template(icon_as_template);
}
#[allow(deprecated)]
if let Some(menu_on_left_click) = options.menu_on_left_click {
builder = builder.menu_on_left_click(menu_on_left_click);
}
if let Some(show_menu_on_left_click) = options.show_menu_on_left_click {
builder = builder.show_menu_on_left_click(show_menu_on_left_click);
}
let (tray, rid) = builder.build_inner(webview.app_handle())?;
let id = tray.id().as_ref().to_string();
Ok((rid, id))
}
#[command(root = "crate")]
fn get_by_id<R: Runtime>(app: AppHandle<R>, id: &str) -> Option<ResourceId> {
app.manager.tray.tray_resource_by_id(id)
}
#[command(root = "crate")]
fn remove_by_id<R: Runtime>(app: AppHandle<R>, id: &str) -> crate::Result<()> {
app
.remove_tray_by_id(id)
.with_context(|| format!("Can't find a tray associated with this id: {id}"))?;
Ok(())
}
#[command(root = "crate")]
fn set_icon<R: Runtime>(
app: AppHandle<R>,
webview: Webview<R>,
rid: ResourceId,
icon: Option<JsImage>,
) -> crate::Result<()> {
let resources_table = app.resources_table();
let tray = resources_table.get::<TrayIcon<R>>(rid)?;
let webview_resources_table = webview.resources_table();
let icon = match icon {
Some(i) => Some(i.into_img(&webview_resources_table)?.as_ref().clone()),
None => None,
};
tray.set_icon(icon)
}
#[command(root = "crate")]
fn set_menu<R: Runtime>(
app: AppHandle<R>,
webview: Webview<R>,
rid: ResourceId,
menu: Option<(ResourceId, ItemKind)>,
) -> crate::Result<()> {
let resources_table = app.resources_table();
let tray = resources_table.get::<TrayIcon<R>>(rid)?;
if let Some((rid, kind)) = menu {
let webview_resources_table = webview.resources_table();
match kind {
ItemKind::Menu => {
let menu = webview_resources_table.get::<Menu<R>>(rid)?;
tray.set_menu(Some((*menu).clone()))?;
}
ItemKind::Submenu => {
let submenu = webview_resources_table.get::<Submenu<R>>(rid)?;
tray.set_menu(Some((*submenu).clone()))?;
}
_ => return Err(anyhow::anyhow!("unexpected menu item kind").into()),
};
} else {
tray.set_menu(None::<Menu<R>>)?;
}
Ok(())
}
#[command(root = "crate")]
fn set_tooltip<R: Runtime>(
app: AppHandle<R>,
rid: ResourceId,
tooltip: Option<String>,
) -> crate::Result<()> {
let resources_table = app.resources_table();
let tray = resources_table.get::<TrayIcon<R>>(rid)?;
tray.set_tooltip(tooltip)
}
#[command(root = "crate")]
fn set_title<R: Runtime>(
app: AppHandle<R>,
rid: ResourceId,
title: Option<String>,
) -> crate::Result<()> {
let resources_table = app.resources_table();
let tray = resources_table.get::<TrayIcon<R>>(rid)?;
tray.set_title(title)
}
#[command(root = "crate")]
fn set_visible<R: Runtime>(app: AppHandle<R>, rid: ResourceId, visible: bool) -> crate::Result<()> {
let resources_table = app.resources_table();
let tray = resources_table.get::<TrayIcon<R>>(rid)?;
tray.set_visible(visible)
}
#[command(root = "crate")]
fn set_temp_dir_path<R: Runtime>(
app: AppHandle<R>,
rid: ResourceId,
path: Option<PathBuf>,
) -> crate::Result<()> {
let resources_table = app.resources_table();
let tray = resources_table.get::<TrayIcon<R>>(rid)?;
tray.set_temp_dir_path(path)
}
#[command(root = "crate")]
fn set_icon_as_template<R: Runtime>(
app: AppHandle<R>,
rid: ResourceId,
as_template: bool,
) -> crate::Result<()> {
let resources_table = app.resources_table();
let tray = resources_table.get::<TrayIcon<R>>(rid)?;
tray.set_icon_as_template(as_template)
}
#[command(root = "crate")]
fn set_show_menu_on_left_click<R: Runtime>(
app: AppHandle<R>,
rid: ResourceId,
on_left: bool,
) -> crate::Result<()> {
let resources_table = app.resources_table();
let tray = resources_table.get::<TrayIcon<R>>(rid)?;
tray.set_show_menu_on_left_click(on_left)
}
pub(crate) fn init<R: Runtime>() -> TauriPlugin<R> {
Builder::new("tray")
.invoke_handler(crate::generate_handler![
#![plugin(tray)]
new,
get_by_id,
remove_by_id,
set_icon,
set_menu,
set_tooltip,
set_title,
set_visible,
set_temp_dir_path,
set_icon_as_template,
set_show_menu_on_left_click,
])
.build()
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/image/mod.rs | crates/tauri/src/image/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Image types used by this crate and also referenced by the JavaScript API layer.
pub(crate) mod plugin;
use std::borrow::Cow;
use std::sync::Arc;
use crate::{Resource, ResourceId, ResourceTable};
/// An RGBA Image in row-major order from top to bottom.
#[derive(Clone)]
pub struct Image<'a> {
rgba: Cow<'a, [u8]>,
width: u32,
height: u32,
}
impl std::fmt::Debug for Image<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Image")
.field(
"rgba",
// Reduces the debug size compared to the derived default, as the default
// would format the raw bytes as numbers `[0, 0, 0, 0]` for 1 pixel.
// The custom format doesn't grow as much with larger images:
// `Image { rgba: Cow::Borrowed([u8; 4096]), width: 32, height: 32 }`
&format_args!(
"Cow::{}([u8; {}])",
match &self.rgba {
Cow::Borrowed(_) => "Borrowed",
Cow::Owned(_) => "Owned",
},
self.rgba.len()
),
)
.field("width", &self.width)
.field("height", &self.height)
.finish()
}
}
impl Resource for Image<'static> {}
impl Image<'static> {
/// Creates a new Image using RGBA data, in row-major order from top to bottom, and with specified width and height.
///
/// Similar to [`Self::new`] but avoids cloning the rgba data to get an owned Image.
pub const fn new_owned(rgba: Vec<u8>, width: u32, height: u32) -> Self {
Self {
rgba: Cow::Owned(rgba),
width,
height,
}
}
}
impl<'a> Image<'a> {
/// Creates a new Image using RGBA data, in row-major order from top to bottom, and with specified width and height.
pub const fn new(rgba: &'a [u8], width: u32, height: u32) -> Self {
Self {
rgba: Cow::Borrowed(rgba),
width,
height,
}
}
/// Creates a new image using the provided bytes.
///
/// Only `ico` and `png` are supported (based on activated feature flag).
#[cfg(any(feature = "image-ico", feature = "image-png"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "image-ico", feature = "image-png"))))]
pub fn from_bytes(bytes: &[u8]) -> crate::Result<Self> {
use image::GenericImageView;
let img = image::load_from_memory(bytes)?;
let pixels = img
.pixels()
.flat_map(|(_, _, pixel)| pixel.0)
.collect::<Vec<_>>();
Ok(Self {
rgba: Cow::Owned(pixels),
width: img.width(),
height: img.height(),
})
}
/// Creates a new image using the provided path.
///
/// Only `ico` and `png` are supported (based on activated feature flag).
#[cfg(any(feature = "image-ico", feature = "image-png"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "image-ico", feature = "image-png"))))]
pub fn from_path<P: AsRef<std::path::Path>>(path: P) -> crate::Result<Self> {
let bytes = std::fs::read(path)?;
Self::from_bytes(&bytes)
}
/// Returns the RGBA data for this image, in row-major order from top to bottom.
pub fn rgba(&'a self) -> &'a [u8] {
&self.rgba
}
/// Returns the width of this image.
pub fn width(&self) -> u32 {
self.width
}
/// Returns the height of this image.
pub fn height(&self) -> u32 {
self.height
}
/// Convert into a 'static owned [`Image`].
/// This will allocate.
pub fn to_owned(self) -> Image<'static> {
Image {
rgba: match self.rgba {
Cow::Owned(v) => Cow::Owned(v),
Cow::Borrowed(v) => Cow::Owned(v.to_vec()),
},
height: self.height,
width: self.width,
}
}
}
impl<'a> From<Image<'a>> for crate::runtime::Icon<'a> {
fn from(img: Image<'a>) -> Self {
Self {
rgba: img.rgba,
width: img.width,
height: img.height,
}
}
}
#[cfg(desktop)]
impl TryFrom<Image<'_>> for muda::Icon {
type Error = crate::Error;
fn try_from(img: Image<'_>) -> Result<Self, Self::Error> {
muda::Icon::from_rgba(img.rgba.to_vec(), img.width, img.height).map_err(Into::into)
}
}
#[cfg(all(desktop, feature = "tray-icon"))]
impl TryFrom<Image<'_>> for tray_icon::Icon {
type Error = crate::Error;
fn try_from(img: Image<'_>) -> Result<Self, Self::Error> {
tray_icon::Icon::from_rgba(img.rgba.to_vec(), img.width, img.height).map_err(Into::into)
}
}
/// An image type that accepts file paths, raw bytes, previously loaded images and image objects.
///
/// This type is meant to be used along the [transformImage](https://v2.tauri.app/reference/javascript/api/namespaceimage/#transformimage) API.
///
/// # Stability
///
/// The stability of the variants are not guaranteed, and matching against them is not recommended.
/// Use [`JsImage::into_img`] instead.
#[derive(serde::Deserialize)]
#[serde(untagged)]
#[non_exhaustive]
pub enum JsImage {
/// A reference to a image in the filesystem.
#[non_exhaustive]
Path(std::path::PathBuf),
/// Image from raw bytes.
#[non_exhaustive]
Bytes(Vec<u8>),
/// An image that was previously loaded with the API and is stored in the resource table.
#[non_exhaustive]
Resource(ResourceId),
/// Raw RGBA definition of an image.
#[non_exhaustive]
Rgba {
/// Image bytes.
rgba: Vec<u8>,
/// Image width.
width: u32,
/// Image height.
height: u32,
},
}
impl JsImage {
/// Converts this intermediate image format into an actual [`Image`].
///
/// This will retrieve the image from the passed [`ResourceTable`] if it is [`JsImage::Resource`]
/// and will return an error if it doesn't exist in the passed [`ResourceTable`] so make sure
/// the passed [`ResourceTable`] is the same one used to store the image, usually this should be
/// the webview [resources table](crate::webview::Webview::resources_table).
pub fn into_img(self, resources_table: &ResourceTable) -> crate::Result<Arc<Image<'_>>> {
match self {
Self::Resource(rid) => resources_table.get::<Image<'static>>(rid),
#[cfg(any(feature = "image-ico", feature = "image-png"))]
Self::Path(path) => Image::from_path(path).map(Arc::new),
#[cfg(any(feature = "image-ico", feature = "image-png"))]
Self::Bytes(bytes) => Image::from_bytes(&bytes).map(Arc::new),
Self::Rgba {
rgba,
width,
height,
} => Ok(Arc::new(Image::new_owned(rgba, width, height))),
#[cfg(not(any(feature = "image-ico", feature = "image-png")))]
_ => Err(
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!(
"expected RGBA image data, found {}",
match self {
JsImage::Path(_) => "a file path",
JsImage::Bytes(_) => "raw bytes",
_ => unreachable!(),
}
),
)
.into(),
),
}
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/image/plugin.rs | crates/tauri/src/image/plugin.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use serde::Serialize;
use crate::plugin::{Builder, TauriPlugin};
use crate::Manager;
use crate::{command, image::Image, ResourceId, Runtime, Webview};
#[command(root = "crate")]
fn new<R: Runtime>(
webview: Webview<R>,
rgba: Vec<u8>,
width: u32,
height: u32,
) -> crate::Result<ResourceId> {
let image = Image::new_owned(rgba, width, height);
let mut resources_table = webview.resources_table();
let rid = resources_table.add(image);
Ok(rid)
}
#[cfg(any(feature = "image-ico", feature = "image-png"))]
#[command(root = "crate")]
fn from_bytes<R: Runtime>(webview: Webview<R>, bytes: Vec<u8>) -> crate::Result<ResourceId> {
let image = Image::from_bytes(&bytes)?.to_owned();
let mut resources_table = webview.resources_table();
let rid = resources_table.add(image);
Ok(rid)
}
#[cfg(not(any(feature = "image-ico", feature = "image-png")))]
#[command(root = "crate")]
fn from_bytes() -> std::result::Result<(), &'static str> {
Err("from_bytes is only supported if the `image-ico` or `image-png` Cargo features are enabled")
}
#[cfg(any(feature = "image-ico", feature = "image-png"))]
#[command(root = "crate")]
fn from_path<R: Runtime>(
webview: Webview<R>,
path: std::path::PathBuf,
) -> crate::Result<ResourceId> {
let image = Image::from_path(path)?.to_owned();
let mut resources_table = webview.resources_table();
let rid = resources_table.add(image);
Ok(rid)
}
#[cfg(not(any(feature = "image-ico", feature = "image-png")))]
#[command(root = "crate")]
fn from_path() -> std::result::Result<(), &'static str> {
Err("from_path is only supported if the `image-ico` or `image-png` Cargo features are enabled")
}
#[command(root = "crate")]
fn rgba<R: Runtime>(webview: Webview<R>, rid: ResourceId) -> crate::Result<Vec<u8>> {
let resources_table = webview.resources_table();
let image = resources_table.get::<Image<'_>>(rid)?;
Ok(image.rgba().to_vec())
}
#[derive(Serialize)]
struct Size {
width: u32,
height: u32,
}
#[command(root = "crate")]
fn size<R: Runtime>(webview: Webview<R>, rid: ResourceId) -> crate::Result<Size> {
let resources_table = webview.resources_table();
let image = resources_table.get::<Image<'_>>(rid)?;
Ok(Size {
width: image.width(),
height: image.height(),
})
}
/// Initializes the plugin.
pub fn init<R: Runtime>() -> TauriPlugin<R> {
Builder::new("image")
.invoke_handler(crate::generate_handler![
#![plugin(image)]
new, from_bytes, from_path, rgba, size
])
.build()
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/app/plugin.rs | crates/tauri/src/app/plugin.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use tauri_utils::{config::BundleType, Theme};
use crate::{
command,
plugin::{Builder, TauriPlugin},
AppHandle, Manager, ResourceId, Runtime, Webview,
};
#[command(root = "crate")]
pub fn version<R: Runtime>(app: AppHandle<R>) -> String {
app.package_info().version.to_string()
}
#[command(root = "crate")]
pub fn name<R: Runtime>(app: AppHandle<R>) -> String {
app.package_info().name.clone()
}
#[command(root = "crate")]
pub fn tauri_version() -> &'static str {
crate::VERSION
}
#[command(root = "crate")]
pub fn identifier<R: Runtime>(app: AppHandle<R>) -> String {
app.config().identifier.clone()
}
#[command(root = "crate")]
#[allow(unused_variables)]
pub fn app_show<R: Runtime>(app: AppHandle<R>) -> crate::Result<()> {
#[cfg(target_os = "macos")]
app.show()?;
Ok(())
}
#[command(root = "crate")]
#[allow(unused_variables)]
pub fn app_hide<R: Runtime>(app: AppHandle<R>) -> crate::Result<()> {
#[cfg(target_os = "macos")]
app.hide()?;
Ok(())
}
#[command(root = "crate")]
#[allow(unused_variables)]
pub async fn fetch_data_store_identifiers<R: Runtime>(
app: AppHandle<R>,
) -> crate::Result<Vec<[u8; 16]>> {
#[cfg(target_vendor = "apple")]
return app.fetch_data_store_identifiers().await;
#[cfg(not(target_vendor = "apple"))]
return Ok(Vec::new());
}
#[command(root = "crate")]
#[allow(unused_variables)]
pub async fn remove_data_store<R: Runtime>(app: AppHandle<R>, uuid: [u8; 16]) -> crate::Result<()> {
#[cfg(target_vendor = "apple")]
app.remove_data_store(uuid).await?;
#[cfg(not(target_vendor = "apple"))]
let _ = uuid;
Ok(())
}
#[command(root = "crate")]
pub fn default_window_icon<R: Runtime>(
webview: Webview<R>,
app: AppHandle<R>,
) -> Option<ResourceId> {
app.default_window_icon().cloned().map(|icon| {
let mut resources_table = webview.resources_table();
resources_table.add(icon.to_owned())
})
}
#[command(root = "crate")]
pub async fn set_app_theme<R: Runtime>(app: AppHandle<R>, theme: Option<Theme>) {
app.set_theme(theme);
}
#[command(root = "crate")]
pub async fn set_dock_visibility<R: Runtime>(
app: AppHandle<R>,
visible: bool,
) -> crate::Result<()> {
#[cfg(target_os = "macos")]
{
let mut focused_window = None;
for window in app.manager.windows().into_values() {
if window.is_focused().unwrap_or_default() {
focused_window.replace(window);
break;
}
}
app.set_dock_visibility(visible)?;
// retain focus
if let Some(focused_window) = focused_window {
let _ = focused_window.set_focus();
}
}
#[cfg(not(target_os = "macos"))]
let (_app, _visible) = (app, visible);
Ok(())
}
#[command(root = "crate")]
pub fn bundle_type() -> Option<BundleType> {
tauri_utils::platform::bundle_type()
}
pub fn init<R: Runtime>() -> TauriPlugin<R> {
Builder::new("app")
.invoke_handler(crate::generate_handler![
#![plugin(app)]
version,
name,
tauri_version,
identifier,
app_show,
app_hide,
fetch_data_store_identifiers,
remove_data_store,
default_window_icon,
set_app_theme,
set_dock_visibility,
bundle_type,
])
.setup(|_app, _api| {
#[cfg(target_os = "android")]
{
let handle = _api.register_android_plugin("app.tauri", "AppPlugin")?;
_app.manage(AppPlugin(handle));
}
Ok(())
})
.build()
}
#[cfg(target_os = "android")]
pub(crate) struct AppPlugin<R: Runtime>(pub crate::plugin::PluginHandle<R>);
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/window/mod.rs | crates/tauri/src/window/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! The Tauri window types and functions.
pub(crate) mod plugin;
use tauri_runtime::{
dpi::{PhysicalPosition, PhysicalRect, PhysicalSize},
webview::PendingWebview,
};
pub use tauri_utils::{config::Color, WindowEffect as Effect, WindowEffectState as EffectState};
#[cfg(desktop)]
pub use crate::runtime::ProgressBarStatus;
use crate::{
app::AppHandle,
event::{Event, EventId, EventTarget},
ipc::{CommandArg, CommandItem, InvokeError},
manager::{AppManager, EmitPayload},
runtime::{
monitor::Monitor as RuntimeMonitor,
window::{DetachedWindow, PendingWindow, WindowBuilder as _},
RuntimeHandle, WindowDispatch,
},
sealed::{ManagerBase, RuntimeOrDispatch},
utils::config::{WindowConfig, WindowEffectsConfig},
webview::WebviewBuilder,
Emitter, EventLoopMessage, EventName, Listener, Manager, ResourceTable, Runtime, Theme, Webview,
WindowEvent,
};
#[cfg(desktop)]
use crate::{
image::Image,
menu::{ContextMenu, Menu, MenuId},
runtime::{
dpi::{Position, Size},
UserAttentionType,
},
CursorIcon,
};
use serde::Serialize;
#[cfg(windows)]
use windows::Win32::Foundation::HWND;
use tauri_macros::default_runtime;
use std::{
fmt,
hash::{Hash, Hasher},
sync::{Arc, Mutex, MutexGuard},
};
/// Monitor descriptor.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Monitor {
pub(crate) name: Option<String>,
pub(crate) size: PhysicalSize<u32>,
pub(crate) position: PhysicalPosition<i32>,
pub(crate) work_area: PhysicalRect<i32, u32>,
pub(crate) scale_factor: f64,
}
impl From<RuntimeMonitor> for Monitor {
fn from(monitor: RuntimeMonitor) -> Self {
Self {
name: monitor.name,
size: monitor.size,
position: monitor.position,
work_area: monitor.work_area,
scale_factor: monitor.scale_factor,
}
}
}
impl Monitor {
/// Returns a human-readable name of the monitor.
/// Returns None if the monitor doesn't exist anymore.
pub fn name(&self) -> Option<&String> {
self.name.as_ref()
}
/// Returns the monitor's resolution.
pub fn size(&self) -> &PhysicalSize<u32> {
&self.size
}
/// Returns the top-left corner position of the monitor relative to the larger full screen area.
pub fn position(&self) -> &PhysicalPosition<i32> {
&self.position
}
/// Returns the monitor's work_area.
pub fn work_area(&self) -> &PhysicalRect<i32, u32> {
&self.work_area
}
/// Returns the scale factor that can be used to map logical pixels to physical pixels, and vice versa.
pub fn scale_factor(&self) -> f64 {
self.scale_factor
}
}
macro_rules! unstable_struct {
(#[doc = $doc:expr] $($tokens:tt)*) => {
#[cfg(feature = "unstable")]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
#[doc = $doc]
pub $($tokens)*
#[cfg(not(feature = "unstable"))]
pub(crate) $($tokens)*
}
}
unstable_struct!(
#[doc = "A builder for a window managed by Tauri."]
struct WindowBuilder<'a, R: Runtime, M: Manager<R>> {
manager: &'a M,
pub(crate) label: String,
pub(crate) window_builder:
<R::WindowDispatcher as WindowDispatch<EventLoopMessage>>::WindowBuilder,
#[cfg(desktop)]
pub(crate) menu: Option<Menu<R>>,
#[cfg(desktop)]
on_menu_event: Option<crate::app::GlobalMenuEventListener<Window<R>>>,
window_effects: Option<WindowEffectsConfig>,
}
);
impl<R: Runtime, M: Manager<R>> fmt::Debug for WindowBuilder<'_, R, M> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("WindowBuilder")
.field("label", &self.label)
.field("window_builder", &self.window_builder)
.finish()
}
}
#[cfg_attr(not(feature = "unstable"), allow(dead_code))]
impl<'a, R: Runtime, M: Manager<R>> WindowBuilder<'a, R, M> {
/// Initializes a window builder with the given window label.
///
/// # Known issues
///
/// On Windows, this function deadlocks when used in a synchronous command or event handlers, see [the Webview2 issue].
/// You should use `async` commands and separate threads when creating windows.
///
/// # Examples
///
/// - Create a window in the setup hook:
///
#[cfg_attr(
feature = "unstable",
doc = r####"
```
tauri::Builder::default()
.setup(|app| {
let window = tauri::window::WindowBuilder::new(app, "label")
.build()?;
Ok(())
});
```
"####
)]
/// - Create a window in a separate thread:
///
#[cfg_attr(
feature = "unstable",
doc = r####"
```
tauri::Builder::default()
.setup(|app| {
let handle = app.handle().clone();
std::thread::spawn(move || {
let window = tauri::window::WindowBuilder::new(&handle, "label")
.build()
.unwrap();
});
Ok(())
});
```
"####
)]
///
/// - Create a window in a command:
///
#[cfg_attr(
feature = "unstable",
doc = r####"
```
#[tauri::command]
async fn create_window(app: tauri::AppHandle) {
let window = tauri::window::WindowBuilder::new(&app, "label")
.build()
.unwrap();
}
```
"####
)]
///
/// [the Webview2 issue]: https://github.com/tauri-apps/wry/issues/583
pub fn new<L: Into<String>>(manager: &'a M, label: L) -> Self {
Self {
manager,
label: label.into(),
window_builder: <R::WindowDispatcher as WindowDispatch<EventLoopMessage>>::WindowBuilder::new(
),
#[cfg(desktop)]
menu: None,
#[cfg(desktop)]
on_menu_event: None,
window_effects: None,
}
}
/// Initializes a window builder from a [`WindowConfig`] from tauri.conf.json.
/// Keep in mind that you can't create 2 windows with the same `label` so make sure
/// that the initial window was closed or change the label of the new [`WindowBuilder`].
///
/// # Known issues
///
/// On Windows, this function deadlocks when used in a synchronous command or event handlers, see [the Webview2 issue].
/// You should use `async` commands and separate threads when creating windows.
///
/// # Examples
///
/// - Create a window in a command:
///
#[cfg_attr(
feature = "unstable",
doc = r####"
```
#[tauri::command]
async fn reopen_window(app: tauri::AppHandle) {
let window = tauri::window::WindowBuilder::from_config(&app, &app.config().app.windows.get(0).unwrap().clone())
.unwrap()
.build()
.unwrap();
}
```
"####
)]
///
/// [the Webview2 issue]: https://github.com/tauri-apps/wry/issues/583
pub fn from_config(manager: &'a M, config: &WindowConfig) -> crate::Result<Self> {
#[cfg_attr(not(windows), allow(unused_mut))]
let mut builder = Self {
manager,
label: config.label.clone(),
window_effects: config.window_effects.clone(),
window_builder:
<R::WindowDispatcher as WindowDispatch<EventLoopMessage>>::WindowBuilder::with_config(
config,
),
#[cfg(desktop)]
menu: None,
#[cfg(desktop)]
on_menu_event: None,
};
#[cfg(desktop)]
if let Some(parent) = &config.parent {
let window = manager
.manager()
.get_window(parent)
.ok_or(crate::Error::WindowNotFound)?;
builder = builder.parent(&window)?;
}
Ok(builder)
}
/// Registers a global menu event listener.
///
/// Note that this handler is called for any menu event,
/// whether it is coming from this window, another window or from the tray icon menu.
///
/// Also note that this handler will not be called if
/// the window used to register it was closed.
///
/// # Examples
#[cfg_attr(
feature = "unstable",
doc = r####"
```
use tauri::menu::{Menu, Submenu, MenuItem};
tauri::Builder::default()
.setup(|app| {
let handle = app.handle();
let save_menu_item = MenuItem::new(handle, "Save", true, None::<&str>)?;
let menu = Menu::with_items(handle, &[
&Submenu::with_items(handle, "File", true, &[
&save_menu_item,
])?,
])?;
let window = tauri::window::WindowBuilder::new(app, "editor")
.menu(menu)
.on_menu_event(move |window, event| {
if event.id == save_menu_item.id() {
// save menu item
}
})
.build()
.unwrap();
///
Ok(())
});
```"####
)]
#[cfg(desktop)]
pub fn on_menu_event<F: Fn(&Window<R>, crate::menu::MenuEvent) + Send + Sync + 'static>(
mut self,
f: F,
) -> Self {
self.on_menu_event.replace(Box::new(f));
self
}
/// Creates this window with a webview with it.
#[cfg_attr(
feature = "tracing",
tracing::instrument(name = "webview::create", skip_all)
)]
pub(crate) fn with_webview(
self,
webview: WebviewBuilder<R>,
) -> crate::Result<(Window<R>, Webview<R>)> {
let pending_webview = webview.into_pending_webview(self.manager, &self.label)?;
let window = self.build_internal(Some(pending_webview))?;
let webview = window.webviews().first().unwrap().clone();
Ok((window, webview))
}
/// Creates a new window.
pub fn build(self) -> crate::Result<Window<R>> {
self.build_internal(None)
}
/// Creates a new window with an optional webview.
fn build_internal(
self,
webview: Option<PendingWebview<EventLoopMessage, R>>,
) -> crate::Result<Window<R>> {
#[cfg(desktop)]
let theme = self.window_builder.get_theme();
let mut pending = PendingWindow::new(self.window_builder, self.label)?;
if let Some(webview) = webview {
pending.set_webview(webview);
}
let app_manager = self.manager.manager();
let pending = app_manager.window.prepare_window(pending)?;
#[cfg(desktop)]
let window_menu = {
let is_app_wide = self.menu.is_none();
self
.menu
.or_else(|| self.manager.app_handle().menu())
.map(|menu| WindowMenu { is_app_wide, menu })
};
#[cfg(desktop)]
let handler = app_manager
.menu
.prepare_window_menu_creation_handler(window_menu.as_ref(), theme);
#[cfg(not(desktop))]
#[allow(clippy::type_complexity)]
let handler: Option<Box<dyn Fn(tauri_runtime::window::RawWindow<'_>) + Send>> = None;
let window = match &mut self.manager.runtime() {
RuntimeOrDispatch::Runtime(runtime) => runtime.create_window(pending, handler),
RuntimeOrDispatch::RuntimeHandle(handle) => handle.create_window(pending, handler),
RuntimeOrDispatch::Dispatch(dispatcher) => dispatcher.create_window(pending, handler),
}
.map(|detached_window| {
let window = app_manager.window.attach_window(
self.manager.app_handle().clone(),
detached_window.clone(),
#[cfg(desktop)]
window_menu,
);
if let Some(webview) = detached_window.webview {
app_manager.webview.attach_webview(
window.clone(),
webview.webview,
webview.use_https_scheme,
);
}
window
})?;
#[cfg(desktop)]
if let Some(handler) = self.on_menu_event {
window.on_menu_event(handler);
}
let app_manager = self.manager.manager_owned();
let window_label = window.label().to_string();
let window_ = window.clone();
// run on the main thread to fix a deadlock on webview.eval if the tracing feature is enabled
let _ = window.run_on_main_thread(move || {
if let Some(effects) = self.window_effects {
_ = crate::vibrancy::set_window_effects(&window_, Some(effects));
}
let event = crate::EventName::from_str("tauri://window-created");
let payload = Some(crate::webview::CreatedEvent {
label: window_label,
});
let _ = app_manager.emit(event, EmitPayload::Serialize(&payload));
});
Ok(window)
}
}
/// Desktop APIs.
#[cfg(desktop)]
#[cfg_attr(not(feature = "unstable"), allow(dead_code))]
impl<'a, R: Runtime, M: Manager<R>> WindowBuilder<'a, R, M> {
/// Sets the menu for the window.
#[must_use]
pub fn menu(mut self, menu: Menu<R>) -> Self {
self.menu.replace(menu);
self
}
/// Show window in the center of the screen.
#[must_use]
pub fn center(mut self) -> Self {
self.window_builder = self.window_builder.center();
self
}
/// The initial position of the window in logical pixels.
#[must_use]
pub fn position(mut self, x: f64, y: f64) -> Self {
self.window_builder = self.window_builder.position(x, y);
self
}
/// Window size in logical pixels.
#[must_use]
pub fn inner_size(mut self, width: f64, height: f64) -> Self {
self.window_builder = self.window_builder.inner_size(width, height);
self
}
/// Window min inner size in logical pixels.
#[must_use]
pub fn min_inner_size(mut self, min_width: f64, min_height: f64) -> Self {
self.window_builder = self.window_builder.min_inner_size(min_width, min_height);
self
}
/// Window max inner size in logical pixels.
#[must_use]
pub fn max_inner_size(mut self, max_width: f64, max_height: f64) -> Self {
self.window_builder = self.window_builder.max_inner_size(max_width, max_height);
self
}
/// Window inner size constraints.
#[must_use]
pub fn inner_size_constraints(
mut self,
constraints: tauri_runtime::window::WindowSizeConstraints,
) -> Self {
self.window_builder = self.window_builder.inner_size_constraints(constraints);
self
}
/// Prevent the window from overflowing the working area (e.g. monitor size - taskbar size)
/// on creation, which means the window size will be limited to `monitor size - taskbar size`
///
/// **NOTE**: The overflow check is only performed on window creation, resizes can still overflow
///
/// ## Platform-specific
///
/// - **iOS / Android:** Unsupported.
#[must_use]
pub fn prevent_overflow(mut self) -> Self {
self.window_builder = self.window_builder.prevent_overflow();
self
}
/// Prevent the window from overflowing the working area (e.g. monitor size - taskbar size)
/// on creation with a margin, which means the window size will be limited to `monitor size - taskbar size - margin size`
///
/// **NOTE**: The overflow check is only performed on window creation, resizes can still overflow
///
/// ## Platform-specific
///
/// - **iOS / Android:** Unsupported.
#[must_use]
pub fn prevent_overflow_with_margin(mut self, margin: impl Into<Size>) -> Self {
self.window_builder = self
.window_builder
.prevent_overflow_with_margin(margin.into());
self
}
/// Whether the window is resizable or not.
/// When resizable is set to false, native window's maximize button is automatically disabled.
#[must_use]
pub fn resizable(mut self, resizable: bool) -> Self {
self.window_builder = self.window_builder.resizable(resizable);
self
}
/// Whether the window's native maximize button is enabled or not.
/// If resizable is set to false, this setting is ignored.
///
/// ## Platform-specific
///
/// - **macOS:** Disables the "zoom" button in the window titlebar, which is also used to enter fullscreen mode.
/// - **Linux / iOS / Android:** Unsupported.
#[must_use]
pub fn maximizable(mut self, maximizable: bool) -> Self {
self.window_builder = self.window_builder.maximizable(maximizable);
self
}
/// Whether the window's native minimize button is enabled or not.
///
/// ## Platform-specific
///
/// - **Linux / iOS / Android:** Unsupported.
#[must_use]
pub fn minimizable(mut self, minimizable: bool) -> Self {
self.window_builder = self.window_builder.minimizable(minimizable);
self
}
/// Whether the window's native close button is enabled or not.
///
/// ## Platform-specific
///
/// - **Linux:** "GTK+ will do its best to convince the window manager not to show a close button.
/// Depending on the system, this function may not have any effect when called on a window that is already visible"
/// - **iOS / Android:** Unsupported.
#[must_use]
pub fn closable(mut self, closable: bool) -> Self {
self.window_builder = self.window_builder.closable(closable);
self
}
/// The title of the window in the title bar.
#[must_use]
pub fn title<S: Into<String>>(mut self, title: S) -> Self {
self.window_builder = self.window_builder.title(title);
self
}
/// Whether to start the window in fullscreen or not.
#[must_use]
pub fn fullscreen(mut self, fullscreen: bool) -> Self {
self.window_builder = self.window_builder.fullscreen(fullscreen);
self
}
/// Sets the window to be initially focused.
#[must_use]
#[deprecated(
since = "1.2.0",
note = "The window is automatically focused by default. This function Will be removed in 3.0.0. Use `focused` instead."
)]
pub fn focus(mut self) -> Self {
self.window_builder = self.window_builder.focused(true);
self
}
/// Whether the window will be initially focused or not.
#[must_use]
pub fn focused(mut self, focused: bool) -> Self {
self.window_builder = self.window_builder.focused(focused);
self
}
/// Whether the window will be focusable or not.
#[must_use]
pub fn focusable(mut self, focusable: bool) -> Self {
self.window_builder = self.window_builder.focusable(focusable);
self
}
/// Whether the window should be maximized upon creation.
#[must_use]
pub fn maximized(mut self, maximized: bool) -> Self {
self.window_builder = self.window_builder.maximized(maximized);
self
}
/// Whether the window should be immediately visible upon creation.
#[must_use]
pub fn visible(mut self, visible: bool) -> Self {
self.window_builder = self.window_builder.visible(visible);
self
}
/// Forces a theme or uses the system settings if None was provided.
///
/// ## Platform-specific
///
/// - **macOS**: Only supported on macOS 10.14+.
#[must_use]
pub fn theme(mut self, theme: Option<Theme>) -> Self {
self.window_builder = self.window_builder.theme(theme);
self
}
/// Whether the window should be transparent. If this is true, writing colors
/// with alpha values different than `1.0` will produce a transparent window.
#[cfg(any(not(target_os = "macos"), feature = "macos-private-api"))]
#[cfg_attr(
docsrs,
doc(cfg(any(not(target_os = "macos"), feature = "macos-private-api")))
)]
#[must_use]
pub fn transparent(mut self, transparent: bool) -> Self {
self.window_builder = self.window_builder.transparent(transparent);
self
}
/// Whether the window should have borders and bars.
#[must_use]
pub fn decorations(mut self, decorations: bool) -> Self {
self.window_builder = self.window_builder.decorations(decorations);
self
}
/// Whether the window should always be below other windows.
#[must_use]
pub fn always_on_bottom(mut self, always_on_bottom: bool) -> Self {
self.window_builder = self.window_builder.always_on_bottom(always_on_bottom);
self
}
/// Whether the window should always be on top of other windows.
#[must_use]
pub fn always_on_top(mut self, always_on_top: bool) -> Self {
self.window_builder = self.window_builder.always_on_top(always_on_top);
self
}
/// Whether the window will be visible on all workspaces or virtual desktops.
///
/// ## Platform-specific
///
/// - **Windows / iOS / Android:** Unsupported.
#[must_use]
pub fn visible_on_all_workspaces(mut self, visible_on_all_workspaces: bool) -> Self {
self.window_builder = self
.window_builder
.visible_on_all_workspaces(visible_on_all_workspaces);
self
}
/// Prevents the window contents from being captured by other apps.
#[must_use]
pub fn content_protected(mut self, protected: bool) -> Self {
self.window_builder = self.window_builder.content_protected(protected);
self
}
/// Sets the window icon.
pub fn icon(mut self, icon: Image<'a>) -> crate::Result<Self> {
self.window_builder = self.window_builder.icon(icon.into())?;
Ok(self)
}
/// Sets whether or not the window icon should be hidden from the taskbar.
///
/// ## Platform-specific
///
/// - **macOS**: Unsupported.
#[must_use]
pub fn skip_taskbar(mut self, skip: bool) -> Self {
self.window_builder = self.window_builder.skip_taskbar(skip);
self
}
/// Sets custom name for Windows' window class. **Windows only**.
#[must_use]
pub fn window_classname<S: Into<String>>(mut self, classname: S) -> Self {
self.window_builder = self.window_builder.window_classname(classname);
self
}
/// Sets whether or not the window has shadow.
///
/// ## Platform-specific
///
/// - **Windows:**
/// - `false` has no effect on decorated window, shadows are always ON.
/// - `true` will make undecorated window have a 1px white border,
/// and on Windows 11, it will have a rounded corners.
/// - **Linux:** Unsupported.
#[must_use]
pub fn shadow(mut self, enable: bool) -> Self {
self.window_builder = self.window_builder.shadow(enable);
self
}
/// Sets a parent to the window to be created.
///
/// ## Platform-specific
///
/// - **Windows**: This sets the passed parent as an owner window to the window to be created.
/// From [MSDN owned windows docs](https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows):
/// - An owned window is always above its owner in the z-order.
/// - The system automatically destroys an owned window when its owner is destroyed.
/// - An owned window is hidden when its owner is minimized.
/// - **Linux**: This makes the new window transient for parent, see <https://docs.gtk.org/gtk3/method.Window.set_transient_for.html>
/// - **macOS**: This adds the window as a child of parent, see <https://developer.apple.com/documentation/appkit/nswindow/1419152-addchildwindow?language=objc>
pub fn parent(mut self, parent: &Window<R>) -> crate::Result<Self> {
#[cfg(windows)]
{
self.window_builder = self.window_builder.owner(parent.hwnd()?);
}
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
{
self.window_builder = self.window_builder.transient_for(&parent.gtk_window()?);
}
#[cfg(target_os = "macos")]
{
self.window_builder = self.window_builder.parent(parent.ns_window()?);
}
Ok(self)
}
/// Set an owner to the window to be created.
///
/// From MSDN:
/// - An owned window is always above its owner in the z-order.
/// - The system automatically destroys an owned window when its owner is destroyed.
/// - An owned window is hidden when its owner is minimized.
///
/// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows>
#[cfg(windows)]
pub fn owner(mut self, owner: &Window<R>) -> crate::Result<Self> {
self.window_builder = self.window_builder.owner(owner.hwnd()?);
Ok(self)
}
/// Set an owner to the window to be created.
///
/// From MSDN:
/// - An owned window is always above its owner in the z-order.
/// - The system automatically destroys an owned window when its owner is destroyed.
/// - An owned window is hidden when its owner is minimized.
///
/// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows>
///
/// **Note:** This is a low level API. See [`Self::parent`] for a higher level wrapper for Tauri windows.
#[cfg(windows)]
#[must_use]
pub fn owner_raw(mut self, owner: HWND) -> Self {
self.window_builder = self.window_builder.owner(owner);
self
}
/// Sets a parent to the window to be created.
///
/// A child window has the WS_CHILD style and is confined to the client area of its parent window.
///
/// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#child-windows>
///
/// **Note:** This is a low level API. See [`Self::parent`] for a higher level wrapper for Tauri windows.
#[cfg(windows)]
#[must_use]
pub fn parent_raw(mut self, parent: HWND) -> Self {
self.window_builder = self.window_builder.parent(parent);
self
}
/// Sets a parent to the window to be created.
///
/// See <https://developer.apple.com/documentation/appkit/nswindow/1419152-addchildwindow?language=objc>
///
/// **Note:** This is a low level API. See [`Self::parent`] for a higher level wrapper for Tauri windows.
#[cfg(target_os = "macos")]
#[must_use]
pub fn parent_raw(mut self, parent: *mut std::ffi::c_void) -> Self {
self.window_builder = self.window_builder.parent(parent);
self
}
/// Sets the window to be created transient for parent.
///
/// See <https://docs.gtk.org/gtk3/method.Window.set_transient_for.html>
///
/// **Note:** This is a low level API. See [`Self::parent`] for a higher level wrapper for Tauri windows.
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
pub fn transient_for(mut self, parent: &Window<R>) -> crate::Result<Self> {
self.window_builder = self.window_builder.transient_for(&parent.gtk_window()?);
Ok(self)
}
/// Sets the window to be created transient for parent.
///
/// See <https://docs.gtk.org/gtk3/method.Window.set_transient_for.html>
///
/// **Note:** This is a low level API. See [`Self::parent`] and [`Self::transient_for`] for higher level wrappers for Tauri windows.
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
#[must_use]
pub fn transient_for_raw(mut self, parent: &impl gtk::glib::IsA<gtk::Window>) -> Self {
self.window_builder = self.window_builder.transient_for(parent);
self
}
/// Enables or disables drag and drop support.
#[cfg(windows)]
#[must_use]
pub fn drag_and_drop(mut self, enabled: bool) -> Self {
self.window_builder = self.window_builder.drag_and_drop(enabled);
self
}
/// Sets the [`crate::TitleBarStyle`].
#[cfg(target_os = "macos")]
#[must_use]
pub fn title_bar_style(mut self, style: crate::TitleBarStyle) -> Self {
self.window_builder = self.window_builder.title_bar_style(style);
self
}
/// Hide the window title.
#[cfg(target_os = "macos")]
#[must_use]
pub fn hidden_title(mut self, hidden: bool) -> Self {
self.window_builder = self.window_builder.hidden_title(hidden);
self
}
/// Defines the window [tabbing identifier] for macOS.
///
/// Windows with matching tabbing identifiers will be grouped together.
/// If the tabbing identifier is not set, automatic tabbing will be disabled.
///
/// [tabbing identifier]: <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier>
#[cfg(target_os = "macos")]
#[must_use]
pub fn tabbing_identifier(mut self, identifier: &str) -> Self {
self.window_builder = self.window_builder.tabbing_identifier(identifier);
self
}
/// Sets window effects.
///
/// Requires the window to be transparent.
///
/// ## Platform-specific:
///
/// - **Windows**: If using decorations or shadows, you may want to try this workaround <https://github.com/tauri-apps/tao/issues/72#issuecomment-975607891>
/// - **Linux**: Unsupported
pub fn effects(mut self, effects: WindowEffectsConfig) -> Self {
self.window_effects.replace(effects);
self
}
}
impl<R: Runtime, M: Manager<R>> WindowBuilder<'_, R, M> {
/// Set the window and webview background color.
///
/// ## Platform-specific:
///
/// - **Windows**: alpha channel is ignored.
#[must_use]
pub fn background_color(mut self, color: Color) -> Self {
self.window_builder = self.window_builder.background_color(color);
self
}
}
/// A wrapper struct to hold the window menu state
/// and whether it is global per-app or specific to this window.
#[cfg(desktop)]
pub(crate) struct WindowMenu<R: Runtime> {
pub(crate) is_app_wide: bool,
pub(crate) menu: Menu<R>,
}
// TODO: expand these docs since this is a pretty important type
/// A window managed by Tauri.
///
/// This type also implements [`Manager`] which allows you to manage other windows attached to
/// the same application.
#[default_runtime(crate::Wry, wry)]
pub struct Window<R: Runtime> {
/// The window created by the runtime.
pub(crate) window: DetachedWindow<EventLoopMessage, R>,
/// The manager to associate this window with.
pub(crate) manager: Arc<AppManager<R>>,
pub(crate) app_handle: AppHandle<R>,
// The menu set for this window
#[cfg(desktop)]
pub(crate) menu: Arc<Mutex<Option<WindowMenu<R>>>>,
pub(crate) resources_table: Arc<Mutex<ResourceTable>>,
}
impl<R: Runtime> std::fmt::Debug for Window<R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Window")
.field("window", &self.window)
.field("manager", &self.manager)
.field("app_handle", &self.app_handle)
.finish()
}
}
impl<R: Runtime> raw_window_handle::HasWindowHandle for Window<R> {
fn window_handle(
&self,
) -> std::result::Result<raw_window_handle::WindowHandle<'_>, raw_window_handle::HandleError> {
self.window.dispatcher.window_handle()
}
}
impl<R: Runtime> raw_window_handle::HasDisplayHandle for Window<R> {
fn display_handle(
&self,
) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, raw_window_handle::HandleError> {
self.app_handle.display_handle()
}
}
impl<R: Runtime> Clone for Window<R> {
fn clone(&self) -> Self {
Self {
window: self.window.clone(),
manager: self.manager.clone(),
app_handle: self.app_handle.clone(),
#[cfg(desktop)]
menu: self.menu.clone(),
resources_table: self.resources_table.clone(),
}
}
}
impl<R: Runtime> Hash for Window<R> {
/// Only use the [`Window`]'s label to represent its hash.
fn hash<H: Hasher>(&self, state: &mut H) {
self.window.label.hash(state)
}
}
impl<R: Runtime> Eq for Window<R> {}
impl<R: Runtime> PartialEq for Window<R> {
/// Only use the [`Window`]'s label to compare equality.
fn eq(&self, other: &Self) -> bool {
self.window.label.eq(&other.window.label)
}
}
impl<R: Runtime> Manager<R> for Window<R> {
fn resources_table(&self) -> MutexGuard<'_, ResourceTable> {
self
.resources_table
.lock()
.expect("poisoned window resources table")
}
}
impl<R: Runtime> ManagerBase<R> for Window<R> {
fn manager(&self) -> &AppManager<R> {
&self.manager
}
fn manager_owned(&self) -> Arc<AppManager<R>> {
self.manager.clone()
}
fn runtime(&self) -> RuntimeOrDispatch<'_, R> {
RuntimeOrDispatch::Dispatch(self.window.dispatcher.clone())
}
fn managed_app_handle(&self) -> &AppHandle<R> {
&self.app_handle
}
}
impl<'de, R: Runtime> CommandArg<'de, R> for Window<R> {
/// Grabs the [`Window`] from the [`CommandItem`]. This will never fail.
fn from_command(command: CommandItem<'de, R>) -> Result<Self, InvokeError> {
Ok(command.message.webview().window())
}
}
/// Base window functions.
impl<R: Runtime> Window<R> {
/// Create a new window that is attached to the manager.
pub(crate) fn new(
manager: Arc<AppManager<R>>,
window: DetachedWindow<EventLoopMessage, R>,
app_handle: AppHandle<R>,
#[cfg(desktop)] menu: Option<WindowMenu<R>>,
) -> Self {
Self {
window,
manager,
app_handle,
#[cfg(desktop)]
menu: Arc::new(std::sync::Mutex::new(menu)),
resources_table: Default::default(),
}
}
/// Initializes a window builder with the given window label.
///
/// Data URLs are only supported with the `webview-data-url` feature flag.
#[cfg(feature = "unstable")]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
pub fn builder<M: Manager<R>, L: Into<String>>(manager: &M, label: L) -> WindowBuilder<'_, R, M> {
WindowBuilder::new(manager, label.into())
}
/// Adds a new webview as a child of this window.
#[cfg(any(test, all(desktop, feature = "unstable")))]
#[cfg_attr(docsrs, doc(cfg(all(desktop, feature = "unstable"))))]
pub fn add_child<P: Into<Position>, S: Into<Size>>(
&self,
webview_builder: WebviewBuilder<R>,
position: P,
size: S,
) -> crate::Result<Webview<R>> {
use std::sync::mpsc::channel;
let (tx, rx) = channel();
let position = position.into();
let size = size.into();
let window_ = self.clone();
self.run_on_main_thread(move || {
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | true |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/window/plugin.rs | crates/tauri/src/window/plugin.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! The tauri plugin to create and manipulate windows from JS.
use crate::{
plugin::{Builder, TauriPlugin},
Runtime,
};
#[cfg(desktop)]
mod desktop_commands {
use tauri_runtime::{window::WindowSizeConstraints, ResizeDirection};
use tauri_utils::TitleBarStyle;
use super::*;
use crate::{
command,
sealed::ManagerBase,
utils::config::{WindowConfig, WindowEffectsConfig},
window::Color,
window::{ProgressBarState, WindowBuilder},
AppHandle, CursorIcon, Manager, Monitor, PhysicalPosition, PhysicalSize, Position, Size, Theme,
UserAttentionType, Webview, Window,
};
#[command(root = "crate")]
pub async fn get_all_windows<R: Runtime>(app: AppHandle<R>) -> Vec<String> {
app.manager().windows().keys().cloned().collect()
}
#[command(root = "crate")]
pub async fn create<R: Runtime>(app: AppHandle<R>, options: WindowConfig) -> crate::Result<()> {
WindowBuilder::from_config(&app, &options)?.build()?;
Ok(())
}
fn get_window<R: Runtime>(window: Window<R>, label: Option<String>) -> crate::Result<Window<R>> {
match label {
Some(l) if !l.is_empty() => window
.manager()
.get_window(&l)
.ok_or(crate::Error::WindowNotFound),
_ => Ok(window),
}
}
macro_rules! getter {
($cmd: ident, $ret: ty) => {
#[command(root = "crate")]
pub async fn $cmd<R: Runtime>(
window: Window<R>,
label: Option<String>,
) -> crate::Result<$ret> {
get_window(window, label)?.$cmd().map_err(Into::into)
}
};
}
macro_rules! setter {
($cmd: ident) => {
#[command(root = "crate")]
pub async fn $cmd<R: Runtime>(window: Window<R>, label: Option<String>) -> crate::Result<()> {
get_window(window, label)?.$cmd().map_err(Into::into)
}
};
($cmd: ident, $input: ty) => {
#[command(root = "crate")]
pub async fn $cmd<R: Runtime>(
window: Window<R>,
label: Option<String>,
value: $input,
) -> crate::Result<()> {
get_window(window, label)?.$cmd(value).map_err(Into::into)
}
};
}
getter!(scale_factor, f64);
getter!(inner_position, PhysicalPosition<i32>);
getter!(outer_position, PhysicalPosition<i32>);
getter!(inner_size, PhysicalSize<u32>);
getter!(outer_size, PhysicalSize<u32>);
getter!(is_fullscreen, bool);
getter!(is_minimized, bool);
getter!(is_maximized, bool);
getter!(is_focused, bool);
getter!(is_decorated, bool);
getter!(is_resizable, bool);
getter!(is_maximizable, bool);
getter!(is_minimizable, bool);
getter!(is_closable, bool);
getter!(is_visible, bool);
getter!(is_enabled, bool);
getter!(title, String);
getter!(current_monitor, Option<Monitor>);
getter!(primary_monitor, Option<Monitor>);
getter!(available_monitors, Vec<Monitor>);
getter!(cursor_position, PhysicalPosition<f64>);
getter!(theme, Theme);
getter!(is_always_on_top, bool);
setter!(center);
setter!(request_user_attention, Option<UserAttentionType>);
setter!(set_resizable, bool);
setter!(set_maximizable, bool);
setter!(set_minimizable, bool);
setter!(set_closable, bool);
setter!(set_title, &str);
setter!(maximize);
setter!(unmaximize);
setter!(minimize);
setter!(unminimize);
setter!(show);
setter!(hide);
setter!(close);
setter!(destroy);
setter!(set_decorations, bool);
setter!(set_shadow, bool);
setter!(set_effects, Option<WindowEffectsConfig>);
setter!(set_always_on_top, bool);
setter!(set_always_on_bottom, bool);
setter!(set_content_protected, bool);
setter!(set_size, Size);
setter!(set_min_size, Option<Size>);
setter!(set_max_size, Option<Size>);
setter!(set_position, Position);
setter!(set_fullscreen, bool);
setter!(set_simple_fullscreen, bool);
setter!(set_focus);
setter!(set_focusable, bool);
setter!(set_skip_taskbar, bool);
setter!(set_cursor_grab, bool);
setter!(set_cursor_visible, bool);
setter!(set_background_color, Option<Color>);
setter!(set_cursor_icon, CursorIcon);
setter!(set_cursor_position, Position);
setter!(set_ignore_cursor_events, bool);
setter!(start_dragging);
setter!(start_resize_dragging, ResizeDirection);
setter!(set_progress_bar, ProgressBarState);
setter!(set_badge_count, Option<i64>);
#[cfg(target_os = "macos")]
setter!(set_badge_label, Option<String>);
setter!(set_visible_on_all_workspaces, bool);
setter!(set_title_bar_style, TitleBarStyle);
setter!(set_size_constraints, WindowSizeConstraints);
setter!(set_theme, Option<Theme>);
setter!(set_enabled, bool);
#[command(root = "crate")]
#[cfg(target_os = "windows")]
pub async fn set_overlay_icon<R: Runtime>(
webview: Webview<R>,
window: Window<R>,
label: Option<String>,
value: Option<crate::image::JsImage>,
) -> crate::Result<()> {
let window = get_window(window, label)?;
let resources_table = webview.resources_table();
let value = match value {
Some(value) => Some(value.into_img(&resources_table)?.as_ref().clone()),
None => None,
};
window.set_overlay_icon(value)
}
#[command(root = "crate")]
pub async fn set_icon<R: Runtime>(
webview: Webview<R>,
window: Window<R>,
label: Option<String>,
value: crate::image::JsImage,
) -> crate::Result<()> {
let window = get_window(window, label)?;
let resources_table = webview.resources_table();
window.set_icon(value.into_img(&resources_table)?.as_ref().clone())
}
#[command(root = "crate")]
pub async fn toggle_maximize<R: Runtime>(
window: Window<R>,
label: Option<String>,
) -> crate::Result<()> {
let window = get_window(window, label)?;
match window.is_maximized()? {
true => window.unmaximize()?,
false => window.maximize()?,
};
Ok(())
}
#[command(root = "crate")]
pub async fn internal_toggle_maximize<R: Runtime>(
window: Window<R>,
label: Option<String>,
) -> crate::Result<()> {
let window = get_window(window, label)?;
if window.is_resizable()? {
match window.is_maximized()? {
true => window.unmaximize()?,
false => window.maximize()?,
};
}
Ok(())
}
#[command(root = "crate")]
pub async fn monitor_from_point<R: Runtime>(
window: Window<R>,
label: Option<String>,
x: f64,
y: f64,
) -> crate::Result<Option<Monitor>> {
let window = get_window(window, label)?;
window.monitor_from_point(x, y)
}
}
/// Initializes the plugin.
pub fn init<R: Runtime>() -> TauriPlugin<R> {
use serialize_to_javascript::{default_template, DefaultTemplate, Template};
let mut init_script = String::new();
#[derive(Template)]
#[default_template("./scripts/drag.js")]
struct Drag<'a> {
os_name: &'a str,
}
init_script.push_str(
&Drag {
os_name: std::env::consts::OS,
}
.render_default(&Default::default())
.unwrap()
.into_string(),
);
Builder::new("window")
.js_init_script(init_script)
.invoke_handler(
#[cfg(desktop)]
crate::generate_handler![
#![plugin(window)]
desktop_commands::create,
// getters
desktop_commands::get_all_windows,
desktop_commands::scale_factor,
desktop_commands::inner_position,
desktop_commands::outer_position,
desktop_commands::inner_size,
desktop_commands::outer_size,
desktop_commands::is_fullscreen,
desktop_commands::is_minimized,
desktop_commands::is_maximized,
desktop_commands::is_focused,
desktop_commands::is_decorated,
desktop_commands::is_resizable,
desktop_commands::is_maximizable,
desktop_commands::is_minimizable,
desktop_commands::is_closable,
desktop_commands::is_visible,
desktop_commands::is_enabled,
desktop_commands::title,
desktop_commands::current_monitor,
desktop_commands::primary_monitor,
desktop_commands::monitor_from_point,
desktop_commands::available_monitors,
desktop_commands::cursor_position,
desktop_commands::theme,
desktop_commands::is_always_on_top,
// setters
desktop_commands::center,
desktop_commands::request_user_attention,
desktop_commands::set_resizable,
desktop_commands::set_maximizable,
desktop_commands::set_minimizable,
desktop_commands::set_closable,
desktop_commands::set_title,
desktop_commands::maximize,
desktop_commands::unmaximize,
desktop_commands::minimize,
desktop_commands::unminimize,
desktop_commands::show,
desktop_commands::hide,
desktop_commands::close,
desktop_commands::destroy,
desktop_commands::set_decorations,
desktop_commands::set_shadow,
desktop_commands::set_effects,
desktop_commands::set_always_on_top,
desktop_commands::set_always_on_bottom,
desktop_commands::set_content_protected,
desktop_commands::set_size,
desktop_commands::set_min_size,
desktop_commands::set_max_size,
desktop_commands::set_size_constraints,
desktop_commands::set_position,
desktop_commands::set_fullscreen,
desktop_commands::set_simple_fullscreen,
desktop_commands::set_focus,
desktop_commands::set_focusable,
desktop_commands::set_enabled,
desktop_commands::set_skip_taskbar,
desktop_commands::set_cursor_grab,
desktop_commands::set_cursor_visible,
desktop_commands::set_cursor_icon,
desktop_commands::set_cursor_position,
desktop_commands::set_ignore_cursor_events,
desktop_commands::start_dragging,
desktop_commands::start_resize_dragging,
desktop_commands::set_badge_count,
#[cfg(target_os = "macos")]
desktop_commands::set_badge_label,
desktop_commands::set_progress_bar,
#[cfg(target_os = "windows")]
desktop_commands::set_overlay_icon,
desktop_commands::set_icon,
desktop_commands::set_visible_on_all_workspaces,
desktop_commands::set_background_color,
desktop_commands::set_title_bar_style,
desktop_commands::set_theme,
desktop_commands::toggle_maximize,
desktop_commands::internal_toggle_maximize,
],
#[cfg(mobile)]
|invoke| {
invoke.resolver.reject("Window API not available on mobile");
true
},
)
.build()
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/vibrancy/macos.rs | crates/tauri/src/vibrancy/macos.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
#![allow(deprecated)]
use crate::utils::config::WindowEffectsConfig;
use crate::window::{Effect, EffectState};
use raw_window_handle::HasWindowHandle;
use window_vibrancy::{NSVisualEffectMaterial, NSVisualEffectState};
pub fn apply_effects(window: impl HasWindowHandle, effects: WindowEffectsConfig) {
let WindowEffectsConfig {
effects,
radius,
state,
..
} = effects;
let effect = if let Some(effect) = effects.into_iter().find(|e| {
matches!(
e,
Effect::AppearanceBased
| Effect::Light
| Effect::Dark
| Effect::MediumLight
| Effect::UltraDark
| Effect::Titlebar
| Effect::Selection
| Effect::Menu
| Effect::Popover
| Effect::Sidebar
| Effect::HeaderView
| Effect::Sheet
| Effect::WindowBackground
| Effect::HudWindow
| Effect::FullScreenUI
| Effect::Tooltip
| Effect::ContentBackground
| Effect::UnderWindowBackground
| Effect::UnderPageBackground
)
}) {
effect
} else {
return;
};
window_vibrancy::apply_vibrancy(
window,
match effect {
Effect::AppearanceBased => NSVisualEffectMaterial::AppearanceBased,
Effect::Light => NSVisualEffectMaterial::Light,
Effect::Dark => NSVisualEffectMaterial::Dark,
Effect::MediumLight => NSVisualEffectMaterial::MediumLight,
Effect::UltraDark => NSVisualEffectMaterial::UltraDark,
Effect::Titlebar => NSVisualEffectMaterial::Titlebar,
Effect::Selection => NSVisualEffectMaterial::Selection,
Effect::Menu => NSVisualEffectMaterial::Menu,
Effect::Popover => NSVisualEffectMaterial::Popover,
Effect::Sidebar => NSVisualEffectMaterial::Sidebar,
Effect::HeaderView => NSVisualEffectMaterial::HeaderView,
Effect::Sheet => NSVisualEffectMaterial::Sheet,
Effect::WindowBackground => NSVisualEffectMaterial::WindowBackground,
Effect::HudWindow => NSVisualEffectMaterial::HudWindow,
Effect::FullScreenUI => NSVisualEffectMaterial::FullScreenUI,
Effect::Tooltip => NSVisualEffectMaterial::Tooltip,
Effect::ContentBackground => NSVisualEffectMaterial::ContentBackground,
Effect::UnderWindowBackground => NSVisualEffectMaterial::UnderWindowBackground,
Effect::UnderPageBackground => NSVisualEffectMaterial::UnderPageBackground,
_ => unreachable!(),
},
state.map(|s| match s {
EffectState::FollowsWindowActiveState => NSVisualEffectState::FollowsWindowActiveState,
EffectState::Active => NSVisualEffectState::Active,
EffectState::Inactive => NSVisualEffectState::Inactive,
}),
radius,
);
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/vibrancy/windows.rs | crates/tauri/src/vibrancy/windows.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
#![allow(non_snake_case)]
#![allow(non_camel_case_types)]
#![allow(clippy::upper_case_acronyms)]
use std::ffi::c_void;
use crate::utils::config::WindowEffectsConfig;
use crate::window::{Color, Effect};
use raw_window_handle::HasWindowHandle;
use windows::Win32::Foundation::HWND;
pub fn apply_effects(window: impl HasWindowHandle, effects: WindowEffectsConfig) {
let WindowEffectsConfig { effects, color, .. } = effects;
let effect = if let Some(effect) = effects.iter().find(|e| {
matches!(
e,
Effect::Mica
| Effect::MicaDark
| Effect::MicaLight
| Effect::Acrylic
| Effect::Blur
| Effect::Tabbed
| Effect::TabbedDark
| Effect::TabbedLight
)
}) {
effect
} else {
return;
};
match effect {
Effect::Blur => window_vibrancy::apply_blur(window, color.map(Into::into)),
Effect::Acrylic => window_vibrancy::apply_acrylic(window, color.map(Into::into)),
Effect::Mica => window_vibrancy::apply_mica(window, None),
Effect::MicaDark => window_vibrancy::apply_mica(window, Some(true)),
Effect::MicaLight => window_vibrancy::apply_mica(window, Some(false)),
Effect::Tabbed => window_vibrancy::apply_tabbed(window, None),
Effect::TabbedDark => window_vibrancy::apply_tabbed(window, Some(true)),
Effect::TabbedLight => window_vibrancy::apply_tabbed(window, Some(false)),
_ => unreachable!(),
};
}
pub fn clear_effects(window: impl HasWindowHandle) {
window_vibrancy::clear_blur(&window);
window_vibrancy::clear_acrylic(&window);
window_vibrancy::clear_mica(&window);
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/vibrancy/mod.rs | crates/tauri/src/vibrancy/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
#![allow(unused)]
use tauri_utils::config::WindowEffectsConfig;
use crate::{Runtime, Window};
#[cfg(target_os = "macos")]
mod macos;
#[cfg(windows)]
mod windows;
pub fn set_window_effects<R: Runtime>(
window: &Window<R>,
effects: Option<WindowEffectsConfig>,
) -> crate::Result<()> {
if let Some(_effects) = effects {
#[cfg(windows)]
windows::apply_effects(window, _effects);
#[cfg(target_os = "macos")]
macos::apply_effects(window, _effects);
} else {
#[cfg(windows)]
windows::clear_effects(window);
}
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/ipc/command.rs | crates/tauri/src/ipc/command.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! 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::{
ipc::{InvokeBody, InvokeError, InvokeMessage},
Runtime,
};
use serde::{
de::{Error, Visitor},
Deserialize, Deserializer,
};
use tauri_utils::acl::resolved::ResolvedCommand;
/// Represents a custom command.
pub struct CommandItem<'a, R: Runtime> {
/// Name of the plugin if this command targets one.
pub plugin: Option<&'static str>,
/// The name of the command, e.g. `handler` on `#[command] fn handler(value: u64)`
pub name: &'static str,
/// The key of the command item, e.g. `value` on `#[command] fn handler(value: u64)`
pub key: &'static str,
/// The [`InvokeMessage`] that was passed to this command.
pub message: &'a InvokeMessage<R>,
/// The resolved ACL for this command.
pub acl: &'a Option<Vec<ResolvedCommand>>,
}
/// Trait implemented by command arguments to derive a value from a [`CommandItem`].
///
/// # Command Arguments
///
/// A command argument is any type that represents an item parsable from a [`CommandItem`]. Most
/// implementations will use the data stored in [`InvokeMessage`] since [`CommandItem`] is mostly a
/// wrapper around it.
///
/// # Provided Implementations
///
/// Tauri implements [`CommandArg`] automatically for a number of types.
/// * [`crate::Window`]
/// * [`crate::State`]
/// * `T where T: serde::Deserialize`
/// * Any type that implements `Deserialize` can automatically be used as a [`CommandArg`].
pub trait CommandArg<'de, R: Runtime>: Sized {
/// Derives an instance of `Self` from the [`CommandItem`].
///
/// If the derivation fails, the corresponding message will be rejected using [`InvokeMessage#reject`].
fn from_command(command: CommandItem<'de, R>) -> Result<Self, InvokeError>;
}
/// Automatically implement [`CommandArg`] for any type that can be deserialized.
impl<'de, D: Deserialize<'de>, R: Runtime> CommandArg<'de, R> for D {
fn from_command(command: CommandItem<'de, R>) -> Result<D, InvokeError> {
let name = command.name;
let arg = command.key;
#[cfg(feature = "tracing")]
let _span = tracing::trace_span!("ipc::request::deserialize_arg", arg = arg).entered();
Self::deserialize(command).map_err(|e| crate::Error::InvalidArgs(name, arg, e).into())
}
}
/// Pass the result of [`serde_json::Value::get`] into [`serde_json::Value`]'s deserializer.
///
/// Returns an error if the [`CommandItem`]'s key does not exist in the value.
macro_rules! pass {
($fn:ident, $($arg:ident: $argt:ty),+) => {
fn $fn<V: Visitor<'de>>(self, $($arg: $argt),*) -> Result<V::Value, Self::Error> {
self.deserialize_json()?.$fn($($arg),*)
}
}
}
impl<'a, R: Runtime> CommandItem<'a, R> {
fn deserialize_json(self) -> serde_json::Result<&'a serde_json::Value> {
if self.key.is_empty() {
return Err(serde_json::Error::custom(format!(
"command {} has an argument with no name with a non-optional value",
self.name
)));
}
match &self.message.payload {
InvokeBody::Raw(_body) => Err(serde_json::Error::custom(format!(
"command {} expected a value for key {} but the IPC call used a bytes payload",
self.name, self.key
))),
InvokeBody::Json(v) => match v.get(self.key) {
Some(value) => Ok(value),
None => Err(serde_json::Error::custom(format!(
"command {} missing required key {}",
self.name, self.key
))),
},
}
}
}
/// A [`Deserializer`] wrapper around [`CommandItem`].
///
/// If the key doesn't exist, an error will be returned if the deserialized type is not expecting
/// an optional item. If the key does exist, the value will be called with
/// [`Value`](serde_json::Value)'s [`Deserializer`] implementation.
impl<'de, R: Runtime> Deserializer<'de> for CommandItem<'de, R> {
type Error = serde_json::Error;
pass!(deserialize_any, visitor: V);
pass!(deserialize_bool, visitor: V);
pass!(deserialize_i8, visitor: V);
pass!(deserialize_i16, visitor: V);
pass!(deserialize_i32, visitor: V);
pass!(deserialize_i64, visitor: V);
pass!(deserialize_u8, visitor: V);
pass!(deserialize_u16, visitor: V);
pass!(deserialize_u32, visitor: V);
pass!(deserialize_u64, visitor: V);
pass!(deserialize_f32, visitor: V);
pass!(deserialize_f64, visitor: V);
pass!(deserialize_char, visitor: V);
pass!(deserialize_str, visitor: V);
pass!(deserialize_string, visitor: V);
pass!(deserialize_bytes, visitor: V);
pass!(deserialize_byte_buf, visitor: V);
fn deserialize_option<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
match &self.message.payload {
InvokeBody::Raw(_body) => Err(serde_json::Error::custom(format!(
"command {} expected a value for key {} but the IPC call used a bytes payload",
self.name, self.key
))),
InvokeBody::Json(v) => match v.get(self.key) {
Some(value) => value.deserialize_option(visitor),
None => visitor.visit_none(),
},
}
}
pass!(deserialize_unit, visitor: V);
pass!(deserialize_unit_struct, name: &'static str, visitor: V);
pass!(deserialize_newtype_struct, name: &'static str, visitor: V);
pass!(deserialize_seq, visitor: V);
pass!(deserialize_tuple, len: usize, visitor: V);
pass!(
deserialize_tuple_struct,
name: &'static str,
len: usize,
visitor: V
);
pass!(deserialize_map, visitor: V);
pass!(
deserialize_struct,
name: &'static str,
fields: &'static [&'static str],
visitor: V
);
pass!(
deserialize_enum,
name: &'static str,
fields: &'static [&'static str],
visitor: V
);
pass!(deserialize_identifier, visitor: V);
pass!(deserialize_ignored_any, visitor: V);
}
/// [Autoref-based stable specialization](https://github.com/dtolnay/case-studies/blob/master/autoref-specialization/README.md)
///
/// Nothing in this module is considered stable.
#[doc(hidden)]
pub mod private {
use crate::{
ipc::{InvokeError, InvokeResolver, InvokeResponseBody, IpcResponse},
Runtime,
};
use std::future::Future;
#[cfg(feature = "tracing")]
pub use tracing;
// ===== impl IpcResponse =====
pub struct ResponseTag;
pub trait ResponseKind {
#[inline(always)]
fn blocking_kind(&self) -> ResponseTag {
ResponseTag
}
#[inline(always)]
fn async_kind(&self) -> ResponseTag {
ResponseTag
}
}
impl<T: IpcResponse> ResponseKind for &T {}
impl ResponseTag {
#[inline(always)]
pub fn block<R, T>(self, value: T, resolver: InvokeResolver<R>)
where
R: Runtime,
T: IpcResponse,
{
resolver.respond(Ok(value))
}
#[inline(always)]
pub async fn future<T>(self, value: T) -> Result<InvokeResponseBody, InvokeError>
where
T: IpcResponse,
{
Ok(value.body()?)
}
}
// ===== Result<impl Serialize, impl Into<InvokeError>> =====
pub struct ResultTag;
pub trait ResultKind {
#[inline(always)]
fn blocking_kind(&self) -> ResultTag {
ResultTag
}
#[inline(always)]
fn async_kind(&self) -> ResultTag {
ResultTag
}
}
impl<T: IpcResponse, E: Into<InvokeError>> ResultKind for Result<T, E> {}
impl ResultTag {
#[inline(always)]
pub fn block<R, T, E>(self, value: Result<T, E>, resolver: InvokeResolver<R>)
where
R: Runtime,
T: IpcResponse,
E: Into<InvokeError>,
{
resolver.respond(value.map_err(Into::into))
}
#[inline(always)]
pub async fn future<T, E>(self, value: Result<T, E>) -> Result<InvokeResponseBody, InvokeError>
where
T: IpcResponse,
E: Into<InvokeError>,
{
Ok(value.map_err(Into::into)?.body()?)
}
}
// ===== Future<Output = impl IpcResponse> =====
pub struct FutureTag;
pub trait FutureKind {
#[inline(always)]
fn async_kind(&self) -> FutureTag {
FutureTag
}
}
impl<T: IpcResponse, F: Future<Output = T>> FutureKind for &F {}
impl FutureTag {
#[inline(always)]
pub async fn future<T, F>(self, value: F) -> Result<InvokeResponseBody, InvokeError>
where
T: IpcResponse,
F: Future<Output = T> + Send + 'static,
{
Ok(value.await.body()?)
}
}
// ===== Future<Output = Result<impl Serialize, impl Into<InvokeError>>> =====
pub struct ResultFutureTag;
pub trait ResultFutureKind {
#[inline(always)]
fn async_kind(&self) -> ResultFutureTag {
ResultFutureTag
}
}
impl<T: IpcResponse, E: Into<InvokeError>, F: Future<Output = Result<T, E>>> ResultFutureKind
for F
{
}
impl ResultFutureTag {
#[inline(always)]
pub async fn future<T, E, F>(self, value: F) -> Result<InvokeResponseBody, InvokeError>
where
T: IpcResponse,
E: Into<InvokeError>,
F: Future<Output = Result<T, E>> + Send,
{
let response = value.await.map_err(Into::into)?;
Ok(response.body()?)
}
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/ipc/mod.rs | crates/tauri/src/ipc/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Types and functions related to Inter Procedure Call(IPC).
//!
//! This module includes utilities to send messages to the JS layer of the webview.
use std::{
future::Future,
sync::{Arc, Mutex},
};
use http::HeaderMap;
use serde::{
de::{DeserializeOwned, IntoDeserializer},
Deserialize, Serialize,
};
use serde_json::Value as JsonValue;
pub use serialize_to_javascript::Options as SerializeOptions;
use tauri_macros::default_runtime;
use tauri_utils::acl::resolved::ResolvedCommand;
use crate::{webview::Webview, Runtime, StateManager};
mod authority;
#[cfg(feature = "dynamic-acl")]
mod capability_builder;
pub(crate) mod channel;
mod command;
pub(crate) mod format_callback;
pub(crate) mod protocol;
pub use authority::{
CommandScope, GlobalScope, Origin, RuntimeAuthority, ScopeObject, ScopeObjectMatch, ScopeValue,
};
#[cfg(feature = "dynamic-acl")]
pub use capability_builder::{CapabilityBuilder, RuntimeCapability};
pub use channel::{Channel, JavaScriptChannelId};
pub use command::{private, CommandArg, CommandItem};
/// A closure that is run every time Tauri receives a message it doesn't explicitly handle.
pub type InvokeHandler<R> = dyn Fn(Invoke<R>) -> bool + Send + Sync + 'static;
/// A closure that is responsible for respond a JS message.
pub type InvokeResponder<R> =
dyn Fn(&Webview<R>, &str, &InvokeResponse, CallbackFn, CallbackFn) + Send + Sync + 'static;
/// Similar to [`InvokeResponder`] but taking owned arguments.
pub type OwnedInvokeResponder<R> =
dyn FnOnce(Webview<R>, String, InvokeResponse, CallbackFn, CallbackFn) + Send + 'static;
/// Possible values of an IPC payload.
///
/// ### Android
/// On Android, [InvokeBody::Raw] is not supported. The enum will always contain [InvokeBody::Json].
/// When targeting Android Devices, consider passing raw bytes as a base64 [[std::string::String]], which is still more efficient than passing them as a number array in [InvokeBody::Json]
#[derive(Debug, Clone)]
#[cfg_attr(test, derive(PartialEq))]
pub enum InvokeBody {
/// Json payload.
Json(JsonValue),
/// Bytes payload.
Raw(Vec<u8>),
}
impl Default for InvokeBody {
fn default() -> Self {
Self::Json(Default::default())
}
}
impl From<JsonValue> for InvokeBody {
fn from(value: JsonValue) -> Self {
Self::Json(value)
}
}
impl From<Vec<u8>> for InvokeBody {
fn from(value: Vec<u8>) -> Self {
Self::Raw(value)
}
}
impl InvokeBody {
#[cfg(mobile)]
pub(crate) fn into_json(self) -> JsonValue {
match self {
Self::Json(v) => v,
Self::Raw(v) => {
JsonValue::Array(v.into_iter().map(|n| JsonValue::Number(n.into())).collect())
}
}
}
}
/// Possible values of an IPC response.
#[derive(Debug, Clone)]
#[cfg_attr(test, derive(PartialEq))]
pub enum InvokeResponseBody {
/// Json payload.
Json(String),
/// Bytes payload.
Raw(Vec<u8>),
}
impl From<String> for InvokeResponseBody {
fn from(value: String) -> Self {
Self::Json(value)
}
}
impl From<Vec<u8>> for InvokeResponseBody {
fn from(value: Vec<u8>) -> Self {
Self::Raw(value)
}
}
impl From<InvokeBody> for InvokeResponseBody {
fn from(value: InvokeBody) -> Self {
match value {
InvokeBody::Json(v) => Self::Json(serde_json::to_string(&v).unwrap()),
InvokeBody::Raw(v) => Self::Raw(v),
}
}
}
impl IpcResponse for InvokeResponseBody {
fn body(self) -> crate::Result<InvokeResponseBody> {
Ok(self)
}
}
impl InvokeResponseBody {
/// Attempts to deserialize the response.
pub fn deserialize<T: DeserializeOwned>(self) -> serde_json::Result<T> {
match self {
Self::Json(v) => serde_json::from_str(&v),
Self::Raw(v) => T::deserialize(v.into_deserializer()),
}
}
}
/// The IPC request.
///
/// Includes the `body` and `headers` parameters of a Tauri command invocation.
/// This allows commands to accept raw bytes - on all platforms except Android.
#[derive(Debug)]
pub struct Request<'a> {
body: &'a InvokeBody,
headers: &'a HeaderMap,
}
impl Request<'_> {
/// The request body.
pub fn body(&self) -> &InvokeBody {
self.body
}
/// Thr request headers.
pub fn headers(&self) -> &HeaderMap {
self.headers
}
}
impl<'a, R: Runtime> CommandArg<'a, R> for Request<'a> {
/// Returns the invoke [`Request`].
fn from_command(command: CommandItem<'a, R>) -> Result<Self, InvokeError> {
Ok(Self {
body: command.message.payload(),
headers: command.message.headers(),
})
}
}
/// Marks a type as a response to an IPC call.
pub trait IpcResponse {
/// Resolve the IPC response body.
fn body(self) -> crate::Result<InvokeResponseBody>;
}
impl<T: Serialize> IpcResponse for T {
fn body(self) -> crate::Result<InvokeResponseBody> {
serde_json::to_string(&self)
.map(Into::into)
.map_err(Into::into)
}
}
/// The IPC response.
pub struct Response {
body: InvokeResponseBody,
}
impl IpcResponse for Response {
fn body(self) -> crate::Result<InvokeResponseBody> {
Ok(self.body)
}
}
impl Response {
/// Defines a response with the given body.
pub fn new(body: impl Into<InvokeResponseBody>) -> Self {
Self { body: body.into() }
}
}
/// The message and resolver given to a custom command.
///
/// This struct is used internally by macros and is explicitly **NOT** stable.
#[default_runtime(crate::Wry, wry)]
pub struct Invoke<R: Runtime> {
/// The message passed.
pub message: InvokeMessage<R>,
/// The resolver of the message.
pub resolver: InvokeResolver<R>,
/// Resolved ACL for this IPC invoke.
pub acl: Option<Vec<ResolvedCommand>>,
}
/// Error response from an [`InvokeMessage`].
#[derive(Debug)]
pub struct InvokeError(pub serde_json::Value);
impl InvokeError {
/// Create an [`InvokeError`] as a string of the [`std::error::Error`] message.
#[inline(always)]
pub fn from_error<E: std::error::Error>(error: E) -> Self {
Self(serde_json::Value::String(error.to_string()))
}
/// Create an [`InvokeError`] as a string of the [`anyhow::Error`] message.
#[inline(always)]
pub fn from_anyhow(error: anyhow::Error) -> Self {
Self(serde_json::Value::String(format!("{error:#}")))
}
}
impl<T: Serialize> From<T> for InvokeError {
#[inline]
fn from(value: T) -> Self {
serde_json::to_value(value)
.map(Self)
.unwrap_or_else(Self::from_error)
}
}
impl From<crate::Error> for InvokeError {
#[inline(always)]
fn from(error: crate::Error) -> Self {
Self(serde_json::Value::String(error.to_string()))
}
}
/// Response from a [`InvokeMessage`] passed to the [`InvokeResolver`].
#[derive(Debug)]
pub enum InvokeResponse {
/// Resolve the promise.
Ok(InvokeResponseBody),
/// Reject the promise.
Err(InvokeError),
}
impl<T: IpcResponse, E: Into<InvokeError>> From<Result<T, E>> for InvokeResponse {
#[inline]
fn from(result: Result<T, E>) -> Self {
match result {
Ok(ok) => match ok.body() {
Ok(value) => Self::Ok(value),
Err(err) => Self::Err(InvokeError::from_error(err)),
},
Err(err) => Self::Err(err.into()),
}
}
}
impl From<InvokeError> for InvokeResponse {
fn from(error: InvokeError) -> Self {
Self::Err(error)
}
}
/// Resolver of a invoke message.
#[default_runtime(crate::Wry, wry)]
pub struct InvokeResolver<R: Runtime> {
webview: Webview<R>,
responder: Arc<Mutex<Option<Box<OwnedInvokeResponder<R>>>>>,
cmd: String,
pub(crate) callback: CallbackFn,
pub(crate) error: CallbackFn,
}
impl<R: Runtime> Clone for InvokeResolver<R> {
fn clone(&self) -> Self {
Self {
webview: self.webview.clone(),
responder: self.responder.clone(),
cmd: self.cmd.clone(),
callback: self.callback,
error: self.error,
}
}
}
impl<R: Runtime> InvokeResolver<R> {
pub(crate) fn new(
webview: Webview<R>,
responder: Arc<Mutex<Option<Box<OwnedInvokeResponder<R>>>>>,
cmd: String,
callback: CallbackFn,
error: CallbackFn,
) -> Self {
Self {
webview,
responder,
cmd,
callback,
error,
}
}
/// Reply to the invoke promise with an async task.
pub fn respond_async<T, F>(self, task: F)
where
T: IpcResponse,
F: Future<Output = Result<T, InvokeError>> + Send + 'static,
{
crate::async_runtime::spawn(async move {
Self::return_task(
self.webview,
self.responder,
task,
self.cmd,
self.callback,
self.error,
)
.await;
});
}
/// Reply to the invoke promise with an async task which is already serialized.
pub fn respond_async_serialized<F>(self, task: F)
where
F: Future<Output = Result<InvokeResponseBody, InvokeError>> + Send + 'static,
{
// Dynamic dispatch the call in dev for a faster compile time
// TODO: Revisit this and see if we can do this for the release build as well if the performance hit is not a problem
#[cfg(debug_assertions)]
{
self.respond_async_serialized_dyn(Box::pin(task))
}
#[cfg(not(debug_assertions))]
{
self.respond_async_serialized_inner(task)
}
}
/// Dynamic dispatch the [`Self::respond_async_serialized`] call
#[cfg(debug_assertions)]
fn respond_async_serialized_dyn(
self,
task: std::pin::Pin<
Box<dyn Future<Output = Result<InvokeResponseBody, InvokeError>> + Send + 'static>,
>,
) {
self.respond_async_serialized_inner(task)
}
/// Reply to the invoke promise with an async task which is already serialized.
fn respond_async_serialized_inner<F>(self, task: F)
where
F: Future<Output = Result<InvokeResponseBody, InvokeError>> + Send + 'static,
{
crate::async_runtime::spawn(async move {
let response = match task.await {
Ok(ok) => InvokeResponse::Ok(ok),
Err(err) => InvokeResponse::Err(err),
};
Self::return_result(
self.webview,
self.responder,
response,
self.cmd,
self.callback,
self.error,
)
});
}
/// Reply to the invoke promise with a serializable value.
pub fn respond<T: IpcResponse>(self, value: Result<T, InvokeError>) {
Self::return_result(
self.webview,
self.responder,
value.into(),
self.cmd,
self.callback,
self.error,
)
}
/// Resolve the invoke promise with a value.
pub fn resolve<T: IpcResponse>(self, value: T) {
self.respond(Ok(value))
}
/// Reject the invoke promise with a value.
pub fn reject<T: Serialize>(self, value: T) {
Self::return_result(
self.webview,
self.responder,
Result::<(), _>::Err(value).into(),
self.cmd,
self.callback,
self.error,
)
}
/// Reject the invoke promise with an [`InvokeError`].
pub fn invoke_error(self, error: InvokeError) {
Self::return_result(
self.webview,
self.responder,
error.into(),
self.cmd,
self.callback,
self.error,
)
}
/// Asynchronously executes the given task
/// and evaluates its Result to the JS promise described by the `success_callback` and `error_callback` function names.
///
/// If the Result `is_ok()`, the callback will be the `success_callback` function name and the argument will be the Ok value.
/// If the Result `is_err()`, the callback will be the `error_callback` function name and the argument will be the Err value.
pub async fn return_task<T, F>(
webview: Webview<R>,
responder: Arc<Mutex<Option<Box<OwnedInvokeResponder<R>>>>>,
task: F,
cmd: String,
success_callback: CallbackFn,
error_callback: CallbackFn,
) where
T: IpcResponse,
F: Future<Output = Result<T, InvokeError>> + Send + 'static,
{
let result = task.await;
Self::return_closure(
webview,
responder,
|| result,
cmd,
success_callback,
error_callback,
)
}
pub(crate) fn return_closure<T: IpcResponse, F: FnOnce() -> Result<T, InvokeError>>(
webview: Webview<R>,
responder: Arc<Mutex<Option<Box<OwnedInvokeResponder<R>>>>>,
f: F,
cmd: String,
success_callback: CallbackFn,
error_callback: CallbackFn,
) {
Self::return_result(
webview,
responder,
f().into(),
cmd,
success_callback,
error_callback,
)
}
pub(crate) fn return_result(
webview: Webview<R>,
responder: Arc<Mutex<Option<Box<OwnedInvokeResponder<R>>>>>,
response: InvokeResponse,
cmd: String,
success_callback: CallbackFn,
error_callback: CallbackFn,
) {
(responder.lock().unwrap().take().expect("resolver consumed"))(
webview,
cmd,
response,
success_callback,
error_callback,
);
}
}
/// An invoke message.
#[default_runtime(crate::Wry, wry)]
#[derive(Debug)]
pub struct InvokeMessage<R: Runtime> {
/// The webview that received the invoke message.
pub(crate) webview: Webview<R>,
/// Application managed state.
pub(crate) state: Arc<StateManager>,
/// The IPC command.
pub(crate) command: String,
/// The JSON argument passed on the invoke message.
pub(crate) payload: InvokeBody,
/// The request headers.
pub(crate) headers: HeaderMap,
}
impl<R: Runtime> Clone for InvokeMessage<R> {
fn clone(&self) -> Self {
Self {
webview: self.webview.clone(),
state: self.state.clone(),
command: self.command.clone(),
payload: self.payload.clone(),
headers: self.headers.clone(),
}
}
}
impl<R: Runtime> InvokeMessage<R> {
/// Create an new [`InvokeMessage`] from a payload send by a webview.
pub(crate) fn new(
webview: Webview<R>,
state: Arc<StateManager>,
command: String,
payload: InvokeBody,
headers: HeaderMap,
) -> Self {
Self {
webview,
state,
command,
payload,
headers,
}
}
/// The invoke command.
#[inline(always)]
pub fn command(&self) -> &str {
&self.command
}
/// The webview that received the invoke.
#[inline(always)]
pub fn webview(&self) -> Webview<R> {
self.webview.clone()
}
/// A reference to webview that received the invoke.
#[inline(always)]
pub fn webview_ref(&self) -> &Webview<R> {
&self.webview
}
/// A reference to the payload the invoke received.
#[inline(always)]
pub fn payload(&self) -> &InvokeBody {
&self.payload
}
/// The state manager associated with the application
#[inline(always)]
pub fn state(&self) -> Arc<StateManager> {
self.state.clone()
}
/// A reference to the state manager associated with application.
#[inline(always)]
pub fn state_ref(&self) -> &StateManager {
&self.state
}
/// The request headers.
#[inline(always)]
pub fn headers(&self) -> &HeaderMap {
&self.headers
}
}
/// The `Callback` type is the return value of the `transformCallback` JavaScript function.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct CallbackFn(pub u32);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn deserialize_invoke_response_body() {
let json = InvokeResponseBody::Json("[1, 123, 1231]".to_string());
assert_eq!(json.deserialize::<Vec<u16>>().unwrap(), vec![1, 123, 1231]);
let json = InvokeResponseBody::Json("\"string value\"".to_string());
assert_eq!(json.deserialize::<String>().unwrap(), "string value");
let json = InvokeResponseBody::Json("\"string value\"".to_string());
assert!(json.deserialize::<Vec<u16>>().is_err());
let values = vec![1, 2, 3, 4, 5, 6, 1];
let raw = InvokeResponseBody::Raw(values.clone());
assert_eq!(raw.deserialize::<Vec<u8>>().unwrap(), values);
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/ipc/capability_builder.rs | crates/tauri/src/ipc/capability_builder.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use serde::Serialize;
use tauri_utils::{
acl::{
capability::{Capability, CapabilityFile, PermissionEntry},
Scopes,
},
platform::Target,
};
/// A capability that can be added at runtime.
pub trait RuntimeCapability {
/// Creates the capability file.
fn build(self) -> CapabilityFile;
}
impl<T: AsRef<str>> RuntimeCapability for T {
fn build(self) -> CapabilityFile {
self.as_ref().parse().expect("invalid capability")
}
}
/// A builder for a [`Capability`].
pub struct CapabilityBuilder(Capability);
impl CapabilityBuilder {
/// Creates a new capability builder with a unique identifier.
pub fn new(identifier: impl Into<String>) -> Self {
Self(Capability {
identifier: identifier.into(),
description: "".into(),
remote: None,
local: true,
windows: Vec::new(),
webviews: Vec::new(),
permissions: Vec::new(),
platforms: None,
})
}
/// Allows this capability to be used by a remote URL.
pub fn remote(mut self, url: String) -> Self {
self
.0
.remote
.get_or_insert_with(Default::default)
.urls
.push(url);
self
}
/// Whether this capability is applied on local app URLs or not. Defaults to `true`.
pub fn local(mut self, local: bool) -> Self {
self.0.local = local;
self
}
/// Link this capability to the given window label.
pub fn window(mut self, window: impl Into<String>) -> Self {
self.0.windows.push(window.into());
self
}
/// Link this capability to the a list of window labels.
pub fn windows(mut self, windows: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.0.windows.extend(windows.into_iter().map(|w| w.into()));
self
}
/// Link this capability to the given webview label.
pub fn webview(mut self, webview: impl Into<String>) -> Self {
self.0.webviews.push(webview.into());
self
}
/// Link this capability to the a list of window labels.
pub fn webviews(mut self, webviews: impl IntoIterator<Item = impl Into<String>>) -> Self {
self
.0
.webviews
.extend(webviews.into_iter().map(|w| w.into()));
self
}
/// Add a new permission to this capability.
pub fn permission(mut self, permission: impl Into<String>) -> Self {
let permission = permission.into();
self.0.permissions.push(PermissionEntry::PermissionRef(
permission
.clone()
.try_into()
.unwrap_or_else(|_| panic!("invalid permission identifier '{permission}'")),
));
self
}
/// Add a new scoped permission to this capability.
pub fn permission_scoped<T: Serialize>(
mut self,
permission: impl Into<String>,
allowed: Vec<T>,
denied: Vec<T>,
) -> Self {
let permission = permission.into();
let identifier = permission
.clone()
.try_into()
.unwrap_or_else(|_| panic!("invalid permission identifier '{permission}'"));
let allowed_scope = allowed
.into_iter()
.map(|a| {
serde_json::to_value(a)
.expect("failed to serialize scope")
.into()
})
.collect();
let denied_scope = denied
.into_iter()
.map(|a| {
serde_json::to_value(a)
.expect("failed to serialize scope")
.into()
})
.collect();
let scope = Scopes {
allow: Some(allowed_scope),
deny: Some(denied_scope),
};
self
.0
.permissions
.push(PermissionEntry::ExtendedPermission { identifier, scope });
self
}
/// Adds a target platform for this capability.
///
/// By default all platforms are applied.
pub fn platform(mut self, platform: Target) -> Self {
self
.0
.platforms
.get_or_insert_with(Default::default)
.push(platform);
self
}
/// Adds target platforms for this capability.
///
/// By default all platforms are applied.
pub fn platforms(mut self, platforms: impl IntoIterator<Item = Target>) -> Self {
self
.0
.platforms
.get_or_insert_with(Default::default)
.extend(platforms);
self
}
}
impl RuntimeCapability for CapabilityBuilder {
fn build(self) -> CapabilityFile {
CapabilityFile::Capability(self.0)
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/ipc/authority.rs | crates/tauri/src/ipc/authority.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::collections::BTreeMap;
use std::fmt::{Debug, Display};
use std::sync::Arc;
use serde::de::DeserializeOwned;
#[cfg(feature = "dynamic-acl")]
use tauri_utils::acl::capability::CapabilityFile;
#[cfg(any(feature = "dynamic-acl", debug_assertions))]
use tauri_utils::acl::manifest::Manifest;
use tauri_utils::acl::{
resolved::{Resolved, ResolvedCommand, ResolvedScope, ScopeKey},
ExecutionContext, Value, APP_ACL_KEY,
};
use url::Url;
use crate::{ipc::InvokeError, sealed::ManagerBase, Runtime};
use crate::{AppHandle, Manager, StateManager, Webview};
use super::{CommandArg, CommandItem};
/// The runtime authority used to authorize IPC execution based on the Access Control List.
pub struct RuntimeAuthority {
#[cfg(any(feature = "dynamic-acl", debug_assertions))]
acl: BTreeMap<String, Manifest>,
has_app_acl: bool,
allowed_commands: BTreeMap<String, Vec<ResolvedCommand>>,
denied_commands: BTreeMap<String, Vec<ResolvedCommand>>,
pub(crate) scope_manager: ScopeManager,
}
/// The origin trying to access the IPC.
pub enum Origin {
/// Local app origin.
Local,
/// Remote origin.
Remote {
/// Remote URL.
url: Url,
},
}
impl Display for Origin {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Local => write!(f, "local"),
Self::Remote { url } => write!(f, "remote: {url}"),
}
}
}
impl Origin {
fn matches(&self, context: &ExecutionContext) -> bool {
match (self, context) {
(Self::Local, ExecutionContext::Local) => true,
(Self::Remote { url }, ExecutionContext::Remote { url: url_pattern }) => {
url_pattern.test(url)
}
_ => false,
}
}
}
/// This is used internally by [`crate::generate_handler!`] for constructing [`RuntimeAuthority`]
/// to only include the raw ACL when it's needed
///
/// ## Stability
///
/// The output of this macro is managed internally by Tauri,
/// and should not be accessed directly on normal applications.
/// It may have breaking changes in the future.
#[cfg(any(feature = "dynamic-acl", debug_assertions))]
#[doc(hidden)]
#[macro_export]
macro_rules! runtime_authority {
($acl:expr, $resolved_acl:expr) => {
$crate::ipc::RuntimeAuthority::new($acl, $resolved_acl)
};
}
/// This is used internally by [`crate::generate_handler!`] for constructing [`RuntimeAuthority`]
/// to only include the raw ACL when it's needed
///
/// ## Stability
///
/// The output of this macro is managed internally by Tauri,
/// and should not be accessed directly on normal applications.
/// It may have breaking changes in the future.
#[cfg(not(any(feature = "dynamic-acl", debug_assertions)))]
#[doc(hidden)]
#[macro_export]
macro_rules! runtime_authority {
($_acl:expr, $resolved_acl:expr) => {
$crate::ipc::RuntimeAuthority::new($resolved_acl)
};
}
impl RuntimeAuthority {
/// Contruct a new [`RuntimeAuthority`] from the ACL
///
/// **Please prefer using the [`runtime_authority`] macro instead of calling this directly**
#[doc(hidden)]
pub fn new(
#[cfg(any(feature = "dynamic-acl", debug_assertions))] acl: BTreeMap<String, Manifest>,
resolved_acl: Resolved,
) -> Self {
let command_cache = resolved_acl
.command_scope
.keys()
.map(|key| (*key, StateManager::new()))
.collect();
Self {
#[cfg(any(feature = "dynamic-acl", debug_assertions))]
acl,
has_app_acl: resolved_acl.has_app_acl,
allowed_commands: resolved_acl.allowed_commands,
denied_commands: resolved_acl.denied_commands,
scope_manager: ScopeManager {
command_scope: resolved_acl.command_scope,
global_scope: resolved_acl.global_scope,
command_cache,
global_scope_cache: StateManager::new(),
},
}
}
pub(crate) fn has_app_manifest(&self) -> bool {
self.has_app_acl
}
#[doc(hidden)]
pub fn __allow_command(&mut self, command: String, context: ExecutionContext) {
self.allowed_commands.insert(
command,
vec![ResolvedCommand {
context,
windows: vec!["*".parse().unwrap()],
..Default::default()
}],
);
}
/// Adds the given capability to the runtime authority.
#[cfg(feature = "dynamic-acl")]
pub fn add_capability(&mut self, capability: impl super::RuntimeCapability) -> crate::Result<()> {
self.add_capability_inner(capability.build())
}
#[cfg(feature = "dynamic-acl")]
fn add_capability_inner(&mut self, capability: CapabilityFile) -> crate::Result<()> {
let mut capabilities = BTreeMap::new();
match capability {
CapabilityFile::Capability(c) => {
capabilities.insert(c.identifier.clone(), c);
}
CapabilityFile::List(capabilities_list)
| CapabilityFile::NamedList {
capabilities: capabilities_list,
} => {
capabilities.extend(
capabilities_list
.into_iter()
.map(|c| (c.identifier.clone(), c)),
);
}
}
let resolved = Resolved::resolve(
&self.acl,
capabilities,
tauri_utils::platform::Target::current(),
)
.unwrap();
// fill global scope
for (plugin, global_scope) in resolved.global_scope {
let global_scope_entry = self.scope_manager.global_scope.entry(plugin).or_default();
global_scope_entry.allow.extend(global_scope.allow);
global_scope_entry.deny.extend(global_scope.deny);
self.scope_manager.global_scope_cache = StateManager::new();
}
// denied commands
for (cmd_key, resolved_cmds) in resolved.denied_commands {
let entry = self.denied_commands.entry(cmd_key).or_default();
entry.extend(resolved_cmds);
}
// allowed commands
for (cmd_key, resolved_cmds) in resolved.allowed_commands {
// fill command scope
for resolved_cmd in &resolved_cmds {
if let Some(scope_id) = resolved_cmd.scope_id {
let command_scope = resolved.command_scope.get(&scope_id).unwrap();
let command_scope_entry = self
.scope_manager
.command_scope
.entry(scope_id)
.or_default();
command_scope_entry
.allow
.extend(command_scope.allow.clone());
command_scope_entry.deny.extend(command_scope.deny.clone());
self
.scope_manager
.command_cache
.insert(scope_id, StateManager::new());
}
}
let entry = self.allowed_commands.entry(cmd_key).or_default();
entry.extend(resolved_cmds);
}
Ok(())
}
#[cfg(debug_assertions)]
pub(crate) fn resolve_access_message(
&self,
key: &str,
command_name: &str,
window: &str,
webview: &str,
origin: &Origin,
) -> String {
fn print_references(resolved: &[ResolvedCommand]) -> String {
resolved
.iter()
.map(|r| {
format!(
"capability: {}, permission: {}",
r.referenced_by.capability, r.referenced_by.permission
)
})
.collect::<Vec<_>>()
.join(" || ")
}
fn print_allowed_on(resolved: &[ResolvedCommand]) -> String {
if resolved.is_empty() {
"command not allowed on any window/webview/URL context".to_string()
} else {
let mut s = "allowed on: ".to_string();
let last_index = resolved.len() - 1;
for (index, cmd) in resolved.iter().enumerate() {
let windows = cmd
.windows
.iter()
.map(|w| format!("\"{}\"", w.as_str()))
.collect::<Vec<_>>()
.join(", ");
let webviews = cmd
.webviews
.iter()
.map(|w| format!("\"{}\"", w.as_str()))
.collect::<Vec<_>>()
.join(", ");
s.push('[');
if !windows.is_empty() {
s.push_str(&format!("windows: {windows}, "));
}
if !webviews.is_empty() {
s.push_str(&format!("webviews: {webviews}, "));
}
match &cmd.context {
ExecutionContext::Local => s.push_str("URL: local"),
ExecutionContext::Remote { url } => s.push_str(&format!("URL: {}", url.as_str())),
}
s.push(']');
if index != last_index {
s.push_str(", ");
}
}
s
}
}
fn has_permissions_allowing_command(
manifest: &Manifest,
set: &crate::utils::acl::PermissionSet,
command: &str,
) -> bool {
for permission_id in &set.permissions {
if permission_id == "default" {
if let Some(default) = &manifest.default_permission {
if has_permissions_allowing_command(manifest, default, command) {
return true;
}
}
} else if let Some(ref_set) = manifest.permission_sets.get(permission_id) {
if has_permissions_allowing_command(manifest, ref_set, command) {
return true;
}
} else if let Some(permission) = manifest.permissions.get(permission_id) {
if permission.commands.allow.contains(&command.into()) {
return true;
}
}
}
false
}
let command = if key == APP_ACL_KEY {
command_name.to_string()
} else {
format!("plugin:{key}|{command_name}")
};
let command_pretty_name = if key == APP_ACL_KEY {
command_name.to_string()
} else {
format!("{key}.{command_name}")
};
if let Some(resolved) = self.denied_commands.get(&command) {
format!(
"{command_pretty_name} explicitly denied on origin {origin}\n\nreferenced by: {}",
print_references(resolved)
)
} else {
let command_matches = self.allowed_commands.get(&command);
if let Some(resolved) = self.allowed_commands.get(&command) {
let resolved_matching_origin = resolved
.iter()
.filter(|cmd| origin.matches(&cmd.context))
.collect::<Vec<&ResolvedCommand>>();
if resolved_matching_origin
.iter()
.any(|cmd| cmd.webviews.iter().any(|w| w.matches(webview)))
|| resolved_matching_origin
.iter()
.any(|cmd| cmd.windows.iter().any(|w| w.matches(window)))
{
"allowed".to_string()
} else {
format!("{command_pretty_name} not allowed on window \"{window}\", webview \"{webview}\", URL: {}\n\n{}\n\nreferenced by: {}",
match origin {
Origin::Local => "local",
Origin::Remote { url } => url.as_str()
},
print_allowed_on(resolved),
print_references(resolved)
)
}
} else {
let permission_error_detail = if let Some((key, manifest)) = self
.acl
.get_key_value(key)
.or_else(|| self.acl.get_key_value(&format!("core:{key}")))
{
let mut permissions_referencing_command = Vec::new();
if let Some(default) = &manifest.default_permission {
if has_permissions_allowing_command(manifest, default, command_name) {
permissions_referencing_command.push("default".into());
}
}
for set in manifest.permission_sets.values() {
if has_permissions_allowing_command(manifest, set, command_name) {
permissions_referencing_command.push(set.identifier.clone());
}
}
for permission in manifest.permissions.values() {
if permission.commands.allow.contains(&command_name.into()) {
permissions_referencing_command.push(permission.identifier.clone());
}
}
permissions_referencing_command.sort();
let associated_permissions = permissions_referencing_command
.into_iter()
.map(|permission| {
if key == APP_ACL_KEY {
permission
} else {
format!("{key}:{permission}")
}
})
.collect::<Vec<_>>()
.join(", ");
if associated_permissions.is_empty() {
"Command not found".to_string()
} else {
format!("Permissions associated with this command: {associated_permissions}")
}
} else {
"Plugin not found".to_string()
};
if let Some(resolved_cmds) = command_matches {
format!(
"{command_pretty_name} not allowed on origin [{origin}]. Please create a capability that has this origin on the context field.\n\nFound matches for: {}\n\n{permission_error_detail}",
resolved_cmds
.iter()
.map(|resolved| {
let context = match &resolved.context {
ExecutionContext::Local => "[local]".to_string(),
ExecutionContext::Remote { url } => format!("[remote: {}]", url.as_str()),
};
format!(
"- context: {context}, referenced by: capability: {}, permission: {}",
resolved.referenced_by.capability,
resolved.referenced_by.permission
)
})
.collect::<Vec<_>>()
.join("\n")
)
} else {
format!("{command_pretty_name} not allowed. {permission_error_detail}")
}
}
}
}
/// Checks if the given IPC execution is allowed and returns the [`ResolvedCommand`] if it is.
pub fn resolve_access(
&self,
command: &str,
window: &str,
webview: &str,
origin: &Origin,
) -> Option<Vec<ResolvedCommand>> {
if self
.denied_commands
.get(command)
.map(|resolved| resolved.iter().any(|cmd| origin.matches(&cmd.context)))
.is_some()
{
None
} else {
self.allowed_commands.get(command).and_then(|resolved| {
let resolved_cmds = resolved
.iter()
.filter(|cmd| {
origin.matches(&cmd.context)
&& (cmd.webviews.iter().any(|w| w.matches(webview))
|| cmd.windows.iter().any(|w| w.matches(window)))
})
.cloned()
.collect::<Vec<_>>();
if resolved_cmds.is_empty() {
None
} else {
Some(resolved_cmds)
}
})
}
}
}
/// List of allowed and denied objects that match either the command-specific or plugin global scope criteria.
#[derive(Debug)]
pub struct ScopeValue<T: ScopeObject> {
allow: Arc<Vec<Arc<T>>>,
deny: Arc<Vec<Arc<T>>>,
}
impl<T: ScopeObject> ScopeValue<T> {
fn clone(&self) -> Self {
Self {
allow: self.allow.clone(),
deny: self.deny.clone(),
}
}
/// What this access scope allows.
pub fn allows(&self) -> &Vec<Arc<T>> {
&self.allow
}
/// What this access scope denies.
pub fn denies(&self) -> &Vec<Arc<T>> {
&self.deny
}
}
/// Access scope for a command that can be retrieved directly in the command function.
#[derive(Debug)]
pub struct CommandScope<T: ScopeObject> {
allow: Vec<Arc<T>>,
deny: Vec<Arc<T>>,
}
impl<T: ScopeObject> CommandScope<T> {
pub(crate) fn resolve<R: Runtime>(
webview: &Webview<R>,
scope_ids: Vec<u64>,
) -> crate::Result<Self> {
let mut allow = Vec::new();
let mut deny = Vec::new();
for scope_id in scope_ids {
let scope = webview
.manager()
.runtime_authority
.lock()
.unwrap()
.scope_manager
.get_command_scope_typed::<R, T>(webview.app_handle(), &scope_id)?;
for s in scope.allows() {
allow.push(s.clone());
}
for s in scope.denies() {
deny.push(s.clone());
}
}
Ok(CommandScope { allow, deny })
}
/// What this access scope allows.
pub fn allows(&self) -> &Vec<Arc<T>> {
&self.allow
}
/// What this access scope denies.
pub fn denies(&self) -> &Vec<Arc<T>> {
&self.deny
}
}
impl<T: ScopeObjectMatch> CommandScope<T> {
/// Ensure all deny scopes were not matched and any allow scopes were.
///
/// This **WILL** return `true` if the allow scopes are empty and the deny
/// scopes did not trigger. If you require at least one allow scope, then
/// ensure the allow scopes are not empty before calling this method.
///
/// ```
/// # use tauri::ipc::CommandScope;
/// # fn command(scope: CommandScope<()>) -> Result<(), &'static str> {
/// if scope.allows().is_empty() {
/// return Err("you need to specify at least 1 allow scope!");
/// }
/// # Ok(())
/// # }
/// ```
///
/// # Example
///
/// ```
/// # use serde::{Serialize, Deserialize};
/// # use url::Url;
/// # use tauri::{ipc::{CommandScope, ScopeObjectMatch}, command};
/// #
/// #[derive(Debug, Clone, Serialize, Deserialize)]
/// # pub struct Scope;
/// #
/// # impl ScopeObjectMatch for Scope {
/// # type Input = str;
/// #
/// # fn matches(&self, input: &str) -> bool {
/// # true
/// # }
/// # }
/// #
/// # fn do_work(_: String) -> Result<String, &'static str> {
/// # Ok("Output".into())
/// # }
/// #
/// #[command]
/// fn my_command(scope: CommandScope<Scope>, input: String) -> Result<String, &'static str> {
/// if scope.matches(&input) {
/// do_work(input)
/// } else {
/// Err("Scope didn't match input")
/// }
/// }
/// ```
pub fn matches(&self, input: &T::Input) -> bool {
// first make sure the input doesn't match any existing deny scope
if self.deny.iter().any(|s| s.matches(input)) {
return false;
}
// if there are allow scopes, ensure the input matches at least 1
if self.allow.is_empty() {
true
} else {
self.allow.iter().any(|s| s.matches(input))
}
}
}
impl<'a, R: Runtime, T: ScopeObject> CommandArg<'a, R> for CommandScope<T> {
/// Grabs the [`ResolvedScope`] from the [`CommandItem`] and returns the associated [`CommandScope`].
fn from_command(command: CommandItem<'a, R>) -> Result<Self, InvokeError> {
let scope_ids = command.acl.as_ref().map(|resolved| {
resolved
.iter()
.filter_map(|cmd| cmd.scope_id)
.collect::<Vec<_>>()
});
if let Some(scope_ids) = scope_ids {
CommandScope::resolve(&command.message.webview, scope_ids).map_err(Into::into)
} else {
Ok(CommandScope {
allow: Default::default(),
deny: Default::default(),
})
}
}
}
/// Global access scope that can be retrieved directly in the command function.
#[derive(Debug)]
pub struct GlobalScope<T: ScopeObject>(ScopeValue<T>);
impl<T: ScopeObject> GlobalScope<T> {
pub(crate) fn resolve<R: Runtime>(webview: &Webview<R>, plugin: &str) -> crate::Result<Self> {
webview
.manager()
.runtime_authority
.lock()
.unwrap()
.scope_manager
.get_global_scope_typed(webview.app_handle(), plugin)
.map(Self)
}
/// What this access scope allows.
pub fn allows(&self) -> &Vec<Arc<T>> {
&self.0.allow
}
/// What this access scope denies.
pub fn denies(&self) -> &Vec<Arc<T>> {
&self.0.deny
}
}
impl<'a, R: Runtime, T: ScopeObject> CommandArg<'a, R> for GlobalScope<T> {
/// Grabs the [`ResolvedScope`] from the [`CommandItem`] and returns the associated [`GlobalScope`].
fn from_command(command: CommandItem<'a, R>) -> Result<Self, InvokeError> {
GlobalScope::resolve(
&command.message.webview,
command.plugin.unwrap_or(APP_ACL_KEY),
)
.map_err(InvokeError::from_error)
}
}
#[derive(Debug)]
pub struct ScopeManager {
command_scope: BTreeMap<ScopeKey, ResolvedScope>,
global_scope: BTreeMap<String, ResolvedScope>,
command_cache: BTreeMap<ScopeKey, StateManager>,
global_scope_cache: StateManager,
}
/// Marks a type as a scope object.
///
/// Usually you will just rely on [`serde::de::DeserializeOwned`] instead of implementing it manually,
/// though this is useful if you need to do some initialization logic on the type itself.
pub trait ScopeObject: Sized + Send + Sync + Debug + 'static {
/// The error type.
type Error: std::error::Error + Send + Sync;
/// Deserialize the raw scope value.
fn deserialize<R: Runtime>(app: &AppHandle<R>, raw: Value) -> Result<Self, Self::Error>;
}
impl<T: Send + Sync + Debug + DeserializeOwned + 'static> ScopeObject for T {
type Error = serde_json::Error;
fn deserialize<R: Runtime>(_app: &AppHandle<R>, raw: Value) -> Result<Self, Self::Error> {
serde_json::from_value(raw.into())
}
}
/// A [`ScopeObject`] whose validation can be represented as a `bool`.
///
/// # Example
///
/// ```
/// # use serde::{Deserialize, Serialize};
/// # use tauri::{ipc::ScopeObjectMatch, Url};
/// #
/// #[derive(Debug, Clone, Serialize, Deserialize)]
/// #[serde(rename_all = "camelCase")]
/// pub enum Scope {
/// Domain(Url),
/// StartsWith(String),
/// }
///
/// impl ScopeObjectMatch for Scope {
/// type Input = str;
///
/// fn matches(&self, input: &str) -> bool {
/// match self {
/// Scope::Domain(url) => {
/// let parsed: Url = match input.parse() {
/// Ok(parsed) => parsed,
/// Err(_) => return false,
/// };
///
/// let domain = parsed.domain();
///
/// domain.is_some() && domain == url.domain()
/// }
/// Scope::StartsWith(start) => input.starts_with(start),
/// }
/// }
/// }
/// ```
pub trait ScopeObjectMatch: ScopeObject {
/// The type of input expected to validate against the scope.
///
/// This will be borrowed, so if you want to match on a `&str` this type should be `str`.
type Input: ?Sized;
/// Check if the input matches against the scope.
fn matches(&self, input: &Self::Input) -> bool;
}
impl ScopeManager {
pub(crate) fn get_global_scope_typed<R: Runtime, T: ScopeObject>(
&self,
app: &AppHandle<R>,
key: &str,
) -> crate::Result<ScopeValue<T>> {
match self.global_scope_cache.try_get::<ScopeValue<T>>() {
Some(cached) => Ok(cached.inner().clone()),
None => {
let mut allow = Vec::new();
let mut deny = Vec::new();
if let Some(global_scope) = self.global_scope.get(key) {
for allowed in &global_scope.allow {
allow
.push(Arc::new(T::deserialize(app, allowed.clone()).map_err(
|e| crate::Error::CannotDeserializeScope(Box::new(e)),
)?));
}
for denied in &global_scope.deny {
deny
.push(Arc::new(T::deserialize(app, denied.clone()).map_err(
|e| crate::Error::CannotDeserializeScope(Box::new(e)),
)?));
}
}
let scope = ScopeValue {
allow: Arc::new(allow),
deny: Arc::new(deny),
};
self.global_scope_cache.set(scope.clone());
Ok(scope)
}
}
}
fn get_command_scope_typed<R: Runtime, T: ScopeObject>(
&self,
app: &AppHandle<R>,
key: &ScopeKey,
) -> crate::Result<ScopeValue<T>> {
let cache = self.command_cache.get(key).unwrap();
match cache.try_get::<ScopeValue<T>>() {
Some(cached) => Ok(cached.inner().clone()),
None => {
let resolved_scope = self
.command_scope
.get(key)
.unwrap_or_else(|| panic!("missing command scope for key {key}"));
let mut allow = Vec::new();
let mut deny = Vec::new();
for allowed in &resolved_scope.allow {
allow
.push(Arc::new(T::deserialize(app, allowed.clone()).map_err(
|e| crate::Error::CannotDeserializeScope(Box::new(e)),
)?));
}
for denied in &resolved_scope.deny {
deny
.push(Arc::new(T::deserialize(app, denied.clone()).map_err(
|e| crate::Error::CannotDeserializeScope(Box::new(e)),
)?));
}
let value = ScopeValue {
allow: Arc::new(allow),
deny: Arc::new(deny),
};
let _ = cache.set(value.clone());
Ok(value)
}
}
}
}
#[cfg(test)]
mod tests {
use glob::Pattern;
use tauri_utils::acl::{
resolved::{Resolved, ResolvedCommand},
ExecutionContext,
};
use crate::ipc::Origin;
use super::RuntimeAuthority;
#[test]
fn window_glob_pattern_matches() {
let command = "my-command";
let window = "main-*";
let webview = "other-*";
let resolved_cmd = vec![ResolvedCommand {
windows: vec![Pattern::new(window).unwrap()],
..Default::default()
}];
let allowed_commands = [(command.to_string(), resolved_cmd.clone())]
.into_iter()
.collect();
let authority = RuntimeAuthority::new(
Default::default(),
Resolved {
allowed_commands,
..Default::default()
},
);
assert_eq!(
authority.resolve_access(
command,
&window.replace('*', "something"),
webview,
&Origin::Local
),
Some(resolved_cmd)
);
}
#[test]
fn webview_glob_pattern_matches() {
let command = "my-command";
let window = "other-*";
let webview = "main-*";
let resolved_cmd = vec![ResolvedCommand {
windows: vec![Pattern::new(window).unwrap()],
webviews: vec![Pattern::new(webview).unwrap()],
..Default::default()
}];
let allowed_commands = [(command.to_string(), resolved_cmd.clone())]
.into_iter()
.collect();
let authority = RuntimeAuthority::new(
Default::default(),
Resolved {
allowed_commands,
..Default::default()
},
);
assert_eq!(
authority.resolve_access(
command,
window,
&webview.replace('*', "something"),
&Origin::Local
),
Some(resolved_cmd)
);
}
#[test]
fn remote_domain_matches() {
let url = "https://tauri.app";
let command = "my-command";
let window = "main";
let webview = "main";
let resolved_cmd = vec![ResolvedCommand {
windows: vec![Pattern::new(window).unwrap()],
context: ExecutionContext::Remote {
url: url.parse().unwrap(),
},
..Default::default()
}];
let allowed_commands = [(command.to_string(), resolved_cmd.clone())]
.into_iter()
.collect();
let authority = RuntimeAuthority::new(
Default::default(),
Resolved {
allowed_commands,
..Default::default()
},
);
assert_eq!(
authority.resolve_access(
command,
window,
webview,
&Origin::Remote {
url: url.parse().unwrap()
}
),
Some(resolved_cmd)
);
}
#[test]
fn remote_domain_glob_pattern_matches() {
let url = "http://tauri.*";
let command = "my-command";
let window = "main";
let webview = "main";
let resolved_cmd = vec![ResolvedCommand {
windows: vec![Pattern::new(window).unwrap()],
context: ExecutionContext::Remote {
url: url.parse().unwrap(),
},
..Default::default()
}];
let allowed_commands = [(command.to_string(), resolved_cmd.clone())]
.into_iter()
.collect();
let authority = RuntimeAuthority::new(
Default::default(),
Resolved {
allowed_commands,
..Default::default()
},
);
assert_eq!(
authority.resolve_access(
command,
window,
webview,
&Origin::Remote {
url: url.replace('*', "studio").parse().unwrap()
}
),
Some(resolved_cmd)
);
}
#[test]
fn remote_context_denied() {
let command = "my-command";
let window = "main";
let webview = "main";
let resolved_cmd = vec![ResolvedCommand {
windows: vec![Pattern::new(window).unwrap()],
..Default::default()
}];
let allowed_commands = [(command.to_string(), resolved_cmd)].into_iter().collect();
let authority = RuntimeAuthority::new(
Default::default(),
Resolved {
allowed_commands,
..Default::default()
},
);
assert!(authority
.resolve_access(
command,
window,
webview,
&Origin::Remote {
url: "https://tauri.app".parse().unwrap()
}
)
.is_none());
}
#[test]
fn denied_command_takes_precendence() {
let command = "my-command";
let window = "main";
let webview = "main";
let windows = vec![Pattern::new(window).unwrap()];
let allowed_commands = [(
command.to_string(),
vec![ResolvedCommand {
windows: windows.clone(),
..Default::default()
}],
)]
.into_iter()
.collect();
let denied_commands = [(
command.to_string(),
vec![ResolvedCommand {
windows,
..Default::default()
}],
)]
.into_iter()
.collect();
let authority = RuntimeAuthority::new(
Default::default(),
Resolved {
allowed_commands,
denied_commands,
..Default::default()
},
);
assert!(authority
.resolve_access(command, window, webview, &Origin::Local)
.is_none());
}
#[cfg(debug_assertions)]
#[test]
fn resolve_access_message() {
use tauri_utils::acl::manifest::Manifest;
let plugin_name = "myplugin";
let command_allowed_on_window = "my-command-window";
let command_allowed_on_webview_window = "my-command-webview-window";
let window = "main-*";
let webview = "webview-*";
let remote_url = "http://localhost:8080";
let referenced_by = tauri_utils::acl::resolved::ResolvedCommandReference {
capability: "maincap".to_string(),
permission: "allow-command".to_string(),
};
let resolved_window_cmd = ResolvedCommand {
windows: vec![Pattern::new(window).unwrap()],
referenced_by: referenced_by.clone(),
..Default::default()
};
let resolved_webview_window_cmd = ResolvedCommand {
windows: vec![Pattern::new(window).unwrap()],
webviews: vec![Pattern::new(webview).unwrap()],
referenced_by: referenced_by.clone(),
..Default::default()
};
let resolved_webview_window_remote_cmd = ResolvedCommand {
windows: vec![Pattern::new(window).unwrap()],
webviews: vec![Pattern::new(webview).unwrap()],
referenced_by,
context: ExecutionContext::Remote {
url: remote_url.parse().unwrap(),
},
..Default::default()
};
let allowed_commands = [
(
format!("plugin:{plugin_name}|{command_allowed_on_window}"),
vec![resolved_window_cmd],
),
(
format!("plugin:{plugin_name}|{command_allowed_on_webview_window}"),
vec![
resolved_webview_window_cmd,
resolved_webview_window_remote_cmd,
],
),
]
.into_iter()
.collect();
let authority = RuntimeAuthority::new(
[(
plugin_name.to_string(),
Manifest {
default_permission: None,
permissions: Default::default(),
permission_sets: Default::default(),
global_scope_schema: None,
},
)]
.into_iter()
.collect(),
Resolved {
allowed_commands,
..Default::default()
},
);
// unknown plugin
assert_eq!(
authority.resolve_access_message(
"unknown-plugin",
command_allowed_on_window,
window,
webview,
&Origin::Local
),
"unknown-plugin.my-command-window not allowed. Plugin not found"
);
// unknown command
assert_eq!(
authority.resolve_access_message(
plugin_name,
"unknown-command",
window,
webview,
&Origin::Local
),
"myplugin.unknown-command not allowed. Command not found"
);
// window/webview do not match
assert_eq!(
authority.resolve_access_message(
plugin_name,
command_allowed_on_window,
"other-window",
"any-webview",
&Origin::Local
),
"myplugin.my-command-window not allowed on window \"other-window\", webview \"any-webview\", URL: local\n\nallowed on: [windows: \"main-*\", URL: local]\n\nreferenced by: capability: maincap, permission: allow-command"
);
// window matches, but not origin
assert_eq!(
authority.resolve_access_message(
plugin_name,
command_allowed_on_window,
window,
"any-webview",
&Origin::Remote {
url: "http://localhst".parse().unwrap()
}
),
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | true |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/ipc/protocol.rs | crates/tauri/src/ipc/protocol.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{borrow::Cow, sync::Arc};
use crate::{
ipc::InvokeResponseBody,
manager::AppManager,
webview::{InvokeRequest, UriSchemeProtocolHandler},
Runtime,
};
use http::{
header::{
ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_EXPOSE_HEADERS,
CONTENT_TYPE,
},
HeaderValue, Method, Request, StatusCode,
};
use url::Url;
use super::{CallbackFn, InvokeResponse};
const TAURI_CALLBACK_HEADER_NAME: &str = "Tauri-Callback";
const TAURI_ERROR_HEADER_NAME: &str = "Tauri-Error";
const TAURI_INVOKE_KEY_HEADER_NAME: &str = "Tauri-Invoke-Key";
const TAURI_RESPONSE_HEADER_NAME: &str = "Tauri-Response";
const TAURI_RESPONSE_HEADER_ERROR: &str = "error";
const TAURI_RESPONSE_HEADER_OK: &str = "ok";
pub fn message_handler<R: Runtime>(
manager: Arc<AppManager<R>>,
) -> crate::runtime::webview::WebviewIpcHandler<crate::EventLoopMessage, R> {
Box::new(move |webview, request| handle_ipc_message(request, &manager, &webview.label))
}
pub fn get<R: Runtime>(manager: Arc<AppManager<R>>) -> UriSchemeProtocolHandler {
Box::new(move |label, request, responder| {
#[cfg(feature = "tracing")]
let span = tracing::trace_span!(
"ipc::request",
kind = "custom-protocol",
request = tracing::field::Empty
)
.entered();
let respond = move |mut response: http::Response<Cow<'static, [u8]>>| {
response
.headers_mut()
.insert(ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_static("*"));
response.headers_mut().insert(
ACCESS_CONTROL_EXPOSE_HEADERS,
HeaderValue::from_static(TAURI_RESPONSE_HEADER_NAME),
);
responder.respond(response);
};
match *request.method() {
Method::POST => {
if let Some(webview) = manager.get_webview(label) {
match parse_invoke_request(&manager, request) {
Ok(request) => {
#[cfg(feature = "tracing")]
span.record(
"request",
match &request.body {
super::InvokeBody::Json(j) => serde_json::to_string(j).unwrap(),
super::InvokeBody::Raw(b) => serde_json::to_string(b).unwrap(),
},
);
#[cfg(feature = "tracing")]
let request_span = tracing::trace_span!("ipc::request::handle", cmd = request.cmd);
webview.on_message(
request,
Box::new(move |_webview, _cmd, response, _callback, _error| {
#[cfg(feature = "tracing")]
let _respond_span = tracing::trace_span!(
parent: &request_span,
"ipc::request::respond"
)
.entered();
#[cfg(feature = "tracing")]
let response_span = match &response {
InvokeResponse::Ok(InvokeResponseBody::Json(v)) => tracing::trace_span!(
"ipc::request::response",
response = v,
mime_type = tracing::field::Empty
)
.entered(),
InvokeResponse::Ok(InvokeResponseBody::Raw(v)) => tracing::trace_span!(
"ipc::request::response",
response = format!("{v:?}"),
mime_type = tracing::field::Empty
)
.entered(),
InvokeResponse::Err(e) => tracing::trace_span!(
"ipc::request::response",
error = format!("{e:?}"),
mime_type = tracing::field::Empty
)
.entered(),
};
let response_header = match &response {
InvokeResponse::Ok(_) => TAURI_RESPONSE_HEADER_OK,
InvokeResponse::Err(_) => TAURI_RESPONSE_HEADER_ERROR,
};
let (mut response, mime_type) = match response {
InvokeResponse::Ok(InvokeResponseBody::Json(v)) => (
http::Response::new(v.into_bytes().into()),
mime::APPLICATION_JSON,
),
InvokeResponse::Ok(InvokeResponseBody::Raw(v)) => (
http::Response::new(v.into()),
mime::APPLICATION_OCTET_STREAM,
),
InvokeResponse::Err(e) => (
http::Response::new(serde_json::to_vec(&e.0).unwrap().into()),
mime::APPLICATION_JSON,
),
};
response
.headers_mut()
.insert(TAURI_RESPONSE_HEADER_NAME, response_header.parse().unwrap());
#[cfg(feature = "tracing")]
response_span.record("mime_type", mime_type.essence_str());
response.headers_mut().insert(
CONTENT_TYPE,
HeaderValue::from_str(mime_type.essence_str()).unwrap(),
);
respond(response);
}),
);
}
Err(e) => {
respond(
http::Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.header(CONTENT_TYPE, mime::TEXT_PLAIN.essence_str())
.body(e.into_bytes().into())
.unwrap(),
);
}
}
} else {
respond(
http::Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.header(CONTENT_TYPE, mime::TEXT_PLAIN.essence_str())
.body("failed to acquire webview reference".as_bytes().into())
.unwrap(),
);
}
}
Method::OPTIONS => {
let mut r = http::Response::new(Vec::new().into());
r.headers_mut()
.insert(ACCESS_CONTROL_ALLOW_HEADERS, HeaderValue::from_static("*"));
respond(r);
}
_ => {
let mut r = http::Response::new("only POST and OPTIONS are allowed".as_bytes().into());
*r.status_mut() = StatusCode::METHOD_NOT_ALLOWED;
r.headers_mut().insert(
CONTENT_TYPE,
HeaderValue::from_str(mime::TEXT_PLAIN.essence_str()).unwrap(),
);
respond(r);
}
}
})
}
fn handle_ipc_message<R: Runtime>(request: Request<String>, manager: &AppManager<R>, label: &str) {
if let Some(webview) = manager.get_webview(label) {
#[cfg(feature = "tracing")]
let _span = tracing::trace_span!(
"ipc::request",
kind = "post-message",
uri = request.uri().to_string(),
request = request.body()
)
.entered();
use serde::{Deserialize, Deserializer};
#[derive(Default)]
pub(crate) struct HeaderMap(http::HeaderMap);
impl<'de> Deserialize<'de> for HeaderMap {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let map = std::collections::HashMap::<String, String>::deserialize(deserializer)?;
let mut headers = http::HeaderMap::default();
for (key, value) in map {
if let (Ok(key), Ok(value)) = (
http::header::HeaderName::from_bytes(key.as_bytes()),
http::HeaderValue::from_str(&value),
) {
headers.insert(key, value);
} else {
return Err(serde::de::Error::custom(format!(
"invalid header `{key}` `{value}`"
)));
}
}
Ok(Self(headers))
}
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "camelCase")]
struct RequestOptions {
#[serde(default)]
headers: HeaderMap,
#[serde(default)]
custom_protocol_ipc_blocked: bool,
}
#[derive(Deserialize)]
struct Message {
cmd: String,
callback: CallbackFn,
error: CallbackFn,
payload: serde_json::Value,
options: Option<RequestOptions>,
#[serde(rename = "__TAURI_INVOKE_KEY__")]
invoke_key: String,
}
#[allow(unused_mut)]
let mut invoke_message: Option<crate::Result<Message>> = None;
#[cfg(feature = "isolation")]
{
#[derive(serde::Deserialize)]
struct IsolationMessage<'a> {
cmd: String,
callback: CallbackFn,
error: CallbackFn,
payload: crate::utils::pattern::isolation::RawIsolationPayload<'a>,
options: Option<RequestOptions>,
#[serde(rename = "__TAURI_INVOKE_KEY__")]
invoke_key: String,
}
if let crate::Pattern::Isolation { crypto_keys, .. } = &*manager.pattern {
#[cfg(feature = "tracing")]
let _span = tracing::trace_span!("ipc::request::decrypt_isolation_payload").entered();
invoke_message.replace(
serde_json::from_str::<IsolationMessage<'_>>(request.body())
.map_err(Into::into)
.and_then(|message| {
let is_raw =
message.payload.content_type() == &mime::APPLICATION_OCTET_STREAM.to_string();
let payload = crypto_keys.decrypt(message.payload)?;
Ok(Message {
cmd: message.cmd,
callback: message.callback,
error: message.error,
payload: if is_raw {
payload.into()
} else {
serde_json::from_slice(&payload)?
},
options: message.options,
invoke_key: message.invoke_key,
})
}),
);
}
}
let message = invoke_message.unwrap_or_else(|| {
#[cfg(feature = "tracing")]
let _span = tracing::trace_span!("ipc::request::deserialize").entered();
serde_json::from_str::<Message>(request.body()).map_err(Into::into)
});
match message {
Ok(message) => {
let options = message.options.unwrap_or_default();
let request = InvokeRequest {
cmd: message.cmd,
callback: message.callback,
error: message.error,
url: Url::parse(&request.uri().to_string()).expect("invalid IPC request URL"),
body: message.payload.into(),
headers: options.headers.0,
invoke_key: message.invoke_key,
};
#[cfg(feature = "tracing")]
let request_span = tracing::trace_span!("ipc::request::handle", cmd = request.cmd);
webview.on_message(
request,
Box::new(move |webview, cmd, response, callback, error| {
use crate::ipc::Channel;
#[cfg(feature = "tracing")]
let _respond_span = tracing::trace_span!(
parent: &request_span,
"ipc::request::respond"
)
.entered();
fn responder_eval<R: Runtime>(
webview: &crate::Webview<R>,
js: crate::Result<String>,
error: CallbackFn,
) {
let eval_js = match js {
Ok(js) => js,
Err(e) => crate::ipc::format_callback::format(error, &e.to_string())
.expect("unable to serialize response error string to json"),
};
let _ = webview.eval(eval_js);
}
let can_use_channel_for_response = cmd
!= crate::ipc::channel::FETCH_CHANNEL_DATA_COMMAND
&& !options.custom_protocol_ipc_blocked;
#[cfg(feature = "tracing")]
let mime_type = match &response {
InvokeResponse::Ok(InvokeResponseBody::Json(_)) => mime::APPLICATION_JSON,
InvokeResponse::Ok(InvokeResponseBody::Raw(_)) => mime::APPLICATION_OCTET_STREAM,
InvokeResponse::Err(_) => mime::APPLICATION_JSON,
};
#[cfg(feature = "tracing")]
let _response_span = match &response {
InvokeResponse::Ok(InvokeResponseBody::Json(v)) => tracing::trace_span!(
"ipc::request::response",
response = v,
mime_type = mime_type.essence_str()
)
.entered(),
InvokeResponse::Ok(InvokeResponseBody::Raw(v)) => tracing::trace_span!(
"ipc::request::response",
response = format!("{v:?}"),
mime_type = mime_type.essence_str()
)
.entered(),
InvokeResponse::Err(e) => tracing::trace_span!(
"ipc::request::response",
response = format!("{e:?}"),
mime_type = mime_type.essence_str()
)
.entered(),
};
match response {
InvokeResponse::Ok(InvokeResponseBody::Json(v)) => {
if !(cfg!(target_os = "macos") || cfg!(target_os = "ios"))
&& (v.starts_with('{') || v.starts_with('['))
&& can_use_channel_for_response
{
let _ =
Channel::from_callback_fn(webview, callback).send(InvokeResponseBody::Json(v));
} else {
responder_eval(
&webview,
crate::ipc::format_callback::format_result_raw(
Result::<_, String>::Ok(v),
callback,
error,
),
error,
)
}
}
InvokeResponse::Ok(InvokeResponseBody::Raw(v)) => {
if cfg!(target_os = "macos")
|| cfg!(target_os = "ios")
|| !can_use_channel_for_response
{
responder_eval(
&webview,
crate::ipc::format_callback::format_result(
Result::<_, ()>::Ok(v),
callback,
error,
),
error,
);
} else {
let _ =
Channel::from_callback_fn(webview, callback).send(InvokeResponseBody::Raw(v));
}
}
InvokeResponse::Err(e) => responder_eval(
&webview,
crate::ipc::format_callback::format_result(
Result::<(), _>::Err(&e.0),
callback,
error,
),
error,
),
}
}),
);
}
Err(e) => {
#[cfg(feature = "tracing")]
tracing::trace!("ipc.request.error {}", e);
let _ = webview.eval(format!(
r#"console.error({})"#,
serde_json::Value::String(e.to_string())
));
}
}
}
}
fn parse_invoke_request<R: Runtime>(
#[allow(unused_variables)] manager: &AppManager<R>,
request: http::Request<Vec<u8>>,
) -> std::result::Result<InvokeRequest, String> {
#[allow(unused_mut)]
let (parts, mut body) = request.into_parts();
// skip leading `/`
let cmd = percent_encoding::percent_decode(&parts.uri.path().as_bytes()[1..])
.decode_utf8_lossy()
.to_string();
// on Android we cannot read the request body
// so we must ignore it because some commands use the IPC for faster response
let has_payload = !body.is_empty();
#[allow(unused_mut)]
let mut content_type = parts
.headers
.get(http::header::CONTENT_TYPE)
.and_then(|h| h.to_str().ok())
.map(|mime| mime.parse())
.unwrap_or(Ok(mime::APPLICATION_OCTET_STREAM))
.map_err(|_| "unknown content type")?;
#[cfg(feature = "isolation")]
if let crate::Pattern::Isolation { crypto_keys, .. } = &*manager.pattern {
// if the platform does not support request body, we ignore it
if has_payload {
#[cfg(feature = "tracing")]
let _span = tracing::trace_span!("ipc::request::decrypt_isolation_payload").entered();
(body, content_type) = crate::utils::pattern::isolation::RawIsolationPayload::try_from(&body)
.and_then(|raw| {
let content_type = raw.content_type().clone();
crypto_keys.decrypt(raw).map(|decrypted| {
(
decrypted,
content_type
.parse()
.unwrap_or(mime::APPLICATION_OCTET_STREAM),
)
})
})
.map_err(|e| e.to_string())?;
}
}
let invoke_key = parts
.headers
.get(TAURI_INVOKE_KEY_HEADER_NAME)
.ok_or("missing Tauri-Invoke-Key header")?
.to_str()
.map_err(|_| "Tauri invoke key header value must be a string")?
.to_owned();
let url = Url::parse(
parts
.headers
.get("Origin")
.ok_or("missing Origin header")?
.to_str()
.map_err(|_| "Origin header value must be a string")?,
)
.map_err(|_| "Origin header is not a valid URL")?;
let callback = CallbackFn(
parts
.headers
.get(TAURI_CALLBACK_HEADER_NAME)
.ok_or("missing Tauri-Callback header")?
.to_str()
.map_err(|_| "Tauri callback header value must be a string")?
.parse()
.map_err(|_| "Tauri callback header value must be a numeric string")?,
);
let error = CallbackFn(
parts
.headers
.get(TAURI_ERROR_HEADER_NAME)
.ok_or("missing Tauri-Error header")?
.to_str()
.map_err(|_| "Tauri error header value must be a string")?
.parse()
.map_err(|_| "Tauri error header value must be a numeric string")?,
);
#[cfg(feature = "tracing")]
let span = tracing::trace_span!("ipc::request::deserialize").entered();
let body = if content_type == mime::APPLICATION_OCTET_STREAM {
body.into()
} else if content_type == mime::APPLICATION_JSON {
// if the platform does not support request body, we ignore it
if has_payload {
serde_json::from_slice::<serde_json::Value>(&body)
.map_err(|e| e.to_string())?
.into()
} else {
serde_json::Value::Object(Default::default()).into()
}
} else {
return Err(format!("content type {content_type} is not implemented"));
};
#[cfg(feature = "tracing")]
drop(span);
let payload = InvokeRequest {
cmd,
callback,
error,
url,
body,
headers: parts.headers,
invoke_key,
};
Ok(payload)
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use super::*;
use crate::{ipc::InvokeBody, manager::AppManager, plugin::PluginStore, StateManager, Wry};
use http::header::*;
use serde_json::json;
use tauri_macros::generate_context;
#[test]
fn parse_invoke_request() {
let context = generate_context!("test/fixture/src-tauri/tauri.conf.json", crate, test = true);
let manager: AppManager<Wry> = AppManager::with_handlers(
context,
PluginStore::default(),
Box::new(|_| false),
None,
Default::default(),
StateManager::new(),
Default::default(),
#[cfg(all(desktop, feature = "tray-icon"))]
Default::default(),
Default::default(),
Default::default(),
Default::default(),
"".into(),
None,
crate::generate_invoke_key().unwrap(),
);
let cmd = "write_something";
let url = "tauri://localhost";
let invoke_key = "1234ahdsjkl123";
let callback = 12378123;
let error = 6243;
let mut headers = HeaderMap::from_iter(vec![
(
CONTENT_TYPE,
HeaderValue::from_str(mime::APPLICATION_OCTET_STREAM.as_ref()).unwrap(),
),
(
HeaderName::from_str(TAURI_INVOKE_KEY_HEADER_NAME).unwrap(),
HeaderValue::from_str(invoke_key).unwrap(),
),
(
HeaderName::from_str(TAURI_CALLBACK_HEADER_NAME).unwrap(),
HeaderValue::from_str(&callback.to_string()).unwrap(),
),
(
HeaderName::from_str(TAURI_ERROR_HEADER_NAME).unwrap(),
HeaderValue::from_str(&error.to_string()).unwrap(),
),
(ORIGIN, HeaderValue::from_str("tauri://localhost").unwrap()),
]);
let mut request = Request::builder().uri(format!("ipc://localhost/{cmd}"));
*request.headers_mut().unwrap() = headers.clone();
let body = vec![123, 31, 45];
let request = request.body(body.clone()).unwrap();
let invoke_request = super::parse_invoke_request(&manager, request).unwrap();
assert_eq!(invoke_request.cmd, cmd);
assert_eq!(invoke_request.callback.0, callback);
assert_eq!(invoke_request.error.0, error);
assert_eq!(invoke_request.invoke_key, invoke_key);
assert_eq!(invoke_request.url, url.parse().unwrap());
assert_eq!(invoke_request.headers, headers);
assert_eq!(invoke_request.body, InvokeBody::Raw(body));
let body = json!({
"key": 1,
"anotherKey": "asda",
});
headers.insert(
CONTENT_TYPE,
HeaderValue::from_str(mime::APPLICATION_JSON.as_ref()).unwrap(),
);
let mut request = Request::builder().uri(format!("ipc://localhost/{cmd}"));
*request.headers_mut().unwrap() = headers.clone();
let request = request.body(serde_json::to_vec(&body).unwrap()).unwrap();
let invoke_request = super::parse_invoke_request(&manager, request).unwrap();
assert_eq!(invoke_request.headers, headers);
assert_eq!(invoke_request.body, InvokeBody::Json(body));
}
#[test]
#[cfg(feature = "isolation")]
fn parse_invoke_request_isolation() {
let context = generate_context!(
"test/fixture/isolation/src-tauri/tauri.conf.json",
crate,
test = false
);
let crate::pattern::Pattern::Isolation { crypto_keys, .. } = &context.pattern else {
unreachable!()
};
let mut nonce = [0u8; 12];
getrandom::fill(&mut nonce).unwrap();
let body_raw = vec![1, 41, 65, 12, 78];
let body_bytes = crypto_keys.aes_gcm().encrypt(&nonce, &body_raw).unwrap();
let isolation_payload_raw = json!({
"nonce": nonce,
"payload": body_bytes,
"contentType": mime::APPLICATION_OCTET_STREAM.to_string(),
});
let body_json = json!({
"key": 1,
"anotherKey": "string"
});
let body_bytes = crypto_keys
.aes_gcm()
.encrypt(&nonce, &serde_json::to_vec(&body_json).unwrap())
.unwrap();
let isolation_payload_json = json!({
"nonce": nonce,
"payload": body_bytes,
"contentType": mime::APPLICATION_JSON.to_string(),
});
let manager: AppManager<Wry> = AppManager::with_handlers(
context,
PluginStore::default(),
Box::new(|_| false),
None,
Default::default(),
StateManager::new(),
Default::default(),
#[cfg(all(desktop, feature = "tray-icon"))]
Default::default(),
Default::default(),
Default::default(),
Default::default(),
"".into(),
None,
crate::generate_invoke_key().unwrap(),
);
let cmd = "write_something";
let url = "tauri://localhost";
let invoke_key = "1234ahdsjkl123";
let callback = 12378123;
let error = 6243;
let headers = HeaderMap::from_iter(vec![
(
CONTENT_TYPE,
HeaderValue::from_str(mime::APPLICATION_JSON.as_ref()).unwrap(),
),
(
HeaderName::from_str(TAURI_INVOKE_KEY_HEADER_NAME).unwrap(),
HeaderValue::from_str(invoke_key).unwrap(),
),
(
HeaderName::from_str(TAURI_CALLBACK_HEADER_NAME).unwrap(),
HeaderValue::from_str(&callback.to_string()).unwrap(),
),
(
HeaderName::from_str(TAURI_ERROR_HEADER_NAME).unwrap(),
HeaderValue::from_str(&error.to_string()).unwrap(),
),
(ORIGIN, HeaderValue::from_str("tauri://localhost").unwrap()),
]);
let mut request = Request::builder().uri(format!("ipc://localhost/{cmd}"));
*request.headers_mut().unwrap() = headers.clone();
let body = serde_json::to_vec(&isolation_payload_raw).unwrap();
let request = request.body(body).unwrap();
let invoke_request = super::parse_invoke_request(&manager, request).unwrap();
assert_eq!(invoke_request.cmd, cmd);
assert_eq!(invoke_request.callback.0, callback);
assert_eq!(invoke_request.error.0, error);
assert_eq!(invoke_request.invoke_key, invoke_key);
assert_eq!(invoke_request.url, url.parse().unwrap());
assert_eq!(invoke_request.headers, headers);
assert_eq!(invoke_request.body, InvokeBody::Raw(body_raw));
let mut request = Request::builder().uri(format!("ipc://localhost/{cmd}"));
*request.headers_mut().unwrap() = headers.clone();
let body = serde_json::to_vec(&isolation_payload_json).unwrap();
let request = request.body(body).unwrap();
let invoke_request = super::parse_invoke_request(&manager, request).unwrap();
assert_eq!(invoke_request.headers, headers);
assert_eq!(invoke_request.body, InvokeBody::Json(body_json));
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/ipc/channel.rs | crates/tauri/src/ipc/channel.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{
collections::HashMap,
str::FromStr,
sync::{
atomic::{AtomicU32, AtomicUsize, Ordering},
Arc, Mutex,
},
};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::{
command,
ipc::{CommandArg, CommandItem},
plugin::{Builder as PluginBuilder, TauriPlugin},
Manager, Runtime, State, Webview,
};
use super::{
format_callback::format_raw_js, CallbackFn, InvokeError, InvokeResponseBody, IpcResponse,
Request, Response,
};
pub const IPC_PAYLOAD_PREFIX: &str = "__CHANNEL__:";
// TODO: Change this to `channel` in v3
pub const CHANNEL_PLUGIN_NAME: &str = "__TAURI_CHANNEL__";
// TODO: Change this to `plugin:channel|fetch` in v3
pub const FETCH_CHANNEL_DATA_COMMAND: &str = "plugin:__TAURI_CHANNEL__|fetch";
const CHANNEL_ID_HEADER_NAME: &str = "Tauri-Channel-Id";
/// Maximum size a JSON we should send directly without going through the fetch process
// 8192 byte JSON payload runs roughly 2x faster through eval than through fetch on WebView2 v135
const MAX_JSON_DIRECT_EXECUTE_THRESHOLD: usize = 8192;
// 1024 byte payload runs roughly 30% faster through eval than through fetch on macOS
const MAX_RAW_DIRECT_EXECUTE_THRESHOLD: usize = 1024;
static CHANNEL_COUNTER: AtomicU32 = AtomicU32::new(0);
static CHANNEL_DATA_COUNTER: AtomicU32 = AtomicU32::new(0);
/// Maps a channel id to a pending data that must be send to the JavaScript side via the IPC.
#[derive(Default, Clone)]
pub struct ChannelDataIpcQueue(Arc<Mutex<HashMap<u32, InvokeResponseBody>>>);
/// An IPC channel.
pub struct Channel<TSend = InvokeResponseBody> {
inner: Arc<ChannelInner>,
phantom: std::marker::PhantomData<TSend>,
}
#[cfg(feature = "specta")]
const _: () = {
#[derive(specta::Type)]
#[specta(remote = super::Channel, rename = "TAURI_CHANNEL")]
#[allow(dead_code)]
struct Channel<TSend>(std::marker::PhantomData<TSend>);
};
impl<TSend> Clone for Channel<TSend> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
phantom: self.phantom,
}
}
}
type OnDropFn = Option<Box<dyn Fn() + Send + Sync + 'static>>;
type OnMessageFn = Box<dyn Fn(InvokeResponseBody) -> crate::Result<()> + Send + Sync>;
struct ChannelInner {
id: u32,
on_message: OnMessageFn,
on_drop: OnDropFn,
}
impl Drop for ChannelInner {
fn drop(&mut self) {
if let Some(on_drop) = &self.on_drop {
on_drop();
}
}
}
impl<TSend> Serialize for Channel<TSend> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&format!("{IPC_PAYLOAD_PREFIX}{}", self.inner.id))
}
}
/// The ID of a channel that was defined on the JavaScript layer.
///
/// Useful when expecting [`Channel`] as part of a JSON object instead of a top-level command argument.
///
/// # Examples
///
/// ```rust
/// use tauri::{ipc::JavaScriptChannelId, Runtime, Webview};
///
/// #[derive(serde::Deserialize)]
/// #[serde(rename_all = "camelCase")]
/// struct Button {
/// label: String,
/// on_click: JavaScriptChannelId,
/// }
///
/// #[tauri::command]
/// fn add_button<R: Runtime>(webview: Webview<R>, button: Button) {
/// let channel = button.on_click.channel_on(webview);
/// channel.send("clicked").unwrap();
/// }
/// ```
pub struct JavaScriptChannelId(CallbackFn);
impl FromStr for JavaScriptChannelId {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
s.strip_prefix(IPC_PAYLOAD_PREFIX)
.ok_or("invalid channel string")
.and_then(|id| id.parse().map_err(|_| "invalid channel ID"))
.map(|id| Self(CallbackFn(id)))
}
}
impl JavaScriptChannelId {
/// Gets a [`Channel`] for this channel ID on the given [`Webview`].
pub fn channel_on<R: Runtime, TSend>(&self, webview: Webview<R>) -> Channel<TSend> {
let callback_fn = self.0;
let callback_id = callback_fn.0;
let counter = Arc::new(AtomicUsize::new(0));
let counter_clone = counter.clone();
let webview_clone = webview.clone();
Channel::new_with_id(
callback_id,
Box::new(move |body| {
let current_index = counter.fetch_add(1, Ordering::Relaxed);
if let Some(interceptor) = &webview.manager.channel_interceptor {
if interceptor(&webview, callback_fn, current_index, &body) {
return Ok(());
}
}
match body {
// Don't go through the fetch process if the payload is small
InvokeResponseBody::Json(json_string)
if json_string.len() < MAX_JSON_DIRECT_EXECUTE_THRESHOLD =>
{
webview.eval(format_raw_js(
callback_id,
format!("{{ message: {json_string}, index: {current_index} }}"),
))?;
}
InvokeResponseBody::Raw(bytes) if bytes.len() < MAX_RAW_DIRECT_EXECUTE_THRESHOLD => {
let bytes_as_json_array = serde_json::to_string(&bytes)?;
webview.eval(format_raw_js(callback_id, format!("{{ message: new Uint8Array({bytes_as_json_array}).buffer, index: {current_index} }}")))?;
}
// use the fetch API to speed up larger response payloads
_ => {
let data_id = CHANNEL_DATA_COUNTER.fetch_add(1, Ordering::Relaxed);
webview
.state::<ChannelDataIpcQueue>()
.0
.lock()
.unwrap()
.insert(data_id, body);
webview.eval(format!(
"window.__TAURI_INTERNALS__.invoke('{FETCH_CHANNEL_DATA_COMMAND}', null, {{ headers: {{ '{CHANNEL_ID_HEADER_NAME}': '{data_id}' }} }}).then((response) => window.__TAURI_INTERNALS__.runCallback({callback_id}, {{ message: response, index: {current_index} }})).catch(console.error)",
))?;
}
}
Ok(())
}),
Some(Box::new(move || {
let current_index = counter_clone.load(Ordering::Relaxed);
let _ = webview_clone.eval(format_raw_js(
callback_id,
format!("{{ end: true, index: {current_index} }}"),
));
})),
)
}
}
impl<'de> Deserialize<'de> for JavaScriptChannelId {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value: String = Deserialize::deserialize(deserializer)?;
Self::from_str(&value).map_err(|_| {
serde::de::Error::custom(format!(
"invalid channel value `{value}`, expected a string in the `{IPC_PAYLOAD_PREFIX}ID` format"
))
})
}
}
impl<TSend> Channel<TSend> {
/// Creates a new channel with the given message handler.
pub fn new<F: Fn(InvokeResponseBody) -> crate::Result<()> + Send + Sync + 'static>(
on_message: F,
) -> Self {
Self::new_with_id(
CHANNEL_COUNTER.fetch_add(1, Ordering::Relaxed),
Box::new(on_message),
None,
)
}
fn new_with_id(id: u32, on_message: OnMessageFn, on_drop: OnDropFn) -> Self {
#[allow(clippy::let_and_return)]
let channel = Self {
inner: Arc::new(ChannelInner {
id,
on_message,
on_drop,
}),
phantom: Default::default(),
};
#[cfg(mobile)]
crate::plugin::mobile::register_channel(Channel {
inner: channel.inner.clone(),
phantom: Default::default(),
});
channel
}
// This is used from the IPC handler
pub(crate) fn from_callback_fn<R: Runtime>(webview: Webview<R>, callback: CallbackFn) -> Self {
let callback_id = callback.0;
Channel::new_with_id(
callback_id,
Box::new(move |body| {
match body {
// Don't go through the fetch process if the payload is small
InvokeResponseBody::Json(json_string)
if json_string.len() < MAX_JSON_DIRECT_EXECUTE_THRESHOLD =>
{
webview.eval(format_raw_js(callback_id, json_string))?;
}
InvokeResponseBody::Raw(bytes) if bytes.len() < MAX_RAW_DIRECT_EXECUTE_THRESHOLD => {
let bytes_as_json_array = serde_json::to_string(&bytes)?;
webview.eval(format_raw_js(
callback_id,
format!("new Uint8Array({bytes_as_json_array}).buffer"),
))?;
}
// use the fetch API to speed up larger response payloads
_ => {
let data_id = CHANNEL_DATA_COUNTER.fetch_add(1, Ordering::Relaxed);
webview
.state::<ChannelDataIpcQueue>()
.0
.lock()
.unwrap()
.insert(data_id, body);
webview.eval(format!(
"window.__TAURI_INTERNALS__.invoke('{FETCH_CHANNEL_DATA_COMMAND}', null, {{ headers: {{ '{CHANNEL_ID_HEADER_NAME}': '{data_id}' }} }}).then((response) => window.__TAURI_INTERNALS__.runCallback({callback_id}, response)).catch(console.error)",
))?;
}
}
Ok(())
}),
None,
)
}
/// The channel identifier.
pub fn id(&self) -> u32 {
self.inner.id
}
/// Sends the given data through the channel.
pub fn send(&self, data: TSend) -> crate::Result<()>
where
TSend: IpcResponse,
{
(self.inner.on_message)(data.body()?)
}
}
impl<'de, R: Runtime, TSend> CommandArg<'de, R> for Channel<TSend> {
/// Grabs the [`Webview`] from the [`CommandItem`] and returns the associated [`Channel`].
fn from_command(command: CommandItem<'de, R>) -> Result<Self, InvokeError> {
let name = command.name;
let arg = command.key;
let webview = command.message.webview();
let value: String =
Deserialize::deserialize(command).map_err(|e| crate::Error::InvalidArgs(name, arg, e))?;
JavaScriptChannelId::from_str(&value)
.map(|id| id.channel_on(webview))
.map_err(|_| {
InvokeError::from(format!(
"invalid channel value `{value}`, expected a string in the `{IPC_PAYLOAD_PREFIX}ID` format"
))
})
}
}
#[command(root = "crate")]
fn fetch(
request: Request<'_>,
cache: State<'_, ChannelDataIpcQueue>,
) -> Result<Response, &'static str> {
if let Some(id) = request
.headers()
.get(CHANNEL_ID_HEADER_NAME)
.and_then(|v| v.to_str().ok())
.and_then(|id| id.parse().ok())
{
if let Some(data) = cache.0.lock().unwrap().remove(&id) {
Ok(Response::new(data))
} else {
Err("data not found")
}
} else {
Err("missing channel id header")
}
}
pub fn plugin<R: Runtime>() -> TauriPlugin<R> {
PluginBuilder::new(CHANNEL_PLUGIN_NAME)
.invoke_handler(crate::generate_handler![
#![plugin(__TAURI_CHANNEL__)]
fetch
])
.build()
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/ipc/format_callback.rs | crates/tauri/src/ipc/format_callback.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use serde::Serialize;
use serde_json::value::RawValue;
use serialize_to_javascript::Serialized;
use super::CallbackFn;
/// The information about this is quite limited. On Chrome/Edge and Firefox, [the maximum string size is approximately 1 GB](https://stackoverflow.com/a/34958490).
///
/// [From MDN:](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length#description)
///
/// ECMAScript 2016 (ed. 7) established a maximum length of 2^53 - 1 elements. Previously, no maximum length was specified.
///
/// In Firefox, strings have a maximum length of 2\*\*30 - 2 (~1GB). In versions prior to Firefox 65, the maximum length was 2\*\*28 - 1 (~256MB).
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 [`format_json`].
// 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;
/// Transforms & escapes a JSON value.
///
/// If it's an object or array, JSON.parse('{json}') is used, with the '{json}' string properly escaped.
/// The return value of this function can be safely used on [`eval`](crate::Window#method.eval) calls.
///
/// Single quotes chosen because double quotes are already used in JSON. With single quotes, we only
/// need to escape strings that include backslashes or single quotes. If we used double quotes, then
/// there would be no cases that a string doesn't need escaping.
///
/// The function takes a closure to handle the escaped string in order to avoid unnecessary allocations.
///
/// # Safety
///
/// The ability to safely escape JSON into a JSON.parse('{json}') relies entirely on 2 things.
///
/// 1. `serde_json`'s ability to correctly escape and format json into a string.
/// 2. JavaScript engines not accepting anything except another unescaped, literal single quote
/// character to end a string that was opened with it.
fn serialize_js_with<F: FnOnce(&str) -> String>(
json_string: String,
options: serialize_to_javascript::Options,
cb: F,
) -> crate::Result<String> {
// get a raw &str representation of a serialized json value.
let raw = RawValue::from_string(json_string)?;
// from here we know json.len() > 1 because an empty string is not a valid json value.
let json = raw.get();
let first = json.as_bytes()[0];
#[cfg(debug_assertions)]
if first == b'"' {
assert!(
json.len() < MAX_JSON_STR_LEN,
"passing a string larger than the max JavaScript literal string size"
)
}
let return_val = if json.len() > MIN_JSON_PARSE_LEN && (first == b'{' || first == b'[') {
let serialized = Serialized::new(&raw, &options).into_string();
// only use JSON.parse('{arg}') for arrays and objects less than the limit
// smaller literals do not benefit from being parsed from json
if serialized.len() < MAX_JSON_STR_LEN {
cb(&serialized)
} else {
cb(json)
}
} else {
cb(json)
};
Ok(return_val)
}
/// Formats a function name and a serializable argument to be evaluated as callback.
///
/// See [`format_raw`] for more information.
pub fn format<T: Serialize>(function_name: CallbackFn, arg: &T) -> crate::Result<String> {
format_raw(function_name, serde_json::to_string(arg)?)
}
/// Formats a function name and a raw JSON string argument to be evaluated as callback.
///
/// This will serialize primitive JSON types (e.g. booleans, strings, numbers, etc.) as JavaScript literals,
/// but will serialize arrays and objects whose serialized JSON string is smaller than 1 GB and larger
/// than 10 KiB with `JSON.parse('...')`.
/// See [json-parse-benchmark](https://github.com/GoogleChromeLabs/json-parse-benchmark).
pub fn format_raw(function_name: CallbackFn, json_string: String) -> crate::Result<String> {
let callback_id = function_name.0;
serialize_js_with(json_string, Default::default(), |arg| {
format_raw_js(callback_id, arg)
})
}
/// Formats a function name and a JavaScript string argument to be evaluated as callback.
pub fn format_raw_js(callback_id: u32, js: impl AsRef<str>) -> String {
fn format_inner(callback_id: u32, js: &str) -> String {
format!("window.__TAURI_INTERNALS__.runCallback({callback_id}, {js})")
}
format_inner(callback_id, js.as_ref())
}
/// Formats a serializable Result type to its Promise response.
///
/// See [`format_result_raw`] for more information.
pub fn format_result<T: Serialize, E: Serialize>(
result: Result<T, E>,
success_callback: CallbackFn,
error_callback: CallbackFn,
) -> crate::Result<String> {
match result {
Ok(res) => format(success_callback, &res),
Err(err) => format(error_callback, &err),
}
}
/// Formats a Result type of raw JSON strings to its Promise response.
/// Useful for Promises handling.
/// If the Result `is_ok()`, the callback will be the `success_callback` function name and the argument will be the Ok value.
/// If the Result `is_err()`, the callback will be the `error_callback` function name and the argument will be the Err value.
///
/// * `result` the Result to check
/// * `success_callback` the function name of the Ok callback. Usually the `resolve` of the JS Promise.
/// * `error_callback` the function name of the Err callback. Usually the `reject` of the JS Promise.
///
/// Note that the callback strings are automatically generated by the `invoke` helper.
pub fn format_result_raw(
raw_result: Result<String, String>,
success_callback: CallbackFn,
error_callback: CallbackFn,
) -> crate::Result<String> {
match raw_result {
Ok(res) => format_raw(success_callback, res),
Err(err) => format_raw(error_callback, err),
}
}
#[cfg(test)]
mod test {
use super::*;
use quickcheck::{Arbitrary, Gen};
use quickcheck_macros::quickcheck;
impl Arbitrary for CallbackFn {
fn arbitrary(g: &mut Gen) -> CallbackFn {
CallbackFn(u32::arbitrary(g))
}
}
#[derive(Debug, Clone)]
struct JsonStr(String);
impl Arbitrary for JsonStr {
fn arbitrary(g: &mut Gen) -> Self {
if bool::arbitrary(g) {
Self(format!(
"{{ {}: {} }}",
serde_json::to_string(&String::arbitrary(g)).unwrap(),
serde_json::to_string(&String::arbitrary(g)).unwrap()
))
} else {
Self(serde_json::to_string(&String::arbitrary(g)).unwrap())
}
}
}
fn serialize_js<T: Serialize>(value: &T) -> crate::Result<String> {
serialize_js_with(serde_json::to_string(value)?, Default::default(), |v| {
v.into()
})
}
fn serialize_js_raw(value: impl Into<String>) -> crate::Result<String> {
serialize_js_with(value.into(), Default::default(), |v| v.into())
}
#[test]
fn test_serialize_js() {
assert_eq!(serialize_js(&()).unwrap(), "null");
assert_eq!(serialize_js(&5i32).unwrap(), "5");
#[derive(serde::Serialize)]
struct JsonObj {
value: String,
}
let raw_str = "T".repeat(MIN_JSON_PARSE_LEN);
assert_eq!(serialize_js(&raw_str).unwrap(), format!("\"{raw_str}\""));
assert_eq!(
serialize_js(&JsonObj {
value: raw_str.clone()
})
.unwrap(),
format!("JSON.parse('{{\"value\":\"{raw_str}\"}}')")
);
assert_eq!(
serialize_js(&JsonObj {
value: format!("\"{raw_str}\"")
})
.unwrap(),
format!("JSON.parse('{{\"value\":\"\\\\\"{raw_str}\\\\\"\"}}')")
);
let dangerous_json = RawValue::from_string(
r#"{"test":"don\\🚀🐱👤\\'t forget to escape me!🚀🐱👤","te🚀🐱👤st2":"don't forget to escape me!","test3":"\\🚀🐱👤\\\\'''\\\\🚀🐱👤\\\\🚀🐱👤\\'''''"}"#.into()
).unwrap();
let definitely_escaped_dangerous_json = format!(
"JSON.parse('{}')",
dangerous_json
.get()
.replace('\\', "\\\\")
.replace('\'', "\\'")
);
let escape_single_quoted_json_test =
serialize_to_javascript::Serialized::new(&dangerous_json, &Default::default()).into_string();
let result = r#"JSON.parse('{"test":"don\\\\🚀🐱👤\\\\\'t forget to escape me!🚀🐱👤","te🚀🐱👤st2":"don\'t forget to escape me!","test3":"\\\\🚀🐱👤\\\\\\\\\'\'\'\\\\\\\\🚀🐱👤\\\\\\\\🚀🐱👤\\\\\'\'\'\'\'"}')"#;
assert_eq!(definitely_escaped_dangerous_json, result);
assert_eq!(escape_single_quoted_json_test, result);
}
// check arbitrary strings in the format callback function
#[quickcheck]
fn qc_formatting(f: CallbackFn, a: String) -> bool {
// call format callback
let fc = format(f, &a).unwrap();
fc.contains(&format!(
"window.__TAURI_INTERNALS__.runCallback({}, JSON.parse('{}'))",
f.0,
serde_json::Value::String(a.clone()),
)) || fc.contains(&format!(
r#"window.__TAURI_INTERNALS__.runCallback({}, {})"#,
f.0,
serde_json::Value::String(a),
))
}
// check arbitrary strings in format_result
#[quickcheck]
fn qc_format_res(result: Result<String, String>, c: CallbackFn, ec: CallbackFn) -> bool {
let resp = format_result(result.clone(), c, ec).expect("failed to format callback result");
let (function, value) = match result {
Ok(v) => (c, v),
Err(e) => (ec, e),
};
resp.contains(&format!(
r#"window.__TAURI_INTERNALS__.runCallback({}, {})"#,
function.0,
serde_json::Value::String(value),
))
}
#[test]
fn test_serialize_js_raw() {
assert_eq!(serialize_js_raw("null").unwrap(), "null");
assert_eq!(serialize_js_raw("5").unwrap(), "5");
assert_eq!(
serialize_js_raw("{ \"x\": [1, 2, 3] }").unwrap(),
"{ \"x\": [1, 2, 3] }"
);
#[derive(serde::Serialize)]
struct JsonObj {
value: String,
}
let raw_str = "T".repeat(MIN_JSON_PARSE_LEN);
assert_eq!(
serialize_js_raw(format!("\"{raw_str}\"")).unwrap(),
format!("\"{raw_str}\"")
);
assert_eq!(
serialize_js_raw(format!("{{\"value\":\"{raw_str}\"}}")).unwrap(),
format!("JSON.parse('{{\"value\":\"{raw_str}\"}}')")
);
assert_eq!(
serialize_js(&JsonObj {
value: format!("\"{raw_str}\"")
})
.unwrap(),
format!("JSON.parse('{{\"value\":\"\\\\\"{raw_str}\\\\\"\"}}')")
);
let dangerous_json = RawValue::from_string(
r#"{"test":"don\\🚀🐱👤\\'t forget to escape me!🚀🐱👤","te🚀🐱👤st2":"don't forget to escape me!","test3":"\\🚀🐱👤\\\\'''\\\\🚀🐱👤\\\\🚀🐱👤\\'''''"}"#.into()
).unwrap();
let definitely_escaped_dangerous_json = format!(
"JSON.parse('{}')",
dangerous_json
.get()
.replace('\\', "\\\\")
.replace('\'', "\\'")
);
let escape_single_quoted_json_test =
serialize_to_javascript::Serialized::new(&dangerous_json, &Default::default()).into_string();
let result = r#"JSON.parse('{"test":"don\\\\🚀🐱👤\\\\\'t forget to escape me!🚀🐱👤","te🚀🐱👤st2":"don\'t forget to escape me!","test3":"\\\\🚀🐱👤\\\\\\\\\'\'\'\\\\\\\\🚀🐱👤\\\\\\\\🚀🐱👤\\\\\'\'\'\'\'"}')"#;
assert_eq!(definitely_escaped_dangerous_json, result);
assert_eq!(escape_single_quoted_json_test, result);
}
// check arbitrary strings in the format callback function
#[quickcheck]
fn qc_formatting_raw(f: CallbackFn, a: JsonStr) -> bool {
let a = a.0;
// call format callback
let fc = format_raw(f, a.clone()).unwrap();
fc.contains(&format!(
r#"window.__TAURI_INTERNALS__.runCallback({}, JSON.parse('{}'))"#,
f.0, a
)) || fc.contains(&format!(
r#"window.__TAURI_INTERNALS__.runCallback({}, {})"#,
f.0, a
))
}
// check arbitrary strings in format_result
#[quickcheck]
fn qc_format_raw_res(result: Result<JsonStr, JsonStr>, c: CallbackFn, ec: CallbackFn) -> bool {
let result = result.map(|v| v.0).map_err(|e| e.0);
let resp = format_result_raw(result.clone(), c, ec).expect("failed to format callback result");
let (function, value) = match result {
Ok(v) => (c, v),
Err(e) => (ec, e),
};
resp.contains(&format!(
r#"window.__TAURI_INTERNALS__.runCallback({}, {})"#,
function.0, value
))
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/manager/tray.rs | crates/tauri/src/manager/tray.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{
collections::HashMap,
fmt,
sync::{Arc, Mutex},
};
use crate::{
app::GlobalTrayIconEventListener,
image::Image,
tray::{TrayIcon, TrayIconEvent, TrayIconId},
AppHandle, Manager, Resource, ResourceId, Runtime,
};
pub struct TrayManager<R: Runtime> {
pub(crate) icon: Option<Image<'static>>,
/// Tray icons
pub(crate) icons: Mutex<Vec<(TrayIconId, ResourceId)>>,
/// Global Tray icon event listeners.
pub(crate) global_event_listeners: Mutex<Vec<GlobalTrayIconEventListener<AppHandle<R>>>>,
/// Tray icon event listeners.
pub(crate) event_listeners: Mutex<HashMap<TrayIconId, GlobalTrayIconEventListener<TrayIcon<R>>>>,
}
impl<R: Runtime> fmt::Debug for TrayManager<R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TrayManager")
.field("icon", &self.icon)
.finish()
}
}
impl<R: Runtime> TrayManager<R> {
pub fn on_tray_icon_event<F: Fn(&AppHandle<R>, TrayIconEvent) + Send + Sync + 'static>(
&self,
handler: F,
) {
self
.global_event_listeners
.lock()
.unwrap()
.push(Box::new(handler));
}
pub fn tray_by_id<'a, I>(&self, app: &AppHandle<R>, id: &'a I) -> Option<TrayIcon<R>>
where
I: ?Sized,
TrayIconId: PartialEq<&'a I>,
{
let icons = self.icons.lock().unwrap();
icons.iter().find_map(|(tray_icon_id, rid)| {
if tray_icon_id == &id {
let icon = app.resources_table().get::<TrayIcon<R>>(*rid).ok()?;
Some(Arc::unwrap_or_clone(icon))
} else {
None
}
})
}
pub fn tray_resource_by_id<'a, I>(&self, id: &'a I) -> Option<ResourceId>
where
I: ?Sized,
TrayIconId: PartialEq<&'a I>,
{
let icons = self.icons.lock().unwrap();
icons.iter().find_map(|(tray_icon_id, rid)| {
if tray_icon_id == &id {
Some(*rid)
} else {
None
}
})
}
pub fn remove_tray_by_id<'a, I>(&self, app: &AppHandle<R>, id: &'a I) -> Option<TrayIcon<R>>
where
I: ?Sized,
TrayIconId: PartialEq<&'a I>,
{
let rid = self.tray_resource_by_id(id)?;
let icon = app.resources_table().take::<TrayIcon<R>>(rid).ok()?;
let icon_to_return = icon.clone();
icon.close();
Some(Arc::unwrap_or_clone(icon_to_return))
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/manager/menu.rs | crates/tauri/src/manager/menu.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{
collections::HashMap,
sync::{Arc, Mutex, MutexGuard},
};
use crate::{
menu::{Menu, MenuEvent, MenuId},
AppHandle, Runtime, Window,
};
pub struct MenuManager<R: Runtime> {
/// A set containing a reference to the active menus, including
/// the app-wide menu and the window-specific menus
///
/// This should be mainly used to access [`Menu::haccel`]
/// to setup the accelerator handling in the event loop
pub menus: Arc<Mutex<HashMap<MenuId, Menu<R>>>>,
/// The menu set to all windows.
pub menu: Mutex<Option<Menu<R>>>,
/// Menu event listeners to all windows.
pub global_event_listeners: Mutex<Vec<crate::app::GlobalMenuEventListener<AppHandle<R>>>>,
/// Menu event listeners to specific windows.
pub event_listeners: Mutex<HashMap<String, crate::app::GlobalMenuEventListener<Window<R>>>>,
}
impl<R: Runtime> MenuManager<R> {
/// App-wide menu.
pub fn menu_lock(&self) -> MutexGuard<'_, Option<Menu<R>>> {
self.menu.lock().expect("poisoned menu mutex")
}
pub fn menus_stash_lock(&self) -> MutexGuard<'_, HashMap<MenuId, Menu<R>>> {
self.menus.lock().expect("poisoned menu mutex")
}
pub fn is_menu_in_use<I: PartialEq<MenuId>>(&self, id: &I) -> bool {
self
.menu_lock()
.as_ref()
.map(|m| id.eq(m.id()))
.unwrap_or(false)
}
pub fn insert_menu_into_stash(&self, menu: &Menu<R>) {
self
.menus_stash_lock()
.insert(menu.id().clone(), menu.clone());
}
pub(crate) fn prepare_window_menu_creation_handler(
&self,
window_menu: Option<&crate::window::WindowMenu<R>>,
#[allow(unused)] theme: Option<tauri_utils::Theme>,
) -> Option<impl Fn(tauri_runtime::window::RawWindow<'_>)> {
{
if let Some(menu) = window_menu {
self
.menus_stash_lock()
.insert(menu.menu.id().clone(), menu.menu.clone());
}
}
#[cfg(target_os = "macos")]
return None;
#[cfg_attr(target_os = "macos", allow(unused_variables, unreachable_code))]
if let Some(menu) = &window_menu {
let menu = menu.menu.clone();
Some(move |raw: tauri_runtime::window::RawWindow<'_>| {
#[cfg(target_os = "windows")]
{
let theme = theme
.map(crate::menu::map_to_menu_theme)
.unwrap_or(muda::MenuTheme::Auto);
let _ = unsafe { menu.inner().init_for_hwnd_with_theme(raw.hwnd as _, theme) };
}
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
let _ = menu
.inner()
.init_for_gtk_window(raw.gtk_window, raw.default_vbox);
})
} else {
None
}
}
pub fn on_menu_event<F: Fn(&AppHandle<R>, MenuEvent) + Send + Sync + 'static>(&self, handler: F) {
self
.global_event_listeners
.lock()
.unwrap()
.push(Box::new(handler));
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/manager/mod.rs | crates/tauri/src/manager/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{
borrow::Cow,
collections::HashMap,
fmt,
sync::{atomic::AtomicBool, Arc, Mutex, MutexGuard},
};
use serde::Serialize;
use url::Url;
use tauri_macros::default_runtime;
use tauri_utils::{
assets::{AssetKey, CspHash, SCRIPT_NONCE_TOKEN, STYLE_NONCE_TOKEN},
config::{Csp, CspDirectiveSources},
};
use crate::{
app::{
AppHandle, ChannelInterceptor, GlobalWebviewEventListener, GlobalWindowEventListener,
OnPageLoad,
},
event::{EmitArgs, Event, EventId, EventTarget, Listeners},
ipc::{Invoke, InvokeHandler, RuntimeAuthority},
plugin::PluginStore,
resources::ResourceTable,
utils::{config::Config, PackageInfo},
Assets, Context, DebugAppIcon, EventName, Pattern, Runtime, StateManager, Webview, Window,
};
#[cfg(desktop)]
mod menu;
#[cfg(all(desktop, feature = "tray-icon"))]
mod tray;
pub mod webview;
pub mod window;
#[derive(Default)]
/// Spaced and quoted Content-Security-Policy hash values.
struct CspHashStrings {
script: Vec<String>,
style: Vec<String>,
}
/// Sets the CSP value to the asset HTML if needed (on Linux).
/// Returns the CSP string for access on the response header (on Windows and macOS).
pub(crate) fn set_csp<R: Runtime>(
asset: &mut String,
assets: &impl std::borrow::Borrow<dyn Assets<R>>,
asset_path: &AssetKey,
manager: &AppManager<R>,
csp: Csp,
) -> HashMap<String, CspDirectiveSources> {
let mut csp = csp.into();
let hash_strings =
assets
.borrow()
.csp_hashes(asset_path)
.fold(CspHashStrings::default(), |mut acc, hash| {
match hash {
CspHash::Script(hash) => {
acc.script.push(hash.into());
}
CspHash::Style(hash) => {
acc.style.push(hash.into());
}
_csp_hash => {
log::debug!("Unknown CspHash variant encountered: {:?}", _csp_hash);
}
}
acc
});
let dangerous_disable_asset_csp_modification = &manager
.config()
.app
.security
.dangerous_disable_asset_csp_modification;
if dangerous_disable_asset_csp_modification.can_modify("script-src") {
replace_csp_nonce(
asset,
SCRIPT_NONCE_TOKEN,
&mut csp,
"script-src",
hash_strings.script,
);
}
if dangerous_disable_asset_csp_modification.can_modify("style-src") {
replace_csp_nonce(
asset,
STYLE_NONCE_TOKEN,
&mut csp,
"style-src",
hash_strings.style,
);
}
csp
}
// inspired by <https://github.com/rust-lang/rust/blob/1be5c8f90912c446ecbdc405cbc4a89f9acd20fd/library/alloc/src/str.rs#L260-L297>
fn replace_with_callback<F: FnMut() -> String>(
original: &str,
pattern: &str,
mut replacement: F,
) -> String {
let mut result = String::new();
let mut last_end = 0;
for (start, part) in original.match_indices(pattern) {
result.push_str(unsafe { original.get_unchecked(last_end..start) });
result.push_str(&replacement());
last_end = start + part.len();
}
result.push_str(unsafe { original.get_unchecked(last_end..original.len()) });
result
}
fn replace_csp_nonce(
asset: &mut String,
token: &str,
csp: &mut HashMap<String, CspDirectiveSources>,
directive: &str,
hashes: Vec<String>,
) {
let mut nonces = Vec::new();
*asset = replace_with_callback(asset, token, || {
let nonce = getrandom::u64().expect("failed to get random bytes");
nonces.push(nonce);
nonce.to_string()
});
if !(nonces.is_empty() && hashes.is_empty()) {
let nonce_sources = nonces
.into_iter()
.map(|n| format!("'nonce-{n}'"))
.collect::<Vec<String>>();
let sources = csp.entry(directive.into()).or_default();
let self_source = "'self'".to_string();
if !sources.contains(&self_source) {
sources.push(self_source);
}
sources.extend(nonce_sources);
sources.extend(hashes);
}
}
/// A resolved asset.
#[non_exhaustive]
pub struct Asset {
/// The asset bytes.
pub bytes: Vec<u8>,
/// The asset's mime type.
pub mime_type: String,
/// The `Content-Security-Policy` header value.
pub csp_header: Option<String>,
}
impl Asset {
/// The asset bytes.
pub fn bytes(&self) -> &[u8] {
&self.bytes
}
/// The asset's mime type.
pub fn mime_type(&self) -> &str {
&self.mime_type
}
/// The `Content-Security-Policy` header value.
pub fn csp_header(&self) -> Option<&str> {
self.csp_header.as_deref()
}
}
#[default_runtime(crate::Wry, wry)]
pub struct AppManager<R: Runtime> {
pub runtime_authority: Mutex<RuntimeAuthority>,
pub window: window::WindowManager<R>,
pub webview: webview::WebviewManager<R>,
#[cfg(all(desktop, feature = "tray-icon"))]
pub tray: tray::TrayManager<R>,
#[cfg(desktop)]
pub menu: menu::MenuManager<R>,
pub(crate) plugins: Mutex<PluginStore<R>>,
pub listeners: Listeners,
pub state: Arc<StateManager>,
pub config: Config,
#[cfg(dev)]
pub config_parent: Option<std::path::PathBuf>,
pub assets: Box<dyn Assets<R>>,
pub app_icon: Option<Vec<u8>>,
pub package_info: PackageInfo,
/// Application pattern.
pub pattern: Arc<Pattern>,
/// Global API scripts collected from plugins.
pub plugin_global_api_scripts: Arc<Option<&'static [&'static str]>>,
/// Application Resources Table
pub(crate) resources_table: Arc<Mutex<ResourceTable>>,
/// Runtime-generated invoke key.
pub(crate) invoke_key: String,
pub(crate) channel_interceptor: Option<ChannelInterceptor<R>>,
/// Sets to true in [`AppHandle::request_restart`] and [`AppHandle::restart`]
/// and we will call `restart` on the next `RuntimeRunEvent::Exit` event
pub(crate) restart_on_exit: AtomicBool,
}
impl<R: Runtime> fmt::Debug for AppManager<R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut d = f.debug_struct("AppManager");
d.field("window", &self.window)
.field("plugins", &self.plugins)
.field("state", &self.state)
.field("config", &self.config)
.field("app_icon", &DebugAppIcon(&self.app_icon))
.field("package_info", &self.package_info)
.field("pattern", &self.pattern);
#[cfg(all(desktop, feature = "tray-icon"))]
{
d.field("tray", &self.tray);
}
d.finish()
}
}
pub(crate) enum EmitPayload<'a, S: Serialize> {
Serialize(&'a S),
Str(String),
}
impl<R: Runtime> AppManager<R> {
#[allow(clippy::too_many_arguments, clippy::type_complexity)]
pub(crate) fn with_handlers(
#[allow(unused_mut)] mut context: Context<R>,
plugins: PluginStore<R>,
invoke_handler: Box<InvokeHandler<R>>,
on_page_load: Option<Arc<OnPageLoad<R>>>,
uri_scheme_protocols: HashMap<String, Arc<webview::UriSchemeProtocol<R>>>,
state: StateManager,
#[cfg(desktop)] menu_event_listener: Vec<crate::app::GlobalMenuEventListener<AppHandle<R>>>,
#[cfg(all(desktop, feature = "tray-icon"))] tray_icon_event_listeners: Vec<
crate::app::GlobalTrayIconEventListener<AppHandle<R>>,
>,
window_event_listeners: Vec<GlobalWindowEventListener<R>>,
webview_event_listeners: Vec<GlobalWebviewEventListener<R>>,
#[cfg(desktop)] window_menu_event_listeners: HashMap<
String,
crate::app::GlobalMenuEventListener<Window<R>>,
>,
invoke_initialization_script: String,
channel_interceptor: Option<ChannelInterceptor<R>>,
invoke_key: String,
) -> Self {
// generate a random isolation key at runtime
#[cfg(feature = "isolation")]
if let Pattern::Isolation { key, .. } = &mut context.pattern {
*key = uuid::Uuid::new_v4().to_string();
}
Self {
runtime_authority: Mutex::new(context.runtime_authority),
window: window::WindowManager {
windows: Mutex::default(),
default_icon: context.default_window_icon,
event_listeners: Arc::new(window_event_listeners),
},
webview: webview::WebviewManager {
webviews: Mutex::default(),
invoke_handler,
on_page_load,
uri_scheme_protocols: Mutex::new(uri_scheme_protocols),
event_listeners: Arc::new(webview_event_listeners),
invoke_initialization_script,
invoke_key: invoke_key.clone(),
},
#[cfg(all(desktop, feature = "tray-icon"))]
tray: tray::TrayManager {
icon: context.tray_icon,
icons: Default::default(),
global_event_listeners: Mutex::new(tray_icon_event_listeners),
event_listeners: Default::default(),
},
#[cfg(desktop)]
menu: menu::MenuManager {
menus: Default::default(),
menu: Default::default(),
global_event_listeners: Mutex::new(menu_event_listener),
event_listeners: Mutex::new(window_menu_event_listeners),
},
plugins: Mutex::new(plugins),
listeners: Listeners::default(),
state: Arc::new(state),
config: context.config,
#[cfg(dev)]
config_parent: context.config_parent,
assets: context.assets,
app_icon: context.app_icon,
package_info: context.package_info,
pattern: Arc::new(context.pattern),
plugin_global_api_scripts: Arc::new(context.plugin_global_api_scripts),
resources_table: Arc::default(),
invoke_key,
channel_interceptor,
restart_on_exit: AtomicBool::new(false),
}
}
/// State managed by the application.
pub(crate) fn state(&self) -> Arc<StateManager> {
self.state.clone()
}
/// The `tauri` custom protocol URL we use to serve the embedded assets.
/// Returns `tauri://localhost` or its `wry` workaround URL `http://tauri.localhost`/`https://tauri.localhost`
pub(crate) fn tauri_protocol_url(&self, https: bool) -> Cow<'_, Url> {
if cfg!(windows) || cfg!(target_os = "android") {
let scheme = if https { "https" } else { "http" };
Cow::Owned(Url::parse(&format!("{scheme}://tauri.localhost")).unwrap())
} else {
Cow::Owned(Url::parse("tauri://localhost").unwrap())
}
}
/// Get the base app URL for [`WebviewUrl::App`](tauri_utils::config::WebviewUrl::App).
///
/// * In dev mode, this is the [`devUrl`](tauri_utils::config::BuildConfig::dev_url) configuration value if it exsits.
/// * In production mode, this is the [`frontendDist`](tauri_utils::config::BuildConfig::frontend_dist) configuration value if it's a [`FrontendDist::Url`](tauri_utils::config::FrontendDist::Url).
/// * Returns [`Self::tauri_protocol_url`] (e.g. `tauri://localhost`) otherwise.
pub(crate) fn get_app_url(&self, https: bool) -> Cow<'_, Url> {
#[cfg(dev)]
let url = self.config.build.dev_url.as_ref();
#[cfg(not(dev))]
let url = match self.config.build.frontend_dist.as_ref() {
Some(crate::utils::config::FrontendDist::Url(url)) => Some(url),
_ => None,
};
if let Some(url) = url {
Cow::Borrowed(url)
} else {
self.tauri_protocol_url(https)
}
}
fn csp(&self) -> Option<Csp> {
if !crate::is_dev() {
self.config.app.security.csp.clone()
} else {
self
.config
.app
.security
.dev_csp
.clone()
.or_else(|| self.config.app.security.csp.clone())
}
}
pub fn get_asset(
&self,
mut path: String,
_use_https_schema: bool,
) -> Result<Asset, Box<dyn std::error::Error>> {
let assets = &self.assets;
if path.ends_with('/') {
path.pop();
}
path = percent_encoding::percent_decode(path.as_bytes())
.decode_utf8_lossy()
.to_string();
let path = if path.is_empty() {
// if the url is `tauri://localhost`, we should load `index.html`
"index.html".to_string()
} else {
// skip the leading `/`, if it starts with one.
path.strip_prefix('/').unwrap_or(path.as_str()).to_string()
};
let mut asset_path = AssetKey::from(path.as_str());
let asset_response = assets
.get(&asset_path)
.or_else(|| {
log::debug!("Asset `{path}` not found; fallback to {path}.html");
let fallback = format!("{path}.html").into();
let asset = assets.get(&fallback);
asset_path = fallback;
asset
})
.or_else(|| {
log::debug!("Asset `{path}` not found; fallback to {path}/index.html",);
let fallback = format!("{path}/index.html").into();
let asset = assets.get(&fallback);
asset_path = fallback;
asset
})
.or_else(|| {
log::debug!("Asset `{path}` not found; fallback to index.html");
let fallback = AssetKey::from("index.html");
let asset = assets.get(&fallback);
asset_path = fallback;
asset
})
.ok_or_else(|| crate::Error::AssetNotFound(path.clone()))
.map(Cow::into_owned);
let mut csp_header = None;
let is_html = asset_path.as_ref().ends_with(".html");
match asset_response {
Ok(asset) => {
let final_data = if is_html {
let mut asset = String::from_utf8_lossy(&asset).into_owned();
if let Some(csp) = self.csp() {
#[allow(unused_mut)]
let mut csp_map = set_csp(&mut asset, &self.assets, &asset_path, self, csp);
#[cfg(feature = "isolation")]
if let Pattern::Isolation { schema, .. } = &*self.pattern {
let default_src = csp_map
.entry("default-src".into())
.or_insert_with(Default::default);
default_src.push(crate::pattern::format_real_schema(
schema,
_use_https_schema,
));
}
csp_header.replace(Csp::DirectiveMap(csp_map).to_string());
}
asset.into_bytes()
} else {
asset
};
let mime_type = tauri_utils::mime_type::MimeType::parse(&final_data, &path);
Ok(Asset {
bytes: final_data,
mime_type,
csp_header,
})
}
Err(e) => {
log::error!("{:?}", e);
Err(Box::new(e))
}
}
}
pub(crate) fn listeners(&self) -> &Listeners {
&self.listeners
}
pub fn run_invoke_handler(&self, invoke: Invoke<R>) -> bool {
(self.webview.invoke_handler)(invoke)
}
pub fn extend_api(&self, plugin: &str, invoke: Invoke<R>) -> bool {
self
.plugins
.lock()
.expect("poisoned plugin store")
.extend_api(plugin, invoke)
}
pub fn initialize_plugins(&self, app: &AppHandle<R>) -> crate::Result<()> {
self
.plugins
.lock()
.expect("poisoned plugin store")
.initialize_all(app, &self.config.plugins)
}
pub fn config(&self) -> &Config {
&self.config
}
#[cfg(dev)]
pub fn config_parent(&self) -> Option<&std::path::PathBuf> {
self.config_parent.as_ref()
}
pub fn package_info(&self) -> &PackageInfo {
&self.package_info
}
/// # Panics
/// Will panic if `event` contains characters other than alphanumeric, `-`, `/`, `:` and `_`
pub(crate) fn listen<F: Fn(Event) + Send + 'static>(
&self,
event: EventName,
target: EventTarget,
handler: F,
) -> EventId {
self.listeners().listen(event, target, handler)
}
/// # Panics
/// Will panic if `event` contains characters other than alphanumeric, `-`, `/`, `:` and `_`
pub(crate) fn once<F: FnOnce(Event) + Send + 'static>(
&self,
event: EventName,
target: EventTarget,
handler: F,
) -> EventId {
self.listeners().once(event, target, handler)
}
pub fn unlisten(&self, id: EventId) {
self.listeners().unlisten(id)
}
#[cfg_attr(
feature = "tracing",
tracing::instrument("app::emit", skip(self, payload))
)]
pub(crate) fn emit<S: Serialize>(
&self,
event: EventName<&str>,
payload: EmitPayload<'_, S>,
) -> crate::Result<()> {
#[cfg(feature = "tracing")]
let _span = tracing::debug_span!("emit::run").entered();
let emit_args = match payload {
EmitPayload::Serialize(payload) => EmitArgs::new(event, payload)?,
EmitPayload::Str(payload) => EmitArgs::new_str(event, payload)?,
};
let listeners = self.listeners();
listeners.emit_js(self.webview.webviews_lock().values(), &emit_args)?;
listeners.emit(emit_args)?;
Ok(())
}
#[cfg_attr(
feature = "tracing",
tracing::instrument("app::emit::filter", skip(self, payload, filter))
)]
pub(crate) fn emit_filter<S, F>(
&self,
event: EventName<&str>,
payload: EmitPayload<'_, S>,
filter: F,
) -> crate::Result<()>
where
S: Serialize,
F: Fn(&EventTarget) -> bool,
{
#[cfg(feature = "tracing")]
let _span = tracing::debug_span!("emit::run").entered();
let emit_args = match payload {
EmitPayload::Serialize(payload) => EmitArgs::new(event, payload)?,
EmitPayload::Str(payload) => EmitArgs::new_str(event, payload)?,
};
let listeners = self.listeners();
listeners.emit_js_filter(
self.webview.webviews_lock().values(),
&emit_args,
Some(&filter),
)?;
listeners.emit_filter(emit_args, Some(filter))?;
Ok(())
}
#[cfg_attr(
feature = "tracing",
tracing::instrument("app::emit::to", skip(self, target, payload), fields(target))
)]
pub(crate) fn emit_to<S>(
&self,
target: EventTarget,
event: EventName<&str>,
payload: EmitPayload<'_, S>,
) -> crate::Result<()>
where
S: Serialize,
{
#[cfg(feature = "tracing")]
tracing::Span::current().record("target", format!("{target:?}"));
fn filter_target(target: &EventTarget, candidate: &EventTarget) -> bool {
match target {
// if targeting any label, filter matching labels
EventTarget::AnyLabel { label } => match candidate {
EventTarget::Window { label: l }
| EventTarget::Webview { label: l }
| EventTarget::WebviewWindow { label: l }
| EventTarget::AnyLabel { label: l } => l == label,
_ => false,
},
EventTarget::Window { label } => match candidate {
EventTarget::AnyLabel { label: l } | EventTarget::Window { label: l } => l == label,
_ => false,
},
EventTarget::Webview { label } => match candidate {
EventTarget::AnyLabel { label: l } | EventTarget::Webview { label: l } => l == label,
_ => false,
},
EventTarget::WebviewWindow { label } => match candidate {
EventTarget::AnyLabel { label: l } | EventTarget::WebviewWindow { label: l } => {
l == label
}
_ => false,
},
// otherwise match same target
_ => target == candidate,
}
}
match target {
// if targeting all, emit to all using emit without filter
EventTarget::Any => self.emit(event, payload),
target => self.emit_filter(event, payload, |t| filter_target(&target, t)),
}
}
pub fn get_window(&self, label: &str) -> Option<Window<R>> {
self.window.windows_lock().get(label).cloned()
}
pub fn get_focused_window(&self) -> Option<Window<R>> {
self
.window
.windows_lock()
.iter()
.find(|w| w.1.is_focused().unwrap_or(false))
.map(|w| w.1.clone())
}
pub(crate) fn on_window_close(&self, label: &str) {
let window = self.window.windows_lock().remove(label);
if let Some(window) = window {
for webview in window.webviews() {
self.webview.webviews_lock().remove(webview.label());
}
}
}
#[cfg(desktop)]
pub(crate) fn on_webview_close(&self, label: &str) {
self.webview.webviews_lock().remove(label);
}
pub fn windows(&self) -> HashMap<String, Window<R>> {
self.window.windows_lock().clone()
}
pub fn get_webview(&self, label: &str) -> Option<Webview<R>> {
self.webview.webviews_lock().get(label).cloned()
}
pub fn webviews(&self) -> HashMap<String, Webview<R>> {
self.webview.webviews_lock().clone()
}
pub(crate) fn resources_table(&self) -> MutexGuard<'_, ResourceTable> {
self
.resources_table
.lock()
.expect("poisoned window manager")
}
pub(crate) fn invoke_key(&self) -> &str {
&self.invoke_key
}
}
#[cfg(desktop)]
impl<R: Runtime> AppManager<R> {
pub fn remove_menu_from_stash_by_id(&self, id: Option<&crate::menu::MenuId>) {
if let Some(id) = id {
let is_used_by_a_window = self
.window
.windows_lock()
.values()
.any(|w| w.is_menu_in_use(id));
if !(self.menu.is_menu_in_use(id) || is_used_by_a_window) {
self.menu.menus_stash_lock().remove(id);
}
}
}
}
#[cfg(test)]
mod tests {
use super::replace_with_callback;
#[test]
fn string_replace_with_callback() {
let mut tauri_index = 0;
#[allow(clippy::single_element_loop)]
for (src, pattern, replacement, result) in [(
"tauri is awesome, tauri is amazing",
"tauri",
|| {
tauri_index += 1;
tauri_index.to_string()
},
"1 is awesome, 2 is amazing",
)] {
assert_eq!(replace_with_callback(src, pattern, replacement), result);
}
}
}
#[cfg(test)]
mod test {
use std::{
sync::mpsc::{channel, Receiver, Sender},
time::Duration,
};
use crate::{
event::EventTarget,
generate_context,
plugin::PluginStore,
test::{mock_app, MockRuntime},
webview::WebviewBuilder,
window::WindowBuilder,
App, Emitter, Listener, Manager, StateManager, Webview, WebviewWindow, WebviewWindowBuilder,
Window, Wry,
};
use super::AppManager;
const APP_LISTEN_ID: &str = "App::listen";
const APP_LISTEN_ANY_ID: &str = "App::listen_any";
const WINDOW_LISTEN_ID: &str = "Window::listen";
const WINDOW_LISTEN_ANY_ID: &str = "Window::listen_any";
const WEBVIEW_LISTEN_ID: &str = "Webview::listen";
const WEBVIEW_LISTEN_ANY_ID: &str = "Webview::listen_any";
const WEBVIEW_WINDOW_LISTEN_ID: &str = "WebviewWindow::listen";
const WEBVIEW_WINDOW_LISTEN_ANY_ID: &str = "WebviewWindow::listen_any";
const TEST_EVENT_NAME: &str = "event";
#[test]
fn check_get_url() {
let context = generate_context!("test/fixture/src-tauri/tauri.conf.json", crate, test = true);
let manager: AppManager<Wry> = AppManager::with_handlers(
context,
PluginStore::default(),
Box::new(|_| false),
None,
Default::default(),
StateManager::new(),
Default::default(),
#[cfg(all(desktop, feature = "tray-icon"))]
Default::default(),
Default::default(),
Default::default(),
Default::default(),
"".into(),
None,
crate::generate_invoke_key().unwrap(),
);
#[cfg(custom_protocol)]
{
assert_eq!(
manager.get_app_url(false).to_string(),
if cfg!(windows) || cfg!(target_os = "android") {
"http://tauri.localhost/"
} else {
"tauri://localhost"
}
);
assert_eq!(
manager.get_app_url(true).to_string(),
if cfg!(windows) || cfg!(target_os = "android") {
"https://tauri.localhost/"
} else {
"tauri://localhost"
}
);
}
#[cfg(dev)]
assert_eq!(
manager.get_app_url(false).to_string(),
"http://localhost:4000/"
);
}
struct EventSetup {
app: App<MockRuntime>,
window: Window<MockRuntime>,
webview: Webview<MockRuntime>,
webview_window: WebviewWindow<MockRuntime>,
tx: Sender<(&'static str, String)>,
rx: Receiver<(&'static str, String)>,
}
fn setup_events(setup_any: bool) -> EventSetup {
let app = mock_app();
let window = WindowBuilder::new(&app, "main-window").build().unwrap();
let webview = window
.add_child(
WebviewBuilder::new("main-webview", Default::default()),
crate::LogicalPosition::new(0, 0),
window.inner_size().unwrap(),
)
.unwrap();
let webview_window = WebviewWindowBuilder::new(&app, "main-webview-window", Default::default())
.build()
.unwrap();
let (tx, rx) = channel();
macro_rules! setup_listener {
($type:ident, $id:ident, $any_id:ident) => {
let tx_ = tx.clone();
$type.listen(TEST_EVENT_NAME, move |evt| {
tx_
.send(($id, serde_json::from_str::<String>(evt.payload()).unwrap()))
.unwrap();
});
if setup_any {
let tx_ = tx.clone();
$type.listen_any(TEST_EVENT_NAME, move |evt| {
tx_
.send((
$any_id,
serde_json::from_str::<String>(evt.payload()).unwrap(),
))
.unwrap();
});
}
};
}
setup_listener!(app, APP_LISTEN_ID, APP_LISTEN_ANY_ID);
setup_listener!(window, WINDOW_LISTEN_ID, WINDOW_LISTEN_ANY_ID);
setup_listener!(webview, WEBVIEW_LISTEN_ID, WEBVIEW_LISTEN_ANY_ID);
setup_listener!(
webview_window,
WEBVIEW_WINDOW_LISTEN_ID,
WEBVIEW_WINDOW_LISTEN_ANY_ID
);
EventSetup {
app,
window,
webview,
webview_window,
tx,
rx,
}
}
fn assert_events(kind: &str, received: &[&str], expected: &[&str]) {
for e in expected {
assert!(received.contains(e), "{e} did not receive `{kind}` event");
}
assert_eq!(
received.len(),
expected.len(),
"received {received:?} `{kind}` events but expected {expected:?}"
);
}
#[test]
fn emit() {
let EventSetup {
app,
window,
webview,
webview_window,
tx: _,
rx,
} = setup_events(true);
run_emit_test("emit (app)", app, &rx);
run_emit_test("emit (window)", window, &rx);
run_emit_test("emit (webview)", webview, &rx);
run_emit_test("emit (webview_window)", webview_window, &rx);
}
fn run_emit_test<M: Manager<MockRuntime> + Emitter<MockRuntime>>(
kind: &str,
m: M,
rx: &Receiver<(&str, String)>,
) {
let mut received = Vec::new();
let payload = "global-payload";
m.emit(TEST_EVENT_NAME, payload).unwrap();
while let Ok((source, p)) = rx.recv_timeout(Duration::from_secs(1)) {
assert_eq!(p, payload);
received.push(source);
}
assert_events(
kind,
&received,
&[
APP_LISTEN_ID,
APP_LISTEN_ANY_ID,
WINDOW_LISTEN_ID,
WINDOW_LISTEN_ANY_ID,
WEBVIEW_LISTEN_ID,
WEBVIEW_LISTEN_ANY_ID,
WEBVIEW_WINDOW_LISTEN_ID,
WEBVIEW_WINDOW_LISTEN_ANY_ID,
],
);
}
#[test]
fn emit_to() {
let EventSetup {
app,
window,
webview,
webview_window,
tx,
rx,
} = setup_events(false);
run_emit_to_test(
"emit_to (App)",
&app,
&window,
&webview,
&webview_window,
tx.clone(),
&rx,
);
run_emit_to_test(
"emit_to (window)",
&window,
&window,
&webview,
&webview_window,
tx.clone(),
&rx,
);
run_emit_to_test(
"emit_to (webview)",
&webview,
&window,
&webview,
&webview_window,
tx.clone(),
&rx,
);
run_emit_to_test(
"emit_to (webview_window)",
&webview_window,
&window,
&webview,
&webview_window,
tx.clone(),
&rx,
);
}
fn run_emit_to_test<M: Manager<MockRuntime> + Emitter<MockRuntime>>(
kind: &str,
m: &M,
window: &Window<MockRuntime>,
webview: &Webview<MockRuntime>,
webview_window: &WebviewWindow<MockRuntime>,
tx: Sender<(&'static str, String)>,
rx: &Receiver<(&'static str, String)>,
) {
let mut received = Vec::new();
let payload = "global-payload";
macro_rules! test_target {
($target:expr, $id:ident) => {
m.emit_to($target, TEST_EVENT_NAME, payload).unwrap();
while let Ok((source, p)) = rx.recv_timeout(Duration::from_secs(1)) {
assert_eq!(p, payload);
received.push(source);
}
assert_events(kind, &received, &[$id]);
received.clear();
};
}
test_target!(EventTarget::App, APP_LISTEN_ID);
test_target!(window.label(), WINDOW_LISTEN_ID);
test_target!(webview.label(), WEBVIEW_LISTEN_ID);
test_target!(webview_window.label(), WEBVIEW_WINDOW_LISTEN_ID);
let other_webview_listen_id = "OtherWebview::listen";
let other_webview = WebviewWindowBuilder::new(
window,
kind.replace(['(', ')', ' '], ""),
Default::default(),
)
.build()
.unwrap();
other_webview.listen(TEST_EVENT_NAME, move |evt| {
tx.send((
other_webview_listen_id,
serde_json::from_str::<String>(evt.payload()).unwrap(),
))
.unwrap();
});
m.emit_to(other_webview.label(), TEST_EVENT_NAME, payload)
.unwrap();
while let Ok((source, p)) = rx.recv_timeout(Duration::from_secs(1)) {
assert_eq!(p, payload);
received.push(source);
}
assert_events("emit_to", &received, &[other_webview_listen_id]);
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/manager/window.rs | crates/tauri/src/manager/window.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{
collections::{HashMap, HashSet},
fmt,
path::PathBuf,
sync::{Arc, Mutex, MutexGuard},
};
use serde::Serialize;
use tauri_runtime::{
dpi::{PhysicalPosition, PhysicalSize},
window::WindowBuilder,
window::{DetachedWindow, DragDropEvent, PendingWindow},
};
use crate::{
app::GlobalWindowEventListener, event::EventName, image::Image, sealed::ManagerBase, AppHandle,
EventLoopMessage, EventTarget, Manager, Runtime, Scopes, Window, WindowEvent,
};
use super::EmitPayload;
const WINDOW_RESIZED_EVENT: EventName<&str> = EventName::from_str("tauri://resize");
const WINDOW_MOVED_EVENT: EventName<&str> = EventName::from_str("tauri://move");
const WINDOW_CLOSE_REQUESTED_EVENT: EventName<&str> =
EventName::from_str("tauri://close-requested");
const WINDOW_DESTROYED_EVENT: EventName<&str> = EventName::from_str("tauri://destroyed");
const WINDOW_FOCUS_EVENT: EventName<&str> = EventName::from_str("tauri://focus");
const WINDOW_BLUR_EVENT: EventName<&str> = EventName::from_str("tauri://blur");
const WINDOW_SCALE_FACTOR_CHANGED_EVENT: EventName<&str> =
EventName::from_str("tauri://scale-change");
const WINDOW_THEME_CHANGED: EventName<&str> = EventName::from_str("tauri://theme-changed");
pub(crate) const DRAG_ENTER_EVENT: EventName<&str> = EventName::from_str("tauri://drag-enter");
pub(crate) const DRAG_OVER_EVENT: EventName<&str> = EventName::from_str("tauri://drag-over");
pub(crate) const DRAG_DROP_EVENT: EventName<&str> = EventName::from_str("tauri://drag-drop");
pub(crate) const DRAG_LEAVE_EVENT: EventName<&str> = EventName::from_str("tauri://drag-leave");
pub struct WindowManager<R: Runtime> {
pub windows: Mutex<HashMap<String, Window<R>>>,
pub default_icon: Option<Image<'static>>,
/// Window event listeners to all windows.
pub event_listeners: Arc<Vec<GlobalWindowEventListener<R>>>,
}
impl<R: Runtime> fmt::Debug for WindowManager<R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("WindowManager")
.field("default_window_icon", &self.default_icon)
.finish()
}
}
impl<R: Runtime> WindowManager<R> {
/// Get a locked handle to the windows.
pub(crate) fn windows_lock(&self) -> MutexGuard<'_, HashMap<String, Window<R>>> {
self.windows.lock().expect("poisoned window manager")
}
pub fn prepare_window(
&self,
mut pending: PendingWindow<EventLoopMessage, R>,
) -> crate::Result<PendingWindow<EventLoopMessage, R>> {
if self.windows_lock().contains_key(&pending.label) {
return Err(crate::Error::WindowLabelAlreadyExists(pending.label));
}
if !pending.window_builder.has_icon() {
if let Some(default_window_icon) = self.default_icon.clone() {
pending.window_builder = pending.window_builder.icon(default_window_icon.into())?;
}
}
Ok(pending)
}
pub(crate) fn attach_window(
&self,
app_handle: AppHandle<R>,
window: DetachedWindow<EventLoopMessage, R>,
#[cfg(desktop)] menu: Option<crate::window::WindowMenu<R>>,
) -> Window<R> {
let window = Window::new(
app_handle.manager.clone(),
window,
app_handle,
#[cfg(desktop)]
menu,
);
let window_ = window.clone();
let window_event_listeners = self.event_listeners.clone();
window.on_window_event(move |event| {
let _ = on_window_event(&window_, event);
for handler in window_event_listeners.iter() {
handler(&window_, event);
}
});
// insert the window into our manager
{
self
.windows_lock()
.insert(window.label().to_string(), window.clone());
}
// let plugins know that a new window has been added to the manager
let manager = window.manager.clone();
let window_ = window.clone();
// run on main thread so the plugin store doesn't dead lock with the event loop handler in App
let _ = window.run_on_main_thread(move || {
manager
.plugins
.lock()
.expect("poisoned plugin store")
.window_created(window_);
});
window
}
pub fn labels(&self) -> HashSet<String> {
self.windows_lock().keys().cloned().collect()
}
}
impl<R: Runtime> Window<R> {
/// Emits event to [`EventTarget::Window`] and [`EventTarget::WebviewWindow`]
fn emit_to_window<S: Serialize>(&self, event: EventName<&str>, payload: &S) -> crate::Result<()> {
let window_label = self.label();
let payload = EmitPayload::Serialize(payload);
self
.manager()
.emit_filter(event, payload, |target| match target {
EventTarget::Window { label } | EventTarget::WebviewWindow { label } => {
label == window_label
}
_ => false,
})
}
/// Checks whether has js listener for [`EventTarget::Window`] or [`EventTarget::WebviewWindow`]
fn has_js_listener(&self, event: EventName<&str>) -> bool {
let window_label = self.label();
let listeners = self.manager().listeners();
listeners.has_js_listener(event, |target| match target {
EventTarget::Window { label } | EventTarget::WebviewWindow { label } => label == window_label,
_ => false,
})
}
}
#[derive(Serialize, Clone)]
pub(crate) struct DragDropPayload<'a> {
#[serde(skip_serializing_if = "Option::is_none")]
pub paths: Option<&'a Vec<PathBuf>>,
pub position: &'a PhysicalPosition<f64>,
}
fn on_window_event<R: Runtime>(window: &Window<R>, event: &WindowEvent) -> crate::Result<()> {
match event {
WindowEvent::Resized(size) => window.emit_to_window(WINDOW_RESIZED_EVENT, size)?,
WindowEvent::Moved(position) => window.emit_to_window(WINDOW_MOVED_EVENT, position)?,
WindowEvent::CloseRequested { api } => {
if window.has_js_listener(WINDOW_CLOSE_REQUESTED_EVENT) {
api.prevent_close();
}
window.emit_to_window(WINDOW_CLOSE_REQUESTED_EVENT, &())?;
}
WindowEvent::Destroyed => {
window.emit_to_window(WINDOW_DESTROYED_EVENT, &())?;
}
WindowEvent::Focused(focused) => window.emit_to_window(
if *focused {
WINDOW_FOCUS_EVENT
} else {
WINDOW_BLUR_EVENT
},
&(),
)?,
WindowEvent::ScaleFactorChanged {
scale_factor,
new_inner_size,
..
} => window.emit_to_window(
WINDOW_SCALE_FACTOR_CHANGED_EVENT,
&ScaleFactorChanged {
scale_factor: *scale_factor,
size: *new_inner_size,
},
)?,
WindowEvent::DragDrop(event) => match event {
DragDropEvent::Enter { paths, position } => {
let payload = DragDropPayload {
paths: Some(paths),
position,
};
if window.is_webview_window() {
// use underlying manager, otherwise have to recheck EventName
window.manager().emit_to(
EventTarget::labeled(window.label()),
DRAG_ENTER_EVENT,
EmitPayload::Serialize(&payload),
)?
} else {
window.emit_to_window(DRAG_ENTER_EVENT, &payload)?
}
}
DragDropEvent::Over { position } => {
let payload = DragDropPayload {
position,
paths: None,
};
if window.is_webview_window() {
// use underlying manager, otherwise have to recheck EventName
window.manager().emit_to(
EventTarget::labeled(window.label()),
DRAG_OVER_EVENT,
EmitPayload::Serialize(&payload),
)?
} else {
window.emit_to_window(DRAG_OVER_EVENT, &payload)?
}
}
DragDropEvent::Drop { paths, position } => {
let scopes = window.state::<Scopes>();
for path in paths {
if path.is_file() {
let _ = scopes.allow_file(path);
} else {
let _ = scopes.allow_directory(path, true);
}
}
let payload = DragDropPayload {
paths: Some(paths),
position,
};
if window.is_webview_window() {
// use underlying manager, otherwise have to recheck EventName
window.manager().emit_to(
EventTarget::labeled(window.label()),
DRAG_DROP_EVENT,
EmitPayload::Serialize(&payload),
)?
} else {
window.emit_to_window(DRAG_DROP_EVENT, &payload)?
}
}
DragDropEvent::Leave => {
if window.is_webview_window() {
// use underlying manager, otherwise have to recheck EventName
window.manager().emit_to(
EventTarget::labeled(window.label()),
DRAG_LEAVE_EVENT,
EmitPayload::Serialize(&()),
)?
} else {
window.emit_to_window(DRAG_LEAVE_EVENT, &())?
}
}
_ => unimplemented!(),
},
WindowEvent::ThemeChanged(theme) => window.emit_to_window(WINDOW_THEME_CHANGED, &theme)?,
}
Ok(())
}
#[derive(Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct ScaleFactorChanged {
scale_factor: f64,
size: PhysicalSize<u32>,
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/manager/webview.rs | crates/tauri/src/manager/webview.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{
borrow::Cow,
collections::{HashMap, HashSet},
fmt,
fs::create_dir_all,
sync::{Arc, Mutex, MutexGuard},
};
use serde::Serialize;
use serialize_to_javascript::{default_template, DefaultTemplate, Template};
use tauri_runtime::{
webview::{DetachedWebview, InitializationScript, PendingWebview},
window::DragDropEvent,
};
use tauri_utils::config::WebviewUrl;
use url::Url;
use crate::{
app::{GlobalWebviewEventListener, OnPageLoad, UriSchemeResponder, WebviewEvent},
ipc::InvokeHandler,
pattern::PatternJavascript,
sealed::ManagerBase,
webview::PageLoadPayload,
EventLoopMessage, EventTarget, Manager, Runtime, Scopes, UriSchemeContext, Webview, Window,
};
use super::{
window::{DragDropPayload, DRAG_DROP_EVENT, DRAG_ENTER_EVENT, DRAG_LEAVE_EVENT, DRAG_OVER_EVENT},
{AppManager, EmitPayload},
};
// we need to proxy the dev server on mobile because we can't use `localhost`, so we use the local IP address
// and we do not get a secure context without the custom protocol that proxies to the dev server
// additionally, we need the custom protocol to inject the initialization scripts on Android
// must also keep in sync with the `let mut response` assignment in prepare_uri_scheme_protocol
pub(crate) const PROXY_DEV_SERVER: bool = cfg!(all(dev, mobile));
pub(crate) const PROCESS_IPC_MESSAGE_FN: &str =
include_str!("../../scripts/process-ipc-message-fn.js");
#[cfg(feature = "isolation")]
#[derive(Template)]
#[default_template("../../scripts/isolation.js")]
pub(crate) struct IsolationJavascript<'a> {
pub(crate) isolation_src: &'a str,
pub(crate) style: &'a str,
}
#[derive(Template)]
#[default_template("../../scripts/ipc.js")]
pub(crate) struct IpcJavascript<'a> {
pub(crate) isolation_origin: &'a str,
}
/// Uses a custom URI scheme handler to resolve file requests
pub struct UriSchemeProtocol<R: Runtime> {
/// Handler for protocol
#[allow(clippy::type_complexity)]
pub handler:
Box<dyn Fn(UriSchemeContext<'_, R>, http::Request<Vec<u8>>, UriSchemeResponder) + Send + Sync>,
}
pub struct WebviewManager<R: Runtime> {
pub webviews: Mutex<HashMap<String, Webview<R>>>,
/// The JS message handler.
pub invoke_handler: Box<InvokeHandler<R>>,
/// The page load hook, invoked when the webview performs a navigation.
pub on_page_load: Option<Arc<OnPageLoad<R>>>,
/// The webview protocols available to all webviews.
pub uri_scheme_protocols: Mutex<HashMap<String, Arc<UriSchemeProtocol<R>>>>,
/// Webview event listeners to all webviews.
pub event_listeners: Arc<Vec<GlobalWebviewEventListener<R>>>,
/// The script that initializes the invoke system.
pub invoke_initialization_script: String,
/// A runtime generated invoke key.
pub(crate) invoke_key: String,
}
impl<R: Runtime> fmt::Debug for WebviewManager<R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("WebviewManager")
.field(
"invoke_initialization_script",
&self.invoke_initialization_script,
)
.field("invoke_key", &self.invoke_key)
.finish()
}
}
impl<R: Runtime> WebviewManager<R> {
pub(crate) fn register_uri_scheme_protocol<N: Into<String>>(
&self,
uri_scheme: N,
protocol: Arc<UriSchemeProtocol<R>>,
) {
let uri_scheme = uri_scheme.into();
self
.uri_scheme_protocols
.lock()
.unwrap()
.insert(uri_scheme, protocol);
}
/// Get a locked handle to the webviews.
pub(crate) fn webviews_lock(&self) -> MutexGuard<'_, HashMap<String, Webview<R>>> {
self.webviews.lock().expect("poisoned webview manager")
}
fn prepare_pending_webview<M: Manager<R>>(
&self,
mut pending: PendingWebview<EventLoopMessage, R>,
label: &str,
window_label: &str,
manager: &M,
) -> crate::Result<PendingWebview<EventLoopMessage, R>> {
let app_manager = manager.manager();
let plugin_init_scripts = app_manager
.plugins
.lock()
.expect("poisoned plugin store")
.initialization_script();
let pattern_init = PatternJavascript {
pattern: (&*app_manager.pattern).into(),
}
.render_default(&Default::default())?;
let mut webview_attributes = pending.webview_attributes;
let use_https_scheme = webview_attributes.use_https_scheme;
let ipc_init = IpcJavascript {
isolation_origin: &match &*app_manager.pattern {
#[cfg(feature = "isolation")]
crate::Pattern::Isolation { schema, .. } => {
crate::pattern::format_real_schema(schema, use_https_scheme)
}
_ => "".to_owned(),
},
}
.render_default(&Default::default())?;
let mut all_initialization_scripts: Vec<InitializationScript> = vec![];
fn main_frame_script(script: String) -> InitializationScript {
InitializationScript {
script,
for_main_frame_only: true,
}
}
all_initialization_scripts.push(main_frame_script(
r"
Object.defineProperty(window, 'isTauri', {
value: true,
});
if (!window.__TAURI_INTERNALS__) {
Object.defineProperty(window, '__TAURI_INTERNALS__', {
value: {
plugins: {}
}
})
}
"
.to_owned(),
));
all_initialization_scripts.push(main_frame_script(self.invoke_initialization_script.clone()));
all_initialization_scripts.push(main_frame_script(format!(
r#"
Object.defineProperty(window.__TAURI_INTERNALS__, 'metadata', {{
value: {{
currentWindow: {{ label: {current_window_label} }},
currentWebview: {{ label: {current_webview_label} }}
}}
}})
"#,
current_window_label = serde_json::to_string(window_label)?,
current_webview_label = serde_json::to_string(&label)?,
)));
all_initialization_scripts.push(main_frame_script(self.initialization_script(
app_manager,
&ipc_init.into_string(),
&pattern_init.into_string(),
use_https_scheme,
)?));
all_initialization_scripts.extend(plugin_init_scripts);
#[cfg(feature = "isolation")]
if let crate::Pattern::Isolation { schema, .. } = &*app_manager.pattern {
all_initialization_scripts.push(main_frame_script(
IsolationJavascript {
isolation_src: &crate::pattern::format_real_schema(schema, use_https_scheme),
style: tauri_utils::pattern::isolation::IFRAME_STYLE,
}
.render_default(&Default::default())?
.into_string(),
));
}
if let Some(plugin_global_api_scripts) = &*app_manager.plugin_global_api_scripts {
for &script in plugin_global_api_scripts.iter() {
all_initialization_scripts.push(main_frame_script(script.to_owned()));
}
}
// Prepend `all_initialization_scripts` to `webview_attributes.initialization_scripts`
all_initialization_scripts.extend(webview_attributes.initialization_scripts);
webview_attributes.initialization_scripts = all_initialization_scripts;
pending.webview_attributes = webview_attributes;
let mut registered_scheme_protocols = Vec::new();
for (uri_scheme, protocol) in &*self.uri_scheme_protocols.lock().unwrap() {
registered_scheme_protocols.push(uri_scheme.clone());
let protocol = protocol.clone();
let app_handle = manager.app_handle().clone();
pending.register_uri_scheme_protocol(uri_scheme, move |webview_id, request, responder| {
let context = UriSchemeContext {
app_handle: &app_handle,
webview_label: webview_id,
};
(protocol.handler)(context, request, UriSchemeResponder(responder))
});
}
let window_url = Url::parse(&pending.url).unwrap();
let window_origin = if window_url.scheme() == "data" {
"null".into()
} else if (cfg!(windows) || cfg!(target_os = "android"))
&& window_url.scheme() != "http"
&& window_url.scheme() != "https"
{
let https = if use_https_scheme { "https" } else { "http" };
format!("{https}://{}.localhost", window_url.scheme())
} else if let Some(host) = window_url.host() {
format!(
"{}://{}{}",
window_url.scheme(),
host,
window_url
.port()
.map(|p| format!(":{p}"))
.unwrap_or_default()
)
} else {
"null".into()
};
if !registered_scheme_protocols.contains(&"tauri".into()) {
let web_resource_request_handler = pending.web_resource_request_handler.take();
let protocol = crate::protocol::tauri::get(
manager.manager_owned(),
&window_origin,
web_resource_request_handler,
);
pending.register_uri_scheme_protocol("tauri", move |webview_id, request, responder| {
protocol(webview_id, request, UriSchemeResponder(responder))
});
registered_scheme_protocols.push("tauri".into());
}
if !registered_scheme_protocols.contains(&"ipc".into()) {
let protocol = crate::ipc::protocol::get(manager.manager_owned());
pending.register_uri_scheme_protocol("ipc", move |webview_id, request, responder| {
protocol(webview_id, request, UriSchemeResponder(responder))
});
registered_scheme_protocols.push("ipc".into());
}
let label = pending.label.clone();
let app_manager_ = manager.manager_owned();
let on_page_load_handler = pending.on_page_load_handler.take();
pending
.on_page_load_handler
.replace(Box::new(move |url, event| {
let payload = PageLoadPayload { url: &url, event };
if let Some(w) = app_manager_.get_webview(&label) {
if let Some(on_page_load) = &app_manager_.webview.on_page_load {
on_page_load(&w, &payload);
}
app_manager_
.plugins
.lock()
.unwrap()
.on_page_load(&w, &payload);
}
if let Some(handler) = &on_page_load_handler {
handler(url, event);
}
}));
#[cfg(feature = "protocol-asset")]
if !registered_scheme_protocols.contains(&"asset".into()) {
let asset_scope = app_manager
.state()
.get::<crate::Scopes>()
.asset_protocol
.clone();
let protocol = crate::protocol::asset::get(asset_scope, window_origin.clone());
pending.register_uri_scheme_protocol("asset", move |webview_id, request, responder| {
protocol(webview_id, request, UriSchemeResponder(responder))
});
}
#[cfg(feature = "isolation")]
if let crate::Pattern::Isolation {
assets,
schema,
key: _,
crypto_keys,
} = &*app_manager.pattern
{
let protocol = crate::protocol::isolation::get(
manager.manager_owned(),
schema,
assets.clone(),
*crypto_keys.aes_gcm().raw(),
window_origin,
use_https_scheme,
);
pending.register_uri_scheme_protocol(schema, move |webview_id, request, responder| {
protocol(webview_id, request, UriSchemeResponder(responder))
});
}
Ok(pending)
}
fn initialization_script(
&self,
app_manager: &AppManager<R>,
ipc_script: &str,
pattern_script: &str,
use_https_scheme: bool,
) -> crate::Result<String> {
#[derive(Template)]
#[default_template("../../scripts/init.js")]
struct InitJavascript<'a> {
#[raw]
pattern_script: &'a str,
#[raw]
ipc_script: &'a str,
#[raw]
core_script: &'a str,
#[raw]
event_initialization_script: &'a str,
#[raw]
freeze_prototype: &'a str,
}
#[derive(Template)]
#[default_template("../../scripts/core.js")]
struct CoreJavascript<'a> {
os_name: &'a str,
protocol_scheme: &'a str,
invoke_key: &'a str,
}
let freeze_prototype = if app_manager.config.app.security.freeze_prototype {
include_str!("../../scripts/freeze_prototype.js")
} else {
""
};
InitJavascript {
pattern_script,
ipc_script,
core_script: &CoreJavascript {
os_name: std::env::consts::OS,
protocol_scheme: if use_https_scheme { "https" } else { "http" },
invoke_key: self.invoke_key(),
}
.render_default(&Default::default())?
.into_string(),
event_initialization_script: &crate::event::event_initialization_script(
app_manager.listeners().function_name(),
app_manager.listeners().listeners_object_name(),
),
freeze_prototype,
}
.render_default(&Default::default())
.map(|s| s.into_string())
.map_err(Into::into)
}
pub fn prepare_webview<M: Manager<R>>(
&self,
manager: &M,
mut pending: PendingWebview<EventLoopMessage, R>,
window_label: &str,
) -> crate::Result<PendingWebview<EventLoopMessage, R>> {
if self.webviews_lock().contains_key(&pending.label) {
return Err(crate::Error::WebviewLabelAlreadyExists(pending.label));
}
let app_manager = manager.manager();
#[allow(unused_mut)] // mut url only for the data-url parsing
let mut url = match &pending.webview_attributes.url {
WebviewUrl::App(path) => {
let app_url = app_manager.get_app_url(pending.webview_attributes.use_https_scheme);
let url = if PROXY_DEV_SERVER && is_local_network_url(&app_url) {
Cow::Owned(Url::parse("tauri://localhost").unwrap())
} else {
app_url
};
// ignore "index.html" just to simplify the url
if path.to_str() != Some("index.html") {
url
.join(&path.to_string_lossy())
.map_err(crate::Error::InvalidUrl)
// this will never fail
.unwrap()
} else {
url.into_owned()
}
}
WebviewUrl::External(url) => {
let config_url = app_manager.get_app_url(pending.webview_attributes.use_https_scheme);
let is_app_url = config_url.make_relative(url).is_some();
let mut url = url.clone();
if is_app_url && PROXY_DEV_SERVER && is_local_network_url(&url) {
Url::parse("tauri://localhost").unwrap()
} else {
url
}
}
WebviewUrl::CustomProtocol(url) => url.clone(),
_ => unimplemented!(),
};
#[cfg(not(feature = "webview-data-url"))]
if url.scheme() == "data" {
return Err(crate::Error::InvalidWebviewUrl(
"data URLs are not supported without the `webview-data-url` feature.",
));
}
#[cfg(feature = "webview-data-url")]
if let Some(csp) = app_manager.csp() {
if url.scheme() == "data" {
if let Ok(data_url) = data_url::DataUrl::process(url.as_str()) {
let (body, _) = data_url.decode_to_vec().unwrap();
let html = String::from_utf8_lossy(&body).into_owned();
// naive way to check if it's an html
if html.contains('<') && html.contains('>') {
let document = tauri_utils::html::parse(html);
tauri_utils::html::inject_csp(&document, &csp.to_string());
url.set_path(&format!("{},{document}", mime::TEXT_HTML));
}
}
}
}
pending.url = url.to_string();
#[cfg(target_os = "android")]
{
pending = pending.on_webview_created(move |ctx| {
let plugin_manager = ctx
.env
.call_method(
ctx.activity,
"getPluginManager",
"()Lapp/tauri/plugin/PluginManager;",
&[],
)?
.l()?;
// tell the manager the webview is ready
ctx.env.call_method(
plugin_manager,
"onWebViewCreated",
"(Landroid/webkit/WebView;)V",
&[ctx.webview.into()],
)?;
Ok(())
});
}
let label = pending.label.clone();
pending = self.prepare_pending_webview(pending, &label, window_label, manager)?;
pending.ipc_handler = Some(crate::ipc::protocol::message_handler(
manager.manager_owned(),
));
// in `windows`, we need to force a data_directory
// but we do respect user-specification
#[cfg(any(target_os = "linux", target_os = "windows"))]
if pending.webview_attributes.data_directory.is_none() {
let local_app_data = manager.path().resolve(
&app_manager.config.identifier,
crate::path::BaseDirectory::LocalData,
);
if let Ok(user_data_dir) = local_app_data {
pending.webview_attributes.data_directory = Some(user_data_dir);
}
}
// make sure the directory is created and available to prevent a panic
if let Some(user_data_dir) = &pending.webview_attributes.data_directory {
if !user_data_dir.exists() {
create_dir_all(user_data_dir)?;
}
}
#[cfg(all(desktop, not(target_os = "windows")))]
if pending.webview_attributes.zoom_hotkeys_enabled {
#[derive(Template)]
#[default_template("../webview/scripts/zoom-hotkey.js")]
struct HotkeyZoom<'a> {
os_name: &'a str,
}
pending
.webview_attributes
.initialization_scripts
.push(InitializationScript {
script: HotkeyZoom {
os_name: std::env::consts::OS,
}
.render_default(&Default::default())?
.into_string(),
for_main_frame_only: true,
})
}
#[cfg(feature = "isolation")]
let pattern = app_manager.pattern.clone();
let navigation_handler = pending.navigation_handler.take();
let app_manager = manager.manager_owned();
let label = pending.label.clone();
pending.navigation_handler = Some(Box::new(move |url| {
// always allow navigation events for the isolation iframe and do not emit them for consumers
#[cfg(feature = "isolation")]
if let crate::Pattern::Isolation { schema, .. } = &*pattern {
if url.scheme() == schema
&& url.domain() == Some(crate::pattern::ISOLATION_IFRAME_SRC_DOMAIN)
{
return true;
}
}
if let Some(handler) = &navigation_handler {
if !handler(url) {
return false;
}
}
let webview = app_manager.webview.webviews_lock().get(&label).cloned();
if let Some(w) = webview {
app_manager
.plugins
.lock()
.expect("poisoned plugin store")
.on_navigation(&w, url)
} else {
true
}
}));
Ok(pending)
}
pub(crate) fn attach_webview(
&self,
window: Window<R>,
webview: DetachedWebview<EventLoopMessage, R>,
use_https_scheme: bool,
) -> Webview<R> {
let webview = Webview::new(window, webview, use_https_scheme);
let webview_event_listeners = self.event_listeners.clone();
let webview_ = webview.clone();
webview.on_webview_event(move |event| {
let _ = on_webview_event(&webview_, event);
for handler in webview_event_listeners.iter() {
handler(&webview_, event);
}
});
// insert the webview into our manager
{
self
.webviews_lock()
.insert(webview.label().to_string(), webview.clone());
}
// let plugins know that a new webview has been added to the manager
let manager = webview.manager_owned();
let webview_ = webview.clone();
// run on main thread so the plugin store doesn't dead lock with the event loop handler in App
let _ = webview.run_on_main_thread(move || {
manager
.plugins
.lock()
.expect("poisoned plugin store")
.webview_created(webview_);
});
#[cfg(all(target_os = "ios", feature = "wry"))]
{
webview
.with_webview(|w| {
unsafe { crate::ios::on_webview_created(w.inner() as _, w.view_controller() as _) };
})
.expect("failed to run on_webview_created hook");
}
let event = crate::EventName::from_str("tauri://webview-created");
let payload = Some(crate::webview::CreatedEvent {
label: webview.label().into(),
});
let _ = webview
.manager
.emit(event, EmitPayload::Serialize(&payload));
webview
}
pub fn eval_script_all<S: Into<String>>(&self, script: S) -> crate::Result<()> {
let script = script.into();
let webviews = self.webviews_lock().values().cloned().collect::<Vec<_>>();
webviews
.iter()
.try_for_each(|webview| webview.eval(&script))
}
pub fn labels(&self) -> HashSet<String> {
self.webviews_lock().keys().cloned().collect()
}
pub(crate) fn invoke_key(&self) -> &str {
&self.invoke_key
}
}
impl<R: Runtime> Webview<R> {
/// Emits event to [`EventTarget::Window`] and [`EventTarget::WebviewWindow`]
fn emit_to_webview<S: Serialize>(
&self,
event: crate::EventName<&str>,
payload: &S,
) -> crate::Result<()> {
let window_label = self.label();
let payload = EmitPayload::Serialize(payload);
self
.manager()
.emit_filter(event, payload, |target| match target {
EventTarget::Webview { label } | EventTarget::WebviewWindow { label } => {
label == window_label
}
_ => false,
})
}
}
fn on_webview_event<R: Runtime>(webview: &Webview<R>, event: &WebviewEvent) -> crate::Result<()> {
match event {
WebviewEvent::DragDrop(event) => match event {
DragDropEvent::Enter { paths, position } => {
let payload = DragDropPayload {
paths: Some(paths),
position,
};
webview.emit_to_webview(DRAG_ENTER_EVENT, &payload)?
}
DragDropEvent::Over { position } => {
let payload = DragDropPayload {
position,
paths: None,
};
webview.emit_to_webview(DRAG_OVER_EVENT, &payload)?
}
DragDropEvent::Drop { paths, position } => {
let scopes = webview.state::<Scopes>();
for path in paths {
if path.is_file() {
let _ = scopes.allow_file(path);
} else {
let _ = scopes.allow_directory(path, false);
}
}
let payload = DragDropPayload {
paths: Some(paths),
position,
};
webview.emit_to_webview(DRAG_DROP_EVENT, &payload)?
}
DragDropEvent::Leave => webview.emit_to_webview(DRAG_LEAVE_EVENT, &())?,
_ => unimplemented!(),
},
}
Ok(())
}
fn is_local_network_url(url: &url::Url) -> bool {
match url.host() {
Some(url::Host::Domain(s)) => s == "localhost",
Some(url::Host::Ipv4(_)) | Some(url::Host::Ipv6(_)) => true,
None => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn local_network_url() {
assert!(is_local_network_url(&"http://localhost".parse().unwrap()));
assert!(is_local_network_url(
&"http://127.0.0.1:8080".parse().unwrap()
));
assert!(is_local_network_url(
&"https://192.168.3.17".parse().unwrap()
));
assert!(!is_local_network_url(&"https://tauri.app".parse().unwrap()));
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/test/mod.rs | crates/tauri/src/test/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Utilities for unit testing on Tauri applications.
//!
//! # Stability
//!
//! This module is unstable.
//!
//! # Examples
//!
//! ```rust
//! use tauri::test::{mock_builder, mock_context, noop_assets};
//!
//! #[tauri::command]
//! fn ping() -> &'static str {
//! "pong"
//! }
//!
//! fn create_app<R: tauri::Runtime>(builder: tauri::Builder<R>) -> tauri::App<R> {
//! builder
//! .invoke_handler(tauri::generate_handler![ping])
//! // remove the string argument to use your app's config file
//! .build(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
//! .expect("failed to build app")
//! }
//!
//! fn main() {
//! // Use `tauri::Builder::default()` to use the default runtime rather than the `MockRuntime`;
//! // let app = create_app(tauri::Builder::default());
//! let app = create_app(mock_builder());
//! let webview = tauri::WebviewWindowBuilder::new(&app, "main", Default::default()).build().unwrap();
//!
//! // run the `ping` command and assert it returns `pong`
//! let res = tauri::test::get_ipc_response(
//! &webview,
//! tauri::webview::InvokeRequest {
//! cmd: "ping".into(),
//! callback: tauri::ipc::CallbackFn(0),
//! error: tauri::ipc::CallbackFn(1),
//! // alternatively use "tauri://localhost"
//! url: "http://tauri.localhost".parse().unwrap(),
//! body: tauri::ipc::InvokeBody::default(),
//! headers: Default::default(),
//! invoke_key: tauri::test::INVOKE_KEY.to_string(),
//! },
//! ).map(|b| b.deserialize::<String>().unwrap());
//! }
//! ```
#![allow(unused_variables)]
mod mock_runtime;
pub use mock_runtime::*;
use serde::Serialize;
use serialize_to_javascript::DefaultTemplate;
use std::{borrow::Cow, collections::HashMap, fmt::Debug};
use crate::{
ipc::{InvokeError, InvokeResponse, InvokeResponseBody},
webview::InvokeRequest,
App, Assets, Builder, Context, Pattern, Runtime, Webview,
};
use tauri_utils::{
acl::resolved::Resolved,
assets::{AssetKey, AssetsIter, CspHash},
config::{AppConfig, Config},
};
/// The invoke key used for tests.
pub const INVOKE_KEY: &str = "__invoke-key__";
/// An empty [`Assets`] implementation.
pub struct NoopAsset {
assets: HashMap<String, Vec<u8>>,
csp_hashes: Vec<CspHash<'static>>,
}
impl<R: Runtime> Assets<R> for NoopAsset {
fn get(&self, key: &AssetKey) -> Option<Cow<'_, [u8]>> {
None
}
fn iter(&self) -> Box<AssetsIter<'_>> {
Box::new(
self
.assets
.iter()
.map(|(k, b)| (Cow::Borrowed(k.as_str()), Cow::Borrowed(b.as_slice()))),
)
}
fn csp_hashes(&self, html_path: &AssetKey) -> Box<dyn Iterator<Item = CspHash<'_>> + '_> {
Box::new(self.csp_hashes.iter().copied())
}
}
/// Creates a new empty [`Assets`] implementation.
pub fn noop_assets() -> NoopAsset {
NoopAsset {
assets: Default::default(),
csp_hashes: Default::default(),
}
}
/// Creates a new [`crate::Context`] for testing.
pub fn mock_context<R: Runtime, A: Assets<R>>(assets: A) -> crate::Context<R> {
Context {
config: Config {
schema: None,
product_name: Default::default(),
main_binary_name: Default::default(),
version: Default::default(),
identifier: Default::default(),
app: AppConfig {
with_global_tauri: Default::default(),
windows: Vec::new(),
security: Default::default(),
tray_icon: None,
macos_private_api: false,
enable_gtk_app_id: false,
},
bundle: Default::default(),
build: Default::default(),
plugins: Default::default(),
},
assets: Box::new(assets),
default_window_icon: None,
app_icon: None,
#[cfg(all(desktop, feature = "tray-icon"))]
tray_icon: None,
package_info: crate::PackageInfo {
name: "test".into(),
version: "0.1.0".parse().unwrap(),
authors: "Tauri",
description: "Tauri test",
crate_name: "test",
},
pattern: Pattern::Brownfield,
runtime_authority: crate::runtime_authority!(Default::default(), Resolved::default()),
plugin_global_api_scripts: None,
#[cfg(dev)]
config_parent: None,
}
}
/// Creates a new [`Builder`] using the [`MockRuntime`].
///
/// To use a dummy [`Context`], see [`mock_app`].
///
/// # Examples
///
/// ```rust
/// #[cfg(test)]
/// fn do_something() {
/// let app = tauri::test::mock_builder()
/// // remove the string argument to use your app's config file
/// .build(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
/// .unwrap();
/// }
/// ```
pub fn mock_builder() -> Builder<MockRuntime> {
let mut builder = Builder::<MockRuntime>::new().enable_macos_default_menu(false);
builder.invoke_initialization_script = crate::app::InvokeInitializationScript {
process_ipc_message_fn: crate::manager::webview::PROCESS_IPC_MESSAGE_FN,
os_name: std::env::consts::OS,
fetch_channel_data_command: crate::ipc::channel::FETCH_CHANNEL_DATA_COMMAND,
invoke_key: INVOKE_KEY,
}
.render_default(&Default::default())
.unwrap()
.into_string();
builder.invoke_key = INVOKE_KEY.to_string();
builder
}
/// Creates a new [`App`] for testing using the [`mock_context`] with a [`noop_assets`].
pub fn mock_app() -> App<MockRuntime> {
mock_builder().build(mock_context(noop_assets())).unwrap()
}
/// Executes the given IPC message and assert the response matches the expected value.
///
/// # Examples
///
/// ```rust
/// use tauri::test::{mock_builder, mock_context, noop_assets};
///
/// #[tauri::command]
/// fn ping() -> &'static str {
/// "pong"
/// }
///
/// fn create_app<R: tauri::Runtime>(builder: tauri::Builder<R>) -> tauri::App<R> {
/// builder
/// .invoke_handler(tauri::generate_handler![ping])
/// // remove the string argument to use your app's config file
/// .build(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
/// .expect("failed to build app")
/// }
///
/// fn main() {
/// let app = create_app(mock_builder());
/// let webview = tauri::WebviewWindowBuilder::new(&app, "main", Default::default()).build().unwrap();
///
/// // run the `ping` command and assert it returns `pong`
/// tauri::test::assert_ipc_response(
/// &webview,
/// tauri::webview::InvokeRequest {
/// cmd: "ping".into(),
/// callback: tauri::ipc::CallbackFn(0),
/// error: tauri::ipc::CallbackFn(1),
/// url: "http://tauri.localhost".parse().unwrap(),
/// body: tauri::ipc::InvokeBody::default(),
/// headers: Default::default(),
/// invoke_key: tauri::test::INVOKE_KEY.to_string(),
/// },
/// Ok("pong")
/// );
/// }
/// ```
pub fn assert_ipc_response<
T: Serialize + Debug + Send + Sync + 'static,
W: AsRef<Webview<MockRuntime>>,
>(
webview: &W,
request: InvokeRequest,
expected: Result<T, T>,
) {
let response =
get_ipc_response(webview, request).map(|b| b.deserialize::<serde_json::Value>().unwrap());
assert_eq!(
response,
expected
.map(|e| serde_json::to_value(e).unwrap())
.map_err(|e| serde_json::to_value(e).unwrap())
);
}
/// Executes the given IPC message and get the return value.
///
/// # Examples
///
/// ```rust
/// use tauri::test::{mock_builder, mock_context, noop_assets};
///
/// #[tauri::command]
/// fn ping() -> &'static str {
/// "pong"
/// }
///
/// fn create_app<R: tauri::Runtime>(builder: tauri::Builder<R>) -> tauri::App<R> {
/// builder
/// .invoke_handler(tauri::generate_handler![ping])
/// // remove the string argument to use your app's config file
/// .build(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
/// .expect("failed to build app")
/// }
///
/// fn main() {
/// let app = create_app(mock_builder());
/// let webview = tauri::WebviewWindowBuilder::new(&app, "main", Default::default()).build().unwrap();
///
/// // run the `ping` command and assert it returns `pong`
/// let res = tauri::test::get_ipc_response(
/// &webview,
/// tauri::webview::InvokeRequest {
/// cmd: "ping".into(),
/// callback: tauri::ipc::CallbackFn(0),
/// error: tauri::ipc::CallbackFn(1),
/// url: "http://tauri.localhost".parse().unwrap(),
/// body: tauri::ipc::InvokeBody::default(),
/// headers: Default::default(),
/// invoke_key: tauri::test::INVOKE_KEY.to_string(),
/// },
/// );
/// assert!(res.is_ok());
/// assert_eq!(res.unwrap().deserialize::<String>().unwrap(), String::from("pong"));
/// }
///```
pub fn get_ipc_response<W: AsRef<Webview<MockRuntime>>>(
webview: &W,
request: InvokeRequest,
) -> Result<InvokeResponseBody, serde_json::Value> {
let (tx, rx) = std::sync::mpsc::sync_channel(1);
webview.as_ref().clone().on_message(
request,
Box::new(move |_window, _cmd, response, _callback, _error| {
tx.send(response).unwrap();
}),
);
let res = rx.recv().expect("Failed to receive result from command");
match res {
InvokeResponse::Ok(b) => Ok(b),
InvokeResponse::Err(InvokeError(v)) => Err(v),
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use super::mock_app;
#[test]
fn run_app() {
let app = mock_app();
let w = crate::WebviewWindowBuilder::new(&app, "main", Default::default())
.build()
.unwrap();
std::thread::spawn(move || {
std::thread::sleep(Duration::from_secs(1));
w.close().unwrap();
});
app.run(|_app, event| {
println!("{event:?}");
});
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/test/mock_runtime.rs | crates/tauri/src/test/mock_runtime.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
#![allow(dead_code)]
#![allow(missing_docs)]
use tauri_runtime::{
dpi::{PhysicalPosition, PhysicalSize, Position, Size},
monitor::Monitor,
webview::{DetachedWebview, PendingWebview},
window::{
CursorIcon, DetachedWindow, DetachedWindowWebview, PendingWindow, RawWindow, WindowBuilder,
WindowBuilderBase, WindowEvent, WindowId,
},
DeviceEventFilter, Error, EventLoopProxy, ExitRequestedEventAction, Icon, ProgressBarState,
Result, RunEvent, Runtime, RuntimeHandle, RuntimeInitArgs, UserAttentionType, UserEvent,
WebviewDispatch, WindowDispatch, WindowEventId,
};
#[cfg(target_os = "macos")]
use tauri_utils::TitleBarStyle;
use tauri_utils::{config::WindowConfig, Theme};
use url::Url;
#[cfg(windows)]
use windows::Win32::Foundation::HWND;
use std::{
cell::RefCell,
collections::HashMap,
fmt,
sync::{
atomic::{AtomicBool, AtomicU32, Ordering},
mpsc::{channel, sync_channel, Receiver, SyncSender},
Arc, Mutex,
},
};
type ShortcutMap = HashMap<String, Box<dyn Fn() + Send + 'static>>;
enum Message {
Task(Box<dyn FnOnce() + Send>),
CloseWindow(WindowId),
DestroyWindow(WindowId),
}
struct Webview;
struct Window {
label: String,
webviews: Vec<Webview>,
}
#[derive(Clone)]
pub struct RuntimeContext {
is_running: Arc<AtomicBool>,
windows: Arc<RefCell<HashMap<WindowId, Window>>>,
shortcuts: Arc<Mutex<ShortcutMap>>,
run_tx: SyncSender<Message>,
next_window_id: Arc<AtomicU32>,
next_webview_id: Arc<AtomicU32>,
next_window_event_id: Arc<AtomicU32>,
next_webview_event_id: Arc<AtomicU32>,
}
// SAFETY: we ensure this type is only used on the main thread.
#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl Send for RuntimeContext {}
// SAFETY: we ensure this type is only used on the main thread.
#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl Sync for RuntimeContext {}
impl RuntimeContext {
fn send_message(&self, message: Message) -> Result<()> {
if self.is_running.load(Ordering::Relaxed) {
self
.run_tx
.send(message)
.map_err(|_| Error::FailedToSendMessage)
} else {
match message {
Message::Task(task) => task(),
Message::CloseWindow(id) | Message::DestroyWindow(id) => {
self.windows.borrow_mut().remove(&id);
}
}
Ok(())
}
}
fn next_window_id(&self) -> WindowId {
self.next_window_id.fetch_add(1, Ordering::Relaxed).into()
}
fn next_webview_id(&self) -> u32 {
self.next_webview_id.fetch_add(1, Ordering::Relaxed)
}
fn next_window_event_id(&self) -> WindowEventId {
self.next_window_event_id.fetch_add(1, Ordering::Relaxed)
}
fn next_webview_event_id(&self) -> WindowEventId {
self.next_webview_event_id.fetch_add(1, Ordering::Relaxed)
}
}
impl fmt::Debug for RuntimeContext {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RuntimeContext").finish()
}
}
#[derive(Debug, Clone)]
pub struct MockRuntimeHandle {
context: RuntimeContext,
}
impl<T: UserEvent> RuntimeHandle<T> for MockRuntimeHandle {
type Runtime = MockRuntime;
fn create_proxy(&self) -> EventProxy {
EventProxy {}
}
#[cfg(target_os = "macos")]
#[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
fn set_activation_policy(
&self,
activation_policy: tauri_runtime::ActivationPolicy,
) -> Result<()> {
Ok(())
}
#[cfg(target_os = "macos")]
#[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
fn set_dock_visibility(&self, visible: bool) -> Result<()> {
Ok(())
}
fn request_exit(&self, code: i32) -> Result<()> {
unimplemented!()
}
/// Create a new webview window.
fn create_window<F: Fn(RawWindow<'_>) + Send + 'static>(
&self,
pending: PendingWindow<T, Self::Runtime>,
_after_window_creation: Option<F>,
) -> Result<DetachedWindow<T, Self::Runtime>> {
let id = self.context.next_window_id();
let (webview_id, webviews) = if let Some(w) = &pending.webview {
(Some(self.context.next_webview_id()), vec![Webview])
} else {
(None, Vec::new())
};
self.context.windows.borrow_mut().insert(
id,
Window {
label: pending.label.clone(),
webviews,
},
);
let webview = webview_id.map(|id| DetachedWindowWebview {
webview: DetachedWebview {
label: pending.label.clone(),
dispatcher: MockWebviewDispatcher {
id,
context: self.context.clone(),
url: Arc::new(Mutex::new(pending.webview.unwrap().url)),
last_evaluated_script: Default::default(),
},
},
use_https_scheme: false,
});
Ok(DetachedWindow {
id,
label: pending.label,
dispatcher: MockWindowDispatcher {
id,
context: self.context.clone(),
},
webview,
})
}
fn create_webview(
&self,
window_id: WindowId,
pending: PendingWebview<T, Self::Runtime>,
) -> Result<DetachedWebview<T, Self::Runtime>> {
let id = self.context.next_webview_id();
let webview = Webview;
if let Some(w) = self.context.windows.borrow_mut().get_mut(&window_id) {
w.webviews.push(webview);
}
Ok(DetachedWebview {
label: pending.label,
dispatcher: MockWebviewDispatcher {
id,
context: self.context.clone(),
last_evaluated_script: Default::default(),
url: Arc::new(Mutex::new(pending.url)),
},
})
}
/// Run a task on the main thread.
fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> Result<()> {
self.context.send_message(Message::Task(Box::new(f)))
}
fn display_handle(
&self,
) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, raw_window_handle::HandleError> {
#[cfg(target_os = "linux")]
return Ok(unsafe {
raw_window_handle::DisplayHandle::borrow_raw(raw_window_handle::RawDisplayHandle::Xlib(
raw_window_handle::XlibDisplayHandle::new(None, 0),
))
});
#[cfg(target_os = "macos")]
return Ok(unsafe {
raw_window_handle::DisplayHandle::borrow_raw(raw_window_handle::RawDisplayHandle::AppKit(
raw_window_handle::AppKitDisplayHandle::new(),
))
});
#[cfg(windows)]
return Ok(unsafe {
raw_window_handle::DisplayHandle::borrow_raw(raw_window_handle::RawDisplayHandle::Windows(
raw_window_handle::WindowsDisplayHandle::new(),
))
});
#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
unimplemented!();
}
fn primary_monitor(&self) -> Option<Monitor> {
unimplemented!()
}
fn monitor_from_point(&self, x: f64, y: f64) -> Option<Monitor> {
unimplemented!()
}
fn available_monitors(&self) -> Vec<Monitor> {
unimplemented!()
}
fn set_theme(&self, theme: Option<Theme>) {
unimplemented!()
}
/// Shows the application, but does not automatically focus it.
#[cfg(target_os = "macos")]
fn show(&self) -> Result<()> {
Ok(())
}
/// Hides the application.
#[cfg(target_os = "macos")]
fn hide(&self) -> Result<()> {
Ok(())
}
fn set_device_event_filter(&self, _: DeviceEventFilter) {
// no-op
}
#[cfg(target_os = "android")]
fn find_class<'a>(
&self,
env: &mut jni::JNIEnv<'a>,
activity: &jni::objects::JObject<'_>,
name: impl Into<String>,
) -> std::result::Result<jni::objects::JClass<'a>, jni::errors::Error> {
todo!()
}
#[cfg(target_os = "android")]
fn run_on_android_context<F>(&self, f: F)
where
F: FnOnce(&mut jni::JNIEnv, &jni::objects::JObject, &jni::objects::JObject) + Send + 'static,
{
todo!()
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn fetch_data_store_identifiers<F: FnOnce(Vec<[u8; 16]>) + Send + 'static>(
&self,
cb: F,
) -> Result<()> {
todo!()
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn remove_data_store<F: FnOnce(Result<()>) + Send + 'static>(
&self,
uuid: [u8; 16],
cb: F,
) -> Result<()> {
todo!()
}
fn cursor_position(&self) -> Result<PhysicalPosition<f64>> {
Ok(PhysicalPosition::new(0.0, 0.0))
}
}
#[derive(Debug, Clone)]
pub struct MockWebviewDispatcher {
id: u32,
context: RuntimeContext,
url: Arc<Mutex<String>>,
last_evaluated_script: Arc<Mutex<Option<String>>>,
}
impl MockWebviewDispatcher {
pub fn last_evaluated_script(&self) -> Option<String> {
self.last_evaluated_script.lock().unwrap().clone()
}
}
#[derive(Debug, Clone)]
pub struct MockWindowDispatcher {
id: WindowId,
context: RuntimeContext,
}
#[derive(Debug, Clone)]
pub struct MockWindowBuilder {}
impl WindowBuilderBase for MockWindowBuilder {}
impl WindowBuilder for MockWindowBuilder {
fn new() -> Self {
Self {}
}
fn with_config(config: &WindowConfig) -> Self {
Self {}
}
fn center(self) -> Self {
self
}
fn position(self, x: f64, y: f64) -> Self {
self
}
fn inner_size(self, min_width: f64, min_height: f64) -> Self {
self
}
fn min_inner_size(self, min_width: f64, min_height: f64) -> Self {
self
}
fn max_inner_size(self, max_width: f64, max_height: f64) -> Self {
self
}
fn inner_size_constraints(
self,
constraints: tauri_runtime::window::WindowSizeConstraints,
) -> Self {
self
}
fn prevent_overflow(self) -> Self {
self
}
fn prevent_overflow_with_margin(self, margin: tauri_runtime::dpi::Size) -> Self {
self
}
fn resizable(self, resizable: bool) -> Self {
self
}
fn maximizable(self, resizable: bool) -> Self {
self
}
fn minimizable(self, resizable: bool) -> Self {
self
}
fn closable(self, resizable: bool) -> Self {
self
}
fn title<S: Into<String>>(self, title: S) -> Self {
self
}
fn fullscreen(self, fullscreen: bool) -> Self {
self
}
fn focused(self, focused: bool) -> Self {
self
}
fn focusable(self, focusable: bool) -> Self {
self
}
fn maximized(self, maximized: bool) -> Self {
self
}
fn visible(self, visible: bool) -> Self {
self
}
#[cfg(any(not(target_os = "macos"), feature = "macos-private-api"))]
#[cfg_attr(
docsrs,
doc(cfg(any(not(target_os = "macos"), feature = "macos-private-api")))
)]
fn transparent(self, transparent: bool) -> Self {
self
}
fn decorations(self, decorations: bool) -> Self {
self
}
fn always_on_bottom(self, always_on_bottom: bool) -> Self {
self
}
fn always_on_top(self, always_on_top: bool) -> Self {
self
}
fn visible_on_all_workspaces(self, visible_on_all_workspaces: bool) -> Self {
self
}
fn content_protected(self, protected: bool) -> Self {
self
}
fn icon(self, icon: Icon<'_>) -> Result<Self> {
Ok(self)
}
fn skip_taskbar(self, skip: bool) -> Self {
self
}
fn window_classname<S: Into<String>>(self, classname: S) -> Self {
self
}
fn shadow(self, enable: bool) -> Self {
self
}
#[cfg(windows)]
fn owner(self, owner: HWND) -> Self {
self
}
#[cfg(windows)]
fn parent(self, parent: HWND) -> Self {
self
}
#[cfg(target_os = "macos")]
fn parent(self, parent: *mut std::ffi::c_void) -> Self {
self
}
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
fn transient_for(self, parent: &impl gtk::glib::IsA<gtk::Window>) -> Self {
self
}
#[cfg(windows)]
fn drag_and_drop(self, enabled: bool) -> Self {
self
}
#[cfg(target_os = "macos")]
fn title_bar_style(self, style: TitleBarStyle) -> Self {
self
}
#[cfg(target_os = "macos")]
fn traffic_light_position<P: Into<Position>>(self, position: P) -> Self {
self
}
#[cfg(target_os = "macos")]
fn hidden_title(self, transparent: bool) -> Self {
self
}
#[cfg(target_os = "macos")]
fn tabbing_identifier(self, identifier: &str) -> Self {
self
}
fn theme(self, theme: Option<Theme>) -> Self {
self
}
fn has_icon(&self) -> bool {
false
}
fn get_theme(&self) -> Option<Theme> {
None
}
fn background_color(self, _color: tauri_utils::config::Color) -> Self {
self
}
}
impl<T: UserEvent> WebviewDispatch<T> for MockWebviewDispatcher {
type Runtime = MockRuntime;
fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> Result<()> {
self.context.send_message(Message::Task(Box::new(f)))
}
fn on_webview_event<F: Fn(&tauri_runtime::window::WebviewEvent) + Send + 'static>(
&self,
f: F,
) -> tauri_runtime::WebviewEventId {
self.context.next_window_event_id()
}
fn with_webview<F: FnOnce(Box<dyn std::any::Any>) + Send + 'static>(&self, f: F) -> Result<()> {
Ok(())
}
#[cfg(any(debug_assertions, feature = "devtools"))]
fn open_devtools(&self) {}
#[cfg(any(debug_assertions, feature = "devtools"))]
fn close_devtools(&self) {}
#[cfg(any(debug_assertions, feature = "devtools"))]
fn is_devtools_open(&self) -> Result<bool> {
Ok(false)
}
fn set_zoom(&self, scale_factor: f64) -> Result<()> {
Ok(())
}
fn eval_script<S: Into<String>>(&self, script: S) -> Result<()> {
self
.last_evaluated_script
.lock()
.unwrap()
.replace(script.into());
Ok(())
}
fn url(&self) -> Result<String> {
Ok(self.url.lock().unwrap().clone())
}
fn bounds(&self) -> Result<tauri_runtime::dpi::Rect> {
Ok(tauri_runtime::dpi::Rect::default())
}
fn position(&self) -> Result<PhysicalPosition<i32>> {
Ok(PhysicalPosition { x: 0, y: 0 })
}
fn size(&self) -> Result<PhysicalSize<u32>> {
Ok(PhysicalSize {
width: 0,
height: 0,
})
}
fn navigate(&self, url: Url) -> Result<()> {
*self.url.lock().unwrap() = url.to_string();
Ok(())
}
fn reload(&self) -> Result<()> {
Ok(())
}
fn print(&self) -> Result<()> {
Ok(())
}
fn close(&self) -> Result<()> {
Ok(())
}
fn set_bounds(&self, bounds: tauri_runtime::dpi::Rect) -> Result<()> {
Ok(())
}
fn set_size(&self, _size: Size) -> Result<()> {
Ok(())
}
fn set_position(&self, _position: Position) -> Result<()> {
Ok(())
}
fn set_focus(&self) -> Result<()> {
Ok(())
}
fn reparent(&self, window_id: WindowId) -> Result<()> {
Ok(())
}
fn cookies(&self) -> Result<Vec<tauri_runtime::Cookie<'static>>> {
Ok(Vec::new())
}
fn cookies_for_url(&self, url: Url) -> Result<Vec<tauri_runtime::Cookie<'static>>> {
Ok(Vec::new())
}
fn set_cookie(&self, cookie: tauri_runtime::Cookie<'_>) -> Result<()> {
Ok(())
}
fn delete_cookie(&self, cookie: tauri_runtime::Cookie<'_>) -> Result<()> {
Ok(())
}
fn set_auto_resize(&self, auto_resize: bool) -> Result<()> {
Ok(())
}
fn clear_all_browsing_data(&self) -> Result<()> {
Ok(())
}
fn hide(&self) -> Result<()> {
Ok(())
}
fn show(&self) -> Result<()> {
Ok(())
}
fn set_background_color(&self, color: Option<tauri_utils::config::Color>) -> Result<()> {
Ok(())
}
}
impl<T: UserEvent> WindowDispatch<T> for MockWindowDispatcher {
type Runtime = MockRuntime;
type WindowBuilder = MockWindowBuilder;
fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> Result<()> {
self.context.send_message(Message::Task(Box::new(f)))
}
fn on_window_event<F: Fn(&WindowEvent) + Send + 'static>(&self, f: F) -> WindowEventId {
self.context.next_window_event_id()
}
fn scale_factor(&self) -> Result<f64> {
Ok(1.0)
}
fn inner_position(&self) -> Result<PhysicalPosition<i32>> {
Ok(PhysicalPosition { x: 0, y: 0 })
}
fn outer_position(&self) -> Result<PhysicalPosition<i32>> {
Ok(PhysicalPosition { x: 0, y: 0 })
}
fn inner_size(&self) -> Result<PhysicalSize<u32>> {
Ok(PhysicalSize {
width: 0,
height: 0,
})
}
fn outer_size(&self) -> Result<PhysicalSize<u32>> {
Ok(PhysicalSize {
width: 0,
height: 0,
})
}
fn is_fullscreen(&self) -> Result<bool> {
Ok(false)
}
fn is_minimized(&self) -> Result<bool> {
Ok(false)
}
fn is_maximized(&self) -> Result<bool> {
Ok(false)
}
fn is_focused(&self) -> Result<bool> {
Ok(false)
}
fn is_decorated(&self) -> Result<bool> {
Ok(false)
}
fn is_resizable(&self) -> Result<bool> {
Ok(false)
}
fn is_maximizable(&self) -> Result<bool> {
Ok(true)
}
fn is_minimizable(&self) -> Result<bool> {
Ok(true)
}
fn is_closable(&self) -> Result<bool> {
Ok(true)
}
fn is_visible(&self) -> Result<bool> {
Ok(true)
}
fn title(&self) -> Result<String> {
Ok(String::new())
}
fn current_monitor(&self) -> Result<Option<Monitor>> {
Ok(None)
}
fn primary_monitor(&self) -> Result<Option<Monitor>> {
Ok(None)
}
fn monitor_from_point(&self, x: f64, y: f64) -> Result<Option<Monitor>> {
Ok(None)
}
fn available_monitors(&self) -> Result<Vec<Monitor>> {
Ok(Vec::new())
}
fn theme(&self) -> Result<Theme> {
Ok(Theme::Light)
}
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
fn gtk_window(&self) -> Result<gtk::ApplicationWindow> {
unimplemented!()
}
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
fn default_vbox(&self) -> Result<gtk::Box> {
unimplemented!()
}
fn window_handle(
&self,
) -> std::result::Result<raw_window_handle::WindowHandle<'_>, raw_window_handle::HandleError> {
#[cfg(target_os = "linux")]
return unsafe {
Ok(raw_window_handle::WindowHandle::borrow_raw(
raw_window_handle::RawWindowHandle::Xlib(raw_window_handle::XlibWindowHandle::new(0)),
))
};
#[cfg(target_os = "macos")]
return unsafe {
Ok(raw_window_handle::WindowHandle::borrow_raw(
raw_window_handle::RawWindowHandle::AppKit(raw_window_handle::AppKitWindowHandle::new(
std::ptr::NonNull::from(&()).cast(),
)),
))
};
#[cfg(windows)]
return unsafe {
Ok(raw_window_handle::WindowHandle::borrow_raw(
raw_window_handle::RawWindowHandle::Win32(raw_window_handle::Win32WindowHandle::new(
std::num::NonZeroIsize::MIN,
)),
))
};
#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
unimplemented!();
}
fn center(&self) -> Result<()> {
Ok(())
}
fn request_user_attention(&self, request_type: Option<UserAttentionType>) -> Result<()> {
Ok(())
}
fn create_window<F: Fn(RawWindow<'_>) + Send + 'static>(
&mut self,
pending: PendingWindow<T, Self::Runtime>,
_after_window_creation: Option<F>,
) -> Result<DetachedWindow<T, Self::Runtime>> {
let id = self.context.next_window_id();
let (webview_id, webviews) = if let Some(w) = &pending.webview {
(Some(self.context.next_webview_id()), vec![Webview])
} else {
(None, Vec::new())
};
self.context.windows.borrow_mut().insert(
id,
Window {
label: pending.label.clone(),
webviews,
},
);
let webview = webview_id.map(|id| DetachedWindowWebview {
webview: DetachedWebview {
label: pending.label.clone(),
dispatcher: MockWebviewDispatcher {
id,
context: self.context.clone(),
url: Arc::new(Mutex::new(pending.webview.unwrap().url)),
last_evaluated_script: Default::default(),
},
},
use_https_scheme: false,
});
Ok(DetachedWindow {
id,
label: pending.label,
dispatcher: MockWindowDispatcher {
id,
context: self.context.clone(),
},
webview,
})
}
fn create_webview(
&mut self,
pending: PendingWebview<T, Self::Runtime>,
) -> Result<DetachedWebview<T, Self::Runtime>> {
let id = self.context.next_webview_id();
let webview = Webview;
if let Some(w) = self.context.windows.borrow_mut().get_mut(&self.id) {
w.webviews.push(webview);
}
Ok(DetachedWebview {
label: pending.label,
dispatcher: MockWebviewDispatcher {
id,
context: self.context.clone(),
last_evaluated_script: Default::default(),
url: Arc::new(Mutex::new(pending.url)),
},
})
}
fn set_resizable(&self, resizable: bool) -> Result<()> {
Ok(())
}
fn set_maximizable(&self, maximizable: bool) -> Result<()> {
Ok(())
}
fn set_minimizable(&self, minimizable: bool) -> Result<()> {
Ok(())
}
fn set_closable(&self, closable: bool) -> Result<()> {
Ok(())
}
fn set_title<S: Into<String>>(&self, title: S) -> Result<()> {
Ok(())
}
fn maximize(&self) -> Result<()> {
Ok(())
}
fn unmaximize(&self) -> Result<()> {
Ok(())
}
fn minimize(&self) -> Result<()> {
Ok(())
}
fn unminimize(&self) -> Result<()> {
Ok(())
}
fn show(&self) -> Result<()> {
Ok(())
}
fn hide(&self) -> Result<()> {
Ok(())
}
fn close(&self) -> Result<()> {
self.context.send_message(Message::CloseWindow(self.id))?;
Ok(())
}
fn destroy(&self) -> Result<()> {
self.context.send_message(Message::DestroyWindow(self.id))?;
Ok(())
}
fn set_decorations(&self, decorations: bool) -> Result<()> {
Ok(())
}
fn set_shadow(&self, shadow: bool) -> Result<()> {
Ok(())
}
fn set_always_on_bottom(&self, always_on_bottom: bool) -> Result<()> {
Ok(())
}
fn set_always_on_top(&self, always_on_top: bool) -> Result<()> {
Ok(())
}
fn set_visible_on_all_workspaces(&self, visible_on_all_workspaces: bool) -> Result<()> {
Ok(())
}
fn set_content_protected(&self, protected: bool) -> Result<()> {
Ok(())
}
fn set_size(&self, size: Size) -> Result<()> {
Ok(())
}
fn set_min_size(&self, size: Option<Size>) -> Result<()> {
Ok(())
}
fn set_max_size(&self, size: Option<Size>) -> Result<()> {
Ok(())
}
fn set_position(&self, position: Position) -> Result<()> {
Ok(())
}
fn set_fullscreen(&self, fullscreen: bool) -> Result<()> {
Ok(())
}
#[cfg(target_os = "macos")]
fn set_simple_fullscreen(&self, enable: bool) -> Result<()> {
Ok(())
}
fn set_focus(&self) -> Result<()> {
Ok(())
}
fn set_focusable(&self, focusable: bool) -> Result<()> {
Ok(())
}
fn set_icon(&self, icon: Icon<'_>) -> Result<()> {
Ok(())
}
fn set_skip_taskbar(&self, skip: bool) -> Result<()> {
Ok(())
}
fn set_cursor_grab(&self, grab: bool) -> Result<()> {
Ok(())
}
fn set_cursor_visible(&self, visible: bool) -> Result<()> {
Ok(())
}
fn set_cursor_icon(&self, icon: CursorIcon) -> Result<()> {
Ok(())
}
fn set_cursor_position<Pos: Into<Position>>(&self, position: Pos) -> Result<()> {
Ok(())
}
fn set_ignore_cursor_events(&self, ignore: bool) -> Result<()> {
Ok(())
}
fn start_dragging(&self) -> Result<()> {
Ok(())
}
fn start_resize_dragging(&self, direction: tauri_runtime::ResizeDirection) -> Result<()> {
Ok(())
}
fn set_progress_bar(&self, progress_state: ProgressBarState) -> Result<()> {
Ok(())
}
fn set_badge_count(&self, count: Option<i64>, desktop_filename: Option<String>) -> Result<()> {
Ok(())
}
fn set_badge_label(&self, label: Option<String>) -> Result<()> {
Ok(())
}
fn set_overlay_icon(&self, icon: Option<Icon<'_>>) -> Result<()> {
Ok(())
}
fn set_title_bar_style(&self, style: tauri_utils::TitleBarStyle) -> Result<()> {
Ok(())
}
fn set_traffic_light_position(&self, position: Position) -> Result<()> {
Ok(())
}
fn set_size_constraints(
&self,
constraints: tauri_runtime::window::WindowSizeConstraints,
) -> Result<()> {
Ok(())
}
fn set_theme(&self, theme: Option<Theme>) -> Result<()> {
Ok(())
}
fn set_enabled(&self, enabled: bool) -> Result<()> {
Ok(())
}
fn is_enabled(&self) -> Result<bool> {
Ok(true)
}
fn is_always_on_top(&self) -> Result<bool> {
Ok(false)
}
fn set_background_color(&self, color: Option<tauri_utils::config::Color>) -> Result<()> {
Ok(())
}
}
#[derive(Debug, Clone)]
pub struct EventProxy {}
impl<T: UserEvent> EventLoopProxy<T> for EventProxy {
fn send_event(&self, event: T) -> Result<()> {
Ok(())
}
}
#[derive(Debug)]
pub struct MockRuntime {
is_running: Arc<AtomicBool>,
pub context: RuntimeContext,
run_rx: Receiver<Message>,
}
impl MockRuntime {
fn init() -> Self {
let is_running = Arc::new(AtomicBool::new(false));
let (tx, rx) = sync_channel(256);
let context = RuntimeContext {
is_running: is_running.clone(),
windows: Default::default(),
shortcuts: Default::default(),
run_tx: tx,
next_window_id: Default::default(),
next_webview_id: Default::default(),
next_window_event_id: Default::default(),
next_webview_event_id: Default::default(),
};
Self {
is_running,
context,
run_rx: rx,
}
}
}
impl<T: UserEvent> Runtime<T> for MockRuntime {
type WindowDispatcher = MockWindowDispatcher;
type WebviewDispatcher = MockWebviewDispatcher;
type Handle = MockRuntimeHandle;
type EventLoopProxy = EventProxy;
fn new(_args: RuntimeInitArgs) -> Result<Self> {
Ok(Self::init())
}
#[cfg(any(
windows,
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
fn new_any_thread(_args: RuntimeInitArgs) -> Result<Self> {
Ok(Self::init())
}
fn create_proxy(&self) -> EventProxy {
EventProxy {}
}
fn handle(&self) -> Self::Handle {
MockRuntimeHandle {
context: self.context.clone(),
}
}
fn create_window<F: Fn(RawWindow<'_>) + Send + 'static>(
&self,
pending: PendingWindow<T, Self>,
_after_window_creation: Option<F>,
) -> Result<DetachedWindow<T, Self>> {
let id = self.context.next_window_id();
let (webview_id, webviews) = if let Some(w) = &pending.webview {
(Some(self.context.next_webview_id()), vec![Webview])
} else {
(None, Vec::new())
};
self.context.windows.borrow_mut().insert(
id,
Window {
label: pending.label.clone(),
webviews,
},
);
let webview = webview_id.map(|id| DetachedWindowWebview {
webview: DetachedWebview {
label: pending.label.clone(),
dispatcher: MockWebviewDispatcher {
id,
context: self.context.clone(),
url: Arc::new(Mutex::new(pending.webview.unwrap().url)),
last_evaluated_script: Default::default(),
},
},
use_https_scheme: false,
});
Ok(DetachedWindow {
id,
label: pending.label,
dispatcher: MockWindowDispatcher {
id,
context: self.context.clone(),
},
webview,
})
}
fn create_webview(
&self,
window_id: WindowId,
pending: PendingWebview<T, Self>,
) -> Result<DetachedWebview<T, Self>> {
let id = self.context.next_webview_id();
let webview = Webview;
if let Some(w) = self.context.windows.borrow_mut().get_mut(&window_id) {
w.webviews.push(webview);
}
Ok(DetachedWebview {
label: pending.label,
dispatcher: MockWebviewDispatcher {
id,
context: self.context.clone(),
last_evaluated_script: Default::default(),
url: Arc::new(Mutex::new(pending.url)),
},
})
}
fn primary_monitor(&self) -> Option<Monitor> {
unimplemented!()
}
fn monitor_from_point(&self, x: f64, y: f64) -> Option<Monitor> {
unimplemented!()
}
fn available_monitors(&self) -> Vec<Monitor> {
unimplemented!()
}
fn set_theme(&self, theme: Option<Theme>) {
unimplemented!()
}
#[cfg(target_os = "macos")]
#[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
fn set_activation_policy(&mut self, activation_policy: tauri_runtime::ActivationPolicy) {}
#[cfg(target_os = "macos")]
#[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
fn set_dock_visibility(&mut self, visible: bool) {}
#[cfg(target_os = "macos")]
#[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
fn show(&self) {}
#[cfg(target_os = "macos")]
#[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
fn hide(&self) {}
fn set_device_event_filter(&mut self, filter: DeviceEventFilter) {}
#[cfg(any(
target_os = "macos",
windows,
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
fn run_iteration<F: FnMut(RunEvent<T>)>(&mut self, callback: F) {}
fn run_return<F: FnMut(RunEvent<T>) + 'static>(self, callback: F) -> i32 {
self.run(callback);
0
}
fn run<F: FnMut(RunEvent<T>) + 'static>(self, mut callback: F) {
self.is_running.store(true, Ordering::Relaxed);
callback(RunEvent::Ready);
loop {
if let Ok(m) = self.run_rx.try_recv() {
match m {
Message::Task(p) => p(),
Message::CloseWindow(id) => {
let label = self
.context
.windows
.borrow()
.get(&id)
.map(|w| w.label.clone());
if let Some(label) = label {
let (tx, rx) = channel();
callback(RunEvent::WindowEvent {
label,
event: WindowEvent::CloseRequested { signal_tx: tx },
});
let should_prevent = matches!(rx.try_recv(), Ok(true));
if !should_prevent {
self.context.windows.borrow_mut().remove(&id);
let is_empty = self.context.windows.borrow().is_empty();
if is_empty {
let (tx, rx) = channel();
callback(RunEvent::ExitRequested { code: None, tx });
let recv = rx.try_recv();
let should_prevent = matches!(recv, Ok(ExitRequestedEventAction::Prevent));
if !should_prevent {
break;
}
}
}
}
}
Message::DestroyWindow(id) => {
let removed = self.context.windows.borrow_mut().remove(&id).is_some();
if removed {
let is_empty = self.context.windows.borrow().is_empty();
if is_empty {
let (tx, rx) = channel();
callback(RunEvent::ExitRequested { code: None, tx });
let recv = rx.try_recv();
let should_prevent = matches!(recv, Ok(ExitRequestedEventAction::Prevent));
if !should_prevent {
break;
}
}
}
}
}
}
callback(RunEvent::MainEventsCleared);
std::thread::sleep(std::time::Duration::from_secs(1));
}
callback(RunEvent::Exit);
}
fn cursor_position(&self) -> Result<PhysicalPosition<f64>> {
Ok(PhysicalPosition::new(0.0, 0.0))
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/event/event_name.rs | crates/tauri/src/event/event_name.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use serde::{Deserialize, Deserializer};
/// Checks if an event name is valid.
fn is_event_name_valid(event: &str) -> bool {
event
.chars()
.all(|c| c.is_alphanumeric() || c == '-' || c == '/' || c == ':' || c == '_')
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) struct EventName<S = String>(S);
impl Copy for EventName<&str> {}
impl<S: AsRef<str>> EventName<S> {
pub(crate) fn new(s: S) -> crate::Result<EventName<S>> {
if !is_event_name_valid(s.as_ref()) {
return Err(crate::Error::IllegalEventName(s.as_ref().to_string()));
}
Ok(EventName(s))
}
pub(crate) fn as_str_event(&self) -> EventName<&str> {
EventName(self.0.as_ref())
}
pub(crate) fn as_str(&self) -> &str {
self.0.as_ref()
}
}
impl<S: std::fmt::Display> std::fmt::Display for EventName<S> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl EventName<&'static str> {
// this convenience method is for using in const contexts to discharge the preconditions
// &'static prevents using this function accidentally with dynamically built string slices
pub(crate) const fn from_str(s: &'static str) -> EventName<&'static str> {
EventName(s)
}
}
impl EventName<&str> {
pub fn into_owned(self) -> EventName {
EventName(self.0.to_string())
}
}
impl<'de> Deserialize<'de> for EventName {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let event_id = String::deserialize(deserializer)?;
if is_event_name_valid(&event_id) {
Ok(EventName(event_id))
} else {
Err(serde::de::Error::custom(
"Event name must include only alphanumeric characters, `-`, `/`, `:` and `_`.",
))
}
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/event/listener.rs | crates/tauri/src/event/listener.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{Runtime, Webview};
use super::{EmitArgs, Event, EventId, EventTarget};
use std::{
boxed::Box,
cell::Cell,
collections::{HashMap, HashSet},
sync::{
atomic::{AtomicU32, Ordering},
Arc, Mutex,
},
};
/// What to do with the pending handler when resolving it?
enum Pending {
Unlisten(EventId),
Listen {
id: EventId,
event: crate::EventName,
handler: Handler,
},
Emit(EmitArgs),
}
/// Stored in [`Listeners`] to be called upon, when the event that stored it, is triggered.
struct Handler {
target: EventTarget,
callback: Box<dyn Fn(Event) + Send>,
}
impl Handler {
fn new<F: Fn(Event) + Send + 'static>(target: EventTarget, callback: F) -> Self {
Self {
target,
callback: Box::new(callback),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct JsHandler {
target: EventTarget,
id: EventId,
}
impl JsHandler {
fn new(target: EventTarget, id: EventId) -> Self {
Self { target, id }
}
}
type WebviewLabel = String;
/// Holds event handlers and pending event handlers, along with the salts associating them.
struct InnerListeners {
pending: Mutex<Vec<Pending>>,
handlers: Mutex<HashMap<crate::EventName, HashMap<EventId, Handler>>>,
js_event_listeners: Mutex<HashMap<WebviewLabel, HashMap<crate::EventName, HashSet<JsHandler>>>>,
function_name: &'static str,
listeners_object_name: &'static str,
next_event_id: Arc<AtomicU32>,
}
/// A self-contained event manager.
#[derive(Clone)]
pub struct Listeners {
inner: Arc<InnerListeners>,
}
impl Default for Listeners {
fn default() -> Self {
Self {
inner: Arc::new(InnerListeners {
pending: Mutex::default(),
handlers: Mutex::default(),
js_event_listeners: Mutex::default(),
function_name: "__internal_unstable_listeners_function_id__",
listeners_object_name: "__internal_unstable_listeners_object_id__",
next_event_id: Default::default(),
}),
}
}
}
impl Listeners {
pub(crate) fn next_event_id(&self) -> EventId {
self.inner.next_event_id.fetch_add(1, Ordering::Relaxed)
}
/// Function name to represent the JavaScript event function.
pub(crate) fn function_name(&self) -> &str {
self.inner.function_name
}
/// Listener object name to represent the JavaScript event listener object.
pub(crate) fn listeners_object_name(&self) -> &str {
self.inner.listeners_object_name
}
/// Insert a pending event action to the queue.
fn insert_pending(&self, action: Pending) {
self
.inner
.pending
.lock()
.expect("poisoned pending event queue")
.push(action)
}
/// Finish all pending event actions.
fn flush_pending(&self) -> crate::Result<()> {
let pending = {
let mut lock = self
.inner
.pending
.lock()
.expect("poisoned pending event queue");
std::mem::take(&mut *lock)
};
for action in pending {
match action {
Pending::Unlisten(id) => self.unlisten(id),
Pending::Listen { id, event, handler } => self.listen_with_id(id, event, handler),
Pending::Emit(args) => self.emit(args)?,
}
}
Ok(())
}
fn listen_with_id(&self, id: EventId, event: crate::EventName, handler: Handler) {
match self.inner.handlers.try_lock() {
Err(_) => self.insert_pending(Pending::Listen { id, event, handler }),
Ok(mut lock) => {
lock.entry(event).or_default().insert(id, handler);
}
}
}
/// Adds an event listener.
pub(crate) fn listen<F: Fn(Event) + Send + 'static>(
&self,
event: crate::EventName,
target: EventTarget,
handler: F,
) -> EventId {
let id = self.next_event_id();
let handler = Handler::new(target, handler);
self.listen_with_id(id, event, handler);
id
}
/// Listen to an event and immediately unlisten.
pub(crate) fn once<F: FnOnce(Event) + Send + 'static>(
&self,
event: crate::EventName,
target: EventTarget,
handler: F,
) -> EventId {
let self_ = self.clone();
let handler = Cell::new(Some(handler));
self.listen(event, target, move |event| {
let id = event.id;
let handler = handler
.take()
.expect("attempted to call handler more than once");
handler(event);
self_.unlisten(id);
})
}
/// Removes an event listener.
pub(crate) fn unlisten(&self, id: EventId) {
match self.inner.handlers.try_lock() {
Err(_) => self.insert_pending(Pending::Unlisten(id)),
Ok(mut lock) => lock.values_mut().for_each(|handler| {
handler.remove(&id);
}),
}
}
/// Emits the given event with its payload based on a filter.
pub(crate) fn emit_filter<F>(&self, emit_args: EmitArgs, filter: Option<F>) -> crate::Result<()>
where
F: Fn(&EventTarget) -> bool,
{
let mut maybe_pending = false;
match self.inner.handlers.try_lock() {
Err(_) => self.insert_pending(Pending::Emit(emit_args)),
Ok(lock) => {
if let Some(handlers) = lock.get(&emit_args.event) {
let handlers = handlers.iter();
let handlers = handlers.filter(|(_, h)| match_any_or_filter(&h.target, &filter));
for (&id, Handler { callback, .. }) in handlers {
maybe_pending = true;
(callback)(Event::new(id, emit_args.payload.clone()))
}
}
}
}
if maybe_pending {
self.flush_pending()?;
}
Ok(())
}
/// Emits the given event with its payload.
pub(crate) fn emit(&self, emit_args: EmitArgs) -> crate::Result<()> {
self.emit_filter(emit_args, None::<&dyn Fn(&EventTarget) -> bool>)
}
pub(crate) fn listen_js(
&self,
event: crate::EventName<&str>,
source_webview_label: &str,
target: EventTarget,
id: EventId,
) {
let event = event.into_owned();
let mut listeners = self.inner.js_event_listeners.lock().unwrap();
listeners
.entry(source_webview_label.to_string())
.or_default()
.entry(event)
.or_default()
.insert(JsHandler::new(target, id));
}
pub(crate) fn unlisten_js(&self, event: crate::EventName<&str>, id: EventId) {
let event = event.into_owned();
let mut js_listeners = self.inner.js_event_listeners.lock().unwrap();
let js_listeners = js_listeners.values_mut();
for js_listeners in js_listeners {
if let Some(handlers) = js_listeners.get_mut(&event) {
handlers.retain(|h| h.id != id);
if handlers.is_empty() {
js_listeners.remove(&event);
}
}
}
}
pub(crate) fn has_js_listener<F: Fn(&EventTarget) -> bool>(
&self,
event: crate::EventName<&str>,
filter: F,
) -> bool {
let event = event.into_owned();
let js_listeners = self.inner.js_event_listeners.lock().unwrap();
js_listeners.values().any(|events| {
events
.get(&event)
.map(|handlers| handlers.iter().any(|handler| filter(&handler.target)))
.unwrap_or(false)
})
}
pub(crate) fn emit_js_filter<'a, R, I, F>(
&self,
mut webviews: I,
emit_args: &EmitArgs,
filter: Option<F>,
) -> crate::Result<()>
where
R: Runtime,
I: Iterator<Item = &'a Webview<R>>,
F: Fn(&EventTarget) -> bool,
{
let event = &emit_args.event;
let js_listeners = self.inner.js_event_listeners.lock().unwrap();
webviews.try_for_each(|webview| {
if let Some(handlers) = js_listeners.get(webview.label()).and_then(|s| s.get(event)) {
let ids = handlers
.iter()
.filter(|handler| match_any_or_filter(&handler.target, &filter))
.map(|handler| handler.id)
.collect::<Vec<_>>();
webview.emit_js(emit_args, &ids)?;
}
Ok(())
})
}
pub(crate) fn emit_js<'a, R, I>(&self, webviews: I, emit_args: &EmitArgs) -> crate::Result<()>
where
R: Runtime,
I: Iterator<Item = &'a Webview<R>>,
{
self.emit_js_filter(webviews, emit_args, None::<&dyn Fn(&EventTarget) -> bool>)
}
}
#[inline(always)]
fn match_any_or_filter<F: Fn(&EventTarget) -> bool>(
target: &EventTarget,
filter: &Option<F>,
) -> bool {
*target == EventTarget::Any || filter.as_ref().map(|f| f(target)).unwrap_or(true)
}
#[cfg(test)]
mod test {
use super::*;
use crate::event::EventTarget;
use proptest::prelude::*;
// dummy event handler function
fn event_fn(s: Event) {
println!("{s:?}");
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(10000))]
// check to see if listen() is properly passing keys into the LISTENERS map
#[test]
fn listeners_check_key(e in "[a-z]+") {
let listeners: Listeners = Default::default();
// clone e as the key
let key = crate::EventName::new(e).unwrap();
// pass e and an dummy func into listen
listeners.listen(key.clone(), EventTarget::Any, event_fn);
// lock mutex
let l = listeners.inner.handlers.lock().unwrap();
// check if the generated key is in the map
assert!(l.contains_key(&key));
}
// check to see if listen inputs a handler function properly into the LISTENERS map.
#[test]
fn listeners_check_fn(e in "[a-z]+") {
let listeners: Listeners = Default::default();
let key = crate::EventName::new(e).unwrap();
// pass e and an dummy func into listen
listeners.listen(key.clone(), EventTarget::Any, event_fn);
// lock mutex
let mut l = listeners.inner.handlers.lock().unwrap();
// check if l contains key
if l.contains_key(&key) {
// grab key if it exists
let handler = l.get_mut(&key);
// check to see if we get back a handler or not
match handler {
// pass on Some(handler)
Some(_) => {},
// Fail on None
None => panic!("handler is None")
}
}
}
// check to see if on_event properly grabs the stored function from listen.
#[test]
fn check_on_event(e in "[a-z]+", d in "[a-z]+") {
let listeners: Listeners = Default::default();
let key = crate::EventName::new(e).unwrap();
// call listen with key and the event_fn dummy func
listeners.listen(key.clone(), EventTarget::Any, event_fn);
// call on event with key and d.
listeners.emit(EmitArgs::new(key.as_str_event(), &d)?)?;
// lock the mutex
let l = listeners.inner.handlers.lock().unwrap();
// assert that the key is contained in the listeners map
assert!(l.contains_key(&key));
}
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/event/mod.rs | crates/tauri/src/event/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
mod listener;
pub(crate) mod plugin;
use std::{convert::Infallible, str::FromStr};
pub(crate) use listener::Listeners;
use serde::{Deserialize, Serialize};
mod event_name;
pub(crate) use event_name::EventName;
use crate::ipc::CallbackFn;
/// Unique id of an event.
pub type EventId = u32;
/// Event Target
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]
#[serde(tag = "kind")]
#[non_exhaustive]
pub enum EventTarget {
/// Any and all event targets.
Any,
/// Any [`Window`](crate::Window), [`Webview`](crate::Webview) or [`WebviewWindow`](crate::WebviewWindow) that have this label.
AnyLabel {
/// Target label.
label: String,
},
/// [`App`](crate::App) and [`AppHandle`](crate::AppHandle) targets.
App,
/// [`Window`](crate::Window) target.
Window {
/// window label.
label: String,
},
/// [`Webview`](crate::Webview) target.
Webview {
/// webview label.
label: String,
},
/// [`WebviewWindow`](crate::WebviewWindow) target.
WebviewWindow {
/// webview window label.
label: String,
},
}
impl EventTarget {
/// [`Self::Any`] target.
pub fn any() -> Self {
Self::Any
}
/// [`Self::App`] target.
pub fn app() -> Self {
Self::App
}
/// [`Self::AnyLabel`] target.
pub fn labeled(label: impl Into<String>) -> Self {
Self::AnyLabel {
label: label.into(),
}
}
/// [`Self::Window`] target.
pub fn window(label: impl Into<String>) -> Self {
Self::Window {
label: label.into(),
}
}
/// [`Self::Webview`] target.
pub fn webview(label: impl Into<String>) -> Self {
Self::Webview {
label: label.into(),
}
}
/// [`Self::WebviewWindow`] target.
pub fn webview_window(label: impl Into<String>) -> Self {
Self::WebviewWindow {
label: label.into(),
}
}
}
impl<T: AsRef<str>> From<T> for EventTarget {
fn from(value: T) -> Self {
Self::AnyLabel {
label: value.as_ref().to_string(),
}
}
}
impl FromStr for EventTarget {
type Err = Infallible;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self::AnyLabel {
label: s.to_string(),
})
}
}
/// Serialized emit arguments.
#[derive(Clone)]
pub struct EmitArgs {
/// event name.
event: EventName,
/// Serialized payload.
payload: String,
}
impl EmitArgs {
pub fn new<S: Serialize>(event: EventName<&str>, payload: &S) -> crate::Result<Self> {
#[cfg(feature = "tracing")]
let _span = tracing::debug_span!("window::emit::serialize").entered();
Ok(EmitArgs {
event: event.into_owned(),
payload: serde_json::to_string(payload)?,
})
}
pub fn new_str(event: EventName<&str>, payload: String) -> crate::Result<Self> {
#[cfg(feature = "tracing")]
let _span = tracing::debug_span!("window::emit::json").entered();
Ok(EmitArgs {
event: event.into_owned(),
payload,
})
}
}
/// An event that was emitted.
#[derive(Debug, Clone)]
pub struct Event {
id: EventId,
data: String,
}
impl Event {
fn new(id: EventId, data: String) -> Self {
Self { id, data }
}
/// The [`EventId`] of the handler that was triggered.
pub fn id(&self) -> EventId {
self.id
}
/// The event payload.
pub fn payload(&self) -> &str {
&self.data
}
}
pub(crate) fn listen_js_script(
listeners_object_name: &str,
serialized_target: &str,
event: EventName<&str>,
event_id: EventId,
handler: CallbackFn,
) -> String {
let handler_id = handler.0;
format!(
"(function () {{
if (window['{listeners_object_name}'] === void 0) {{
Object.defineProperty(window, '{listeners_object_name}', {{ value: Object.create(null) }});
}}
if (window['{listeners_object_name}']['{event}'] === void 0) {{
Object.defineProperty(window['{listeners_object_name}'], '{event}', {{ value: Object.create(null) }});
}}
const eventListeners = window['{listeners_object_name}']['{event}']
const listener = {{
target: {serialized_target},
handlerId: {handler_id}
}};
Object.defineProperty(eventListeners, '{event_id}', {{ value: listener, configurable: true }});
}})()
",
)
}
pub(crate) fn emit_js_script(
event_emit_function_name: &str,
emit_args: &EmitArgs,
serialized_ids: &str,
) -> crate::Result<String> {
Ok(format!(
"(function () {{ const fn = window['{}']; fn && fn({{event: '{}', payload: {}}}, {ids}) }})()",
event_emit_function_name,
emit_args.event,
emit_args.payload,
ids = serialized_ids,
))
}
pub(crate) fn unlisten_js_script(
listeners_object_name: &str,
event_arg: &str,
event_id_arg: &str,
) -> String {
format!(
"(function () {{
const listeners = (window['{listeners_object_name}'] || {{}})[{event_arg}]
if (listeners) {{
window.__TAURI_INTERNALS__.unregisterCallback(listeners[{event_id_arg}].handlerId)
}}
}})()
",
)
}
pub(crate) fn event_initialization_script(function_name: &str, listeners: &str) -> String {
format!(
"Object.defineProperty(window, '{function_name}', {{
value: function (eventData, ids) {{
const listeners = (window['{listeners}'] && window['{listeners}'][eventData.event]) || []
for (const id of ids) {{
const listener = listeners[id]
if (listener) {{
eventData.id = id
window.__TAURI_INTERNALS__.runCallback(listener.handlerId, eventData)
}}
}}
}}
}});
"
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_illegal_event_name() {
let s = EventName::new("some\r illegal event name")
.unwrap_err()
.to_string();
assert_eq!("only alphanumeric, '-', '/', ':', '_' permitted for event names: \"some\\r illegal event name\"", s);
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/event/plugin.rs | crates/tauri/src/event/plugin.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use serde_json::Value as JsonValue;
use serialize_to_javascript::{default_template, DefaultTemplate, Template};
use crate::plugin::{Builder, TauriPlugin};
use crate::{command, ipc::CallbackFn, EventId, Result, Runtime};
use crate::{AppHandle, Emitter, Manager, Webview};
use super::EventName;
use super::EventTarget;
#[command(root = "crate")]
async fn listen<R: Runtime>(
webview: Webview<R>,
event: EventName,
target: EventTarget,
handler: CallbackFn,
) -> Result<EventId> {
webview.listen_js(event.as_str_event(), target, handler)
}
#[command(root = "crate")]
async fn unlisten<R: Runtime>(
webview: Webview<R>,
event: EventName,
event_id: EventId,
) -> Result<()> {
webview.unlisten_js(event.as_str_event(), event_id)
}
#[command(root = "crate")]
async fn emit<R: Runtime>(
app: AppHandle<R>,
event: EventName,
payload: Option<JsonValue>,
) -> Result<()> {
app.emit(event.as_str(), payload)
}
#[command(root = "crate")]
async fn emit_to<R: Runtime>(
app: AppHandle<R>,
target: EventTarget,
event: EventName,
payload: Option<JsonValue>,
) -> Result<()> {
app.emit_to(target, event.as_str(), payload)
}
/// Initializes the event plugin.
pub(crate) fn init<R: Runtime, M: Manager<R>>(manager: &M) -> TauriPlugin<R> {
let listeners = manager.manager().listeners();
#[derive(Template)]
#[default_template("./init.js")]
struct InitJavascript {
#[raw]
unregister_listener_function: String,
}
let init_script = InitJavascript {
unregister_listener_function: format!(
"(event, eventId) => {}",
crate::event::unlisten_js_script(listeners.listeners_object_name(), "event", "eventId")
),
};
Builder::new("event")
.invoke_handler(crate::generate_handler![
#![plugin(event)]
listen, unlisten, emit, emit_to
])
.js_init_script(
init_script
.render_default(&Default::default())
.unwrap()
.to_string(),
)
.build()
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/menu/icon.rs | crates/tauri/src/menu/icon.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::sync::Arc;
use super::run_item_main_thread;
use super::{IconMenuItem, NativeIcon};
use crate::menu::IconMenuItemInner;
use crate::run_main_thread;
use crate::{image::Image, menu::MenuId, AppHandle, Manager, Runtime};
impl<R: Runtime> IconMenuItem<R> {
/// Create a new menu item.
///
/// - `text` could optionally contain an `&` before a character to assign this character as the mnemonic
/// for this menu item. To display a `&` without assigning a mnemenonic, use `&&`.
pub fn new<M, T, A>(
manager: &M,
text: T,
enabled: bool,
icon: Option<Image<'_>>,
accelerator: Option<A>,
) -> crate::Result<Self>
where
M: Manager<R>,
T: AsRef<str>,
A: AsRef<str>,
{
let handle = manager.app_handle();
let app_handle = handle.clone();
let text = text.as_ref().to_owned();
let accelerator = accelerator.and_then(|s| s.as_ref().parse().ok());
let icon = match icon {
Some(i) => Some(i.try_into()?),
None => None,
};
let item = run_main_thread!(handle, || {
let item = muda::IconMenuItem::new(text, enabled, icon, accelerator);
IconMenuItemInner {
id: item.id().clone(),
inner: Some(item),
app_handle,
}
})?;
Ok(Self(Arc::new(item)))
}
/// Create a new menu item with the specified id.
///
/// - `text` could optionally contain an `&` before a character to assign this character as the mnemonic
/// for this menu item. To display a `&` without assigning a mnemenonic, use `&&`.
pub fn with_id<M, I, T, A>(
manager: &M,
id: I,
text: T,
enabled: bool,
icon: Option<Image<'_>>,
accelerator: Option<A>,
) -> crate::Result<Self>
where
M: Manager<R>,
I: Into<MenuId>,
T: AsRef<str>,
A: AsRef<str>,
{
let handle = manager.app_handle();
let app_handle = handle.clone();
let id = id.into();
let text = text.as_ref().to_owned();
let accelerator = accelerator.and_then(|s| s.as_ref().parse().ok());
let icon = match icon {
Some(i) => Some(i.try_into()?),
None => None,
};
let item = run_main_thread!(handle, || {
let item = muda::IconMenuItem::with_id(id.clone(), text, enabled, icon, accelerator);
IconMenuItemInner {
id,
inner: Some(item),
app_handle,
}
})?;
Ok(Self(Arc::new(item)))
}
/// Create a new icon menu item but with a native icon.
///
/// See [`IconMenuItem::new`] for more info.
///
/// ## Platform-specific:
///
/// - **Windows / Linux**: Unsupported.
pub fn with_native_icon<M, T, A>(
manager: &M,
text: T,
enabled: bool,
native_icon: Option<NativeIcon>,
accelerator: Option<A>,
) -> crate::Result<Self>
where
M: Manager<R>,
T: AsRef<str>,
A: AsRef<str>,
{
let handle = manager.app_handle();
let app_handle = handle.clone();
let text = text.as_ref().to_owned();
let icon = native_icon.map(Into::into);
let accelerator = accelerator.and_then(|s| s.as_ref().parse().ok());
let item = run_main_thread!(handle, || {
let item = muda::IconMenuItem::with_native_icon(text, enabled, icon, accelerator);
IconMenuItemInner {
id: item.id().clone(),
inner: Some(item),
app_handle,
}
})?;
Ok(Self(Arc::new(item)))
}
/// Create a new icon menu item with the specified id but with a native icon.
///
/// See [`IconMenuItem::new`] for more info.
///
/// ## Platform-specific:
///
/// - **Windows / Linux**: Unsupported.
pub fn with_id_and_native_icon<M, I, T, A>(
manager: &M,
id: I,
text: T,
enabled: bool,
native_icon: Option<NativeIcon>,
accelerator: Option<A>,
) -> crate::Result<Self>
where
M: Manager<R>,
I: Into<MenuId>,
T: AsRef<str>,
A: AsRef<str>,
{
let handle = manager.app_handle();
let app_handle = handle.clone();
let id = id.into();
let text = text.as_ref().to_owned();
let icon = native_icon.map(Into::into);
let accelerator = accelerator.and_then(|s| s.as_ref().parse().ok());
let item = run_main_thread!(handle, || {
let item =
muda::IconMenuItem::with_id_and_native_icon(id.clone(), text, enabled, icon, accelerator);
IconMenuItemInner {
id,
inner: Some(item),
app_handle,
}
})?;
Ok(Self(Arc::new(item)))
}
/// The application handle associated with this type.
pub fn app_handle(&self) -> &AppHandle<R> {
&self.0.app_handle
}
/// Returns a unique identifier associated with this menu item.
pub fn id(&self) -> &MenuId {
&self.0.id
}
/// Get the text for this menu item.
pub fn text(&self) -> crate::Result<String> {
run_item_main_thread!(self, |self_: Self| (*self_.0).as_ref().text())
}
/// Set the text for this menu item. `text` could optionally contain
/// an `&` before a character to assign this character as the mnemonic
/// for this menu item. To display a `&` without assigning a mnemenonic, use `&&`.
pub fn set_text<S: AsRef<str>>(&self, text: S) -> crate::Result<()> {
let text = text.as_ref().to_string();
run_item_main_thread!(self, |self_: Self| (*self_.0).as_ref().set_text(text))
}
/// Get whether this menu item is enabled or not.
pub fn is_enabled(&self) -> crate::Result<bool> {
run_item_main_thread!(self, |self_: Self| (*self_.0).as_ref().is_enabled())
}
/// Enable or disable this menu item.
pub fn set_enabled(&self, enabled: bool) -> crate::Result<()> {
run_item_main_thread!(self, |self_: Self| (*self_.0).as_ref().set_enabled(enabled))
}
/// Set this menu item accelerator.
pub fn set_accelerator<S: AsRef<str>>(&self, accelerator: Option<S>) -> crate::Result<()> {
let accel = accelerator.and_then(|s| s.as_ref().parse().ok());
run_item_main_thread!(self, |self_: Self| {
(*self_.0).as_ref().set_accelerator(accel)
})?
.map_err(Into::into)
}
/// Change this menu item icon or remove it.
pub fn set_icon(&self, icon: Option<Image<'_>>) -> crate::Result<()> {
let icon = match icon {
Some(i) => Some(i.try_into()?),
None => None,
};
run_item_main_thread!(self, |self_: Self| (*self_.0).as_ref().set_icon(icon))
}
/// Change this menu item icon to a native image or remove it.
///
/// ## Platform-specific:
///
/// - **Windows / Linux**: Unsupported.
pub fn set_native_icon(&self, _icon: Option<NativeIcon>) -> crate::Result<()> {
#[cfg(target_os = "macos")]
return run_item_main_thread!(self, |self_: Self| {
(*self_.0).as_ref().set_native_icon(_icon.map(Into::into))
});
#[allow(unreachable_code)]
Ok(())
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/menu/normal.rs | crates/tauri/src/menu/normal.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::sync::Arc;
use super::run_item_main_thread;
use crate::menu::MenuItemInner;
use crate::run_main_thread;
use crate::{menu::MenuId, AppHandle, Manager, Runtime};
use super::MenuItem;
impl<R: Runtime> MenuItem<R> {
/// Create a new menu item.
///
/// - `text` could optionally contain an `&` before a character to assign this character as the mnemonic
/// for this menu item. To display a `&` without assigning a mnemenonic, use `&&`.
pub fn new<M, T, A>(
manager: &M,
text: T,
enabled: bool,
accelerator: Option<A>,
) -> crate::Result<Self>
where
M: Manager<R>,
T: AsRef<str>,
A: AsRef<str>,
{
let handle = manager.app_handle();
let app_handle = handle.clone();
let text = text.as_ref().to_owned();
let accelerator = accelerator.and_then(|s| s.as_ref().parse().ok());
let item = run_main_thread!(handle, || {
let item = muda::MenuItem::new(text, enabled, accelerator);
MenuItemInner {
id: item.id().clone(),
inner: Some(item),
app_handle,
}
})?;
Ok(Self(Arc::new(item)))
}
/// Create a new menu item with the specified id.
///
/// - `text` could optionally contain an `&` before a character to assign this character as the mnemonic
/// for this menu item. To display a `&` without assigning a mnemenonic, use `&&`.
pub fn with_id<M, I, T, A>(
manager: &M,
id: I,
text: T,
enabled: bool,
accelerator: Option<A>,
) -> crate::Result<Self>
where
M: Manager<R>,
I: Into<MenuId>,
T: AsRef<str>,
A: AsRef<str>,
{
let handle = manager.app_handle();
let app_handle = handle.clone();
let id = id.into();
let accelerator = accelerator.and_then(|s| s.as_ref().parse().ok());
let text = text.as_ref().to_owned();
let item = run_main_thread!(handle, || {
let item = muda::MenuItem::with_id(id.clone(), text, enabled, accelerator);
MenuItemInner {
id,
inner: Some(item),
app_handle,
}
})?;
Ok(Self(Arc::new(item)))
}
/// The application handle associated with this type.
pub fn app_handle(&self) -> &AppHandle<R> {
&self.0.app_handle
}
/// Returns a unique identifier associated with this menu item.
pub fn id(&self) -> &MenuId {
&self.0.id
}
/// Get the text for this menu item.
pub fn text(&self) -> crate::Result<String> {
run_item_main_thread!(self, |self_: Self| (*self_.0).as_ref().text())
}
/// Set the text for this menu item. `text` could optionally contain
/// an `&` before a character to assign this character as the mnemonic
/// for this menu item. To display a `&` without assigning a mnemenonic, use `&&`.
pub fn set_text<S: AsRef<str>>(&self, text: S) -> crate::Result<()> {
let text = text.as_ref().to_string();
run_item_main_thread!(self, |self_: Self| (*self_.0).as_ref().set_text(text))
}
/// Get whether this menu item is enabled or not.
pub fn is_enabled(&self) -> crate::Result<bool> {
run_item_main_thread!(self, |self_: Self| (*self_.0).as_ref().is_enabled())
}
/// Enable or disable this menu item.
pub fn set_enabled(&self, enabled: bool) -> crate::Result<()> {
run_item_main_thread!(self, |self_: Self| (*self_.0).as_ref().set_enabled(enabled))
}
/// Set this menu item accelerator.
pub fn set_accelerator<S: AsRef<str>>(&self, accelerator: Option<S>) -> crate::Result<()> {
let accel = accelerator.and_then(|s| s.as_ref().parse().ok());
run_item_main_thread!(self, |self_: Self| {
(*self_.0).as_ref().set_accelerator(accel)
})?
.map_err(Into::into)
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/menu/check.rs | crates/tauri/src/menu/check.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::sync::Arc;
use super::run_item_main_thread;
use crate::menu::CheckMenuItemInner;
use crate::run_main_thread;
use crate::{menu::MenuId, AppHandle, Manager, Runtime};
use super::CheckMenuItem;
impl<R: Runtime> CheckMenuItem<R> {
/// Create a new menu item.
///
/// - `text` could optionally contain an `&` before a character to assign this character as the mnemonic
/// for this menu item. To display a `&` without assigning a mnemenonic, use `&&`.
pub fn new<M, T, A>(
manager: &M,
text: T,
enabled: bool,
checked: bool,
accelerator: Option<A>,
) -> crate::Result<Self>
where
M: Manager<R>,
T: AsRef<str>,
A: AsRef<str>,
{
let handle = manager.app_handle();
let app_handle = handle.clone();
let text = text.as_ref().to_owned();
let accelerator = accelerator.and_then(|s| s.as_ref().parse().ok());
let item = run_main_thread!(handle, || {
let item = muda::CheckMenuItem::new(text, enabled, checked, accelerator);
CheckMenuItemInner {
id: item.id().clone(),
inner: Some(item),
app_handle,
}
})?;
Ok(Self(Arc::new(item)))
}
/// Create a new menu item with the specified id.
///
/// - `text` could optionally contain an `&` before a character to assign this character as the mnemonic
/// for this menu item. To display a `&` without assigning a mnemenonic, use `&&`.
pub fn with_id<M, I, T, A>(
manager: &M,
id: I,
text: T,
enabled: bool,
checked: bool,
accelerator: Option<A>,
) -> crate::Result<Self>
where
M: Manager<R>,
I: Into<MenuId>,
T: AsRef<str>,
A: AsRef<str>,
{
let handle = manager.app_handle();
let app_handle = handle.clone();
let id = id.into();
let text = text.as_ref().to_owned();
let accelerator = accelerator.and_then(|s| s.as_ref().parse().ok());
let item = run_main_thread!(handle, || {
let item = muda::CheckMenuItem::with_id(id.clone(), text, enabled, checked, accelerator);
CheckMenuItemInner {
id,
inner: Some(item),
app_handle,
}
})?;
Ok(Self(Arc::new(item)))
}
/// The application handle associated with this type.
pub fn app_handle(&self) -> &AppHandle<R> {
&self.0.app_handle
}
/// Returns a unique identifier associated with this menu item.
pub fn id(&self) -> &MenuId {
&self.0.id
}
/// Get the text for this menu item.
pub fn text(&self) -> crate::Result<String> {
run_item_main_thread!(self, |self_: Self| (*self_.0).as_ref().text())
}
/// Set the text for this menu item. `text` could optionally contain
/// an `&` before a character to assign this character as the mnemonic
/// for this menu item. To display a `&` without assigning a mnemenonic, use `&&`.
pub fn set_text<S: AsRef<str>>(&self, text: S) -> crate::Result<()> {
let text = text.as_ref().to_string();
run_item_main_thread!(self, |self_: Self| (*self_.0).as_ref().set_text(text))
}
/// Get whether this menu item is enabled or not.
pub fn is_enabled(&self) -> crate::Result<bool> {
run_item_main_thread!(self, |self_: Self| (*self_.0).as_ref().is_enabled())
}
/// Enable or disable this menu item.
pub fn set_enabled(&self, enabled: bool) -> crate::Result<()> {
run_item_main_thread!(self, |self_: Self| (*self_.0).as_ref().set_enabled(enabled))
}
/// Set this menu item accelerator.
pub fn set_accelerator<S: AsRef<str>>(&self, accelerator: Option<S>) -> crate::Result<()> {
let accel = accelerator.and_then(|s| s.as_ref().parse().ok());
run_item_main_thread!(self, |self_: Self| {
(*self_.0).as_ref().set_accelerator(accel)
})?
.map_err(Into::into)
}
/// Get whether this check menu item is checked or not.
pub fn is_checked(&self) -> crate::Result<bool> {
run_item_main_thread!(self, |self_: Self| (*self_.0).as_ref().is_checked())
}
/// Check or Uncheck this check menu item.
pub fn set_checked(&self, checked: bool) -> crate::Result<()> {
run_item_main_thread!(self, |self_: Self| (*self_.0).as_ref().set_checked(checked))
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/menu/submenu.rs | crates/tauri/src/menu/submenu.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::sync::Arc;
use super::run_item_main_thread;
use super::Submenu;
use super::{sealed::ContextMenuBase, IsMenuItem, MenuItemKind};
use crate::menu::NativeIcon;
use crate::menu::SubmenuInner;
use crate::run_main_thread;
use crate::{AppHandle, Manager, Position, Runtime, Window};
use muda::{ContextMenu, Icon as MudaIcon, MenuId};
impl<R: Runtime> super::ContextMenu for Submenu<R> {
#[cfg(target_os = "windows")]
fn hpopupmenu(&self) -> crate::Result<isize> {
run_item_main_thread!(self, |self_: Self| (*self_.0).as_ref().hpopupmenu())
}
fn popup<T: Runtime>(&self, window: Window<T>) -> crate::Result<()> {
self.popup_inner(window, None::<Position>)
}
fn popup_at<T: Runtime, P: Into<Position>>(
&self,
window: Window<T>,
position: P,
) -> crate::Result<()> {
self.popup_inner(window, Some(position))
}
}
impl<R: Runtime> ContextMenuBase for Submenu<R> {
fn popup_inner<T: Runtime, P: Into<crate::Position>>(
&self,
window: crate::Window<T>,
position: Option<P>,
) -> crate::Result<()> {
let position = position.map(Into::into);
run_item_main_thread!(self, move |self_: Self| {
#[cfg(target_os = "macos")]
if let Ok(view) = window.ns_view() {
unsafe {
self_
.inner()
.show_context_menu_for_nsview(view as _, position);
}
}
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
if let Ok(w) = window.gtk_window() {
self_
.inner()
.show_context_menu_for_gtk_window(w.as_ref(), position);
}
#[cfg(windows)]
if let Ok(hwnd) = window.hwnd() {
unsafe {
self_
.inner()
.show_context_menu_for_hwnd(hwnd.0 as _, position);
}
}
})
}
fn inner_context(&self) -> &dyn muda::ContextMenu {
(*self.0).as_ref()
}
fn inner_context_owned(&self) -> Box<dyn muda::ContextMenu> {
Box::new((*self.0).as_ref().clone())
}
}
impl<R: Runtime> Submenu<R> {
/// Creates a new submenu.
pub fn new<M: Manager<R>, S: AsRef<str>>(
manager: &M,
text: S,
enabled: bool,
) -> crate::Result<Self> {
let handle = manager.app_handle();
let app_handle = handle.clone();
let text = text.as_ref().to_owned();
let submenu = run_main_thread!(handle, || {
let submenu = muda::Submenu::new(text, enabled);
SubmenuInner {
id: submenu.id().clone(),
inner: Some(submenu),
app_handle,
}
})?;
Ok(Self(Arc::new(submenu)))
}
/// Create a new submenu with an icon.
pub fn new_with_icon<M: Manager<R>, S: AsRef<str>>(
manager: &M,
text: S,
enabled: bool,
icon: Option<crate::image::Image<'_>>,
) -> crate::Result<Self> {
let handle = manager.app_handle();
let app_handle = handle.clone();
let text = text.as_ref().to_owned();
let icon_data = icon.map(|i| (i.rgba().to_vec(), i.width(), i.height()));
let submenu = run_main_thread!(handle, || {
let submenu = muda::Submenu::new(text, enabled);
if let Some((rgba, width, height)) = icon_data.clone() {
submenu.set_icon(Some(MudaIcon::from_rgba(rgba, width, height).unwrap()));
}
SubmenuInner {
id: submenu.id().clone(),
inner: Some(submenu),
app_handle,
}
})?;
Ok(Self(Arc::new(submenu)))
}
/// Create a new submenu with a native icon.
pub fn new_with_native_icon<M: Manager<R>, S: AsRef<str>>(
manager: &M,
text: S,
enabled: bool,
icon: Option<NativeIcon>,
) -> crate::Result<Self> {
let handle = manager.app_handle();
let app_handle = handle.clone();
let text = text.as_ref().to_owned();
let submenu = run_main_thread!(handle, || {
let submenu = muda::Submenu::new(text, enabled);
if let Some(icon) = icon {
submenu.set_native_icon(Some(icon.into()));
}
SubmenuInner {
id: submenu.id().clone(),
inner: Some(submenu),
app_handle,
}
})?;
Ok(Self(Arc::new(submenu)))
}
/// Creates a new submenu with the specified id.
pub fn with_id<M: Manager<R>, I: Into<MenuId>, S: AsRef<str>>(
manager: &M,
id: I,
text: S,
enabled: bool,
) -> crate::Result<Self> {
let handle = manager.app_handle();
let app_handle = handle.clone();
let id = id.into();
let text = text.as_ref().to_owned();
let submenu = run_main_thread!(handle, || {
let submenu = muda::Submenu::with_id(id.clone(), text, enabled);
SubmenuInner {
id,
inner: Some(submenu),
app_handle,
}
})?;
Ok(Self(Arc::new(submenu)))
}
/// Create a new submenu with an id and an icon.
pub fn with_id_and_icon<M: Manager<R>, I: Into<MenuId>, S: AsRef<str>>(
manager: &M,
id: I,
text: S,
enabled: bool,
icon: Option<crate::image::Image<'_>>,
) -> crate::Result<Self> {
let handle = manager.app_handle();
let app_handle = handle.clone();
let id = id.into();
let text = text.as_ref().to_owned();
let icon_data = icon.map(|i| (i.rgba().to_vec(), i.width(), i.height()));
let submenu = run_main_thread!(handle, || {
let submenu = muda::Submenu::with_id(id.clone(), text, enabled);
if let Some((rgba, width, height)) = icon_data.clone() {
submenu.set_icon(Some(MudaIcon::from_rgba(rgba, width, height).unwrap()));
}
SubmenuInner {
id,
inner: Some(submenu),
app_handle,
}
})?;
Ok(Self(Arc::new(submenu)))
}
/// Create a new submenu with an id and a native icon.
pub fn with_id_and_native_icon<M: Manager<R>, I: Into<MenuId>, S: AsRef<str>>(
manager: &M,
id: I,
text: S,
enabled: bool,
icon: Option<NativeIcon>,
) -> crate::Result<Self> {
let handle = manager.app_handle();
let app_handle = handle.clone();
let id = id.into();
let text = text.as_ref().to_owned();
let submenu = run_main_thread!(handle, || {
let submenu = muda::Submenu::with_id(id.clone(), text, enabled);
if let Some(icon) = icon {
submenu.set_native_icon(Some(icon.into()));
}
SubmenuInner {
id,
inner: Some(submenu),
app_handle,
}
})?;
Ok(Self(Arc::new(submenu)))
}
/// Creates a new menu with given `items`. It calls [`Submenu::new`] and [`Submenu::append_items`] internally.
pub fn with_items<M: Manager<R>, S: AsRef<str>>(
manager: &M,
text: S,
enabled: bool,
items: &[&dyn IsMenuItem<R>],
) -> crate::Result<Self> {
let menu = Self::new(manager, text, enabled)?;
menu.append_items(items)?;
Ok(menu)
}
/// Creates a new menu with the specified id and given `items`.
/// It calls [`Submenu::new`] and [`Submenu::append_items`] internally.
pub fn with_id_and_items<M: Manager<R>, I: Into<MenuId>, S: AsRef<str>>(
manager: &M,
id: I,
text: S,
enabled: bool,
items: &[&dyn IsMenuItem<R>],
) -> crate::Result<Self> {
let menu = Self::with_id(manager, id, text, enabled)?;
menu.append_items(items)?;
Ok(menu)
}
pub(crate) fn inner(&self) -> &muda::Submenu {
(*self.0).as_ref()
}
/// The application handle associated with this type.
pub fn app_handle(&self) -> &AppHandle<R> {
&self.0.app_handle
}
/// Returns a unique identifier associated with this submenu.
pub fn id(&self) -> &MenuId {
&self.0.id
}
/// Add a menu item to the end of this submenu.
pub fn append(&self, item: &dyn IsMenuItem<R>) -> crate::Result<()> {
let kind = item.kind();
run_item_main_thread!(self, |self_: Self| {
(*self_.0).as_ref().append(kind.inner().inner_muda())
})?
.map_err(Into::into)
}
/// Add menu items to the end of this submenu. It calls [`Submenu::append`] in a loop internally.
pub fn append_items(&self, items: &[&dyn IsMenuItem<R>]) -> crate::Result<()> {
for item in items {
self.append(*item)?
}
Ok(())
}
/// Add a menu item to the beginning of this submenu.
pub fn prepend(&self, item: &dyn IsMenuItem<R>) -> crate::Result<()> {
let kind = item.kind();
run_item_main_thread!(self, |self_: Self| {
(*self_.0).as_ref().prepend(kind.inner().inner_muda())
})?
.map_err(Into::into)
}
/// Add menu items to the beginning of this submenu. It calls [`Submenu::insert_items`] with position of `0` internally.
pub fn prepend_items(&self, items: &[&dyn IsMenuItem<R>]) -> crate::Result<()> {
self.insert_items(items, 0)
}
/// Insert a menu item at the specified `position` in this submenu.
pub fn insert(&self, item: &dyn IsMenuItem<R>, position: usize) -> crate::Result<()> {
let kind = item.kind();
run_item_main_thread!(self, |self_: Self| {
(*self_.0)
.as_ref()
.insert(kind.inner().inner_muda(), position)
})?
.map_err(Into::into)
}
/// Insert menu items at the specified `position` in this submenu.
pub fn insert_items(&self, items: &[&dyn IsMenuItem<R>], position: usize) -> crate::Result<()> {
for (i, item) in items.iter().enumerate() {
self.insert(*item, position + i)?
}
Ok(())
}
/// Remove a menu item from this submenu.
pub fn remove(&self, item: &dyn IsMenuItem<R>) -> crate::Result<()> {
let kind = item.kind();
run_item_main_thread!(self, |self_: Self| {
(*self_.0).as_ref().remove(kind.inner().inner_muda())
})?
.map_err(Into::into)
}
/// Remove the menu item at the specified position from this submenu and returns it.
pub fn remove_at(&self, position: usize) -> crate::Result<Option<MenuItemKind<R>>> {
run_item_main_thread!(self, |self_: Self| {
(*self_.0)
.as_ref()
.remove_at(position)
.map(|i| MenuItemKind::from_muda(self_.0.app_handle.clone(), i))
})
}
/// Retrieves the menu item matching the given identifier.
pub fn get<'a, I>(&self, id: &'a I) -> Option<MenuItemKind<R>>
where
I: ?Sized,
MenuId: PartialEq<&'a I>,
{
self
.items()
.unwrap_or_default()
.into_iter()
.find(|i| i.id() == &id)
}
/// Returns a list of menu items that has been added to this submenu.
pub fn items(&self) -> crate::Result<Vec<MenuItemKind<R>>> {
run_item_main_thread!(self, |self_: Self| {
(*self_.0)
.as_ref()
.items()
.into_iter()
.map(|i| MenuItemKind::from_muda(self_.0.app_handle.clone(), i))
.collect::<Vec<_>>()
})
}
/// Get the text for this submenu.
pub fn text(&self) -> crate::Result<String> {
run_item_main_thread!(self, |self_: Self| (*self_.0).as_ref().text())
}
/// Set the text for this submenu. `text` could optionally contain
/// an `&` before a character to assign this character as the mnemonic
/// for this submenu. To display a `&` without assigning a mnemonic, use `&&`.
pub fn set_text<S: AsRef<str>>(&self, text: S) -> crate::Result<()> {
let text = text.as_ref().to_string();
run_item_main_thread!(self, |self_: Self| (*self_.0).as_ref().set_text(text))
}
/// Get whether this submenu is enabled or not.
pub fn is_enabled(&self) -> crate::Result<bool> {
run_item_main_thread!(self, |self_: Self| (*self_.0).as_ref().is_enabled())
}
/// Enable or disable this submenu.
pub fn set_enabled(&self, enabled: bool) -> crate::Result<()> {
run_item_main_thread!(self, |self_: Self| (*self_.0).as_ref().set_enabled(enabled))
}
/// Set this submenu as the Window menu for the application on macOS.
///
/// This will cause macOS to automatically add window-switching items and
/// certain other items to the menu.
#[cfg(target_os = "macos")]
pub fn set_as_windows_menu_for_nsapp(&self) -> crate::Result<()> {
run_item_main_thread!(self, |self_: Self| {
(*self_.0).as_ref().set_as_windows_menu_for_nsapp()
})?;
Ok(())
}
/// Set this submenu as the Help menu for the application on macOS.
///
/// This will cause macOS to automatically add a search box to the menu.
///
/// If no menu is set as the Help menu, macOS will automatically use any menu
/// which has a title matching the localized word "Help".
#[cfg(target_os = "macos")]
pub fn set_as_help_menu_for_nsapp(&self) -> crate::Result<()> {
run_item_main_thread!(self, |self_: Self| {
(*self_.0).as_ref().set_as_help_menu_for_nsapp()
})?;
Ok(())
}
/// Change this submenu icon or remove it.
pub fn set_icon(&self, icon: Option<crate::image::Image<'_>>) -> crate::Result<()> {
let icon = match icon {
Some(i) => Some(i.try_into()?),
None => None,
};
run_item_main_thread!(self, |self_: Self| (*self_.0).as_ref().set_icon(icon))
}
/// Change this submenu icon to a native image or remove it.
///
/// ## Platform-specific:
///
/// - **Windows / Linux**: Unsupported.
pub fn set_native_icon(&self, _icon: Option<NativeIcon>) -> crate::Result<()> {
#[cfg(target_os = "macos")]
return run_item_main_thread!(self, |self_: Self| {
(*self_.0).as_ref().set_native_icon(_icon.map(Into::into))
});
#[allow(unreachable_code)]
Ok(())
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/menu/menu.rs | crates/tauri/src/menu/menu.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::sync::Arc;
use super::run_item_main_thread;
use super::sealed::ContextMenuBase;
use super::{
AboutMetadata, IsMenuItem, Menu, MenuInner, MenuItemKind, PredefinedMenuItem, Submenu,
};
use crate::run_main_thread;
use crate::Window;
use crate::{AppHandle, Manager, Position, Runtime};
use muda::ContextMenu;
use muda::MenuId;
/// Expected submenu id of the Window menu for macOS.
pub const WINDOW_SUBMENU_ID: &str = "__tauri_window_menu__";
/// Expected submenu id of the Help menu for macOS.
pub const HELP_SUBMENU_ID: &str = "__tauri_help_menu__";
impl<R: Runtime> super::ContextMenu for Menu<R> {
#[cfg(target_os = "windows")]
fn hpopupmenu(&self) -> crate::Result<isize> {
run_item_main_thread!(self, |self_: Self| (*self_.0).as_ref().hpopupmenu())
}
fn popup<T: Runtime>(&self, window: Window<T>) -> crate::Result<()> {
self.popup_inner(window, None::<Position>)
}
fn popup_at<T: Runtime, P: Into<Position>>(
&self,
window: Window<T>,
position: P,
) -> crate::Result<()> {
self.popup_inner(window, Some(position))
}
}
impl<R: Runtime> ContextMenuBase for Menu<R> {
fn popup_inner<T: Runtime, P: Into<crate::Position>>(
&self,
window: crate::Window<T>,
position: Option<P>,
) -> crate::Result<()> {
let position = position.map(Into::into);
run_item_main_thread!(self, move |self_: Self| {
#[cfg(target_os = "macos")]
if let Ok(view) = window.ns_view() {
unsafe {
self_
.inner()
.show_context_menu_for_nsview(view as _, position);
}
}
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
if let Ok(w) = window.gtk_window() {
self_
.inner()
.show_context_menu_for_gtk_window(w.as_ref(), position);
}
#[cfg(windows)]
if let Ok(hwnd) = window.hwnd() {
unsafe {
self_
.inner()
.show_context_menu_for_hwnd(hwnd.0 as _, position);
}
}
})
}
fn inner_context(&self) -> &dyn muda::ContextMenu {
(*self.0).as_ref()
}
fn inner_context_owned(&self) -> Box<dyn muda::ContextMenu> {
Box::new((*self.0).as_ref().clone())
}
}
impl<R: Runtime> Menu<R> {
/// Creates a new menu.
pub fn new<M: Manager<R>>(manager: &M) -> crate::Result<Self> {
let handle = manager.app_handle();
let app_handle = handle.clone();
let menu = run_main_thread!(handle, || {
let menu = muda::Menu::new();
MenuInner {
id: menu.id().clone(),
inner: Some(menu),
app_handle,
}
})?;
Ok(Self(Arc::new(menu)))
}
/// Creates a new menu with the specified id.
pub fn with_id<M: Manager<R>, I: Into<MenuId>>(manager: &M, id: I) -> crate::Result<Self> {
let handle = manager.app_handle();
let app_handle = handle.clone();
let id = id.into();
let menu = run_main_thread!(handle, || {
let menu = muda::Menu::with_id(id.clone());
MenuInner {
id,
inner: Some(menu),
app_handle,
}
})?;
Ok(Self(Arc::new(menu)))
}
/// Creates a new menu with given `items`. It calls [`Menu::new`] and [`Menu::append_items`] internally.
pub fn with_items<M: Manager<R>>(
manager: &M,
items: &[&dyn IsMenuItem<R>],
) -> crate::Result<Self> {
let menu = Self::new(manager)?;
menu.append_items(items)?;
Ok(menu)
}
/// Creates a new menu with the specified id and given `items`.
/// It calls [`Menu::new`] and [`Menu::append_items`] internally.
pub fn with_id_and_items<M: Manager<R>, I: Into<MenuId>>(
manager: &M,
id: I,
items: &[&dyn IsMenuItem<R>],
) -> crate::Result<Self> {
let menu = Self::with_id(manager, id)?;
menu.append_items(items)?;
Ok(menu)
}
/// Creates a menu filled with default menu items and submenus.
pub fn default(app_handle: &AppHandle<R>) -> crate::Result<Self> {
let pkg_info = app_handle.package_info();
let config = app_handle.config();
let about_metadata = AboutMetadata {
name: Some(pkg_info.name.clone()),
version: Some(pkg_info.version.to_string()),
copyright: config.bundle.copyright.clone(),
authors: config.bundle.publisher.clone().map(|p| vec![p]),
..Default::default()
};
let window_menu = Submenu::with_id_and_items(
app_handle,
WINDOW_SUBMENU_ID,
"Window",
true,
&[
&PredefinedMenuItem::minimize(app_handle, None)?,
&PredefinedMenuItem::maximize(app_handle, None)?,
#[cfg(target_os = "macos")]
&PredefinedMenuItem::separator(app_handle)?,
&PredefinedMenuItem::close_window(app_handle, None)?,
],
)?;
let help_menu = Submenu::with_id_and_items(
app_handle,
HELP_SUBMENU_ID,
"Help",
true,
&[
#[cfg(not(target_os = "macos"))]
&PredefinedMenuItem::about(app_handle, None, Some(about_metadata))?,
],
)?;
let menu = Menu::with_items(
app_handle,
&[
#[cfg(target_os = "macos")]
&Submenu::with_items(
app_handle,
pkg_info.name.clone(),
true,
&[
&PredefinedMenuItem::about(app_handle, None, Some(about_metadata))?,
&PredefinedMenuItem::separator(app_handle)?,
&PredefinedMenuItem::services(app_handle, None)?,
&PredefinedMenuItem::separator(app_handle)?,
&PredefinedMenuItem::hide(app_handle, None)?,
&PredefinedMenuItem::hide_others(app_handle, None)?,
&PredefinedMenuItem::separator(app_handle)?,
&PredefinedMenuItem::quit(app_handle, None)?,
],
)?,
#[cfg(not(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
)))]
&Submenu::with_items(
app_handle,
"File",
true,
&[
&PredefinedMenuItem::close_window(app_handle, None)?,
#[cfg(not(target_os = "macos"))]
&PredefinedMenuItem::quit(app_handle, None)?,
],
)?,
&Submenu::with_items(
app_handle,
"Edit",
true,
&[
&PredefinedMenuItem::undo(app_handle, None)?,
&PredefinedMenuItem::redo(app_handle, None)?,
&PredefinedMenuItem::separator(app_handle)?,
&PredefinedMenuItem::cut(app_handle, None)?,
&PredefinedMenuItem::copy(app_handle, None)?,
&PredefinedMenuItem::paste(app_handle, None)?,
&PredefinedMenuItem::select_all(app_handle, None)?,
],
)?,
#[cfg(target_os = "macos")]
&Submenu::with_items(
app_handle,
"View",
true,
&[&PredefinedMenuItem::fullscreen(app_handle, None)?],
)?,
&window_menu,
&help_menu,
],
)?;
Ok(menu)
}
pub(crate) fn inner(&self) -> &muda::Menu {
(*self.0).as_ref()
}
/// The application handle associated with this type.
pub fn app_handle(&self) -> &AppHandle<R> {
&self.0.app_handle
}
/// Returns a unique identifier associated with this menu.
pub fn id(&self) -> &MenuId {
&self.0.id
}
/// Add a menu item to the end of this menu.
///
/// ## Platform-specific:
///
/// - **macOS:** Only [`Submenu`] can be added to the menu.
///
/// [`Submenu`]: super::Submenu
pub fn append(&self, item: &dyn IsMenuItem<R>) -> crate::Result<()> {
let kind = item.kind();
run_item_main_thread!(self, |self_: Self| {
(*self_.0).as_ref().append(kind.inner().inner_muda())
})?
.map_err(Into::into)
}
/// Add menu items to the end of this menu. It calls [`Menu::append`] in a loop internally.
///
/// ## Platform-specific:
///
/// - **macOS:** Only [`Submenu`] can be added to the menu
///
/// [`Submenu`]: super::Submenu
pub fn append_items(&self, items: &[&dyn IsMenuItem<R>]) -> crate::Result<()> {
for item in items {
self.append(*item)?
}
Ok(())
}
/// Add a menu item to the beginning of this menu.
///
/// ## Platform-specific:
///
/// - **macOS:** Only [`Submenu`] can be added to the menu
///
/// [`Submenu`]: super::Submenu
pub fn prepend(&self, item: &dyn IsMenuItem<R>) -> crate::Result<()> {
let kind = item.kind();
run_item_main_thread!(self, |self_: Self| {
(*self_.0).as_ref().prepend(kind.inner().inner_muda())
})?
.map_err(Into::into)
}
/// Add menu items to the beginning of this menu. It calls [`Menu::insert_items`] with position of `0` internally.
///
/// ## Platform-specific:
///
/// - **macOS:** Only [`Submenu`] can be added to the menu
///
/// [`Submenu`]: super::Submenu
pub fn prepend_items(&self, items: &[&dyn IsMenuItem<R>]) -> crate::Result<()> {
self.insert_items(items, 0)
}
/// Insert a menu item at the specified `position` in the menu.
///
/// ## Platform-specific:
///
/// - **macOS:** Only [`Submenu`] can be added to the menu
///
/// [`Submenu`]: super::Submenu
pub fn insert(&self, item: &dyn IsMenuItem<R>, position: usize) -> crate::Result<()> {
let kind = item.kind();
run_item_main_thread!(self, |self_: Self| (*self_.0)
.as_ref()
.insert(kind.inner().inner_muda(), position))?
.map_err(Into::into)
}
/// Insert menu items at the specified `position` in the menu.
///
/// ## Platform-specific:
///
/// - **macOS:** Only [`Submenu`] can be added to the menu
///
/// [`Submenu`]: super::Submenu
pub fn insert_items(&self, items: &[&dyn IsMenuItem<R>], position: usize) -> crate::Result<()> {
for (i, item) in items.iter().enumerate() {
self.insert(*item, position + i)?
}
Ok(())
}
/// Remove a menu item from this menu.
pub fn remove(&self, item: &dyn IsMenuItem<R>) -> crate::Result<()> {
let kind = item.kind();
run_item_main_thread!(self, |self_: Self| {
(*self_.0).as_ref().remove(kind.inner().inner_muda())
})?
.map_err(Into::into)
}
/// Remove the menu item at the specified position from this menu and returns it.
pub fn remove_at(&self, position: usize) -> crate::Result<Option<MenuItemKind<R>>> {
run_item_main_thread!(self, |self_: Self| {
(*self_.0)
.as_ref()
.remove_at(position)
.map(|i| MenuItemKind::from_muda(self_.0.app_handle.clone(), i))
})
}
/// Retrieves the menu item matching the given identifier.
pub fn get<'a, I>(&self, id: &'a I) -> Option<MenuItemKind<R>>
where
I: ?Sized,
MenuId: PartialEq<&'a I>,
{
self
.items()
.unwrap_or_default()
.into_iter()
.find(|i| i.id() == &id)
}
/// Returns a list of menu items that has been added to this menu.
pub fn items(&self) -> crate::Result<Vec<MenuItemKind<R>>> {
run_item_main_thread!(self, |self_: Self| {
(*self_.0)
.as_ref()
.items()
.into_iter()
.map(|i| MenuItemKind::from_muda(self_.0.app_handle.clone(), i))
.collect::<Vec<_>>()
})
}
/// Set this menu as the application menu.
///
/// This is an alias for [`AppHandle::set_menu`].
pub fn set_as_app_menu(&self) -> crate::Result<Option<Menu<R>>> {
self.0.app_handle.set_menu(self.clone())
}
/// Set this menu as the window menu.
///
/// This is an alias for [`Window::set_menu`].
pub fn set_as_window_menu(&self, window: &Window<R>) -> crate::Result<Option<Menu<R>>> {
window.set_menu(self.clone())
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/menu/mod.rs | crates/tauri/src/menu/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Menu types and utilities.
mod builders;
mod check;
mod icon;
#[allow(clippy::module_inception)]
mod menu;
mod normal;
pub(crate) mod plugin;
mod predefined;
mod submenu;
use std::sync::Arc;
pub use builders::*;
pub use menu::{HELP_SUBMENU_ID, WINDOW_SUBMENU_ID};
use serde::{Deserialize, Serialize};
use crate::{image::Image, AppHandle, Runtime};
pub use muda::MenuId;
macro_rules! run_item_main_thread {
($self:ident, $ex:expr) => {{
use std::sync::mpsc::channel;
let (tx, rx) = channel();
let self_ = $self.clone();
let task = move || {
let f = $ex;
let _ = tx.send(f(self_));
};
$self
.app_handle()
.run_on_main_thread(task)
.and_then(|_| rx.recv().map_err(|_| crate::Error::FailedToReceiveMessage))
}};
}
pub(crate) use run_item_main_thread;
/// Describes a menu event emitted when a menu item is activated
#[derive(Debug, Clone, Serialize)]
pub struct MenuEvent {
/// Id of the menu item which triggered this event
pub id: MenuId,
}
impl MenuEvent {
/// Returns the id of the menu item which triggered this event
pub fn id(&self) -> &MenuId {
&self.id
}
}
impl From<muda::MenuEvent> for MenuEvent {
fn from(value: muda::MenuEvent) -> Self {
Self { id: value.id }
}
}
macro_rules! gen_wrappers {
(
$(
$(#[$attr:meta])*
$type:ident($inner:ident$(, $kind:ident)?)
),*
) => {
$(
#[tauri_macros::default_runtime(crate::Wry, wry)]
pub(crate) struct $inner<R: $crate::Runtime> {
id: $crate::menu::MenuId,
inner: ::std::option::Option<::muda::$type>,
app_handle: $crate::AppHandle<R>,
}
/// # Safety
///
/// We make sure it always runs on the main thread.
unsafe impl<R: $crate::Runtime> Sync for $inner<R> {}
unsafe impl<R: $crate::Runtime> Send for $inner<R> {}
impl<R: Runtime> $crate::Resource for $type<R> {}
impl<R: $crate::Runtime> Clone for $inner<R> {
fn clone(&self) -> Self {
Self {
id: self.id.clone(),
inner: self.inner.clone(),
app_handle: self.app_handle.clone(),
}
}
}
impl<R: Runtime> Drop for $inner<R> {
fn drop(&mut self) {
let inner = self.inner.take();
// SAFETY: inner was created on main thread and is being dropped on main thread
let inner = $crate::UnsafeSend(inner);
let _ = self.app_handle.run_on_main_thread(move || {
drop(inner.take());
});
}
}
impl<R: Runtime> AsRef<::muda::$type> for $inner<R> {
fn as_ref(&self) -> &::muda::$type {
self.inner.as_ref().unwrap()
}
}
$(#[$attr])*
pub struct $type<R: $crate::Runtime>(::std::sync::Arc<$inner<R>>);
impl<R: $crate::Runtime> Clone for $type<R> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
$(
impl<R: $crate::Runtime> $crate::menu::sealed::IsMenuItemBase for $type<R> {
fn inner_muda(&self) -> &dyn muda::IsMenuItem {
(*self.0).as_ref()
}
}
impl<R: $crate::Runtime> $crate::menu::IsMenuItem<R> for $type<R> {
fn kind(&self) -> MenuItemKind<R> {
MenuItemKind::$kind(self.clone())
}
fn id(&self) -> &MenuId {
&self.0.id
}
}
)*
)*
};
}
gen_wrappers!(
/// A type that is either a menu bar on the window
/// on Windows and Linux or as a global menu in the menubar on macOS.
///
/// ## Platform-specific:
///
/// - **macOS**: if using [`Menu`] for the global menubar, it can only contain [`Submenu`]s
Menu(MenuInner),
/// A menu item inside a [`Menu`] or [`Submenu`] and contains only text.
MenuItem(MenuItemInner, MenuItem),
/// A type that is a submenu inside a [`Menu`] or [`Submenu`]
Submenu(SubmenuInner, Submenu),
/// A predefined (native) menu item which has a predefined behavior by the OS or by this crate.
PredefinedMenuItem(PredefinedMenuItemInner, Predefined),
/// A menu item inside a [`Menu`] or [`Submenu`]
/// and usually contains a text and a check mark or a similar toggle
/// that corresponds to a checked and unchecked states.
CheckMenuItem(CheckMenuItemInner, Check),
/// A menu item inside a [`Menu`] or [`Submenu`]
/// and usually contains an icon and a text.
IconMenuItem(IconMenuItemInner, Icon)
);
/// Application metadata for the [`PredefinedMenuItem::about`].
#[derive(Debug, Clone, Default)]
pub struct AboutMetadata<'a> {
/// Sets the application name.
pub name: Option<String>,
/// The application version.
pub version: Option<String>,
/// The short version, e.g. "1.0".
///
/// ## Platform-specific
///
/// - **Windows / Linux:** Appended to the end of `version` in parentheses.
pub short_version: Option<String>,
/// The authors of the application.
///
/// ## Platform-specific
///
/// - **macOS:** Unsupported.
pub authors: Option<Vec<String>>,
/// Application comments.
///
/// ## Platform-specific
///
/// - **macOS:** Unsupported.
pub comments: Option<String>,
/// The copyright of the application.
pub copyright: Option<String>,
/// The license of the application.
///
/// ## Platform-specific
///
/// - **macOS:** Unsupported.
pub license: Option<String>,
/// The application website.
///
/// ## Platform-specific
///
/// - **macOS:** Unsupported.
pub website: Option<String>,
/// The website label.
///
/// ## Platform-specific
///
/// - **macOS:** Unsupported.
pub website_label: Option<String>,
/// The credits.
///
/// ## Platform-specific
///
/// - **Windows / Linux:** Unsupported.
pub credits: Option<String>,
/// The application icon.
///
/// ## Platform-specific
///
/// - **Windows:** Unsupported.
pub icon: Option<Image<'a>>,
}
/// A builder type for [`AboutMetadata`].
#[derive(Clone, Debug, Default)]
pub struct AboutMetadataBuilder<'a>(AboutMetadata<'a>);
impl<'a> AboutMetadataBuilder<'a> {
/// Create a new about metadata builder.
pub fn new() -> Self {
Default::default()
}
/// Sets the application name.
pub fn name<S: Into<String>>(mut self, name: Option<S>) -> Self {
self.0.name = name.map(|s| s.into());
self
}
/// Sets the application version.
pub fn version<S: Into<String>>(mut self, version: Option<S>) -> Self {
self.0.version = version.map(|s| s.into());
self
}
/// Sets the short version, e.g. "1.0".
///
/// ## Platform-specific
///
/// - **Windows / Linux:** Appended to the end of `version` in parentheses.
pub fn short_version<S: Into<String>>(mut self, short_version: Option<S>) -> Self {
self.0.short_version = short_version.map(|s| s.into());
self
}
/// Sets the authors of the application.
///
/// ## Platform-specific
///
/// - **macOS:** Unsupported.
pub fn authors(mut self, authors: Option<Vec<String>>) -> Self {
self.0.authors = authors;
self
}
/// Application comments.
///
/// ## Platform-specific
///
/// - **macOS:** Unsupported.
pub fn comments<S: Into<String>>(mut self, comments: Option<S>) -> Self {
self.0.comments = comments.map(|s| s.into());
self
}
/// Sets the copyright of the application.
pub fn copyright<S: Into<String>>(mut self, copyright: Option<S>) -> Self {
self.0.copyright = copyright.map(|s| s.into());
self
}
/// Sets the license of the application.
///
/// ## Platform-specific
///
/// - **macOS:** Unsupported.
pub fn license<S: Into<String>>(mut self, license: Option<S>) -> Self {
self.0.license = license.map(|s| s.into());
self
}
/// Sets the application website.
///
/// ## Platform-specific
///
/// - **macOS:** Unsupported.
pub fn website<S: Into<String>>(mut self, website: Option<S>) -> Self {
self.0.website = website.map(|s| s.into());
self
}
/// Sets the website label.
///
/// ## Platform-specific
///
/// - **macOS:** Unsupported.
pub fn website_label<S: Into<String>>(mut self, website_label: Option<S>) -> Self {
self.0.website_label = website_label.map(|s| s.into());
self
}
/// Sets the credits.
///
/// ## Platform-specific
///
/// - **Windows / Linux:** Unsupported.
pub fn credits<S: Into<String>>(mut self, credits: Option<S>) -> Self {
self.0.credits = credits.map(|s| s.into());
self
}
/// Sets the application icon.
///
/// ## Platform-specific
///
/// - **Windows:** Unsupported.
pub fn icon(mut self, icon: Option<Image<'a>>) -> Self {
self.0.icon = icon;
self
}
/// Construct the final [`AboutMetadata`]
pub fn build(self) -> AboutMetadata<'a> {
self.0
}
}
impl TryFrom<AboutMetadata<'_>> for muda::AboutMetadata {
type Error = crate::Error;
fn try_from(value: AboutMetadata<'_>) -> Result<Self, Self::Error> {
let icon = match value.icon {
Some(i) => Some(i.try_into()?),
None => None,
};
Ok(Self {
authors: value.authors,
name: value.name,
version: value.version,
short_version: value.short_version,
comments: value.comments,
copyright: value.copyright,
license: value.license,
website: value.website,
website_label: value.website_label,
credits: value.credits,
icon,
})
}
}
/// A native Icon to be used for the menu item
///
/// ## Platform-specific:
///
/// - **Windows / Linux**: Unsupported.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
pub enum NativeIcon {
/// An add item template image.
Add,
/// Advanced preferences toolbar icon for the preferences window.
Advanced,
/// A Bluetooth template image.
Bluetooth,
/// Bookmarks image suitable for a template.
Bookmarks,
/// A caution image.
Caution,
/// A color panel toolbar icon.
ColorPanel,
/// A column view mode template image.
ColumnView,
/// A computer icon.
Computer,
/// An enter full-screen mode template image.
EnterFullScreen,
/// Permissions for all users.
Everyone,
/// An exit full-screen mode template image.
ExitFullScreen,
/// A cover flow view mode template image.
FlowView,
/// A folder image.
Folder,
/// A burnable folder icon.
FolderBurnable,
/// A smart folder icon.
FolderSmart,
/// A link template image.
FollowLinkFreestanding,
/// A font panel toolbar icon.
FontPanel,
/// A `go back` template image.
GoLeft,
/// A `go forward` template image.
GoRight,
/// Home image suitable for a template.
Home,
/// An iChat Theater template image.
IChatTheater,
/// An icon view mode template image.
IconView,
/// An information toolbar icon.
Info,
/// A template image used to denote invalid data.
InvalidDataFreestanding,
/// A generic left-facing triangle template image.
LeftFacingTriangle,
/// A list view mode template image.
ListView,
/// A locked padlock template image.
LockLocked,
/// An unlocked padlock template image.
LockUnlocked,
/// A horizontal dash, for use in menus.
MenuMixedState,
/// A check mark template image, for use in menus.
MenuOnState,
/// A MobileMe icon.
MobileMe,
/// A drag image for multiple items.
MultipleDocuments,
/// A network icon.
Network,
/// A path button template image.
Path,
/// General preferences toolbar icon for the preferences window.
PreferencesGeneral,
/// A Quick Look template image.
QuickLook,
/// A refresh template image.
RefreshFreestanding,
/// A refresh template image.
Refresh,
/// A remove item template image.
Remove,
/// A reveal contents template image.
RevealFreestanding,
/// A generic right-facing triangle template image.
RightFacingTriangle,
/// A share view template image.
Share,
/// A slideshow template image.
Slideshow,
/// A badge for a `smart` item.
SmartBadge,
/// Small green indicator, similar to iChat's available image.
StatusAvailable,
/// Small clear indicator.
StatusNone,
/// Small yellow indicator, similar to iChat's idle image.
StatusPartiallyAvailable,
/// Small red indicator, similar to iChat's unavailable image.
StatusUnavailable,
/// A stop progress template image.
StopProgressFreestanding,
/// A stop progress button template image.
StopProgress,
/// An image of the empty trash can.
TrashEmpty,
/// An image of the full trash can.
TrashFull,
/// Permissions for a single user.
User,
/// User account toolbar icon for the preferences window.
UserAccounts,
/// Permissions for a group of users.
UserGroup,
/// Permissions for guests.
UserGuest,
}
impl From<NativeIcon> for muda::NativeIcon {
fn from(value: NativeIcon) -> Self {
match value {
NativeIcon::Add => muda::NativeIcon::Add,
NativeIcon::Advanced => muda::NativeIcon::Advanced,
NativeIcon::Bluetooth => muda::NativeIcon::Bluetooth,
NativeIcon::Bookmarks => muda::NativeIcon::Bookmarks,
NativeIcon::Caution => muda::NativeIcon::Caution,
NativeIcon::ColorPanel => muda::NativeIcon::ColorPanel,
NativeIcon::ColumnView => muda::NativeIcon::ColumnView,
NativeIcon::Computer => muda::NativeIcon::Computer,
NativeIcon::EnterFullScreen => muda::NativeIcon::EnterFullScreen,
NativeIcon::Everyone => muda::NativeIcon::Everyone,
NativeIcon::ExitFullScreen => muda::NativeIcon::ExitFullScreen,
NativeIcon::FlowView => muda::NativeIcon::FlowView,
NativeIcon::Folder => muda::NativeIcon::Folder,
NativeIcon::FolderBurnable => muda::NativeIcon::FolderBurnable,
NativeIcon::FolderSmart => muda::NativeIcon::FolderSmart,
NativeIcon::FollowLinkFreestanding => muda::NativeIcon::FollowLinkFreestanding,
NativeIcon::FontPanel => muda::NativeIcon::FontPanel,
NativeIcon::GoLeft => muda::NativeIcon::GoLeft,
NativeIcon::GoRight => muda::NativeIcon::GoRight,
NativeIcon::Home => muda::NativeIcon::Home,
NativeIcon::IChatTheater => muda::NativeIcon::IChatTheater,
NativeIcon::IconView => muda::NativeIcon::IconView,
NativeIcon::Info => muda::NativeIcon::Info,
NativeIcon::InvalidDataFreestanding => muda::NativeIcon::InvalidDataFreestanding,
NativeIcon::LeftFacingTriangle => muda::NativeIcon::LeftFacingTriangle,
NativeIcon::ListView => muda::NativeIcon::ListView,
NativeIcon::LockLocked => muda::NativeIcon::LockLocked,
NativeIcon::LockUnlocked => muda::NativeIcon::LockUnlocked,
NativeIcon::MenuMixedState => muda::NativeIcon::MenuMixedState,
NativeIcon::MenuOnState => muda::NativeIcon::MenuOnState,
NativeIcon::MobileMe => muda::NativeIcon::MobileMe,
NativeIcon::MultipleDocuments => muda::NativeIcon::MultipleDocuments,
NativeIcon::Network => muda::NativeIcon::Network,
NativeIcon::Path => muda::NativeIcon::Path,
NativeIcon::PreferencesGeneral => muda::NativeIcon::PreferencesGeneral,
NativeIcon::QuickLook => muda::NativeIcon::QuickLook,
NativeIcon::RefreshFreestanding => muda::NativeIcon::RefreshFreestanding,
NativeIcon::Refresh => muda::NativeIcon::Refresh,
NativeIcon::Remove => muda::NativeIcon::Remove,
NativeIcon::RevealFreestanding => muda::NativeIcon::RevealFreestanding,
NativeIcon::RightFacingTriangle => muda::NativeIcon::RightFacingTriangle,
NativeIcon::Share => muda::NativeIcon::Share,
NativeIcon::Slideshow => muda::NativeIcon::Slideshow,
NativeIcon::SmartBadge => muda::NativeIcon::SmartBadge,
NativeIcon::StatusAvailable => muda::NativeIcon::StatusAvailable,
NativeIcon::StatusNone => muda::NativeIcon::StatusNone,
NativeIcon::StatusPartiallyAvailable => muda::NativeIcon::StatusPartiallyAvailable,
NativeIcon::StatusUnavailable => muda::NativeIcon::StatusUnavailable,
NativeIcon::StopProgressFreestanding => muda::NativeIcon::StopProgressFreestanding,
NativeIcon::StopProgress => muda::NativeIcon::StopProgress,
NativeIcon::TrashEmpty => muda::NativeIcon::TrashEmpty,
NativeIcon::TrashFull => muda::NativeIcon::TrashFull,
NativeIcon::User => muda::NativeIcon::User,
NativeIcon::UserAccounts => muda::NativeIcon::UserAccounts,
NativeIcon::UserGroup => muda::NativeIcon::UserGroup,
NativeIcon::UserGuest => muda::NativeIcon::UserGuest,
}
}
}
/// An enumeration of all menu item kinds that could be added to
/// a [`Menu`] or [`Submenu`]
pub enum MenuItemKind<R: Runtime> {
/// Normal menu item
MenuItem(MenuItem<R>),
/// Submenu menu item
Submenu(Submenu<R>),
/// Predefined menu item
Predefined(PredefinedMenuItem<R>),
/// Check menu item
Check(CheckMenuItem<R>),
/// Icon menu item
Icon(IconMenuItem<R>),
}
impl<R: Runtime> MenuItemKind<R> {
/// Returns a unique identifier associated with this menu item.
pub fn id(&self) -> &MenuId {
match self {
MenuItemKind::MenuItem(i) => i.id(),
MenuItemKind::Submenu(i) => i.id(),
MenuItemKind::Predefined(i) => i.id(),
MenuItemKind::Check(i) => i.id(),
MenuItemKind::Icon(i) => i.id(),
}
}
pub(crate) fn inner(&self) -> &dyn IsMenuItem<R> {
match self {
MenuItemKind::MenuItem(i) => i,
MenuItemKind::Submenu(i) => i,
MenuItemKind::Predefined(i) => i,
MenuItemKind::Check(i) => i,
MenuItemKind::Icon(i) => i,
}
}
pub(crate) fn from_muda(app_handle: AppHandle<R>, i: muda::MenuItemKind) -> Self {
match i {
muda::MenuItemKind::MenuItem(i) => Self::MenuItem(MenuItem(Arc::new(MenuItemInner {
id: i.id().clone(),
inner: i.into(),
app_handle,
}))),
muda::MenuItemKind::Submenu(i) => Self::Submenu(Submenu(Arc::new(SubmenuInner {
id: i.id().clone(),
inner: i.into(),
app_handle,
}))),
muda::MenuItemKind::Predefined(i) => {
Self::Predefined(PredefinedMenuItem(Arc::new(PredefinedMenuItemInner {
id: i.id().clone(),
inner: i.into(),
app_handle,
})))
}
muda::MenuItemKind::Check(i) => Self::Check(CheckMenuItem(Arc::new(CheckMenuItemInner {
id: i.id().clone(),
inner: i.into(),
app_handle,
}))),
muda::MenuItemKind::Icon(i) => Self::Icon(IconMenuItem(Arc::new(IconMenuItemInner {
id: i.id().clone(),
inner: i.into(),
app_handle,
}))),
}
}
/// Casts this item to a [`MenuItem`], and returns `None` if it wasn't.
pub fn as_menuitem(&self) -> Option<&MenuItem<R>> {
match self {
MenuItemKind::MenuItem(i) => Some(i),
_ => None,
}
}
/// Casts this item to a [`MenuItem`], and panics if it wasn't.
pub fn as_menuitem_unchecked(&self) -> &MenuItem<R> {
match self {
MenuItemKind::MenuItem(i) => i,
_ => panic!("Not a MenuItem"),
}
}
/// Casts this item to a [`Submenu`], and returns `None` if it wasn't.
pub fn as_submenu(&self) -> Option<&Submenu<R>> {
match self {
MenuItemKind::Submenu(i) => Some(i),
_ => None,
}
}
/// Casts this item to a [`Submenu`], and panics if it wasn't.
pub fn as_submenu_unchecked(&self) -> &Submenu<R> {
match self {
MenuItemKind::Submenu(i) => i,
_ => panic!("Not a Submenu"),
}
}
/// Casts this item to a [`PredefinedMenuItem`], and returns `None` if it wasn't.
pub fn as_predefined_menuitem(&self) -> Option<&PredefinedMenuItem<R>> {
match self {
MenuItemKind::Predefined(i) => Some(i),
_ => None,
}
}
/// Casts this item to a [`PredefinedMenuItem`], and panics if it wasn't.
pub fn as_predefined_menuitem_unchecked(&self) -> &PredefinedMenuItem<R> {
match self {
MenuItemKind::Predefined(i) => i,
_ => panic!("Not a PredefinedMenuItem"),
}
}
/// Casts this item to a [`CheckMenuItem`], and returns `None` if it wasn't.
pub fn as_check_menuitem(&self) -> Option<&CheckMenuItem<R>> {
match self {
MenuItemKind::Check(i) => Some(i),
_ => None,
}
}
/// Casts this item to a [`CheckMenuItem`], and panics if it wasn't.
pub fn as_check_menuitem_unchecked(&self) -> &CheckMenuItem<R> {
match self {
MenuItemKind::Check(i) => i,
_ => panic!("Not a CheckMenuItem"),
}
}
/// Casts this item to a [`IconMenuItem`], and returns `None` if it wasn't.
pub fn as_icon_menuitem(&self) -> Option<&IconMenuItem<R>> {
match self {
MenuItemKind::Icon(i) => Some(i),
_ => None,
}
}
/// Casts this item to a [`IconMenuItem`], and panics if it wasn't.
pub fn as_icon_menuitem_unchecked(&self) -> &IconMenuItem<R> {
match self {
MenuItemKind::Icon(i) => i,
_ => panic!("Not an IconMenuItem"),
}
}
}
impl<R: Runtime> Clone for MenuItemKind<R> {
fn clone(&self) -> Self {
match self {
Self::MenuItem(i) => Self::MenuItem(i.clone()),
Self::Submenu(i) => Self::Submenu(i.clone()),
Self::Predefined(i) => Self::Predefined(i.clone()),
Self::Check(i) => Self::Check(i.clone()),
Self::Icon(i) => Self::Icon(i.clone()),
}
}
}
impl<R: Runtime> sealed::IsMenuItemBase for MenuItemKind<R> {
fn inner_muda(&self) -> &dyn muda::IsMenuItem {
self.inner().inner_muda()
}
}
impl<R: Runtime> IsMenuItem<R> for MenuItemKind<R> {
fn kind(&self) -> MenuItemKind<R> {
self.clone()
}
fn id(&self) -> &MenuId {
self.id()
}
}
/// A trait that defines a generic item in a menu, which may be one of [`MenuItemKind`]
///
/// # Safety
///
/// This trait is ONLY meant to be implemented internally by the crate.
pub trait IsMenuItem<R: Runtime>: sealed::IsMenuItemBase {
/// Returns the kind of this menu item.
fn kind(&self) -> MenuItemKind<R>;
/// Returns a unique identifier associated with this menu.
fn id(&self) -> &MenuId;
}
/// A helper trait with methods to help creating a context menu.
///
/// # Safety
///
/// This trait is ONLY meant to be implemented internally by the crate.
pub trait ContextMenu: sealed::ContextMenuBase + Send + Sync {
/// Get the popup [`HMENU`] for this menu.
///
/// The returned [`HMENU`] is valid as long as the [`ContextMenu`] is.
///
/// [`HMENU`]: https://learn.microsoft.com/en-us/windows/win32/winprog/windows-data-types#HMENU
#[cfg(windows)]
#[cfg_attr(docsrs, doc(cfg(windows)))]
fn hpopupmenu(&self) -> crate::Result<isize>;
/// Popup this menu as a context menu on the specified window at the cursor position.
fn popup<R: crate::Runtime>(&self, window: crate::Window<R>) -> crate::Result<()>;
/// Popup this menu as a context menu on the specified window at the specified position.
///
/// The position is relative to the window's top-left corner.
fn popup_at<R: crate::Runtime, P: Into<crate::Position>>(
&self,
window: crate::Window<R>,
position: P,
) -> crate::Result<()>;
}
pub(crate) mod sealed {
pub trait IsMenuItemBase {
fn inner_muda(&self) -> &dyn muda::IsMenuItem;
}
pub trait ContextMenuBase {
fn inner_context(&self) -> &dyn muda::ContextMenu;
fn inner_context_owned(&self) -> Box<dyn muda::ContextMenu>;
fn popup_inner<R: crate::Runtime, P: Into<crate::Position>>(
&self,
window: crate::Window<R>,
position: Option<P>,
) -> crate::Result<()>;
}
}
#[cfg(windows)]
pub(crate) fn map_to_menu_theme(theme: tauri_utils::Theme) -> muda::MenuTheme {
match theme {
tauri_utils::Theme::Light => muda::MenuTheme::Light,
tauri_utils::Theme::Dark => muda::MenuTheme::Dark,
_ => muda::MenuTheme::Auto,
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/menu/predefined.rs | crates/tauri/src/menu/predefined.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::sync::Arc;
use super::run_item_main_thread;
use super::{AboutMetadata, PredefinedMenuItem};
use crate::menu::PredefinedMenuItemInner;
use crate::run_main_thread;
use crate::{menu::MenuId, AppHandle, Manager, Runtime};
impl<R: Runtime> PredefinedMenuItem<R> {
/// Separator menu item
pub fn separator<M: Manager<R>>(manager: &M) -> crate::Result<Self> {
let handle = manager.app_handle();
let app_handle = handle.clone();
let item = run_main_thread!(handle, || {
let item = muda::PredefinedMenuItem::separator();
PredefinedMenuItemInner {
id: item.id().clone(),
inner: Some(item),
app_handle,
}
})?;
Ok(Self(Arc::new(item)))
}
/// Copy menu item
pub fn copy<M: Manager<R>>(manager: &M, text: Option<&str>) -> crate::Result<Self> {
let handle = manager.app_handle();
let app_handle = handle.clone();
let text = text.map(|t| t.to_owned());
let item = run_main_thread!(handle, || {
let item = muda::PredefinedMenuItem::copy(text.as_deref());
PredefinedMenuItemInner {
id: item.id().clone(),
inner: Some(item),
app_handle,
}
})?;
Ok(Self(Arc::new(item)))
}
/// Cut menu item
pub fn cut<M: Manager<R>>(manager: &M, text: Option<&str>) -> crate::Result<Self> {
let handle = manager.app_handle();
let app_handle = handle.clone();
let text = text.map(|t| t.to_owned());
let item = run_main_thread!(handle, || {
let item = muda::PredefinedMenuItem::cut(text.as_deref());
PredefinedMenuItemInner {
id: item.id().clone(),
inner: Some(item),
app_handle,
}
})?;
Ok(Self(Arc::new(item)))
}
/// Paste menu item
pub fn paste<M: Manager<R>>(manager: &M, text: Option<&str>) -> crate::Result<Self> {
let handle = manager.app_handle();
let app_handle = handle.clone();
let text = text.map(|t| t.to_owned());
let item = run_main_thread!(handle, || {
let item = muda::PredefinedMenuItem::paste(text.as_deref());
PredefinedMenuItemInner {
id: item.id().clone(),
inner: Some(item),
app_handle,
}
})?;
Ok(Self(Arc::new(item)))
}
/// SelectAll menu item
pub fn select_all<M: Manager<R>>(manager: &M, text: Option<&str>) -> crate::Result<Self> {
let handle = manager.app_handle();
let app_handle = handle.clone();
let text = text.map(|t| t.to_owned());
let item = run_main_thread!(handle, || {
let item = muda::PredefinedMenuItem::select_all(text.as_deref());
PredefinedMenuItemInner {
id: item.id().clone(),
inner: Some(item),
app_handle,
}
})?;
Ok(Self(Arc::new(item)))
}
/// Undo menu item
///
/// ## Platform-specific:
///
/// - **Windows / Linux:** Unsupported.
pub fn undo<M: Manager<R>>(manager: &M, text: Option<&str>) -> crate::Result<Self> {
let handle = manager.app_handle();
let app_handle = handle.clone();
let text = text.map(|t| t.to_owned());
let item = run_main_thread!(handle, || {
let item = muda::PredefinedMenuItem::undo(text.as_deref());
PredefinedMenuItemInner {
id: item.id().clone(),
inner: Some(item),
app_handle,
}
})?;
Ok(Self(Arc::new(item)))
}
/// Redo menu item
///
/// ## Platform-specific:
///
/// - **Windows / Linux:** Unsupported.
pub fn redo<M: Manager<R>>(manager: &M, text: Option<&str>) -> crate::Result<Self> {
let handle = manager.app_handle();
let app_handle = handle.clone();
let text = text.map(|t| t.to_owned());
let item = run_main_thread!(handle, || {
let item = muda::PredefinedMenuItem::redo(text.as_deref());
PredefinedMenuItemInner {
id: item.id().clone(),
inner: Some(item),
app_handle,
}
})?;
Ok(Self(Arc::new(item)))
}
/// Minimize window menu item
///
/// ## Platform-specific:
///
/// - **Linux:** Unsupported.
pub fn minimize<M: Manager<R>>(manager: &M, text: Option<&str>) -> crate::Result<Self> {
let handle = manager.app_handle();
let app_handle = handle.clone();
let text = text.map(|t| t.to_owned());
let item = run_main_thread!(handle, || {
let item = muda::PredefinedMenuItem::minimize(text.as_deref());
PredefinedMenuItemInner {
id: item.id().clone(),
inner: Some(item),
app_handle,
}
})?;
Ok(Self(Arc::new(item)))
}
/// Maximize window menu item
///
/// ## Platform-specific:
///
/// - **Linux:** Unsupported.
pub fn maximize<M: Manager<R>>(manager: &M, text: Option<&str>) -> crate::Result<Self> {
let handle = manager.app_handle();
let app_handle = handle.clone();
let text = text.map(|t| t.to_owned());
let item = run_main_thread!(handle, || {
let item = muda::PredefinedMenuItem::maximize(text.as_deref());
PredefinedMenuItemInner {
id: item.id().clone(),
inner: Some(item),
app_handle,
}
})?;
Ok(Self(Arc::new(item)))
}
/// Fullscreen menu item
///
/// ## Platform-specific:
///
/// - **Windows / Linux:** Unsupported.
pub fn fullscreen<M: Manager<R>>(manager: &M, text: Option<&str>) -> crate::Result<Self> {
let handle = manager.app_handle();
let app_handle = handle.clone();
let text = text.map(|t| t.to_owned());
let item = run_main_thread!(handle, || {
let item = muda::PredefinedMenuItem::fullscreen(text.as_deref());
PredefinedMenuItemInner {
id: item.id().clone(),
inner: Some(item),
app_handle,
}
})?;
Ok(Self(Arc::new(item)))
}
/// Hide window menu item
///
/// ## Platform-specific:
///
/// - **Linux:** Unsupported.
pub fn hide<M: Manager<R>>(manager: &M, text: Option<&str>) -> crate::Result<Self> {
let handle = manager.app_handle();
let app_handle = handle.clone();
let text = text.map(|t| t.to_owned());
let item = run_main_thread!(handle, || {
let item = muda::PredefinedMenuItem::hide(text.as_deref());
PredefinedMenuItemInner {
id: item.id().clone(),
inner: Some(item),
app_handle,
}
})?;
Ok(Self(Arc::new(item)))
}
/// Hide other windows menu item
///
/// ## Platform-specific:
///
/// - **Linux:** Unsupported.
pub fn hide_others<M: Manager<R>>(manager: &M, text: Option<&str>) -> crate::Result<Self> {
let handle = manager.app_handle();
let app_handle = handle.clone();
let text = text.map(|t| t.to_owned());
let item = run_main_thread!(handle, || {
let item = muda::PredefinedMenuItem::hide_others(text.as_deref());
PredefinedMenuItemInner {
id: item.id().clone(),
inner: Some(item),
app_handle,
}
})?;
Ok(Self(Arc::new(item)))
}
/// Show all app windows menu item
///
/// ## Platform-specific:
///
/// - **Windows / Linux:** Unsupported.
pub fn show_all<M: Manager<R>>(manager: &M, text: Option<&str>) -> crate::Result<Self> {
let handle = manager.app_handle();
let app_handle = handle.clone();
let text = text.map(|t| t.to_owned());
let item = run_main_thread!(handle, || {
let item = muda::PredefinedMenuItem::show_all(text.as_deref());
PredefinedMenuItemInner {
id: item.id().clone(),
inner: Some(item),
app_handle,
}
})?;
Ok(Self(Arc::new(item)))
}
/// Close window menu item
///
/// ## Platform-specific:
///
/// - **Linux:** Unsupported.
pub fn close_window<M: Manager<R>>(manager: &M, text: Option<&str>) -> crate::Result<Self> {
let handle = manager.app_handle();
let app_handle = handle.clone();
let text = text.map(|t| t.to_owned());
let item = run_main_thread!(handle, || {
let item = muda::PredefinedMenuItem::close_window(text.as_deref());
PredefinedMenuItemInner {
id: item.id().clone(),
inner: Some(item),
app_handle,
}
})?;
Ok(Self(Arc::new(item)))
}
/// Quit app menu item
///
/// ## Platform-specific:
///
/// - **Linux:** Unsupported.
pub fn quit<M: Manager<R>>(manager: &M, text: Option<&str>) -> crate::Result<Self> {
let handle = manager.app_handle();
let app_handle = handle.clone();
let text = text.map(|t| t.to_owned());
let item = run_main_thread!(handle, || {
let item = muda::PredefinedMenuItem::quit(text.as_deref());
PredefinedMenuItemInner {
id: item.id().clone(),
inner: Some(item),
app_handle,
}
})?;
Ok(Self(Arc::new(item)))
}
/// About app menu item
pub fn about<M: Manager<R>>(
manager: &M,
text: Option<&str>,
metadata: Option<AboutMetadata<'_>>,
) -> crate::Result<Self> {
let handle = manager.app_handle();
let app_handle = handle.clone();
let text = text.map(|t| t.to_owned());
let metadata = match metadata {
Some(m) => Some(m.try_into()?),
None => None,
};
let item = run_main_thread!(handle, || {
let item = muda::PredefinedMenuItem::about(text.as_deref(), metadata);
PredefinedMenuItemInner {
id: item.id().clone(),
inner: Some(item),
app_handle,
}
})?;
Ok(Self(Arc::new(item)))
}
/// Services menu item
///
/// ## Platform-specific:
///
/// - **Windows / Linux:** Unsupported.
pub fn services<M: Manager<R>>(manager: &M, text: Option<&str>) -> crate::Result<Self> {
let handle = manager.app_handle();
let app_handle = handle.clone();
let text = text.map(|t| t.to_owned());
let item = run_main_thread!(handle, || {
let item = muda::PredefinedMenuItem::services(text.as_deref());
PredefinedMenuItemInner {
id: item.id().clone(),
inner: Some(item),
app_handle,
}
})?;
Ok(Self(Arc::new(item)))
}
/// Returns a unique identifier associated with this menu item.
pub fn id(&self) -> &MenuId {
&self.0.id
}
/// Get the text for this menu item.
pub fn text(&self) -> crate::Result<String> {
run_item_main_thread!(self, |self_: Self| (*self_.0).as_ref().text())
}
/// Set the text for this menu item. `text` could optionally contain
/// an `&` before a character to assign this character as the mnemonic
/// for this menu item. To display a `&` without assigning a mnemenonic, use `&&`.
pub fn set_text<S: AsRef<str>>(&self, text: S) -> crate::Result<()> {
let text = text.as_ref().to_string();
run_item_main_thread!(self, |self_: Self| (*self_.0).as_ref().set_text(text))
}
/// The application handle associated with this type.
pub fn app_handle(&self) -> &AppHandle<R> {
&self.0.app_handle
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/menu/plugin.rs | crates/tauri/src/menu/plugin.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{collections::HashMap, sync::Mutex};
use serde::{Deserialize, Serialize};
use tauri_runtime::dpi::Position;
use super::{sealed::ContextMenuBase, *};
use crate::{
command,
image::JsImage,
ipc::{channel::JavaScriptChannelId, Channel},
plugin::{Builder, TauriPlugin},
resources::ResourceId,
sealed::ManagerBase,
Manager, ResourceTable, RunEvent, Runtime, State, Webview, Window,
};
use tauri_macros::do_menu_item;
#[derive(Deserialize, Serialize)]
pub(crate) enum ItemKind {
Menu,
MenuItem,
Predefined,
Submenu,
Check,
Icon,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct AboutMetadata {
pub name: Option<String>,
pub version: Option<String>,
pub short_version: Option<String>,
pub authors: Option<Vec<String>>,
pub comments: Option<String>,
pub copyright: Option<String>,
pub license: Option<String>,
pub website: Option<String>,
pub website_label: Option<String>,
pub credits: Option<String>,
pub icon: Option<JsImage>,
}
impl AboutMetadata {
pub fn into_metadata(
self,
resources_table: &ResourceTable,
) -> crate::Result<super::AboutMetadata<'_>> {
let icon = match self.icon {
Some(i) => Some(i.into_img(resources_table)?.as_ref().clone()),
None => None,
};
Ok(super::AboutMetadata {
name: self.name,
version: self.version,
short_version: self.short_version,
authors: self.authors,
comments: self.comments,
copyright: self.copyright,
license: self.license,
website: self.website,
website_label: self.website_label,
credits: self.credits,
icon,
})
}
}
#[allow(clippy::large_enum_variant)]
#[derive(Deserialize)]
enum Predefined {
Separator,
Copy,
Cut,
Paste,
SelectAll,
Undo,
Redo,
Minimize,
Maximize,
Fullscreen,
Hide,
HideOthers,
ShowAll,
CloseWindow,
Quit,
About(Option<AboutMetadata>),
Services,
}
#[derive(Deserialize)]
struct SubmenuPayload {
id: Option<MenuId>,
text: String,
enabled: Option<bool>,
items: Vec<MenuItemPayloadKind>,
icon: Option<Icon>,
}
impl SubmenuPayload {
pub fn create_item<R: Runtime>(
self,
webview: &Webview<R>,
resources_table: &ResourceTable,
) -> crate::Result<Submenu<R>> {
let mut builder = if let Some(id) = self.id {
SubmenuBuilder::with_id(webview, id, self.text)
} else {
SubmenuBuilder::new(webview, self.text)
};
if let Some(enabled) = self.enabled {
builder = builder.enabled(enabled);
}
if let Some(icon) = self.icon {
builder = match icon {
Icon::Native(native_icon) => builder.submenu_native_icon(native_icon),
Icon::Icon(js_icon) => {
builder.submenu_icon(js_icon.into_img(resources_table)?.as_ref().clone())
}
};
}
for item in self.items {
builder = item.with_item(webview, resources_table, |i| Ok(builder.item(i)))?;
}
builder.build()
}
}
#[derive(Deserialize)]
struct CheckMenuItemPayload {
handler: Option<JavaScriptChannelId>,
id: Option<MenuId>,
text: String,
checked: bool,
enabled: Option<bool>,
accelerator: Option<String>,
}
impl CheckMenuItemPayload {
pub fn create_item<R: Runtime>(self, webview: &Webview<R>) -> crate::Result<CheckMenuItem<R>> {
let mut builder = if let Some(id) = self.id {
CheckMenuItemBuilder::with_id(id, self.text)
} else {
CheckMenuItemBuilder::new(self.text)
};
if let Some(accelerator) = self.accelerator {
builder = builder.accelerator(accelerator);
}
if let Some(enabled) = self.enabled {
builder = builder.enabled(enabled);
}
let item = builder.checked(self.checked).build(webview)?;
if let Some(handler) = self.handler {
let handler = handler.channel_on(webview.clone());
webview
.state::<MenuChannels>()
.0
.lock()
.unwrap()
.insert(item.id().clone(), handler);
}
Ok(item)
}
}
#[derive(Deserialize)]
#[serde(untagged)]
enum Icon {
Native(NativeIcon),
Icon(JsImage),
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct IconMenuItemPayload {
handler: Option<JavaScriptChannelId>,
id: Option<MenuId>,
text: String,
icon: Icon,
enabled: Option<bool>,
accelerator: Option<String>,
}
impl IconMenuItemPayload {
pub fn create_item<R: Runtime>(
self,
webview: &Webview<R>,
resources_table: &ResourceTable,
) -> crate::Result<IconMenuItem<R>> {
let mut builder = if let Some(id) = self.id {
IconMenuItemBuilder::with_id(id, self.text)
} else {
IconMenuItemBuilder::new(self.text)
};
if let Some(accelerator) = self.accelerator {
builder = builder.accelerator(accelerator);
}
if let Some(enabled) = self.enabled {
builder = builder.enabled(enabled);
}
builder = match self.icon {
Icon::Native(native_icon) => builder.native_icon(native_icon),
Icon::Icon(icon) => builder.icon(icon.into_img(resources_table)?.as_ref().clone()),
};
let item = builder.build(webview)?;
if let Some(handler) = self.handler {
let handler = handler.channel_on(webview.clone());
webview
.state::<MenuChannels>()
.0
.lock()
.unwrap()
.insert(item.id().clone(), handler);
}
Ok(item)
}
}
#[derive(Deserialize)]
struct MenuItemPayload {
handler: Option<JavaScriptChannelId>,
id: Option<MenuId>,
text: String,
enabled: Option<bool>,
accelerator: Option<String>,
}
impl MenuItemPayload {
pub fn create_item<R: Runtime>(self, webview: &Webview<R>) -> crate::Result<MenuItem<R>> {
let mut builder = if let Some(id) = self.id {
MenuItemBuilder::with_id(id, self.text)
} else {
MenuItemBuilder::new(self.text)
};
if let Some(accelerator) = self.accelerator {
builder = builder.accelerator(accelerator);
}
if let Some(enabled) = self.enabled {
builder = builder.enabled(enabled);
}
let item = builder.build(webview)?;
if let Some(handler) = self.handler {
let handler = handler.channel_on(webview.clone());
webview
.state::<MenuChannels>()
.0
.lock()
.unwrap()
.insert(item.id().clone(), handler);
}
Ok(item)
}
}
#[derive(Deserialize)]
struct PredefinedMenuItemPayload {
item: Predefined,
text: Option<String>,
}
impl PredefinedMenuItemPayload {
pub fn create_item<R: Runtime>(
self,
webview: &Webview<R>,
resources_table: &ResourceTable,
) -> crate::Result<PredefinedMenuItem<R>> {
match self.item {
Predefined::Separator => PredefinedMenuItem::separator(webview),
Predefined::Copy => PredefinedMenuItem::copy(webview, self.text.as_deref()),
Predefined::Cut => PredefinedMenuItem::cut(webview, self.text.as_deref()),
Predefined::Paste => PredefinedMenuItem::paste(webview, self.text.as_deref()),
Predefined::SelectAll => PredefinedMenuItem::select_all(webview, self.text.as_deref()),
Predefined::Undo => PredefinedMenuItem::undo(webview, self.text.as_deref()),
Predefined::Redo => PredefinedMenuItem::redo(webview, self.text.as_deref()),
Predefined::Minimize => PredefinedMenuItem::minimize(webview, self.text.as_deref()),
Predefined::Maximize => PredefinedMenuItem::maximize(webview, self.text.as_deref()),
Predefined::Fullscreen => PredefinedMenuItem::fullscreen(webview, self.text.as_deref()),
Predefined::Hide => PredefinedMenuItem::hide(webview, self.text.as_deref()),
Predefined::HideOthers => PredefinedMenuItem::hide_others(webview, self.text.as_deref()),
Predefined::ShowAll => PredefinedMenuItem::show_all(webview, self.text.as_deref()),
Predefined::CloseWindow => PredefinedMenuItem::close_window(webview, self.text.as_deref()),
Predefined::Quit => PredefinedMenuItem::quit(webview, self.text.as_deref()),
Predefined::About(metadata) => {
let metadata = match metadata {
Some(m) => Some(m.into_metadata(resources_table)?),
None => None,
};
PredefinedMenuItem::about(webview, self.text.as_deref(), metadata)
}
Predefined::Services => PredefinedMenuItem::services(webview, self.text.as_deref()),
}
}
}
#[derive(Deserialize)]
#[serde(untagged)]
// Note, order matters for untagged enum deserialization
enum MenuItemPayloadKind {
ExistingItem((ResourceId, ItemKind)),
Predefined(PredefinedMenuItemPayload),
Check(CheckMenuItemPayload),
Icon(IconMenuItemPayload),
Submenu(SubmenuPayload),
MenuItem(MenuItemPayload),
}
impl MenuItemPayloadKind {
pub fn with_item<T, R: Runtime, F: FnOnce(&dyn IsMenuItem<R>) -> crate::Result<T>>(
self,
webview: &Webview<R>,
resources_table: &ResourceTable,
f: F,
) -> crate::Result<T> {
match self {
Self::ExistingItem((rid, kind)) => {
do_menu_item!(resources_table, rid, kind, |i| f(&*i))
}
Self::Submenu(i) => f(&i.create_item(webview, resources_table)?),
Self::Predefined(i) => f(&i.create_item(webview, resources_table)?),
Self::Check(i) => f(&i.create_item(webview)?),
Self::Icon(i) => f(&i.create_item(webview, resources_table)?),
Self::MenuItem(i) => f(&i.create_item(webview)?),
}
}
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "camelCase")]
struct NewOptions {
id: Option<MenuId>,
text: Option<String>,
enabled: Option<bool>,
checked: Option<bool>,
accelerator: Option<String>,
#[serde(rename = "item")]
predefined_item: Option<Predefined>,
icon: Option<Icon>,
items: Option<Vec<MenuItemPayloadKind>>,
}
#[command(root = "crate")]
fn new<R: Runtime>(
app: Webview<R>,
webview: Webview<R>,
kind: ItemKind,
options: Option<NewOptions>,
channels: State<'_, MenuChannels>,
handler: Channel<MenuId>,
) -> crate::Result<(ResourceId, MenuId)> {
let options = options.unwrap_or_default();
let mut resources_table = app.resources_table();
let (rid, id) = match kind {
ItemKind::Menu => {
let mut builder = MenuBuilder::new(&app);
if let Some(id) = options.id {
builder = builder.id(id);
}
if let Some(items) = options.items {
for item in items {
builder = item.with_item(&webview, &resources_table, |i| Ok(builder.item(i)))?;
}
}
let menu = builder.build()?;
let id = menu.id().clone();
let rid = resources_table.add(menu);
(rid, id)
}
ItemKind::Submenu => {
let submenu = SubmenuPayload {
id: options.id,
text: options.text.unwrap_or_default(),
enabled: options.enabled,
items: options.items.unwrap_or_default(),
icon: options.icon,
}
.create_item(&webview, &resources_table)?;
let id = submenu.id().clone();
let rid = resources_table.add(submenu);
(rid, id)
}
ItemKind::MenuItem => {
let item = MenuItemPayload {
// handler managed in this function instead
handler: None,
id: options.id,
text: options.text.unwrap_or_default(),
enabled: options.enabled,
accelerator: options.accelerator,
}
.create_item(&webview)?;
let id = item.id().clone();
let rid = resources_table.add(item);
(rid, id)
}
ItemKind::Predefined => {
let item = PredefinedMenuItemPayload {
item: options.predefined_item.unwrap(),
text: options.text,
}
.create_item(&webview, &resources_table)?;
let id = item.id().clone();
let rid = resources_table.add(item);
(rid, id)
}
ItemKind::Check => {
let item = CheckMenuItemPayload {
// handler managed in this function instead
handler: None,
id: options.id,
text: options.text.unwrap_or_default(),
checked: options.checked.unwrap_or_default(),
enabled: options.enabled,
accelerator: options.accelerator,
}
.create_item(&webview)?;
let id = item.id().clone();
let rid = resources_table.add(item);
(rid, id)
}
ItemKind::Icon => {
let item = IconMenuItemPayload {
// handler managed in this function instead
handler: None,
id: options.id,
text: options.text.unwrap_or_default(),
icon: options.icon.unwrap_or(Icon::Native(NativeIcon::User)),
enabled: options.enabled,
accelerator: options.accelerator,
}
.create_item(&webview, &resources_table)?;
let id = item.id().clone();
let rid = resources_table.add(item);
(rid, id)
}
};
channels.0.lock().unwrap().insert(id.clone(), handler);
Ok((rid, id))
}
#[command(root = "crate")]
fn append<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
kind: ItemKind,
items: Vec<MenuItemPayloadKind>,
) -> crate::Result<()> {
let resources_table = webview.resources_table();
match kind {
ItemKind::Menu => {
let menu = resources_table.get::<Menu<R>>(rid)?;
for item in items {
item.with_item(&webview, &resources_table, |i| menu.append(i))?;
}
}
ItemKind::Submenu => {
let submenu = resources_table.get::<Submenu<R>>(rid)?;
for item in items {
item.with_item(&webview, &resources_table, |i| submenu.append(i))?;
}
}
_ => return Err(anyhow::anyhow!("unexpected menu item kind").into()),
};
Ok(())
}
#[command(root = "crate")]
fn prepend<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
kind: ItemKind,
items: Vec<MenuItemPayloadKind>,
) -> crate::Result<()> {
let resources_table = webview.resources_table();
match kind {
ItemKind::Menu => {
let menu = resources_table.get::<Menu<R>>(rid)?;
for item in items {
item.with_item(&webview, &resources_table, |i| menu.prepend(i))?;
}
}
ItemKind::Submenu => {
let submenu = resources_table.get::<Submenu<R>>(rid)?;
for item in items {
item.with_item(&webview, &resources_table, |i| submenu.prepend(i))?;
}
}
_ => return Err(anyhow::anyhow!("unexpected menu item kind").into()),
};
Ok(())
}
#[command(root = "crate")]
fn insert<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
kind: ItemKind,
items: Vec<MenuItemPayloadKind>,
mut position: usize,
) -> crate::Result<()> {
let resources_table = webview.resources_table();
match kind {
ItemKind::Menu => {
let menu = resources_table.get::<Menu<R>>(rid)?;
for item in items {
item.with_item(&webview, &resources_table, |i| menu.insert(i, position))?;
position += 1
}
}
ItemKind::Submenu => {
let submenu = resources_table.get::<Submenu<R>>(rid)?;
for item in items {
item.with_item(&webview, &resources_table, |i| submenu.insert(i, position))?;
position += 1
}
}
_ => return Err(anyhow::anyhow!("unexpected menu item kind").into()),
};
Ok(())
}
#[command(root = "crate")]
fn remove<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
kind: ItemKind,
item: (ResourceId, ItemKind),
) -> crate::Result<()> {
let resources_table = webview.resources_table();
let (item_rid, item_kind) = item;
match kind {
ItemKind::Menu => {
let menu = resources_table.get::<Menu<R>>(rid)?;
do_menu_item!(resources_table, item_rid, item_kind, |i| menu.remove(&*i))?;
}
ItemKind::Submenu => {
let submenu = resources_table.get::<Submenu<R>>(rid)?;
do_menu_item!(resources_table, item_rid, item_kind, |i| submenu
.remove(&*i))?;
}
_ => return Err(anyhow::anyhow!("unexpected menu item kind").into()),
};
Ok(())
}
macro_rules! make_item_resource {
($resources_table:ident, $item:ident) => {{
let id = $item.id().clone();
let (rid, kind) = match $item {
MenuItemKind::MenuItem(i) => ($resources_table.add(i), ItemKind::MenuItem),
MenuItemKind::Submenu(i) => ($resources_table.add(i), ItemKind::Submenu),
MenuItemKind::Predefined(i) => ($resources_table.add(i), ItemKind::Predefined),
MenuItemKind::Check(i) => ($resources_table.add(i), ItemKind::Check),
MenuItemKind::Icon(i) => ($resources_table.add(i), ItemKind::Icon),
};
(rid, id, kind)
}};
}
#[command(root = "crate")]
fn remove_at<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
kind: ItemKind,
position: usize,
) -> crate::Result<Option<(ResourceId, MenuId, ItemKind)>> {
let mut resources_table = webview.resources_table();
match kind {
ItemKind::Menu => {
let menu = resources_table.get::<Menu<R>>(rid)?;
if let Some(item) = menu.remove_at(position)? {
return Ok(Some(make_item_resource!(resources_table, item)));
}
}
ItemKind::Submenu => {
let submenu = resources_table.get::<Submenu<R>>(rid)?;
if let Some(item) = submenu.remove_at(position)? {
return Ok(Some(make_item_resource!(resources_table, item)));
}
}
_ => return Err(anyhow::anyhow!("unexpected menu item kind").into()),
};
Ok(None)
}
#[command(root = "crate")]
fn items<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
kind: ItemKind,
) -> crate::Result<Vec<(ResourceId, MenuId, ItemKind)>> {
let mut resources_table = webview.resources_table();
let items = match kind {
ItemKind::Menu => resources_table.get::<Menu<R>>(rid)?.items()?,
ItemKind::Submenu => resources_table.get::<Submenu<R>>(rid)?.items()?,
_ => return Err(anyhow::anyhow!("unexpected menu item kind").into()),
};
Ok(
items
.into_iter()
.map(|i| make_item_resource!(resources_table, i))
.collect::<Vec<_>>(),
)
}
#[command(root = "crate")]
fn get<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
kind: ItemKind,
id: MenuId,
) -> crate::Result<Option<(ResourceId, MenuId, ItemKind)>> {
let mut resources_table = webview.resources_table();
match kind {
ItemKind::Menu => {
let menu = resources_table.get::<Menu<R>>(rid)?;
if let Some(item) = menu.get(&id) {
return Ok(Some(make_item_resource!(resources_table, item)));
}
}
ItemKind::Submenu => {
let submenu = resources_table.get::<Submenu<R>>(rid)?;
if let Some(item) = submenu.get(&id) {
return Ok(Some(make_item_resource!(resources_table, item)));
}
}
_ => return Err(anyhow::anyhow!("unexpected menu item kind").into()),
};
Ok(None)
}
#[command(root = "crate")]
async fn popup<R: Runtime>(
webview: Webview<R>,
current_window: Window<R>,
rid: ResourceId,
kind: ItemKind,
window: Option<String>,
at: Option<Position>,
) -> crate::Result<()> {
let window = window
.map(|w| webview.manager().get_window(&w))
.unwrap_or(Some(current_window));
if let Some(window) = window {
let resources_table = webview.resources_table();
match kind {
ItemKind::Menu => {
let menu = resources_table.get::<Menu<R>>(rid)?;
menu.popup_inner(window, at)?;
}
ItemKind::Submenu => {
let submenu = resources_table.get::<Submenu<R>>(rid)?;
submenu.popup_inner(window, at)?;
}
_ => return Err(anyhow::anyhow!("unexpected menu item kind").into()),
};
}
Ok(())
}
#[command(root = "crate")]
fn create_default<R: Runtime>(
app: AppHandle<R>,
webview: Webview<R>,
) -> crate::Result<(ResourceId, MenuId)> {
let mut resources_table = webview.resources_table();
let menu = Menu::default(&app)?;
let id = menu.id().clone();
let rid = resources_table.add(menu);
Ok((rid, id))
}
#[command(root = "crate")]
async fn set_as_app_menu<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
) -> crate::Result<Option<(ResourceId, MenuId)>> {
let mut resources_table = webview.resources_table();
let menu = resources_table.get::<Menu<R>>(rid)?;
if let Some(menu) = menu.set_as_app_menu()? {
let id = menu.id().clone();
let rid = resources_table.add(menu);
return Ok(Some((rid, id)));
}
Ok(None)
}
#[command(root = "crate")]
async fn set_as_window_menu<R: Runtime>(
webview: Webview<R>,
current_window: Window<R>,
rid: ResourceId,
window: Option<String>,
) -> crate::Result<Option<(ResourceId, MenuId)>> {
let window = window
.map(|w| webview.manager().get_window(&w))
.unwrap_or(Some(current_window));
if let Some(window) = window {
let mut resources_table = webview.resources_table();
let menu = resources_table.get::<Menu<R>>(rid)?;
if let Some(menu) = menu.set_as_window_menu(&window)? {
let id = menu.id().clone();
let rid = resources_table.add(menu);
return Ok(Some((rid, id)));
}
}
Ok(None)
}
#[command(root = "crate")]
fn text<R: Runtime>(webview: Webview<R>, rid: ResourceId, kind: ItemKind) -> crate::Result<String> {
let resources_table = webview.resources_table();
do_menu_item!(resources_table, rid, kind, |i| i.text())
}
#[command(root = "crate")]
fn set_text<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
kind: ItemKind,
text: String,
) -> crate::Result<()> {
let resources_table = webview.resources_table();
do_menu_item!(resources_table, rid, kind, |i| i.set_text(text))
}
#[command(root = "crate")]
fn is_enabled<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
kind: ItemKind,
) -> crate::Result<bool> {
let resources_table = webview.resources_table();
do_menu_item!(resources_table, rid, kind, |i| i.is_enabled(), !Predefined)
}
#[command(root = "crate")]
fn set_enabled<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
kind: ItemKind,
enabled: bool,
) -> crate::Result<()> {
let resources_table = webview.resources_table();
do_menu_item!(
resources_table,
rid,
kind,
|i| i.set_enabled(enabled),
!Predefined
)
}
#[command(root = "crate")]
fn set_accelerator<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
kind: ItemKind,
accelerator: Option<String>,
) -> crate::Result<()> {
let resources_table = webview.resources_table();
do_menu_item!(
resources_table,
rid,
kind,
|i| i.set_accelerator(accelerator),
!Predefined | !Submenu
)
}
#[command(root = "crate")]
fn set_as_windows_menu_for_nsapp<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
) -> crate::Result<()> {
#[cfg(target_os = "macos")]
{
let resources_table = webview.resources_table();
let submenu = resources_table.get::<Submenu<R>>(rid)?;
submenu.set_as_help_menu_for_nsapp()?;
}
let _ = rid;
let _ = webview;
Ok(())
}
#[command(root = "crate")]
fn set_as_help_menu_for_nsapp<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
) -> crate::Result<()> {
#[cfg(target_os = "macos")]
{
let resources_table = webview.resources_table();
let submenu = resources_table.get::<Submenu<R>>(rid)?;
submenu.set_as_help_menu_for_nsapp()?;
}
let _ = rid;
let _ = webview;
Ok(())
}
#[command(root = "crate")]
fn is_checked<R: Runtime>(webview: Webview<R>, rid: ResourceId) -> crate::Result<bool> {
let resources_table = webview.resources_table();
let check_item = resources_table.get::<CheckMenuItem<R>>(rid)?;
check_item.is_checked()
}
#[command(root = "crate")]
fn set_checked<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
checked: bool,
) -> crate::Result<()> {
let resources_table = webview.resources_table();
let check_item = resources_table.get::<CheckMenuItem<R>>(rid)?;
check_item.set_checked(checked)
}
#[command(root = "crate")]
fn set_icon<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
kind: ItemKind,
icon: Option<Icon>,
) -> crate::Result<()> {
let resources_table = webview.resources_table();
do_menu_item!(
resources_table,
rid,
kind,
|icon_item| match icon {
Some(Icon::Native(icon)) => icon_item.set_native_icon(Some(icon)),
Some(Icon::Icon(icon)) => {
icon_item.set_icon(Some(icon.into_img(&resources_table)?.as_ref().clone()))
}
None => {
icon_item.set_icon(None)?;
icon_item.set_native_icon(None)?;
Ok(())
}
},
Icon | Submenu
)
}
struct MenuChannels(Mutex<HashMap<MenuId, Channel<MenuId>>>);
pub(crate) fn init<R: Runtime>() -> TauriPlugin<R> {
Builder::new("menu")
.setup(|app, _api| {
app.manage(MenuChannels(Mutex::default()));
Ok(())
})
.on_event(|app, e| {
if let RunEvent::MenuEvent(e) = e {
if let Some(channel) = app.state::<MenuChannels>().0.lock().unwrap().get(&e.id) {
let _ = channel.send(e.id.clone());
}
}
})
.invoke_handler(crate::generate_handler![
#![plugin(menu)]
new,
append,
prepend,
insert,
remove,
remove_at,
items,
get,
popup,
create_default,
set_as_app_menu,
set_as_window_menu,
text,
set_text,
is_enabled,
set_enabled,
set_accelerator,
set_as_windows_menu_for_nsapp,
set_as_help_menu_for_nsapp,
is_checked,
set_checked,
set_icon,
])
.build()
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/menu/builders/icon.rs | crates/tauri/src/menu/builders/icon.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{
image::Image,
menu::{IconMenuItem, MenuId, NativeIcon},
Manager, Runtime,
};
/// A builder type for [`IconMenuItem`]
pub struct IconMenuItemBuilder<'a> {
id: Option<MenuId>,
text: String,
enabled: bool,
icon: Option<Image<'a>>,
native_icon: Option<NativeIcon>,
accelerator: Option<String>,
}
impl<'a> IconMenuItemBuilder<'a> {
/// Create a new menu item builder.
///
/// - `text` could optionally contain an `&` before a character to assign this character as the mnemonic
/// for this menu item. To display a `&` without assigning a mnemenonic, use `&&`.
pub fn new<S: AsRef<str>>(text: S) -> Self {
Self {
id: None,
text: text.as_ref().to_string(),
enabled: true,
icon: None,
native_icon: None,
accelerator: None,
}
}
/// Create a new menu item builder with the specified id.
///
/// - `text` could optionally contain an `&` before a character to assign this character as the mnemonic
/// for this menu item. To display a `&` without assigning a mnemenonic, use `&&`.
pub fn with_id<I: Into<MenuId>, S: AsRef<str>>(id: I, text: S) -> Self {
Self {
id: Some(id.into()),
text: text.as_ref().to_string(),
enabled: true,
icon: None,
native_icon: None,
accelerator: None,
}
}
/// Set the id for this menu item.
pub fn id<I: Into<MenuId>>(mut self, id: I) -> Self {
self.id.replace(id.into());
self
}
/// Set the enabled state for this menu item.
pub fn enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}
/// Set the accelerator for this menu item.
pub fn accelerator<S: AsRef<str>>(mut self, accelerator: S) -> Self {
self.accelerator.replace(accelerator.as_ref().to_string());
self
}
/// Set the icon for this menu item.
///
/// **Note:** This method conflicts with [`Self::native_icon`]
/// so calling one of them, will reset the other.
pub fn icon(mut self, icon: Image<'a>) -> Self {
self.icon.replace(icon);
self.native_icon = None;
self
}
/// Set the icon for this menu item.
///
/// **Note:** This method conflicts with [`Self::icon`]
/// so calling one of them, will reset the other.
pub fn native_icon(mut self, icon: NativeIcon) -> Self {
self.native_icon.replace(icon);
self.icon = None;
self
}
/// Build the menu item
pub fn build<R: Runtime, M: Manager<R>>(self, manager: &M) -> crate::Result<IconMenuItem<R>> {
if self.icon.is_some() {
if let Some(id) = self.id {
IconMenuItem::with_id(
manager,
id,
self.text,
self.enabled,
self.icon,
self.accelerator,
)
} else {
IconMenuItem::new(
manager,
self.text,
self.enabled,
self.icon,
self.accelerator,
)
}
} else if let Some(id) = self.id {
IconMenuItem::with_id_and_native_icon(
manager,
id,
self.text,
self.enabled,
self.native_icon,
self.accelerator,
)
} else {
IconMenuItem::with_native_icon(
manager,
self.text,
self.enabled,
self.native_icon,
self.accelerator,
)
}
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/menu/builders/normal.rs | crates/tauri/src/menu/builders/normal.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{menu::MenuId, menu::MenuItem, Manager, Runtime};
/// A builder type for [`MenuItem`]
pub struct MenuItemBuilder {
id: Option<MenuId>,
text: String,
enabled: bool,
accelerator: Option<String>,
}
impl MenuItemBuilder {
/// Create a new menu item builder.
///
/// - `text` could optionally contain an `&` before a character to assign this character as the mnemonic
/// for this menu item. To display a `&` without assigning a mnemenonic, use `&&`.
pub fn new<S: AsRef<str>>(text: S) -> Self {
Self {
id: None,
text: text.as_ref().to_string(),
enabled: true,
accelerator: None,
}
}
/// Create a new menu item builder with the specified id.
///
/// - `text` could optionally contain an `&` before a character to assign this character as the mnemonic
/// for this menu item. To display a `&` without assigning a mnemenonic, use `&&`.
pub fn with_id<I: Into<MenuId>, S: AsRef<str>>(id: I, text: S) -> Self {
Self {
id: Some(id.into()),
text: text.as_ref().to_string(),
enabled: true,
accelerator: None,
}
}
/// Set the id for this menu item.
pub fn id<I: Into<MenuId>>(mut self, id: I) -> Self {
self.id.replace(id.into());
self
}
/// Set the enabled state for this menu item.
pub fn enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}
/// Set the accelerator for this menu item.
pub fn accelerator<S: AsRef<str>>(mut self, accelerator: S) -> Self {
self.accelerator.replace(accelerator.as_ref().to_string());
self
}
/// Build the menu item
pub fn build<R: Runtime, M: Manager<R>>(self, manager: &M) -> crate::Result<MenuItem<R>> {
if let Some(id) = self.id {
MenuItem::with_id(manager, id, self.text, self.enabled, self.accelerator)
} else {
MenuItem::new(manager, self.text, self.enabled, self.accelerator)
}
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/menu/builders/check.rs | crates/tauri/src/menu/builders/check.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{menu::CheckMenuItem, menu::MenuId, Manager, Runtime};
/// A builder type for [`CheckMenuItem`]
pub struct CheckMenuItemBuilder {
id: Option<MenuId>,
text: String,
enabled: bool,
checked: bool,
accelerator: Option<String>,
}
impl CheckMenuItemBuilder {
/// Create a new menu item builder.
///
/// - `text` could optionally contain an `&` before a character to assign this character as the mnemonic
/// for this menu item. To display a `&` without assigning a mnemenonic, use `&&`.
pub fn new<S: AsRef<str>>(text: S) -> Self {
Self {
id: None,
text: text.as_ref().to_string(),
enabled: true,
checked: true,
accelerator: None,
}
}
/// Create a new menu item builder with the specified id.
///
/// - `text` could optionally contain an `&` before a character to assign this character as the mnemonic
/// for this menu item. To display a `&` without assigning a mnemenonic, use `&&`.
pub fn with_id<I: Into<MenuId>, S: AsRef<str>>(id: I, text: S) -> Self {
Self {
id: Some(id.into()),
text: text.as_ref().to_string(),
enabled: true,
checked: true,
accelerator: None,
}
}
/// Set the id for this menu item.
pub fn id<I: Into<MenuId>>(mut self, id: I) -> Self {
self.id.replace(id.into());
self
}
/// Set the enabled state for this menu item.
pub fn enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}
/// Set the checked state for this menu item.
pub fn checked(mut self, checked: bool) -> Self {
self.checked = checked;
self
}
/// Set the accelerator for this menu item.
pub fn accelerator<S: AsRef<str>>(mut self, accelerator: S) -> Self {
self.accelerator.replace(accelerator.as_ref().to_string());
self
}
/// Build the menu item
pub fn build<R: Runtime, M: Manager<R>>(self, manager: &M) -> crate::Result<CheckMenuItem<R>> {
if let Some(id) = self.id {
CheckMenuItem::with_id(
manager,
id,
self.text,
self.enabled,
self.checked,
self.accelerator,
)
} else {
CheckMenuItem::new(
manager,
self.text,
self.enabled,
self.checked,
self.accelerator,
)
}
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/menu/builders/menu.rs | crates/tauri/src/menu/builders/menu.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{image::Image, menu::*, Manager, Runtime};
/// A builder type for [`Menu`]
///
/// ## Platform-specific:
///
/// - **macOS**: if using [`MenuBuilder`] for the global menubar, it can only contain [`Submenu`]s
///
/// # Example
///
/// ```no_run
/// use tauri::menu::*;
/// tauri::Builder::default()
/// .setup(move |app| {
/// let handle = app.handle();
/// # let icon1 = tauri::image::Image::new(&[], 0, 0);
/// let menu = MenuBuilder::new(handle)
/// .item(&MenuItem::new(handle, "MenuItem 1", true, None::<&str>)?)
/// .items(&[
/// &CheckMenuItem::new(handle, "CheckMenuItem 1", true, true, None::<&str>)?,
/// &IconMenuItem::new(handle, "IconMenuItem 1", true, Some(icon1), None::<&str>)?,
/// ])
/// .separator()
/// .cut()
/// .copy()
/// .paste()
/// .separator()
/// .text("item2", "MenuItem 2")
/// .check("checkitem2", "CheckMenuItem 2")
/// .icon("iconitem2", "IconMenuItem 2", app.default_window_icon().cloned().unwrap())
/// .build()?;
/// app.set_menu(menu);
/// Ok(())
/// });
/// ```
pub struct MenuBuilder<'m, R: Runtime, M: Manager<R>> {
pub(crate) id: Option<MenuId>,
pub(crate) manager: &'m M,
pub(crate) items: Vec<crate::Result<MenuItemKind<R>>>,
}
impl<'m, R: Runtime, M: Manager<R>> MenuBuilder<'m, R, M> {
/// Create a new menu builder.
pub fn new(manager: &'m M) -> Self {
Self {
id: None,
items: Vec::new(),
manager,
}
}
/// Create a new menu builder with the specified id.
pub fn with_id<I: Into<MenuId>>(manager: &'m M, id: I) -> Self {
Self {
id: Some(id.into()),
items: Vec::new(),
manager,
}
}
/// Builds this menu
pub fn build(self) -> crate::Result<Menu<R>> {
let menu = if let Some(id) = self.id {
Menu::with_id(self.manager, id)?
} else {
Menu::new(self.manager)?
};
for item in self.items {
let item = item?;
menu.append(&item)?;
}
Ok(menu)
}
}
/// A builder type for [`Submenu`]
///
/// # Example
///
/// ```no_run
/// use tauri::menu::*;
/// tauri::Builder::default()
/// .setup(move |app| {
/// let handle = app.handle();
/// # let icon1 = tauri::image::Image::new(&[], 0, 0);
/// # let icon2 = icon1.clone();
/// let menu = Menu::new(handle)?;
/// let submenu = SubmenuBuilder::new(handle, "File")
/// .item(&MenuItem::new(handle, "MenuItem 1", true, None::<&str>)?)
/// .items(&[
/// &CheckMenuItem::new(handle, "CheckMenuItem 1", true, true, None::<&str>)?,
/// &IconMenuItem::new(handle, "IconMenuItem 1", true, Some(icon1), None::<&str>)?,
/// ])
/// .separator()
/// .cut()
/// .copy()
/// .paste()
/// .separator()
/// .text("item2", "MenuItem 2")
/// .check("checkitem2", "CheckMenuItem 2")
/// .icon("iconitem2", "IconMenuItem 2", app.default_window_icon().cloned().unwrap())
/// .build()?;
/// menu.append(&submenu)?;
/// app.set_menu(menu);
/// Ok(())
/// });
/// ```
pub struct SubmenuBuilder<'m, R: Runtime, M: Manager<R>> {
pub(crate) id: Option<MenuId>,
pub(crate) manager: &'m M,
pub(crate) text: String,
pub(crate) enabled: bool,
pub(crate) items: Vec<crate::Result<MenuItemKind<R>>>,
pub(crate) icon: Option<crate::image::Image<'m>>,
pub(crate) native_icon: Option<NativeIcon>,
}
impl<'m, R: Runtime, M: Manager<R>> SubmenuBuilder<'m, R, M> {
/// Create a new submenu builder.
///
/// - `text` could optionally contain an `&` before a character to assign this character as the mnemonic
/// for this menu item. To display a `&` without assigning a mnemenonic, use `&&`.
pub fn new<S: AsRef<str>>(manager: &'m M, text: S) -> Self {
Self {
id: None,
items: Vec::new(),
text: text.as_ref().to_string(),
enabled: true,
manager,
icon: None,
native_icon: None,
}
}
/// Create a new submenu builder with the specified id.
///
/// - `text` could optionally contain an `&` before a character to assign this character as the mnemonic
/// for this menu item. To display a `&` without assigning a mnemenonic, use `&&`.
pub fn with_id<I: Into<MenuId>, S: AsRef<str>>(manager: &'m M, id: I, text: S) -> Self {
Self {
id: Some(id.into()),
text: text.as_ref().to_string(),
enabled: true,
items: Vec::new(),
manager,
icon: None,
native_icon: None,
}
}
/// Set an icon for the submenu.
/// Calling this method resets the native_icon.
pub fn submenu_icon(mut self, icon: crate::image::Image<'m>) -> Self {
self.icon = Some(icon);
self.native_icon = None;
self
}
/// Set a native icon for the submenu.
/// Calling this method resets the icon.
pub fn submenu_native_icon(mut self, icon: NativeIcon) -> Self {
self.native_icon = Some(icon);
self.icon = None;
self
}
/// Set the enabled state for the submenu.
pub fn enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}
/// Builds this submenu
pub fn build(self) -> crate::Result<Submenu<R>> {
let submenu = if let Some(id) = self.id {
if let Some(icon) = self.icon {
Submenu::with_id_and_icon(self.manager, id, self.text, self.enabled, Some(icon))?
} else if let Some(native_icon) = self.native_icon {
Submenu::with_id_and_native_icon(
self.manager,
id,
self.text,
self.enabled,
Some(native_icon),
)?
} else {
Submenu::with_id(self.manager, id, self.text, self.enabled)?
}
} else if let Some(icon) = self.icon {
Submenu::new_with_icon(self.manager, self.text, self.enabled, Some(icon))?
} else if let Some(native_icon) = self.native_icon {
Submenu::new_with_native_icon(self.manager, self.text, self.enabled, Some(native_icon))?
} else {
Submenu::new(self.manager, self.text, self.enabled)?
};
for item in self.items {
let item = item?;
submenu.append(&item)?;
}
Ok(submenu)
}
}
macro_rules! shared_menu_builder {
($menu: ty) => {
impl<'m, R: Runtime, M: Manager<R>> $menu {
/// Set the id for this menu.
pub fn id<I: Into<MenuId>>(mut self, id: I) -> Self {
self.id.replace(id.into());
self
}
/// Add this item to the menu.
pub fn item(mut self, item: &dyn IsMenuItem<R>) -> Self {
self.items.push(Ok(item.kind()));
self
}
/// Add these items to the menu.
pub fn items(mut self, items: &[&dyn IsMenuItem<R>]) -> Self {
for item in items {
self = self.item(*item);
}
self
}
/// Add a [MenuItem] to the menu.
pub fn text<I: Into<MenuId>, S: AsRef<str>>(mut self, id: I, text: S) -> Self {
self
.items
.push(MenuItem::with_id(self.manager, id, text, true, None::<&str>).map(|i| i.kind()));
self
}
/// Add a [CheckMenuItem] to the menu.
pub fn check<I: Into<MenuId>, S: AsRef<str>>(mut self, id: I, text: S) -> Self {
self.items.push(
CheckMenuItem::with_id(self.manager, id, text, true, true, None::<&str>)
.map(|i| i.kind()),
);
self
}
/// Add an [IconMenuItem] to the menu.
pub fn icon<I: Into<MenuId>, S: AsRef<str>>(
mut self,
id: I,
text: S,
icon: Image<'_>,
) -> Self {
self.items.push(
IconMenuItem::with_id(self.manager, id, text, true, Some(icon), None::<&str>)
.map(|i| i.kind()),
);
self
}
/// Add an [IconMenuItem] with a native icon to the menu.
///
/// ## Platform-specific:
///
/// - **Windows / Linux**: Unsupported.
pub fn native_icon<I: Into<MenuId>, S: AsRef<str>>(
mut self,
id: I,
text: S,
icon: NativeIcon,
) -> Self {
self.items.push(
IconMenuItem::with_id_and_native_icon(
self.manager,
id,
text,
true,
Some(icon),
None::<&str>,
)
.map(|i| i.kind()),
);
self
}
/// Add Separator menu item to the menu.
pub fn separator(mut self) -> Self {
self
.items
.push(PredefinedMenuItem::separator(self.manager).map(|i| i.kind()));
self
}
/// Add Copy menu item to the menu.
pub fn copy(mut self) -> Self {
self
.items
.push(PredefinedMenuItem::copy(self.manager, None).map(|i| i.kind()));
self
}
/// Add Copy menu item with specified text to the menu.
pub fn copy_with_text<S: AsRef<str>>(mut self, text: S) -> Self {
self
.items
.push(PredefinedMenuItem::copy(self.manager, Some(text.as_ref())).map(|i| i.kind()));
self
}
/// Add Cut menu item to the menu.
pub fn cut(mut self) -> Self {
self
.items
.push(PredefinedMenuItem::cut(self.manager, None).map(|i| i.kind()));
self
}
/// Add Cut menu item with specified text to the menu.
pub fn cut_with_text<S: AsRef<str>>(mut self, text: S) -> Self {
self
.items
.push(PredefinedMenuItem::cut(self.manager, Some(text.as_ref())).map(|i| i.kind()));
self
}
/// Add Paste menu item to the menu.
pub fn paste(mut self) -> Self {
self
.items
.push(PredefinedMenuItem::paste(self.manager, None).map(|i| i.kind()));
self
}
/// Add Paste menu item with specified text to the menu.
pub fn paste_with_text<S: AsRef<str>>(mut self, text: S) -> Self {
self
.items
.push(PredefinedMenuItem::paste(self.manager, Some(text.as_ref())).map(|i| i.kind()));
self
}
/// Add SelectAll menu item to the menu.
pub fn select_all(mut self) -> Self {
self
.items
.push(PredefinedMenuItem::select_all(self.manager, None).map(|i| i.kind()));
self
}
/// Add SelectAll menu item with specified text to the menu.
pub fn select_all_with_text<S: AsRef<str>>(mut self, text: S) -> Self {
self.items.push(
PredefinedMenuItem::select_all(self.manager, Some(text.as_ref())).map(|i| i.kind()),
);
self
}
/// Add Undo menu item to the menu.
///
/// ## Platform-specific:
///
/// - **Windows / Linux:** Unsupported.
pub fn undo(mut self) -> Self {
self
.items
.push(PredefinedMenuItem::undo(self.manager, None).map(|i| i.kind()));
self
}
/// Add Undo menu item with specified text to the menu.
///
/// ## Platform-specific:
///
/// - **Windows / Linux:** Unsupported.
pub fn undo_with_text<S: AsRef<str>>(mut self, text: S) -> Self {
self
.items
.push(PredefinedMenuItem::undo(self.manager, Some(text.as_ref())).map(|i| i.kind()));
self
}
/// Add Redo menu item to the menu.
///
/// ## Platform-specific:
///
/// - **Windows / Linux:** Unsupported.
pub fn redo(mut self) -> Self {
self
.items
.push(PredefinedMenuItem::redo(self.manager, None).map(|i| i.kind()));
self
}
/// Add Redo menu item with specified text to the menu.
///
/// ## Platform-specific:
///
/// - **Windows / Linux:** Unsupported.
pub fn redo_with_text<S: AsRef<str>>(mut self, text: S) -> Self {
self
.items
.push(PredefinedMenuItem::redo(self.manager, Some(text.as_ref())).map(|i| i.kind()));
self
}
/// Add Minimize window menu item to the menu.
///
/// ## Platform-specific:
///
/// - **Linux:** Unsupported.
pub fn minimize(mut self) -> Self {
self
.items
.push(PredefinedMenuItem::minimize(self.manager, None).map(|i| i.kind()));
self
}
/// Add Minimize window menu item with specified text to the menu.
///
/// ## Platform-specific:
///
/// - **Linux:** Unsupported.
pub fn minimize_with_text<S: AsRef<str>>(mut self, text: S) -> Self {
self
.items
.push(PredefinedMenuItem::minimize(self.manager, Some(text.as_ref())).map(|i| i.kind()));
self
}
/// Add Maximize window menu item to the menu.
///
/// ## Platform-specific:
///
/// - **Linux:** Unsupported.
pub fn maximize(mut self) -> Self {
self
.items
.push(PredefinedMenuItem::maximize(self.manager, None).map(|i| i.kind()));
self
}
/// Add Maximize window menu item with specified text to the menu.
///
/// ## Platform-specific:
///
/// - **Linux:** Unsupported.
pub fn maximize_with_text<S: AsRef<str>>(mut self, text: S) -> Self {
self
.items
.push(PredefinedMenuItem::maximize(self.manager, Some(text.as_ref())).map(|i| i.kind()));
self
}
/// Add Fullscreen menu item to the menu.
///
/// ## Platform-specific:
///
/// - **Windows / Linux:** Unsupported.
pub fn fullscreen(mut self) -> Self {
self
.items
.push(PredefinedMenuItem::fullscreen(self.manager, None).map(|i| i.kind()));
self
}
/// Add Fullscreen menu item with specified text to the menu.
///
/// ## Platform-specific:
///
/// - **Windows / Linux:** Unsupported.
pub fn fullscreen_with_text<S: AsRef<str>>(mut self, text: S) -> Self {
self.items.push(
PredefinedMenuItem::fullscreen(self.manager, Some(text.as_ref())).map(|i| i.kind()),
);
self
}
/// Add Hide window menu item to the menu.
///
/// ## Platform-specific:
///
/// - **Linux:** Unsupported.
pub fn hide(mut self) -> Self {
self
.items
.push(PredefinedMenuItem::hide(self.manager, None).map(|i| i.kind()));
self
}
/// Add Hide window menu item with specified text to the menu.
///
/// ## Platform-specific:
///
/// - **Linux:** Unsupported.
pub fn hide_with_text<S: AsRef<str>>(mut self, text: S) -> Self {
self
.items
.push(PredefinedMenuItem::hide(self.manager, Some(text.as_ref())).map(|i| i.kind()));
self
}
/// Add Hide other windows menu item to the menu.
///
/// ## Platform-specific:
///
/// - **Linux:** Unsupported.
pub fn hide_others(mut self) -> Self {
self
.items
.push(PredefinedMenuItem::hide_others(self.manager, None).map(|i| i.kind()));
self
}
/// Add Hide other windows menu item with specified text to the menu.
///
/// ## Platform-specific:
///
/// - **Linux:** Unsupported.
pub fn hide_others_with_text<S: AsRef<str>>(mut self, text: S) -> Self {
self.items.push(
PredefinedMenuItem::hide_others(self.manager, Some(text.as_ref())).map(|i| i.kind()),
);
self
}
/// Add Show all app windows menu item to the menu.
///
/// ## Platform-specific:
///
/// - **Windows / Linux:** Unsupported.
pub fn show_all(mut self) -> Self {
self
.items
.push(PredefinedMenuItem::show_all(self.manager, None).map(|i| i.kind()));
self
}
/// Add Show all app windows menu item with specified text to the menu.
///
/// ## Platform-specific:
///
/// - **Windows / Linux:** Unsupported.
pub fn show_all_with_text<S: AsRef<str>>(mut self, text: S) -> Self {
self
.items
.push(PredefinedMenuItem::show_all(self.manager, Some(text.as_ref())).map(|i| i.kind()));
self
}
/// Add Close window menu item to the menu.
///
/// ## Platform-specific:
///
/// - **Linux:** Unsupported.
pub fn close_window(mut self) -> Self {
self
.items
.push(PredefinedMenuItem::close_window(self.manager, None).map(|i| i.kind()));
self
}
/// Add Close window menu item with specified text to the menu.
///
/// ## Platform-specific:
///
/// - **Linux:** Unsupported.
pub fn close_window_with_text<S: AsRef<str>>(mut self, text: S) -> Self {
self.items.push(
PredefinedMenuItem::close_window(self.manager, Some(text.as_ref())).map(|i| i.kind()),
);
self
}
/// Add Quit app menu item to the menu.
///
/// ## Platform-specific:
///
/// - **Linux:** Unsupported.
pub fn quit(mut self) -> Self {
self
.items
.push(PredefinedMenuItem::quit(self.manager, None).map(|i| i.kind()));
self
}
/// Add Quit app menu item with specified text to the menu.
///
/// ## Platform-specific:
///
/// - **Linux:** Unsupported.
pub fn quit_with_text<S: AsRef<str>>(mut self, text: S) -> Self {
self
.items
.push(PredefinedMenuItem::quit(self.manager, Some(text.as_ref())).map(|i| i.kind()));
self
}
/// Add About app menu item to the menu.
pub fn about(mut self, metadata: Option<AboutMetadata<'_>>) -> Self {
self
.items
.push(PredefinedMenuItem::about(self.manager, None, metadata).map(|i| i.kind()));
self
}
/// Add About app menu item with specified text to the menu.
pub fn about_with_text<S: AsRef<str>>(
mut self,
text: S,
metadata: Option<AboutMetadata<'_>>,
) -> Self {
self.items.push(
PredefinedMenuItem::about(self.manager, Some(text.as_ref()), metadata).map(|i| i.kind()),
);
self
}
/// Add Services menu item to the menu.
///
/// ## Platform-specific:
///
/// - **Windows / Linux:** Unsupported.
pub fn services(mut self) -> Self {
self
.items
.push(PredefinedMenuItem::services(self.manager, None).map(|i| i.kind()));
self
}
/// Add Services menu item with specified text to the menu.
///
/// ## Platform-specific:
///
/// - **Windows / Linux:** Unsupported.
pub fn services_with_text<S: AsRef<str>>(mut self, text: S) -> Self {
self
.items
.push(PredefinedMenuItem::services(self.manager, Some(text.as_ref())).map(|i| i.kind()));
self
}
}
};
}
shared_menu_builder!(MenuBuilder<'m, R, M>);
shared_menu_builder!(SubmenuBuilder<'m, R, M>);
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/menu/builders/mod.rs | crates/tauri/src/menu/builders/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
#![cfg(desktop)]
//! A module containing menu builder types
mod menu;
pub use menu::MenuBuilder;
pub use menu::SubmenuBuilder;
mod normal;
pub use normal::MenuItemBuilder;
mod check;
pub use check::CheckMenuItemBuilder;
mod icon;
pub use icon::IconMenuItemBuilder;
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/webview/webview_window.rs | crates/tauri/src/webview/webview_window.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! [`Window`] that hosts a single [`Webview`].
use std::{
borrow::Cow,
path::{Path, PathBuf},
sync::{Arc, MutexGuard},
};
use crate::{
event::EventTarget,
ipc::ScopeObject,
runtime::dpi::{PhysicalPosition, PhysicalSize},
webview::{NewWindowResponse, ScrollBarStyle},
window::Monitor,
Emitter, EventName, Listener, ResourceTable, Window,
};
#[cfg(desktop)]
use crate::{
image::Image,
menu::{ContextMenu, Menu},
runtime::{
dpi::{Position, Size},
window::CursorIcon,
UserAttentionType,
},
};
use tauri_runtime::webview::NewWindowFeatures;
use tauri_utils::config::{BackgroundThrottlingPolicy, Color, WebviewUrl, WindowConfig};
use url::Url;
use crate::{
ipc::{CommandArg, CommandItem, InvokeError, OwnedInvokeResponder},
manager::AppManager,
sealed::{ManagerBase, RuntimeOrDispatch},
webview::{Cookie, PageLoadPayload, WebviewBuilder, WebviewEvent},
window::WindowBuilder,
AppHandle, Event, EventId, Manager, Runtime, Webview, WindowEvent,
};
use tauri_macros::default_runtime;
#[cfg(windows)]
use windows::Win32::Foundation::HWND;
use super::{DownloadEvent, ResolvedScope};
/// A builder for [`WebviewWindow`], a window that hosts a single webview.
pub struct WebviewWindowBuilder<'a, R: Runtime, M: Manager<R>> {
window_builder: WindowBuilder<'a, R, M>,
webview_builder: WebviewBuilder<R>,
}
impl<'a, R: Runtime, M: Manager<R>> WebviewWindowBuilder<'a, R, M> {
/// Initializes a webview window builder with the given window label.
///
/// # Known issues
///
/// On Windows, this function deadlocks when used in a synchronous command and event handlers, see [the Webview2 issue].
/// You should use `async` commands and separate threads when creating windows.
///
/// # Examples
///
/// - Create a window in the setup hook:
///
/// ```
/// tauri::Builder::default()
/// .setup(|app| {
/// let webview_window = tauri::WebviewWindowBuilder::new(app, "label", tauri::WebviewUrl::App("index.html".into()))
/// .build()?;
/// Ok(())
/// });
/// ```
///
/// - Create a window in a separate thread:
///
/// ```
/// tauri::Builder::default()
/// .setup(|app| {
/// let handle = app.handle().clone();
/// std::thread::spawn(move || {
/// let webview_window = tauri::WebviewWindowBuilder::new(&handle, "label", tauri::WebviewUrl::App("index.html".into()))
/// .build()
/// .unwrap();
/// });
/// Ok(())
/// });
/// ```
///
/// - Create a window in a command:
///
/// ```
/// #[tauri::command]
/// async fn create_window(app: tauri::AppHandle) {
/// let webview_window = tauri::WebviewWindowBuilder::new(&app, "label", tauri::WebviewUrl::App("index.html".into()))
/// .build()
/// .unwrap();
/// }
/// ```
///
/// [the Webview2 issue]: https://github.com/tauri-apps/wry/issues/583
pub fn new<L: Into<String>>(manager: &'a M, label: L, url: WebviewUrl) -> Self {
let label = label.into();
Self {
window_builder: WindowBuilder::new(manager, &label),
webview_builder: WebviewBuilder::new(&label, url),
}
}
/// Initializes a webview window builder from a [`WindowConfig`] from tauri.conf.json.
/// Keep in mind that you can't create 2 windows with the same `label` so make sure
/// that the initial window was closed or change the label of the cloned [`WindowConfig`].
///
/// # Known issues
///
/// On Windows, this function deadlocks when used in a synchronous command or event handlers, see [the Webview2 issue].
/// You should use `async` commands and separate threads when creating windows.
///
/// # Examples
///
/// - Create a window in a command:
///
/// ```
/// #[tauri::command]
/// async fn reopen_window(app: tauri::AppHandle) {
/// let webview_window = tauri::WebviewWindowBuilder::from_config(&app, &app.config().app.windows.get(0).unwrap())
/// .unwrap()
/// .build()
/// .unwrap();
/// }
/// ```
///
/// - Create a window in a command from a config with a specific label, and change its label so multiple instances can exist:
///
/// ```
/// #[tauri::command]
/// async fn open_window_multiple(app: tauri::AppHandle) {
/// let mut conf = app.config().app.windows.iter().find(|c| c.label == "template-for-multiwindow").unwrap().clone();
/// // This should be a unique label for all windows. For example, we can use a random suffix:
/// let mut buf = [0u8; 1];
/// assert_eq!(getrandom::fill(&mut buf), Ok(()));
/// conf.label = format!("my-multiwindow-{}", buf[0]);
/// let webview_window = tauri::WebviewWindowBuilder::from_config(&app, &conf)
/// .unwrap()
/// .build()
/// .unwrap();
/// }
/// ```
///
/// [the Webview2 issue]: https://github.com/tauri-apps/wry/issues/583
pub fn from_config(manager: &'a M, config: &WindowConfig) -> crate::Result<Self> {
Ok(Self {
window_builder: WindowBuilder::from_config(manager, config)?,
webview_builder: WebviewBuilder::from_config(config),
})
}
/// Registers a global menu event listener.
///
/// Note that this handler is called for any menu event,
/// whether it is coming from this window, another window or from the tray icon menu.
///
/// Also note that this handler will not be called if
/// the window used to register it was closed.
///
/// # Examples
/// ```
/// use tauri::menu::{Menu, Submenu, MenuItem};
/// tauri::Builder::default()
/// .setup(|app| {
/// let handle = app.handle();
/// let save_menu_item = MenuItem::new(handle, "Save", true, None::<&str>)?;
/// let menu = Menu::with_items(handle, &[
/// &Submenu::with_items(handle, "File", true, &[
/// &save_menu_item,
/// ])?,
/// ])?;
/// let webview_window = tauri::WebviewWindowBuilder::new(app, "editor", tauri::WebviewUrl::App("index.html".into()))
/// .menu(menu)
/// .on_menu_event(move |window, event| {
/// if event.id == save_menu_item.id() {
/// // save menu item
/// }
/// })
/// .build()
/// .unwrap();
///
/// Ok(())
/// });
/// ```
#[cfg(desktop)]
pub fn on_menu_event<F: Fn(&crate::Window<R>, crate::menu::MenuEvent) + Send + Sync + 'static>(
mut self,
f: F,
) -> Self {
self.window_builder = self.window_builder.on_menu_event(f);
self
}
/// Defines a closure to be executed when the webview makes an HTTP request for a web resource, allowing you to modify the response.
///
/// Currently only implemented for the `tauri` URI protocol.
///
/// **NOTE:** Currently this is **not** executed when using external URLs such as a development server,
/// but it might be implemented in the future. **Always** check the request URL.
///
/// # Examples
/// ```rust,no_run
/// use tauri::{
/// utils::config::{Csp, CspDirectiveSources, WebviewUrl},
/// webview::WebviewWindowBuilder,
/// };
/// use http::header::HeaderValue;
/// use std::collections::HashMap;
/// tauri::Builder::default()
/// .setup(|app| {
/// let webview_window = WebviewWindowBuilder::new(app, "core", WebviewUrl::App("index.html".into()))
/// .on_web_resource_request(|request, response| {
/// if request.uri().scheme_str() == Some("tauri") {
/// // if we have a CSP header, Tauri is loading an HTML file
/// // for this example, let's dynamically change the CSP
/// if let Some(csp) = response.headers_mut().get_mut("Content-Security-Policy") {
/// // use the tauri helper to parse the CSP policy to a map
/// let mut csp_map: HashMap<String, CspDirectiveSources> = Csp::Policy(csp.to_str().unwrap().to_string()).into();
/// csp_map.entry("script-src".to_string()).or_insert_with(Default::default).push("'unsafe-inline'");
/// // use the tauri helper to get a CSP string from the map
/// let csp_string = Csp::from(csp_map).to_string();
/// *csp = HeaderValue::from_str(&csp_string).unwrap();
/// }
/// }
/// })
/// .build()?;
/// Ok(())
/// });
/// ```
pub fn on_web_resource_request<
F: Fn(http::Request<Vec<u8>>, &mut http::Response<Cow<'static, [u8]>>) + Send + Sync + 'static,
>(
mut self,
f: F,
) -> Self {
self.webview_builder = self.webview_builder.on_web_resource_request(f);
self
}
/// Defines a closure to be executed when the webview navigates to a URL. Returning `false` cancels the navigation.
///
/// # Examples
/// ```rust,no_run
/// use tauri::{
/// utils::config::{Csp, CspDirectiveSources, WebviewUrl},
/// webview::WebviewWindowBuilder,
/// };
/// use http::header::HeaderValue;
/// use std::collections::HashMap;
/// tauri::Builder::default()
/// .setup(|app| {
/// let webview_window = WebviewWindowBuilder::new(app, "core", WebviewUrl::App("index.html".into()))
/// .on_navigation(|url| {
/// // allow the production URL or localhost on dev
/// url.scheme() == "tauri" || (cfg!(dev) && url.host_str() == Some("localhost"))
/// })
/// .build()?;
/// Ok(())
/// });
/// ```
pub fn on_navigation<F: Fn(&Url) -> bool + Send + 'static>(mut self, f: F) -> Self {
self.webview_builder = self.webview_builder.on_navigation(f);
self
}
/// Set a new window request handler to decide if incoming url is allowed to be opened.
///
/// A new window is requested to be opened by the [window.open] API.
///
/// The closure take the URL to open and the window features object and returns [`NewWindowResponse`] to determine whether the window should open.
///
/// # Examples
/// ```rust,no_run
/// use tauri::{
/// utils::config::WebviewUrl,
/// webview::WebviewWindowBuilder,
/// };
/// use http::header::HeaderValue;
/// use std::collections::HashMap;
/// tauri::Builder::default()
/// .setup(|app| {
/// let app_ = app.handle().clone();
/// let webview_window = WebviewWindowBuilder::new(app, "core", WebviewUrl::App("index.html".into()))
/// .on_new_window(move |url, features| {
/// let builder = tauri::WebviewWindowBuilder::new(
/// &app_,
/// // note: add an ID counter or random label generator to support multiple opened windows at the same time
/// "opened-window",
/// tauri::WebviewUrl::External("about:blank".parse().unwrap()),
/// )
/// .window_features(features)
/// .on_document_title_changed(|window, title| {
/// window.set_title(&title).unwrap();
/// })
/// .title(url.as_str());
///
/// let window = builder.build().unwrap();
/// tauri::webview::NewWindowResponse::Create { window }
/// })
/// .build()?;
/// Ok(())
/// });
/// ```
///
/// # Platform-specific
///
/// - **Android / iOS**: Not supported.
/// - **Windows**: The closure is executed on a separate thread to prevent a deadlock.
///
/// [window.open]: https://developer.mozilla.org/en-US/docs/Web/API/Window/open
pub fn on_new_window<
F: Fn(Url, NewWindowFeatures) -> NewWindowResponse<R> + Send + Sync + 'static,
>(
mut self,
f: F,
) -> Self {
self.webview_builder = self.webview_builder.on_new_window(f);
self
}
/// Defines a closure to be executed when the document title changes.
///
/// Note that it may run before or after the navigation event.
pub fn on_document_title_changed<F: Fn(WebviewWindow<R>, String) + Send + 'static>(
mut self,
f: F,
) -> Self {
self.webview_builder = self
.webview_builder
.on_document_title_changed(move |webview, url| {
f(
WebviewWindow {
window: webview.window(),
webview,
},
url,
)
});
self
}
/// Set a download event handler to be notified when a download is requested or finished.
///
/// Returning `false` prevents the download from happening on a [`DownloadEvent::Requested`] event.
///
/// # Examples
///
#[cfg_attr(
feature = "unstable",
doc = r####"
```rust,no_run
use tauri::{
utils::config::{Csp, CspDirectiveSources, WebviewUrl},
webview::{DownloadEvent, WebviewWindowBuilder},
};
tauri::Builder::default()
.setup(|app| {
let handle = app.handle();
let webview_window = WebviewWindowBuilder::new(handle, "core", WebviewUrl::App("index.html".into()))
.on_download(|webview, event| {
match event {
DownloadEvent::Requested { url, destination } => {
println!("downloading {}", url);
*destination = "/home/tauri/target/path".into();
}
DownloadEvent::Finished { url, path, success } => {
println!("downloaded {} to {:?}, success: {}", url, path, success);
}
_ => (),
}
// let the download start
true
})
.build()?;
Ok(())
});
```
"####
)]
pub fn on_download<F: Fn(Webview<R>, DownloadEvent<'_>) -> bool + Send + Sync + 'static>(
mut self,
f: F,
) -> Self {
self.webview_builder.download_handler.replace(Arc::new(f));
self
}
/// Defines a closure to be executed when a page load event is triggered.
/// The event can be either [`tauri_runtime::webview::PageLoadEvent::Started`] if the page has started loading
/// or [`tauri_runtime::webview::PageLoadEvent::Finished`] when the page finishes loading.
///
/// # Examples
/// ```rust,no_run
/// use tauri::{
/// utils::config::{Csp, CspDirectiveSources, WebviewUrl},
/// webview::{PageLoadEvent, WebviewWindowBuilder},
/// };
/// use http::header::HeaderValue;
/// use std::collections::HashMap;
/// tauri::Builder::default()
/// .setup(|app| {
/// let webview_window = WebviewWindowBuilder::new(app, "core", WebviewUrl::App("index.html".into()))
/// .on_page_load(|window, payload| {
/// match payload.event() {
/// PageLoadEvent::Started => {
/// println!("{} finished loading", payload.url());
/// }
/// PageLoadEvent::Finished => {
/// println!("{} finished loading", payload.url());
/// }
/// }
/// })
/// .build()?;
/// Ok(())
/// });
/// ```
pub fn on_page_load<F: Fn(WebviewWindow<R>, PageLoadPayload<'_>) + Send + Sync + 'static>(
mut self,
f: F,
) -> Self {
self.webview_builder = self.webview_builder.on_page_load(move |webview, payload| {
f(
WebviewWindow {
window: webview.window(),
webview,
},
payload,
)
});
self
}
/// Creates a new window.
pub fn build(self) -> crate::Result<WebviewWindow<R>> {
let (window, webview) = self.window_builder.with_webview(self.webview_builder)?;
Ok(WebviewWindow { window, webview })
}
}
/// Desktop APIs.
#[cfg(desktop)]
impl<'a, R: Runtime, M: Manager<R>> WebviewWindowBuilder<'a, R, M> {
/// Sets the menu for the window.
#[must_use]
pub fn menu(mut self, menu: crate::menu::Menu<R>) -> Self {
self.window_builder = self.window_builder.menu(menu);
self
}
/// Show window in the center of the screen.
#[must_use]
pub fn center(mut self) -> Self {
self.window_builder = self.window_builder.center();
self
}
/// The initial position of the window in logical pixels.
#[must_use]
pub fn position(mut self, x: f64, y: f64) -> Self {
self.window_builder = self.window_builder.position(x, y);
self
}
/// Window size in logical pixels.
#[must_use]
pub fn inner_size(mut self, width: f64, height: f64) -> Self {
self.window_builder = self.window_builder.inner_size(width, height);
self
}
/// Window min inner size in logical pixels.
#[must_use]
pub fn min_inner_size(mut self, min_width: f64, min_height: f64) -> Self {
self.window_builder = self.window_builder.min_inner_size(min_width, min_height);
self
}
/// Window max inner size in logical pixels.
#[must_use]
pub fn max_inner_size(mut self, max_width: f64, max_height: f64) -> Self {
self.window_builder = self.window_builder.max_inner_size(max_width, max_height);
self
}
/// Window inner size constraints.
#[must_use]
pub fn inner_size_constraints(
mut self,
constraints: tauri_runtime::window::WindowSizeConstraints,
) -> Self {
self.window_builder = self.window_builder.inner_size_constraints(constraints);
self
}
/// Prevent the window from overflowing the working area (e.g. monitor size - taskbar size)
/// on creation, which means the window size will be limited to `monitor size - taskbar size`
///
/// **NOTE**: The overflow check is only performed on window creation, resizes can still overflow
///
/// ## Platform-specific
///
/// - **iOS / Android:** Unsupported.
#[must_use]
pub fn prevent_overflow(mut self) -> Self {
self.window_builder = self.window_builder.prevent_overflow();
self
}
/// Prevent the window from overflowing the working area (e.g. monitor size - taskbar size)
/// on creation with a margin, which means the window size will be limited to `monitor size - taskbar size - margin size`
///
/// **NOTE**: The overflow check is only performed on window creation, resizes can still overflow
///
/// ## Platform-specific
///
/// - **iOS / Android:** Unsupported.
#[must_use]
pub fn prevent_overflow_with_margin(mut self, margin: impl Into<Size>) -> Self {
self.window_builder = self.window_builder.prevent_overflow_with_margin(margin);
self
}
/// Whether the window is resizable or not.
/// When resizable is set to false, native window's maximize button is automatically disabled.
#[must_use]
pub fn resizable(mut self, resizable: bool) -> Self {
self.window_builder = self.window_builder.resizable(resizable);
self
}
/// Whether the window's native maximize button is enabled or not.
/// If resizable is set to false, this setting is ignored.
///
/// ## Platform-specific
///
/// - **macOS:** Disables the "zoom" button in the window titlebar, which is also used to enter fullscreen mode.
/// - **Linux / iOS / Android:** Unsupported.
#[must_use]
pub fn maximizable(mut self, maximizable: bool) -> Self {
self.window_builder = self.window_builder.maximizable(maximizable);
self
}
/// Whether the window's native minimize button is enabled or not.
///
/// ## Platform-specific
///
/// - **Linux / iOS / Android:** Unsupported.
#[must_use]
pub fn minimizable(mut self, minimizable: bool) -> Self {
self.window_builder = self.window_builder.minimizable(minimizable);
self
}
/// Whether the window's native close button is enabled or not.
///
/// ## Platform-specific
///
/// - **Linux:** "GTK+ will do its best to convince the window manager not to show a close button.
/// Depending on the system, this function may not have any effect when called on a window that is already visible"
/// - **iOS / Android:** Unsupported.
#[must_use]
pub fn closable(mut self, closable: bool) -> Self {
self.window_builder = self.window_builder.closable(closable);
self
}
/// The title of the window in the title bar.
#[must_use]
pub fn title<S: Into<String>>(mut self, title: S) -> Self {
self.window_builder = self.window_builder.title(title);
self
}
/// Whether to start the window in fullscreen or not.
#[must_use]
pub fn fullscreen(mut self, fullscreen: bool) -> Self {
self.window_builder = self.window_builder.fullscreen(fullscreen);
self
}
/// Sets the window to be initially focused.
#[must_use]
#[deprecated(
since = "1.2.0",
note = "The window is automatically focused by default. This function Will be removed in 3.0.0. Use `focused` instead."
)]
pub fn focus(mut self) -> Self {
self.window_builder = self.window_builder.focused(true);
self.webview_builder = self.webview_builder.focused(true);
self
}
/// Whether the window will be focusable or not.
#[must_use]
pub fn focusable(mut self, focusable: bool) -> Self {
self.window_builder = self.window_builder.focusable(focusable);
self
}
/// Whether the window will be initially focused or not.
#[must_use]
pub fn focused(mut self, focused: bool) -> Self {
self.window_builder = self.window_builder.focused(focused);
self.webview_builder = self.webview_builder.focused(focused);
self
}
/// Whether the window should be maximized upon creation.
#[must_use]
pub fn maximized(mut self, maximized: bool) -> Self {
self.window_builder = self.window_builder.maximized(maximized);
self
}
/// Whether the window should be immediately visible upon creation.
#[must_use]
pub fn visible(mut self, visible: bool) -> Self {
self.window_builder = self.window_builder.visible(visible);
self
}
/// Forces a theme or uses the system settings if None was provided.
///
/// ## Platform-specific
///
/// - **macOS**: Only supported on macOS 10.14+.
#[must_use]
pub fn theme(mut self, theme: Option<crate::Theme>) -> Self {
self.window_builder = self.window_builder.theme(theme);
self
}
/// Whether the window should have borders and bars.
#[must_use]
pub fn decorations(mut self, decorations: bool) -> Self {
self.window_builder = self.window_builder.decorations(decorations);
self
}
/// Whether the window should always be below other windows.
#[must_use]
pub fn always_on_bottom(mut self, always_on_bottom: bool) -> Self {
self.window_builder = self.window_builder.always_on_bottom(always_on_bottom);
self
}
/// Whether the window should always be on top of other windows.
#[must_use]
pub fn always_on_top(mut self, always_on_top: bool) -> Self {
self.window_builder = self.window_builder.always_on_top(always_on_top);
self
}
/// Whether the window will be visible on all workspaces or virtual desktops.
#[must_use]
pub fn visible_on_all_workspaces(mut self, visible_on_all_workspaces: bool) -> Self {
self.window_builder = self
.window_builder
.visible_on_all_workspaces(visible_on_all_workspaces);
self
}
/// Prevents the window contents from being captured by other apps.
#[must_use]
pub fn content_protected(mut self, protected: bool) -> Self {
self.window_builder = self.window_builder.content_protected(protected);
self
}
/// Sets the window icon.
pub fn icon(mut self, icon: Image<'a>) -> crate::Result<Self> {
self.window_builder = self.window_builder.icon(icon)?;
Ok(self)
}
/// Sets whether or not the window icon should be hidden from the taskbar.
///
/// ## Platform-specific
///
/// - **macOS**: Unsupported.
#[must_use]
pub fn skip_taskbar(mut self, skip: bool) -> Self {
self.window_builder = self.window_builder.skip_taskbar(skip);
self
}
/// Sets custom name for Windows' window class. **Windows only**.
#[must_use]
pub fn window_classname<S: Into<String>>(mut self, classname: S) -> Self {
self.window_builder = self.window_builder.window_classname(classname);
self
}
/// Sets whether or not the window has shadow.
///
/// ## Platform-specific
///
/// - **Windows:**
/// - `false` has no effect on decorated window, shadows are always ON.
/// - `true` will make undecorated window have a 1px white border,
/// and on Windows 11, it will have a rounded corners.
/// - **Linux:** Unsupported.
#[must_use]
pub fn shadow(mut self, enable: bool) -> Self {
self.window_builder = self.window_builder.shadow(enable);
self
}
/// Sets a parent to the window to be created.
///
/// ## Platform-specific
///
/// - **Windows**: This sets the passed parent as an owner window to the window to be created.
/// From [MSDN owned windows docs](https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows):
/// - An owned window is always above its owner in the z-order.
/// - The system automatically destroys an owned window when its owner is destroyed.
/// - An owned window is hidden when its owner is minimized.
/// - **Linux**: This makes the new window transient for parent, see <https://docs.gtk.org/gtk3/method.Window.set_transient_for.html>
/// - **macOS**: This adds the window as a child of parent, see <https://developer.apple.com/documentation/appkit/nswindow/1419152-addchildwindow?language=objc>
pub fn parent(mut self, parent: &WebviewWindow<R>) -> crate::Result<Self> {
self.window_builder = self.window_builder.parent(&parent.window)?;
Ok(self)
}
/// Set an owner to the window to be created.
///
/// From MSDN:
/// - An owned window is always above its owner in the z-order.
/// - The system automatically destroys an owned window when its owner is destroyed.
/// - An owned window is hidden when its owner is minimized.
///
/// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows>
#[cfg(windows)]
pub fn owner(mut self, owner: &WebviewWindow<R>) -> crate::Result<Self> {
self.window_builder = self.window_builder.owner(&owner.window)?;
Ok(self)
}
/// Set an owner to the window to be created.
///
/// From MSDN:
/// - An owned window is always above its owner in the z-order.
/// - The system automatically destroys an owned window when its owner is destroyed.
/// - An owned window is hidden when its owner is minimized.
///
/// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows>
#[cfg(windows)]
#[must_use]
pub fn owner_raw(mut self, owner: HWND) -> Self {
self.window_builder = self.window_builder.owner_raw(owner);
self
}
/// Sets a parent to the window to be created.
///
/// A child window has the WS_CHILD style and is confined to the client area of its parent window.
///
/// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#child-windows>
#[cfg(windows)]
#[must_use]
pub fn parent_raw(mut self, parent: HWND) -> Self {
self.window_builder = self.window_builder.parent_raw(parent);
self
}
/// Sets a parent to the window to be created.
///
/// See <https://developer.apple.com/documentation/appkit/nswindow/1419152-addchildwindow?language=objc>
#[cfg(target_os = "macos")]
#[must_use]
pub fn parent_raw(mut self, parent: *mut std::ffi::c_void) -> Self {
self.window_builder = self.window_builder.parent_raw(parent);
self
}
/// Sets the window to be created transient for parent.
///
/// See <https://docs.gtk.org/gtk3/method.Window.set_transient_for.html>
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
pub fn transient_for(mut self, parent: &WebviewWindow<R>) -> crate::Result<Self> {
self.window_builder = self.window_builder.transient_for(&parent.window)?;
Ok(self)
}
/// Sets the window to be created transient for parent.
///
/// See <https://docs.gtk.org/gtk3/method.Window.set_transient_for.html>
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
#[must_use]
pub fn transient_for_raw(mut self, parent: &impl gtk::glib::IsA<gtk::Window>) -> Self {
self.window_builder = self.window_builder.transient_for_raw(parent);
self
}
/// Enables or disables drag and drop support.
#[cfg(windows)]
#[must_use]
pub fn drag_and_drop(mut self, enabled: bool) -> Self {
self.window_builder = self.window_builder.drag_and_drop(enabled);
self
}
/// Sets the [`crate::TitleBarStyle`].
#[cfg(target_os = "macos")]
#[must_use]
pub fn title_bar_style(mut self, style: crate::TitleBarStyle) -> Self {
self.window_builder = self.window_builder.title_bar_style(style);
self
}
/// Change the position of the window controls on macOS.
///
/// Requires titleBarStyle: Overlay and decorations: true.
#[cfg(target_os = "macos")]
#[must_use]
pub fn traffic_light_position<P: Into<Position>>(mut self, position: P) -> Self {
self.webview_builder.webview_attributes = self
.webview_builder
.webview_attributes
.traffic_light_position(position.into());
self
}
/// Whether to show a link preview when long pressing on links. Available on macOS and iOS only.
///
/// Default is true.
///
/// See https://docs.rs/objc2-web-kit/latest/objc2_web_kit/struct.WKWebView.html#method.allowsLinkPreview
///
/// ## Platform-specific
///
/// - **Linux / Windows / Android:** Unsupported.
#[cfg(target_os = "macos")]
#[must_use]
pub fn allow_link_preview(mut self, allow_link_preview: bool) -> Self {
self.webview_builder = self.webview_builder.allow_link_preview(allow_link_preview);
self
}
/// Hide the window title.
#[cfg(target_os = "macos")]
#[must_use]
pub fn hidden_title(mut self, hidden: bool) -> Self {
self.window_builder = self.window_builder.hidden_title(hidden);
self
}
/// Defines the window [tabbing identifier] for macOS.
///
/// Windows with matching tabbing identifiers will be grouped together.
/// If the tabbing identifier is not set, automatic tabbing will be disabled.
///
/// [tabbing identifier]: <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier>
#[cfg(target_os = "macos")]
#[must_use]
pub fn tabbing_identifier(mut self, identifier: &str) -> Self {
self.window_builder = self.window_builder.tabbing_identifier(identifier);
self
}
/// Sets window effects.
///
/// Requires the window to be transparent.
///
/// ## Platform-specific:
///
/// - **Windows**: If using decorations or shadows, you may want to try this workaround <https://github.com/tauri-apps/tao/issues/72#issuecomment-975607891>
/// - **Linux**: Unsupported
pub fn effects(mut self, effects: crate::utils::config::WindowEffectsConfig) -> Self {
self.window_builder = self.window_builder.effects(effects);
self
}
}
/// Webview attributes.
impl<R: Runtime, M: Manager<R>> WebviewWindowBuilder<'_, R, M> {
/// Sets whether clicking an inactive window also clicks through to the webview.
#[must_use]
pub fn accept_first_mouse(mut self, accept: bool) -> Self {
self.webview_builder = self.webview_builder.accept_first_mouse(accept);
self
}
/// Adds the provided JavaScript to a list of scripts that should be run after the global object has been created,
/// but before the HTML document has been parsed and before any other script included by the HTML document is run.
///
/// Since it runs on all top-level document navigations,
/// it's recommended to check the `window.location` to guard your script from running on unexpected origins.
///
/// This is executed only on the main frame.
/// If you only want to run it in all frames, use [Self::initialization_script_for_all_frames] instead.
///
/// ## Platform-specific
///
/// - **Windows:** scripts are always added to subframes.
/// - **Android:** When [addDocumentStartJavaScript] is not supported,
/// we prepend initialization scripts to each HTML head (implementation only supported on custom protocol URLs).
/// For remote URLs, we use [onPageStarted] which is not guaranteed to run before other scripts.
///
/// # Examples
///
/// ```rust
/// const INIT_SCRIPT: &str = r#"
/// if (window.location.origin === 'https://tauri.app') {
/// console.log("hello world from js init script");
///
/// window.__MY_CUSTOM_PROPERTY__ = { foo: 'bar' };
/// }
/// "#;
///
/// fn main() {
/// tauri::Builder::default()
/// .setup(|app| {
/// let webview = tauri::WebviewWindowBuilder::new(app, "label", tauri::WebviewUrl::App("index.html".into()))
/// .initialization_script(INIT_SCRIPT)
/// .build()?;
/// Ok(())
/// });
/// }
/// ```
#[must_use]
pub fn initialization_script(mut self, script: impl Into<String>) -> Self {
self.webview_builder = self.webview_builder.initialization_script(script);
self
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | true |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/webview/mod.rs | crates/tauri/src/webview/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! The Tauri webview types and functions.
pub(crate) mod plugin;
mod webview_window;
pub use webview_window::{WebviewWindow, WebviewWindowBuilder};
/// Cookie crate used for [`Webview::set_cookie`] and [`Webview::delete_cookie`].
///
/// # Stability
///
/// This re-exported crate is still on an alpha release and might receive updates in minor Tauri releases.
pub use cookie;
use http::HeaderMap;
use serde::Serialize;
use tauri_macros::default_runtime;
pub use tauri_runtime::webview::{NewWindowFeatures, PageLoadEvent, ScrollBarStyle};
// Remove this re-export in v3
pub use tauri_runtime::Cookie;
#[cfg(desktop)]
use tauri_runtime::{
dpi::{PhysicalPosition, PhysicalSize, Position, Size},
WindowDispatch,
};
use tauri_runtime::{
webview::{DetachedWebview, InitializationScript, PendingWebview, WebviewAttributes},
WebviewDispatch,
};
pub use tauri_utils::config::Color;
use tauri_utils::config::{BackgroundThrottlingPolicy, WebviewUrl, WindowConfig};
pub use url::Url;
use crate::{
app::{UriSchemeResponder, WebviewEvent},
event::{EmitArgs, EventTarget},
ipc::{
CallbackFn, CommandArg, CommandItem, CommandScope, GlobalScope, Invoke, InvokeBody,
InvokeError, InvokeMessage, InvokeResolver, Origin, OwnedInvokeResponder, ScopeObject,
},
manager::AppManager,
path::SafePathBuf,
sealed::{ManagerBase, RuntimeOrDispatch},
AppHandle, Emitter, Event, EventId, EventLoopMessage, EventName, Listener, Manager,
ResourceTable, Runtime, Window,
};
use std::{
borrow::Cow,
hash::{Hash, Hasher},
path::{Path, PathBuf},
sync::{Arc, Mutex, MutexGuard},
};
pub(crate) type WebResourceRequestHandler =
dyn Fn(http::Request<Vec<u8>>, &mut http::Response<Cow<'static, [u8]>>) + Send + Sync;
pub(crate) type NavigationHandler = dyn Fn(&Url) -> bool + Send;
pub(crate) type NewWindowHandler<R> =
dyn Fn(Url, NewWindowFeatures) -> NewWindowResponse<R> + Send + Sync;
pub(crate) type UriSchemeProtocolHandler =
Box<dyn Fn(&str, http::Request<Vec<u8>>, UriSchemeResponder) + Send + Sync>;
pub(crate) type OnPageLoad<R> = dyn Fn(Webview<R>, PageLoadPayload<'_>) + Send + Sync + 'static;
pub(crate) type OnDocumentTitleChanged<R> = dyn Fn(Webview<R>, String) + Send + 'static;
pub(crate) type DownloadHandler<R> = dyn Fn(Webview<R>, DownloadEvent<'_>) -> bool + Send + Sync;
#[derive(Clone, Serialize)]
pub(crate) struct CreatedEvent {
pub(crate) label: String,
}
/// Download event for the [`WebviewBuilder#method.on_download`] hook.
#[non_exhaustive]
pub enum DownloadEvent<'a> {
/// Download requested.
Requested {
/// The url being downloaded.
url: Url,
/// Represents where the file will be downloaded to.
/// Can be used to set the download location by assigning a new path to it.
/// The assigned path _must_ be absolute.
destination: &'a mut PathBuf,
},
/// Download finished.
Finished {
/// The URL of the original download request.
url: Url,
/// Potentially representing the filesystem path the file was downloaded to.
///
/// A value of `None` being passed instead of a `PathBuf` does not necessarily indicate that the download
/// did not succeed, and may instead indicate some other failure - always check the third parameter if you need to
/// know if the download succeeded.
///
/// ## Platform-specific:
///
/// - **macOS**: The second parameter indicating the path the file was saved to is always empty, due to API
/// limitations.
path: Option<PathBuf>,
/// Indicates if the download succeeded or not.
success: bool,
},
}
/// The payload for the [`WebviewBuilder::on_page_load`] hook.
#[derive(Debug, Clone)]
pub struct PageLoadPayload<'a> {
pub(crate) url: &'a Url,
pub(crate) event: PageLoadEvent,
}
impl<'a> PageLoadPayload<'a> {
/// The page URL.
pub fn url(&self) -> &'a Url {
self.url
}
/// The page load event.
pub fn event(&self) -> PageLoadEvent {
self.event
}
}
/// The IPC invoke request.
///
/// # Stability
///
/// This struct is **NOT** part of the public stable API and is only meant to be used
/// by internal code and external testing/fuzzing tools or custom invoke systems.
#[derive(Debug)]
pub struct InvokeRequest {
/// The invoke command.
pub cmd: String,
/// The success callback.
pub callback: CallbackFn,
/// The error callback.
pub error: CallbackFn,
/// URL of the frame that requested this command.
pub url: Url,
/// The body of the request.
pub body: InvokeBody,
/// The request headers.
pub headers: HeaderMap,
/// The invoke key. Must match what was passed to the app manager.
pub invoke_key: String,
}
/// The platform webview handle. Accessed with [`Webview#method.with_webview`];
#[cfg(feature = "wry")]
#[cfg_attr(docsrs, doc(cfg(feature = "wry")))]
pub struct PlatformWebview(tauri_runtime_wry::Webview);
#[cfg(feature = "wry")]
impl PlatformWebview {
/// Returns [`webkit2gtk::WebView`] handle.
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
#[cfg_attr(
docsrs,
doc(cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
)))
)]
pub fn inner(&self) -> webkit2gtk::WebView {
self.0.clone()
}
/// Returns the WebView2 controller.
#[cfg(windows)]
#[cfg_attr(docsrs, doc(cfg(windows)))]
pub fn controller(
&self,
) -> webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2Controller {
self.0.controller.clone()
}
/// Returns the WebView2 environment.
#[cfg(windows)]
#[cfg_attr(docsrs, doc(cfg(windows)))]
pub fn environment(
&self,
) -> webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2Environment {
self.0.environment.clone()
}
/// Returns the [WKWebView] handle.
///
/// [WKWebView]: https://developer.apple.com/documentation/webkit/wkwebview
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[cfg_attr(docsrs, doc(cfg(any(target_os = "macos", target_os = "ios"))))]
pub fn inner(&self) -> *mut std::ffi::c_void {
self.0.webview
}
/// Returns WKWebView [controller] handle.
///
/// [controller]: https://developer.apple.com/documentation/webkit/wkusercontentcontroller
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[cfg_attr(docsrs, doc(cfg(any(target_os = "macos", target_os = "ios"))))]
pub fn controller(&self) -> *mut std::ffi::c_void {
self.0.manager
}
/// Returns [NSWindow] associated with the WKWebView webview.
///
/// [NSWindow]: https://developer.apple.com/documentation/appkit/nswindow
#[cfg(target_os = "macos")]
#[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
pub fn ns_window(&self) -> *mut std::ffi::c_void {
self.0.ns_window
}
/// Returns [UIViewController] used by the WKWebView webview NSWindow.
///
/// [UIViewController]: https://developer.apple.com/documentation/uikit/uiviewcontroller
#[cfg(target_os = "ios")]
#[cfg_attr(docsrs, doc(cfg(target_os = "ios")))]
pub fn view_controller(&self) -> *mut std::ffi::c_void {
self.0.view_controller
}
/// Returns handle for JNI execution.
#[cfg(target_os = "android")]
pub fn jni_handle(&self) -> tauri_runtime_wry::wry::JniHandle {
self.0
}
}
/// Response for the new window request handler.
pub enum NewWindowResponse<R: Runtime> {
/// Allow the window to be opened with the default implementation.
Allow,
/// Allow the window to be opened, with the given window.
///
/// ## Platform-specific:
///
/// **Linux**: The webview must be related to the caller webview. See [`WebviewBuilder::related_view`].
/// **Windows**: The webview must use the same environment as the caller webview. See [`WebviewBuilder::environment`].
/// **macOS**: The webview must use the same webview configuration as the caller webview. See [`WebviewBuilder::with_webview_configuration`] and [`NewWindowFeatures::webview_configuration`].
Create {
/// Window that was created.
window: crate::WebviewWindow<R>,
},
/// Deny the window from being opened.
Deny,
}
macro_rules! unstable_struct {
(#[doc = $doc:expr] $($tokens:tt)*) => {
#[cfg(any(test, feature = "unstable"))]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
#[doc = $doc]
pub $($tokens)*
#[cfg(not(any(test, feature = "unstable")))]
pub(crate) $($tokens)*
}
}
unstable_struct!(
#[doc = "A builder for a webview."]
struct WebviewBuilder<R: Runtime> {
pub(crate) label: String,
pub(crate) webview_attributes: WebviewAttributes,
pub(crate) web_resource_request_handler: Option<Box<WebResourceRequestHandler>>,
pub(crate) navigation_handler: Option<Box<NavigationHandler>>,
pub(crate) new_window_handler: Option<Box<NewWindowHandler<R>>>,
pub(crate) on_page_load_handler: Option<Box<OnPageLoad<R>>>,
pub(crate) document_title_changed_handler: Option<Box<OnDocumentTitleChanged<R>>>,
pub(crate) download_handler: Option<Arc<DownloadHandler<R>>>,
}
);
#[cfg_attr(not(feature = "unstable"), allow(dead_code))]
impl<R: Runtime> WebviewBuilder<R> {
/// Initializes a webview builder with the given webview label and URL to load.
///
/// # Known issues
///
/// On Windows, this function deadlocks when used in a synchronous command or event handlers, see [the Webview2 issue].
/// You should use `async` commands and separate threads when creating webviews.
///
/// # Examples
///
/// - Create a webview in the setup hook:
///
#[cfg_attr(
feature = "unstable",
doc = r####"
```
tauri::Builder::default()
.setup(|app| {
let window = tauri::window::WindowBuilder::new(app, "label").build()?;
let webview_builder = tauri::webview::WebviewBuilder::new("label", tauri::WebviewUrl::App("index.html".into()));
let webview = window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap());
Ok(())
});
```
"####
)]
///
/// - Create a webview in a separate thread:
///
#[cfg_attr(
feature = "unstable",
doc = r####"
```
tauri::Builder::default()
.setup(|app| {
let handle = app.handle().clone();
std::thread::spawn(move || {
let window = tauri::window::WindowBuilder::new(&handle, "label").build().unwrap();
let webview_builder = tauri::webview::WebviewBuilder::new("label", tauri::WebviewUrl::App("index.html".into()));
window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap());
});
Ok(())
});
```
"####
)]
///
/// - Create a webview in a command:
///
#[cfg_attr(
feature = "unstable",
doc = r####"
```
#[tauri::command]
async fn create_window(app: tauri::AppHandle) {
let window = tauri::window::WindowBuilder::new(&app, "label").build().unwrap();
let webview_builder = tauri::webview::WebviewBuilder::new("label", tauri::WebviewUrl::External("https://tauri.app/".parse().unwrap()));
window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap());
}
```
"####
)]
///
/// [the Webview2 issue]: https://github.com/tauri-apps/wry/issues/583
pub fn new<L: Into<String>>(label: L, url: WebviewUrl) -> Self {
Self {
label: label.into(),
webview_attributes: WebviewAttributes::new(url),
web_resource_request_handler: None,
navigation_handler: None,
new_window_handler: None,
on_page_load_handler: None,
document_title_changed_handler: None,
download_handler: None,
}
}
/// Initializes a webview builder from a [`WindowConfig`] from tauri.conf.json.
/// Keep in mind that you can't create 2 webviews with the same `label` so make sure
/// that the initial webview was closed or change the label of the new [`WebviewBuilder`].
///
/// # Known issues
///
/// On Windows, this function deadlocks when used in a synchronous command or event handlers, see [the Webview2 issue].
/// You should use `async` commands and separate threads when creating webviews.
///
/// # Examples
///
/// - Create a webview in a command:
///
#[cfg_attr(
feature = "unstable",
doc = r####"
```
#[tauri::command]
async fn create_window(app: tauri::AppHandle) {
let window = tauri::window::WindowBuilder::new(&app, "label").build().unwrap();
let webview_builder = tauri::webview::WebviewBuilder::from_config(&app.config().app.windows.get(0).unwrap().clone());
window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap());
}
```
"####
)]
///
/// [the Webview2 issue]: https://github.com/tauri-apps/wry/issues/583
pub fn from_config(config: &WindowConfig) -> Self {
let mut config = config.to_owned();
if let Some(data_directory) = &config.data_directory {
let resolve_data_dir_res = dirs::data_local_dir()
.or({
#[cfg(feature = "tracing")]
tracing::error!("failed to resolve data directory");
None
})
.and_then(|local_dir| {
SafePathBuf::new(data_directory.clone())
.inspect_err(|_err| {
#[cfg(feature = "tracing")]
tracing::error!(
"data_directory `{}` is not a safe path, ignoring config. Validation error was: {_err}",
data_directory.display()
);
})
.map(|p| (local_dir, p))
.ok()
})
.and_then(|(local_dir, data_directory)| {
if data_directory.as_ref().is_relative() {
Some(local_dir.join(&config.label).join(data_directory.as_ref()))
} else {
#[cfg(feature = "tracing")]
tracing::error!(
"data_directory `{}` is not a relative path, ignoring config.",
data_directory.display()
);
None
}
});
if let Some(resolved_data_directory) = resolve_data_dir_res {
config.data_directory = Some(resolved_data_directory);
}
}
Self {
label: config.label.clone(),
webview_attributes: WebviewAttributes::from(&config),
web_resource_request_handler: None,
navigation_handler: None,
new_window_handler: None,
on_page_load_handler: None,
document_title_changed_handler: None,
download_handler: None,
}
}
/// Defines a closure to be executed when the webview makes an HTTP request for a web resource, allowing you to modify the response.
///
/// Currently only implemented for the `tauri` URI protocol.
///
/// **NOTE:** Currently this is **not** executed when using external URLs such as a development server,
/// but it might be implemented in the future. **Always** check the request URL.
///
/// # Examples
///
#[cfg_attr(
feature = "unstable",
doc = r####"
```rust,no_run
use tauri::{
utils::config::{Csp, CspDirectiveSources, WebviewUrl},
window::WindowBuilder,
webview::WebviewBuilder,
};
use http::header::HeaderValue;
use std::collections::HashMap;
tauri::Builder::default()
.setup(|app| {
let window = tauri::window::WindowBuilder::new(app, "label").build()?;
let webview_builder = WebviewBuilder::new("core", WebviewUrl::App("index.html".into()))
.on_web_resource_request(|request, response| {
if request.uri().scheme_str() == Some("tauri") {
// if we have a CSP header, Tauri is loading an HTML file
// for this example, let's dynamically change the CSP
if let Some(csp) = response.headers_mut().get_mut("Content-Security-Policy") {
// use the tauri helper to parse the CSP policy to a map
let mut csp_map: HashMap<String, CspDirectiveSources> = Csp::Policy(csp.to_str().unwrap().to_string()).into();
csp_map.entry("script-src".to_string()).or_insert_with(Default::default).push("'unsafe-inline'");
// use the tauri helper to get a CSP string from the map
let csp_string = Csp::from(csp_map).to_string();
*csp = HeaderValue::from_str(&csp_string).unwrap();
}
}
});
let webview = window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap())?;
Ok(())
});
```
"####
)]
pub fn on_web_resource_request<
F: Fn(http::Request<Vec<u8>>, &mut http::Response<Cow<'static, [u8]>>) + Send + Sync + 'static,
>(
mut self,
f: F,
) -> Self {
self.web_resource_request_handler.replace(Box::new(f));
self
}
/// Defines a closure to be executed when the webview navigates to a URL. Returning `false` cancels the navigation.
///
/// # Examples
///
#[cfg_attr(
feature = "unstable",
doc = r####"
```rust,no_run
use tauri::{
utils::config::{Csp, CspDirectiveSources, WebviewUrl},
window::WindowBuilder,
webview::WebviewBuilder,
};
use http::header::HeaderValue;
use std::collections::HashMap;
tauri::Builder::default()
.setup(|app| {
let window = tauri::window::WindowBuilder::new(app, "label").build()?;
let webview_builder = WebviewBuilder::new("core", WebviewUrl::App("index.html".into()))
.on_navigation(|url| {
// allow the production URL or localhost on dev
url.scheme() == "tauri" || (cfg!(dev) && url.host_str() == Some("localhost"))
});
let webview = window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap())?;
Ok(())
});
```
"####
)]
pub fn on_navigation<F: Fn(&Url) -> bool + Send + 'static>(mut self, f: F) -> Self {
self.navigation_handler.replace(Box::new(f));
self
}
/// Set a new window request handler to decide if incoming url is allowed to be opened.
///
/// A new window is requested to be opened by the [window.open] API.
///
/// The closure take the URL to open and the window features object and returns [`NewWindowResponse`] to determine whether the window should open.
///
#[cfg_attr(
feature = "unstable",
doc = r####"
```rust,no_run
use tauri::{
utils::config::{Csp, CspDirectiveSources, WebviewUrl},
window::WindowBuilder,
webview::WebviewBuilder,
};
use http::header::HeaderValue;
use std::collections::HashMap;
tauri::Builder::default()
.setup(|app| {
let window = tauri::window::WindowBuilder::new(app, "label").build()?;
let app_ = app.handle().clone();
let webview_builder = WebviewBuilder::new("core", WebviewUrl::App("index.html".into()))
.on_new_window(move |url, features| {
let builder = tauri::WebviewWindowBuilder::new(
&app_,
// note: add an ID counter or random label generator to support multiple opened windows at the same time
"opened-window",
tauri::WebviewUrl::External("about:blank".parse().unwrap()),
)
.window_features(features)
.on_document_title_changed(|window, title| {
window.set_title(&title).unwrap();
})
.title(url.as_str());
let window = builder.build().unwrap();
tauri::webview::NewWindowResponse::Create { window }
});
let webview = window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap())?;
Ok(())
});
```
"####
)]
///
/// # Platform-specific
///
/// - **Android / iOS**: Not supported.
/// - **Windows**: The closure is executed on a separate thread to prevent a deadlock.
///
/// [window.open]: https://developer.mozilla.org/en-US/docs/Web/API/Window/open
pub fn on_new_window<
F: Fn(Url, NewWindowFeatures) -> NewWindowResponse<R> + Send + Sync + 'static,
>(
mut self,
f: F,
) -> Self {
self.new_window_handler.replace(Box::new(f));
self
}
/// Defines a closure to be executed when document title change.
pub fn on_document_title_changed<F: Fn(Webview<R>, String) + Send + 'static>(
mut self,
f: F,
) -> Self {
self.document_title_changed_handler.replace(Box::new(f));
self
}
/// Set a download event handler to be notified when a download is requested or finished.
///
/// Returning `false` prevents the download from happening on a [`DownloadEvent::Requested`] event.
///
/// # Examples
///
#[cfg_attr(
feature = "unstable",
doc = r####"
```rust,no_run
use tauri::{
utils::config::{Csp, CspDirectiveSources, WebviewUrl},
window::WindowBuilder,
webview::{DownloadEvent, WebviewBuilder},
};
tauri::Builder::default()
.setup(|app| {
let window = WindowBuilder::new(app, "label").build()?;
let webview_builder = WebviewBuilder::new("core", WebviewUrl::App("index.html".into()))
.on_download(|webview, event| {
match event {
DownloadEvent::Requested { url, destination } => {
println!("downloading {}", url);
*destination = "/home/tauri/target/path".into();
}
DownloadEvent::Finished { url, path, success } => {
println!("downloaded {} to {:?}, success: {}", url, path, success);
}
_ => (),
}
// let the download start
true
});
let webview = window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap())?;
Ok(())
});
```
"####
)]
pub fn on_download<F: Fn(Webview<R>, DownloadEvent<'_>) -> bool + Send + Sync + 'static>(
mut self,
f: F,
) -> Self {
self.download_handler.replace(Arc::new(f));
self
}
/// Defines a closure to be executed when a page load event is triggered.
/// The event can be either [`PageLoadEvent::Started`] if the page has started loading
/// or [`PageLoadEvent::Finished`] when the page finishes loading.
///
/// # Examples
///
#[cfg_attr(
feature = "unstable",
doc = r####"
```rust,no_run
use tauri::{
utils::config::{Csp, CspDirectiveSources, WebviewUrl},
window::WindowBuilder,
webview::{PageLoadEvent, WebviewBuilder},
};
use http::header::HeaderValue;
use std::collections::HashMap;
tauri::Builder::default()
.setup(|app| {
let window = tauri::window::WindowBuilder::new(app, "label").build()?;
let webview_builder = WebviewBuilder::new("core", WebviewUrl::App("index.html".into()))
.on_page_load(|webview, payload| {
match payload.event() {
PageLoadEvent::Started => {
println!("{} finished loading", payload.url());
}
PageLoadEvent::Finished => {
println!("{} finished loading", payload.url());
}
}
});
let webview = window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap())?;
Ok(())
});
```
"####
)]
pub fn on_page_load<F: Fn(Webview<R>, PageLoadPayload<'_>) + Send + Sync + 'static>(
mut self,
f: F,
) -> Self {
self.on_page_load_handler.replace(Box::new(f));
self
}
pub(crate) fn into_pending_webview<M: Manager<R>>(
mut self,
manager: &M,
window_label: &str,
) -> crate::Result<PendingWebview<EventLoopMessage, R>> {
let mut pending = PendingWebview::new(self.webview_attributes, self.label.clone())?;
pending.navigation_handler = self.navigation_handler.take();
pending.new_window_handler = self.new_window_handler.take().map(|handler| {
Box::new(
move |url, features: NewWindowFeatures| match handler(url, features) {
NewWindowResponse::Allow => tauri_runtime::webview::NewWindowResponse::Allow,
#[cfg(mobile)]
NewWindowResponse::Create { window: _ } => {
tauri_runtime::webview::NewWindowResponse::Allow
}
#[cfg(desktop)]
NewWindowResponse::Create { window } => {
tauri_runtime::webview::NewWindowResponse::Create {
window_id: window.window.window.id,
}
}
NewWindowResponse::Deny => tauri_runtime::webview::NewWindowResponse::Deny,
},
)
as Box<
dyn Fn(Url, NewWindowFeatures) -> tauri_runtime::webview::NewWindowResponse
+ Send
+ Sync
+ 'static,
>
});
if let Some(document_title_changed_handler) = self.document_title_changed_handler.take() {
let label = pending.label.clone();
let manager = manager.manager_owned();
pending
.document_title_changed_handler
.replace(Box::new(move |title| {
if let Some(w) = manager.get_webview(&label) {
document_title_changed_handler(w, title);
}
}));
}
pending.web_resource_request_handler = self.web_resource_request_handler.take();
if let Some(download_handler) = self.download_handler.take() {
let label = pending.label.clone();
let manager = manager.manager_owned();
pending.download_handler.replace(Arc::new(move |event| {
if let Some(w) = manager.get_webview(&label) {
download_handler(
w,
match event {
tauri_runtime::webview::DownloadEvent::Requested { url, destination } => {
DownloadEvent::Requested { url, destination }
}
tauri_runtime::webview::DownloadEvent::Finished { url, path, success } => {
DownloadEvent::Finished { url, path, success }
}
},
)
} else {
false
}
}));
}
let label_ = pending.label.clone();
let manager_ = manager.manager_owned();
pending
.on_page_load_handler
.replace(Box::new(move |url, event| {
if let Some(w) = manager_.get_webview(&label_) {
if let Some(handler) = self.on_page_load_handler.as_ref() {
handler(w, PageLoadPayload { url: &url, event });
}
}
}));
manager
.manager()
.webview
.prepare_webview(manager, pending, window_label)
}
/// Creates a new webview on the given window.
#[cfg(desktop)]
pub(crate) fn build(
self,
window: Window<R>,
position: Position,
size: Size,
) -> crate::Result<Webview<R>> {
let app_manager = window.manager();
let mut pending = self.into_pending_webview(&window, window.label())?;
pending.webview_attributes.bounds = Some(tauri_runtime::dpi::Rect { size, position });
let use_https_scheme = pending.webview_attributes.use_https_scheme;
let webview = match &mut window.runtime() {
RuntimeOrDispatch::Dispatch(dispatcher) => dispatcher.create_webview(pending),
_ => unimplemented!(),
}
.map(|webview| {
app_manager
.webview
.attach_webview(window.clone(), webview, use_https_scheme)
})?;
Ok(webview)
}
}
/// Webview attributes.
impl<R: Runtime> WebviewBuilder<R> {
/// Sets whether clicking an inactive window also clicks through to the webview.
#[must_use]
pub fn accept_first_mouse(mut self, accept: bool) -> Self {
self.webview_attributes.accept_first_mouse = accept;
self
}
/// Adds the provided JavaScript to a list of scripts that should be run after the global object has been created,
/// but before the HTML document has been parsed and before any other script included by the HTML document is run.
///
/// Since it runs on all top-level document navigations,
/// it's recommended to check the `window.location` to guard your script from running on unexpected origins.
///
/// This is executed only on the main frame.
/// If you only want to run it in all frames, use [`Self::initialization_script_for_all_frames`] instead.
///
/// ## Platform-specific
///
/// - **Windows:** scripts are always added to subframes.
/// - **Android:** When [addDocumentStartJavaScript] is not supported,
/// we prepend initialization scripts to each HTML head (implementation only supported on custom protocol URLs).
/// For remote URLs, we use [onPageStarted] which is not guaranteed to run before other scripts.
///
/// # Examples
///
#[cfg_attr(
feature = "unstable",
doc = r####"
```rust
use tauri::{WindowBuilder, Runtime};
const INIT_SCRIPT: &str = r#"
if (window.location.origin === 'https://tauri.app') {
console.log("hello world from js init script");
window.__MY_CUSTOM_PROPERTY__ = { foo: 'bar' };
}
"#;
fn main() {
tauri::Builder::default()
.setup(|app| {
let window = tauri::window::WindowBuilder::new(app, "label").build()?;
let webview_builder = tauri::webview::WebviewBuilder::new("label", tauri::WebviewUrl::App("index.html".into()))
.initialization_script(INIT_SCRIPT);
let webview = window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap())?;
Ok(())
});
}
```
"####
)]
///
/// [addDocumentStartJavaScript]: https://developer.android.com/reference/androidx/webkit/WebViewCompat#addDocumentStartJavaScript(android.webkit.WebView,java.lang.String,java.util.Set%3Cjava.lang.String%3E)
/// [onPageStarted]: https://developer.android.com/reference/android/webkit/WebViewClient#onPageStarted(android.webkit.WebView,%20java.lang.String,%20android.graphics.Bitmap)
#[must_use]
pub fn initialization_script(mut self, script: impl Into<String>) -> Self {
self
.webview_attributes
.initialization_scripts
.push(InitializationScript {
script: script.into(),
for_main_frame_only: true,
});
self
}
/// Adds the provided JavaScript to a list of scripts that should be run after the global object has been created,
/// but before the HTML document has been parsed and before any other script included by the HTML document is run.
///
/// Since it runs on all top-level document navigations and also child frame page navigations,
/// it's recommended to check the `window.location` to guard your script from running on unexpected origins.
///
/// This is executed on all frames (main frame and also sub frames).
/// If you only want to run the script in the main frame, use [`Self::initialization_script`] instead.
///
/// ## Platform-specific
///
/// - **Android:** When [addDocumentStartJavaScript] is not supported,
/// we prepend initialization scripts to each HTML head (implementation only supported on custom protocol URLs).
/// For remote URLs, we use [onPageStarted] which is not guaranteed to run before other scripts.
///
/// # Examples
///
#[cfg_attr(
feature = "unstable",
doc = r####"
```rust
use tauri::{WindowBuilder, Runtime};
const INIT_SCRIPT: &str = r#"
if (window.location.origin === 'https://tauri.app') {
console.log("hello world from js init script");
window.__MY_CUSTOM_PROPERTY__ = { foo: 'bar' };
}
"#;
fn main() {
tauri::Builder::default()
.setup(|app| {
let window = tauri::window::WindowBuilder::new(app, "label").build()?;
let webview_builder = tauri::webview::WebviewBuilder::new("label", tauri::WebviewUrl::App("index.html".into()))
.initialization_script_for_all_frames(INIT_SCRIPT);
let webview = window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap())?;
Ok(())
});
}
```
"####
)]
///
/// [addDocumentStartJavaScript]: https://developer.android.com/reference/androidx/webkit/WebViewCompat#addDocumentStartJavaScript(android.webkit.WebView,java.lang.String,java.util.Set%3Cjava.lang.String%3E)
/// [onPageStarted]: https://developer.android.com/reference/android/webkit/WebViewClient#onPageStarted(android.webkit.WebView,%20java.lang.String,%20android.graphics.Bitmap)
#[must_use]
pub fn initialization_script_for_all_frames(mut self, script: impl Into<String>) -> Self {
self
.webview_attributes
.initialization_scripts
.push(InitializationScript {
script: script.into(),
for_main_frame_only: false,
});
self
}
/// Set the user agent for the webview
#[must_use]
pub fn user_agent(mut self, user_agent: &str) -> Self {
self.webview_attributes.user_agent = Some(user_agent.to_string());
self
}
/// Set additional arguments for the webview.
///
/// ## Platform-specific
///
/// - **macOS / Linux / Android / iOS**: Unsupported.
///
/// ## Warning
///
/// By default wry passes `--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection`
/// so if you use this method, you also need to disable these components by yourself if you want.
#[must_use]
pub fn additional_browser_args(mut self, additional_args: &str) -> Self {
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | true |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/webview/plugin.rs | crates/tauri/src/webview/plugin.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! The tauri plugin to create and manipulate windows from JS.
use crate::{
plugin::{Builder, TauriPlugin},
Runtime,
};
#[cfg(desktop)]
mod desktop_commands {
use serde::Serialize;
use tauri_runtime::dpi::{Position, Size};
use tauri_utils::config::WindowConfig;
use super::*;
use crate::{
command, sealed::ManagerBase, webview::Color, AppHandle, Webview, WebviewWindowBuilder,
};
#[derive(Serialize)]
pub struct WebviewRef {
window_label: String,
label: String,
}
#[command(root = "crate")]
pub async fn get_all_webviews<R: Runtime>(app: AppHandle<R>) -> Vec<WebviewRef> {
app
.manager()
.webviews()
.values()
.map(|webview| WebviewRef {
window_label: webview.window_ref().label().into(),
label: webview.label().into(),
})
.collect()
}
#[command(root = "crate")]
pub async fn create_webview_window<R: Runtime>(
app: AppHandle<R>,
options: WindowConfig,
) -> crate::Result<()> {
WebviewWindowBuilder::from_config(&app, &options)?.build()?;
Ok(())
}
#[cfg(not(feature = "unstable"))]
#[command(root = "crate")]
pub async fn create_webview() -> crate::Result<()> {
Err(crate::Error::UnstableFeatureNotSupported)
}
#[cfg(feature = "unstable")]
#[command(root = "crate")]
pub async fn create_webview<R: Runtime>(
app: AppHandle<R>,
window_label: String,
options: WindowConfig,
) -> crate::Result<()> {
use anyhow::Context;
let window = app
.manager()
.get_window(&window_label)
.ok_or(crate::Error::WindowNotFound)?;
let x = options.x.context("missing parameter `options.x`")?;
let y = options.y.context("missing parameter `options.y`")?;
let width = options.width;
let height = options.height;
let builder = crate::webview::WebviewBuilder::from_config(&options);
window.add_child(
builder,
tauri_runtime::dpi::LogicalPosition::new(x, y),
tauri_runtime::dpi::LogicalSize::new(width, height),
)?;
Ok(())
}
fn get_webview<R: Runtime>(
webview: Webview<R>,
label: Option<String>,
) -> crate::Result<Webview<R>> {
match label {
Some(l) if !l.is_empty() => webview
.manager()
.get_webview(&l)
.ok_or(crate::Error::WebviewNotFound),
_ => Ok(webview),
}
}
macro_rules! getter {
($cmd: ident, $ret: ty) => {
getter!($cmd, $cmd, $ret)
};
($fn: ident, $cmd: ident, $ret: ty) => {
#[command(root = "crate")]
pub async fn $fn<R: Runtime>(
webview: Webview<R>,
label: Option<String>,
) -> crate::Result<$ret> {
get_webview(webview, label)?.$cmd().map_err(Into::into)
}
};
}
macro_rules! setter {
($cmd: ident) => {
setter!($cmd, $cmd);
};
($fn: ident, $cmd: ident) => {
#[command(root = "crate")]
pub async fn $fn<R: Runtime>(
webview: Webview<R>,
label: Option<String>,
) -> crate::Result<()> {
get_webview(webview, label)?.$cmd().map_err(Into::into)
}
};
($fn: ident, $cmd: ident, $input: ty) => {
#[command(root = "crate")]
pub async fn $fn<R: Runtime>(
webview: Webview<R>,
label: Option<String>,
value: $input,
) -> crate::Result<()> {
get_webview(webview, label)?.$cmd(value).map_err(Into::into)
}
};
}
// TODO
getter!(
webview_position,
position,
tauri_runtime::dpi::PhysicalPosition<i32>
);
getter!(webview_size, size, tauri_runtime::dpi::PhysicalSize<u32>);
//getter!(is_focused, bool);
setter!(print);
setter!(webview_close, close);
setter!(set_webview_size, set_size, Size);
setter!(set_webview_position, set_position, Position);
setter!(set_webview_focus, set_focus);
setter!(set_webview_auto_resize, set_auto_resize, bool);
setter!(webview_hide, hide);
setter!(webview_show, show);
setter!(set_webview_zoom, set_zoom, f64);
setter!(
set_webview_background_color,
set_background_color,
Option<Color>
);
setter!(clear_all_browsing_data, clear_all_browsing_data);
#[command(root = "crate")]
pub async fn reparent<R: Runtime>(
webview: crate::Webview<R>,
label: Option<String>,
window: String,
) -> crate::Result<()> {
let webview = get_webview(webview, label)?;
if let Some(window) = webview.manager.get_window(&window) {
webview.reparent(&window)?;
}
Ok(())
}
#[cfg(any(debug_assertions, feature = "devtools"))]
#[command(root = "crate")]
pub async fn internal_toggle_devtools<R: Runtime>(
webview: crate::Webview<R>,
label: Option<String>,
) -> crate::Result<()> {
let webview = get_webview(webview, label)?;
if webview.is_devtools_open() {
webview.close_devtools();
} else {
webview.open_devtools();
}
Ok(())
}
}
/// Initializes the plugin.
pub fn init<R: Runtime>() -> TauriPlugin<R> {
#[allow(unused_mut)]
let mut init_script = String::new();
// window.print works on Linux/Windows; need to use the API on macOS
#[cfg(any(target_os = "macos", target_os = "ios"))]
{
init_script.push_str(include_str!("./scripts/print.js"));
}
#[cfg(any(debug_assertions, feature = "devtools"))]
{
use serialize_to_javascript::{default_template, DefaultTemplate, Template};
#[derive(Template)]
#[default_template("./scripts/toggle-devtools.js")]
struct Devtools<'a> {
os_name: &'a str,
}
init_script.push_str(
&Devtools {
os_name: std::env::consts::OS,
}
.render_default(&Default::default())
.unwrap()
.into_string(),
);
}
let mut builder = Builder::new("webview");
if !init_script.is_empty() {
builder = builder.js_init_script(init_script);
}
builder
.invoke_handler(
#[cfg(desktop)]
crate::generate_handler![
#![plugin(webview)]
desktop_commands::create_webview,
desktop_commands::create_webview_window,
// getters
desktop_commands::get_all_webviews,
desktop_commands::webview_position,
desktop_commands::webview_size,
// setters
desktop_commands::webview_close,
desktop_commands::set_webview_size,
desktop_commands::set_webview_position,
desktop_commands::set_webview_focus,
desktop_commands::set_webview_auto_resize,
desktop_commands::set_webview_background_color,
desktop_commands::set_webview_zoom,
desktop_commands::webview_hide,
desktop_commands::webview_show,
desktop_commands::print,
desktop_commands::reparent,
desktop_commands::clear_all_browsing_data,
#[cfg(any(debug_assertions, feature = "devtools"))]
desktop_commands::internal_toggle_devtools,
],
#[cfg(mobile)]
|invoke| {
invoke
.resolver
.reject("Webview API not available on mobile");
true
},
)
.build()
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/path/android.rs | crates/tauri/src/path/android.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use super::Result;
use crate::{plugin::PluginHandle, Runtime};
use std::path::{Path, PathBuf};
/// A helper class to access the mobile path APIs.
pub struct PathResolver<R: Runtime>(pub(crate) PluginHandle<R>);
impl<R: Runtime> Clone for PathResolver<R> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
#[derive(serde::Deserialize)]
struct PathResponse {
path: PathBuf,
}
#[derive(serde::Serialize)]
struct GetFileNameFromUriRequest<'a> {
uri: &'a str,
}
#[derive(serde::Deserialize)]
struct GetFileNameFromUriResponse {
name: Option<String>,
}
impl<R: Runtime> PathResolver<R> {
/// Returns the final component of the `Path`, if there is one.
///
/// If the path is a normal file, this is the file name. If it's the path of a directory, this
/// is the directory name.
///
/// Returns [`None`] if the path terminates in `..`.
///
/// On Android this also supports checking the file name of content URIs, such as the values returned by the dialog plugin.
///
/// If you are dealing with plain file system paths or not worried about Android content URIs, prefer [`Path::file_name`].
pub fn file_name(&self, path: &str) -> Option<String> {
if path.starts_with("content://") || path.starts_with("file://") {
self
.0
.run_mobile_plugin::<GetFileNameFromUriResponse>(
"getFileNameFromUri",
GetFileNameFromUriRequest { uri: path },
)
.map(|r| r.name)
.unwrap_or_else(|e| {
log::error!("failed to get file name from URI: {e}");
None
})
} else {
Path::new(path)
.file_name()
.map(|name| name.to_string_lossy().into_owned())
}
}
fn call_resolve(&self, dir: &str) -> Result<PathBuf> {
self
.0
.run_mobile_plugin::<PathResponse>(dir, ())
.map(|r| r.path)
.map_err(Into::into)
}
/// Returns the path to the user's audio directory.
pub fn audio_dir(&self) -> Result<PathBuf> {
self.call_resolve("getAudioDir")
}
/// Returns the path to the user's cache directory.
pub fn cache_dir(&self) -> Result<PathBuf> {
self.call_resolve("getExternalCacheDir")
}
/// Returns the path to the user's config directory.
pub fn config_dir(&self) -> Result<PathBuf> {
self.call_resolve("getConfigDir")
}
/// Returns the path to the user's data directory.
pub fn data_dir(&self) -> Result<PathBuf> {
self.call_resolve("getDataDir")
}
/// Returns the path to the user's local data directory.
pub fn local_data_dir(&self) -> Result<PathBuf> {
self.call_resolve("getDataDir")
}
/// Returns the path to the user's document directory.
pub fn document_dir(&self) -> Result<PathBuf> {
self.call_resolve("getDocumentDir")
}
/// Returns the path to the user's download directory.
pub fn download_dir(&self) -> Result<PathBuf> {
self.call_resolve("getDownloadDir")
}
/// Returns the path to the user's picture directory.
pub fn picture_dir(&self) -> Result<PathBuf> {
self.call_resolve("getPictureDir")
}
/// Returns the path to the user's public directory.
pub fn public_dir(&self) -> Result<PathBuf> {
self.call_resolve("getPublicDir")
}
/// Returns the path to the user's video dir
pub fn video_dir(&self) -> Result<PathBuf> {
self.call_resolve("getVideoDir")
}
/// Returns the path to the resource directory of this app.
pub fn resource_dir(&self) -> Result<PathBuf> {
self.call_resolve("getResourcesDir")
}
/// Returns the path to the suggested directory for your app's config files.
///
/// Resolves to [`config_dir`]`/${bundle_identifier}`.
pub fn app_config_dir(&self) -> Result<PathBuf> {
self.call_resolve("getConfigDir")
}
/// Returns the path to the suggested directory for your app's data files.
///
/// Resolves to [`data_dir`]`/${bundle_identifier}`.
pub fn app_data_dir(&self) -> Result<PathBuf> {
self.call_resolve("getDataDir")
}
/// Returns the path to the suggested directory for your app's local data files.
///
/// Resolves to [`local_data_dir`]`/${bundle_identifier}`.
pub fn app_local_data_dir(&self) -> Result<PathBuf> {
self.call_resolve("getDataDir")
}
/// Returns the path to the suggested directory for your app's cache files.
///
/// Resolves to [`cache_dir`]`/${bundle_identifier}`.
pub fn app_cache_dir(&self) -> Result<PathBuf> {
self.call_resolve("getCacheDir")
}
/// Returns the path to the suggested directory for your app's log files.
pub fn app_log_dir(&self) -> Result<PathBuf> {
self
.call_resolve("getConfigDir")
.map(|dir| dir.join("logs"))
}
/// A temporary directory. Resolves to [`std::env::temp_dir`].
pub fn temp_dir(&self) -> Result<PathBuf> {
Ok(std::env::temp_dir())
}
/// Returns the path to the user's home directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to `$HOME`.
/// - **macOS:** Resolves to `$HOME`.
/// - **Windows:** Resolves to `{FOLDERID_Profile}`.
/// - **iOS**: Cannot be written to directly, use one of the app paths instead.
pub fn home_dir(&self) -> Result<PathBuf> {
self.call_resolve("getHomeDir")
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/path/mod.rs | crates/tauri/src/path/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{
path::{Component, Display, Path, PathBuf},
str::FromStr,
};
use crate::Runtime;
use serde::{de::Error as DeError, Deserialize, Deserializer, Serialize};
use serde_repr::{Deserialize_repr, Serialize_repr};
pub(crate) mod plugin;
use crate::error::*;
#[cfg(target_os = "android")]
mod android;
#[cfg(not(target_os = "android"))]
mod desktop;
#[cfg(target_os = "android")]
pub use android::PathResolver;
#[cfg(not(target_os = "android"))]
pub use desktop::PathResolver;
/// A wrapper for [`PathBuf`] that prevents path traversal.
///
/// # Examples
///
/// ```
/// # use tauri::path::SafePathBuf;
/// assert!(SafePathBuf::new("../secret.txt".into()).is_err());
/// assert!(SafePathBuf::new("/home/user/stuff/../secret.txt".into()).is_err());
///
/// assert!(SafePathBuf::new("./file.txt".into()).is_ok());
/// assert!(SafePathBuf::new("/home/user/secret.txt".into()).is_ok());
/// ```
#[derive(Clone, Debug, Serialize)]
pub struct SafePathBuf(PathBuf);
impl SafePathBuf {
/// Validates the path for directory traversal vulnerabilities and returns a new [`SafePathBuf`] instance if it is safe.
pub fn new(path: PathBuf) -> std::result::Result<Self, &'static str> {
if path.components().any(|x| matches!(x, Component::ParentDir)) {
Err("cannot traverse directory, rewrite the path without the use of `../`")
} else {
Ok(Self(path))
}
}
/// Returns an object that implements [`std::fmt::Display`] for safely printing paths.
///
/// See [`PathBuf#method.display`] for more information.
pub fn display(&self) -> Display<'_> {
self.0.display()
}
}
impl AsRef<Path> for SafePathBuf {
fn as_ref(&self) -> &Path {
self.0.as_ref()
}
}
impl FromStr for SafePathBuf {
type Err = &'static str;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Self::new(s.into())
}
}
impl<'de> Deserialize<'de> for SafePathBuf {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let path = PathBuf::deserialize(deserializer)?;
SafePathBuf::new(path).map_err(DeError::custom)
}
}
/// A base directory for a 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` documentation](https://docs.rs/dirs/).
#[derive(Serialize_repr, Deserialize_repr, Clone, Copy, Debug)]
#[repr(u16)]
#[non_exhaustive]
pub enum BaseDirectory {
/// The Audio directory.
/// Resolves to [`crate::path::PathResolver::audio_dir`].
Audio = 1,
/// The Cache directory.
/// Resolves to [`crate::path::PathResolver::cache_dir`].
Cache = 2,
/// The Config directory.
/// Resolves to [`crate::path::PathResolver::config_dir`].
Config = 3,
/// The Data directory.
/// Resolves to [`crate::path::PathResolver::data_dir`].
Data = 4,
/// The LocalData directory.
/// Resolves to [`crate::path::PathResolver::local_data_dir`].
LocalData = 5,
/// The Document directory.
/// Resolves to [`crate::path::PathResolver::document_dir`].
Document = 6,
/// The Download directory.
/// Resolves to [`crate::path::PathResolver::download_dir`].
Download = 7,
/// The Picture directory.
/// Resolves to [`crate::path::PathResolver::picture_dir`].
Picture = 8,
/// The Public directory.
/// Resolves to [`crate::path::PathResolver::public_dir`].
Public = 9,
/// The Video directory.
/// Resolves to [`crate::path::PathResolver::video_dir`].
Video = 10,
/// The Resource directory.
/// Resolves to [`crate::path::PathResolver::resource_dir`].
Resource = 11,
/// A temporary directory.
/// Resolves to [`std::env::temp_dir`].
Temp = 12,
/// The default app config directory.
/// Resolves to [`BaseDirectory::Config`]`/{bundle_identifier}`.
AppConfig = 13,
/// The default app data directory.
/// Resolves to [`BaseDirectory::Data`]`/{bundle_identifier}`.
AppData = 14,
/// The default app local data directory.
/// Resolves to [`BaseDirectory::LocalData`]`/{bundle_identifier}`.
AppLocalData = 15,
/// The default app cache directory.
/// Resolves to [`BaseDirectory::Cache`]`/{bundle_identifier}`.
AppCache = 16,
/// The default app log directory.
/// Resolves to [`BaseDirectory::Home`]`/Library/Logs/{bundle_identifier}` on macOS
/// and [`BaseDirectory::Config`]`/{bundle_identifier}/logs` on linux and Windows.
AppLog = 17,
/// The Desktop directory.
/// Resolves to [`crate::path::PathResolver::desktop_dir`].
#[cfg(not(target_os = "android"))]
Desktop = 18,
/// The Executable directory.
/// Resolves to [`crate::path::PathResolver::executable_dir`].
#[cfg(not(target_os = "android"))]
Executable = 19,
/// The Font directory.
/// Resolves to [`crate::path::PathResolver::font_dir`].
#[cfg(not(target_os = "android"))]
Font = 20,
/// The Home directory.
/// Resolves to [`crate::path::PathResolver::home_dir`].
Home = 21,
/// The Runtime directory.
/// Resolves to [`crate::path::PathResolver::runtime_dir`].
#[cfg(not(target_os = "android"))]
Runtime = 22,
/// The Template directory.
/// Resolves to [`crate::path::PathResolver::template_dir`].
#[cfg(not(target_os = "android"))]
Template = 23,
}
impl BaseDirectory {
/// Gets the variable that represents this [`BaseDirectory`] for string paths.
pub fn variable(self) -> &'static str {
match self {
Self::Audio => "$AUDIO",
Self::Cache => "$CACHE",
Self::Config => "$CONFIG",
Self::Data => "$DATA",
Self::LocalData => "$LOCALDATA",
Self::Document => "$DOCUMENT",
Self::Download => "$DOWNLOAD",
Self::Picture => "$PICTURE",
Self::Public => "$PUBLIC",
Self::Video => "$VIDEO",
Self::Resource => "$RESOURCE",
Self::Temp => "$TEMP",
Self::AppConfig => "$APPCONFIG",
Self::AppData => "$APPDATA",
Self::AppLocalData => "$APPLOCALDATA",
Self::AppCache => "$APPCACHE",
Self::AppLog => "$APPLOG",
Self::Home => "$HOME",
#[cfg(not(target_os = "android"))]
Self::Desktop => "$DESKTOP",
#[cfg(not(target_os = "android"))]
Self::Executable => "$EXE",
#[cfg(not(target_os = "android"))]
Self::Font => "$FONT",
#[cfg(not(target_os = "android"))]
Self::Runtime => "$RUNTIME",
#[cfg(not(target_os = "android"))]
Self::Template => "$TEMPLATE",
}
}
/// Gets the [`BaseDirectory`] associated with the given variable, or [`None`] if the variable doesn't match any.
pub fn from_variable(variable: &str) -> Option<Self> {
let res = match variable {
"$AUDIO" => Self::Audio,
"$CACHE" => Self::Cache,
"$CONFIG" => Self::Config,
"$DATA" => Self::Data,
"$LOCALDATA" => Self::LocalData,
"$DOCUMENT" => Self::Document,
"$DOWNLOAD" => Self::Download,
"$PICTURE" => Self::Picture,
"$PUBLIC" => Self::Public,
"$VIDEO" => Self::Video,
"$RESOURCE" => Self::Resource,
"$TEMP" => Self::Temp,
"$APPCONFIG" => Self::AppConfig,
"$APPDATA" => Self::AppData,
"$APPLOCALDATA" => Self::AppLocalData,
"$APPCACHE" => Self::AppCache,
"$APPLOG" => Self::AppLog,
"$HOME" => Self::Home,
#[cfg(not(target_os = "android"))]
"$DESKTOP" => Self::Desktop,
#[cfg(not(target_os = "android"))]
"$EXE" => Self::Executable,
#[cfg(not(target_os = "android"))]
"$FONT" => Self::Font,
#[cfg(not(target_os = "android"))]
"$RUNTIME" => Self::Runtime,
#[cfg(not(target_os = "android"))]
"$TEMPLATE" => Self::Template,
_ => return None,
};
Some(res)
}
}
impl<R: Runtime> PathResolver<R> {
/// Resolves the path with the base directory.
///
/// # Examples
///
/// ```rust,no_run
/// use tauri::{path::BaseDirectory, Manager};
/// tauri::Builder::default()
/// .setup(|app| {
/// let path = app.path().resolve("path/to/something", BaseDirectory::Config)?;
/// assert_eq!(path.to_str().unwrap(), "/home/${whoami}/.config/path/to/something");
/// Ok(())
/// });
/// ```
pub fn resolve<P: AsRef<Path>>(&self, path: P, base_directory: BaseDirectory) -> Result<PathBuf> {
resolve_path::<R>(self, base_directory, Some(path.as_ref().to_path_buf()))
}
/// Parse the given path, resolving a [`BaseDirectory`] variable if the path starts with one.
///
/// # Examples
///
/// ```rust,no_run
/// use tauri::Manager;
/// tauri::Builder::default()
/// .setup(|app| {
/// let path = app.path().parse("$HOME/.bashrc")?;
/// assert_eq!(path.to_str().unwrap(), "/home/${whoami}/.bashrc");
/// Ok(())
/// });
/// ```
pub fn parse<P: AsRef<Path>>(&self, path: P) -> Result<PathBuf> {
let mut p = PathBuf::new();
let mut components = path.as_ref().components();
match components.next() {
Some(Component::Normal(str)) => {
if let Some(base_directory) = BaseDirectory::from_variable(&str.to_string_lossy()) {
p.push(resolve_path::<R>(self, base_directory, None)?);
} else {
p.push(str);
}
}
Some(component) => p.push(component),
None => (),
}
for component in components {
if let Component::ParentDir = component {
continue;
}
p.push(component);
}
Ok(p)
}
}
fn resolve_path<R: Runtime>(
resolver: &PathResolver<R>,
directory: BaseDirectory,
path: Option<PathBuf>,
) -> Result<PathBuf> {
let resolve_resource = matches!(directory, BaseDirectory::Resource);
let mut base_dir_path = match directory {
BaseDirectory::Audio => resolver.audio_dir(),
BaseDirectory::Cache => resolver.cache_dir(),
BaseDirectory::Config => resolver.config_dir(),
BaseDirectory::Data => resolver.data_dir(),
BaseDirectory::LocalData => resolver.local_data_dir(),
BaseDirectory::Document => resolver.document_dir(),
BaseDirectory::Download => resolver.download_dir(),
BaseDirectory::Picture => resolver.picture_dir(),
BaseDirectory::Public => resolver.public_dir(),
BaseDirectory::Video => resolver.video_dir(),
BaseDirectory::Resource => resolver.resource_dir(),
BaseDirectory::Temp => resolver.temp_dir(),
BaseDirectory::AppConfig => resolver.app_config_dir(),
BaseDirectory::AppData => resolver.app_data_dir(),
BaseDirectory::AppLocalData => resolver.app_local_data_dir(),
BaseDirectory::AppCache => resolver.app_cache_dir(),
BaseDirectory::AppLog => resolver.app_log_dir(),
BaseDirectory::Home => resolver.home_dir(),
#[cfg(not(target_os = "android"))]
BaseDirectory::Desktop => resolver.desktop_dir(),
#[cfg(not(target_os = "android"))]
BaseDirectory::Executable => resolver.executable_dir(),
#[cfg(not(target_os = "android"))]
BaseDirectory::Font => resolver.font_dir(),
#[cfg(not(target_os = "android"))]
BaseDirectory::Runtime => resolver.runtime_dir(),
#[cfg(not(target_os = "android"))]
BaseDirectory::Template => resolver.template_dir(),
}?;
if let Some(path) = path {
// use the same path resolution mechanism as the bundler's resource injection algorithm
if resolve_resource {
let mut resource_path = PathBuf::new();
for component in path.components() {
match component {
Component::Prefix(_) => {}
Component::RootDir => resource_path.push("_root_"),
Component::CurDir => {}
Component::ParentDir => resource_path.push("_up_"),
Component::Normal(p) => resource_path.push(p),
}
}
base_dir_path.push(resource_path);
} else {
base_dir_path.push(path);
}
}
Ok(base_dir_path)
}
#[cfg(test)]
mod test {
use super::SafePathBuf;
use quickcheck::{Arbitrary, Gen};
use std::path::PathBuf;
impl Arbitrary for SafePathBuf {
fn arbitrary(g: &mut Gen) -> Self {
Self(PathBuf::arbitrary(g))
}
fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
Box::new(self.0.shrink().map(SafePathBuf))
}
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/path/desktop.rs | crates/tauri/src/path/desktop.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use super::{Error, Result};
use crate::{AppHandle, Manager, Runtime};
use std::path::{Path, PathBuf};
/// The path resolver is a helper class for general and application-specific path APIs.
pub struct PathResolver<R: Runtime>(pub(crate) AppHandle<R>);
impl<R: Runtime> Clone for PathResolver<R> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<R: Runtime> PathResolver<R> {
/// Returns the final component of the `Path`, if there is one.
///
/// If the path is a normal file, this is the file name. If it's the path of a directory, this
/// is the directory name.
///
/// Returns [`None`] if the path terminates in `..`.
///
/// On Android this also supports checking the file name of content URIs, such as the values returned by the dialog plugin.
///
/// If you are dealing with plain file system paths or not worried about Android content URIs, prefer [`Path::file_name`].
pub fn file_name(&self, path: &str) -> Option<String> {
Path::new(path)
.file_name()
.map(|name| name.to_string_lossy().into_owned())
}
/// Returns the path to the user's audio directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to [`xdg-user-dirs`](https://www.freedesktop.org/wiki/Software/xdg-user-dirs/)' `XDG_MUSIC_DIR`.
/// - **macOS:** Resolves to `$HOME/Music`.
/// - **Windows:** Resolves to `{FOLDERID_Music}`.
pub fn audio_dir(&self) -> Result<PathBuf> {
dirs::audio_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's cache directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to `$XDG_CACHE_HOME` or `$HOME/.cache`.
/// - **macOS:** Resolves to `$HOME/Library/Caches`.
/// - **Windows:** Resolves to `{FOLDERID_LocalAppData}`.
pub fn cache_dir(&self) -> Result<PathBuf> {
dirs::cache_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's config directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to `$XDG_CONFIG_HOME` or `$HOME/.config`.
/// - **macOS:** Resolves to `$HOME/Library/Application Support`.
/// - **Windows:** Resolves to `{FOLDERID_RoamingAppData}`.
pub fn config_dir(&self) -> Result<PathBuf> {
dirs::config_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's data directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to `$XDG_DATA_HOME` or `$HOME/.local/share`.
/// - **macOS:** Resolves to `$HOME/Library/Application Support`.
/// - **Windows:** Resolves to `{FOLDERID_RoamingAppData}`.
pub fn data_dir(&self) -> Result<PathBuf> {
dirs::data_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's local data directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to `$XDG_DATA_HOME` or `$HOME/.local/share`.
/// - **macOS:** Resolves to `$HOME/Library/Application Support`.
/// - **Windows:** Resolves to `{FOLDERID_LocalAppData}`.
pub fn local_data_dir(&self) -> Result<PathBuf> {
dirs::data_local_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's desktop directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to [`xdg-user-dirs`](https://www.freedesktop.org/wiki/Software/xdg-user-dirs/)' `XDG_DESKTOP_DIR`.
/// - **macOS:** Resolves to `$HOME/Desktop`.
/// - **Windows:** Resolves to `{FOLDERID_Desktop}`.
pub fn desktop_dir(&self) -> Result<PathBuf> {
dirs::desktop_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's document directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to [`xdg-user-dirs`](https://www.freedesktop.org/wiki/Software/xdg-user-dirs/)' `XDG_DOCUMENTS_DIR`.
/// - **macOS:** Resolves to `$HOME/Documents`.
/// - **Windows:** Resolves to `{FOLDERID_Documents}`.
pub fn document_dir(&self) -> Result<PathBuf> {
dirs::document_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's download directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to [`xdg-user-dirs`](https://www.freedesktop.org/wiki/Software/xdg-user-dirs/)' `XDG_DOWNLOAD_DIR`.
/// - **macOS:** Resolves to `$HOME/Downloads`.
/// - **Windows:** Resolves to `{FOLDERID_Downloads}`.
pub fn download_dir(&self) -> Result<PathBuf> {
dirs::download_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's executable directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to `$XDG_BIN_HOME/../bin` or `$XDG_DATA_HOME/../bin` or `$HOME/.local/bin`.
/// - **macOS:** Not supported.
/// - **Windows:** Not supported.
pub fn executable_dir(&self) -> Result<PathBuf> {
dirs::executable_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's font directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to `$XDG_DATA_HOME/fonts` or `$HOME/.local/share/fonts`.
/// - **macOS:** Resolves to `$HOME/Library/Fonts`.
/// - **Windows:** Not supported.
pub fn font_dir(&self) -> Result<PathBuf> {
dirs::font_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's home directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to `$HOME`.
/// - **macOS:** Resolves to `$HOME`.
/// - **Windows:** Resolves to `{FOLDERID_Profile}`.
/// - **iOS**: Cannot be written to directly, use one of the app paths instead.
pub fn home_dir(&self) -> Result<PathBuf> {
dirs::home_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's picture directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to [`xdg-user-dirs`](https://www.freedesktop.org/wiki/Software/xdg-user-dirs/)' `XDG_PICTURES_DIR`.
/// - **macOS:** Resolves to `$HOME/Pictures`.
/// - **Windows:** Resolves to `{FOLDERID_Pictures}`.
pub fn picture_dir(&self) -> Result<PathBuf> {
dirs::picture_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's public directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to [`xdg-user-dirs`](https://www.freedesktop.org/wiki/Software/xdg-user-dirs/)' `XDG_PUBLICSHARE_DIR`.
/// - **macOS:** Resolves to `$HOME/Public`.
/// - **Windows:** Resolves to `{FOLDERID_Public}`.
pub fn public_dir(&self) -> Result<PathBuf> {
dirs::public_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's runtime directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to `$XDG_RUNTIME_DIR`.
/// - **macOS:** Not supported.
/// - **Windows:** Not supported.
pub fn runtime_dir(&self) -> Result<PathBuf> {
dirs::runtime_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's template directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to [`xdg-user-dirs`](https://www.freedesktop.org/wiki/Software/xdg-user-dirs/)' `XDG_TEMPLATES_DIR`.
/// - **macOS:** Not supported.
/// - **Windows:** Resolves to `{FOLDERID_Templates}`.
pub fn template_dir(&self) -> Result<PathBuf> {
dirs::template_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's video dir
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to [`xdg-user-dirs`](https://www.freedesktop.org/wiki/Software/xdg-user-dirs/)' `XDG_VIDEOS_DIR`.
/// - **macOS:** Resolves to `$HOME/Movies`.
/// - **Windows:** Resolves to `{FOLDERID_Videos}`.
pub fn video_dir(&self) -> Result<PathBuf> {
dirs::video_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the resource directory of this app.
///
/// ## Platform-specific
///
/// Although we provide the exact path where this function resolves to,
/// this is not a contract and things might change in the future
///
/// - **Windows:** Resolves to the directory that contains the main executable.
/// - **Linux:** When running in an AppImage, the `APPDIR` variable will be set to
/// the mounted location of the app, and the resource dir will be `${APPDIR}/usr/lib/${exe_name}`.
/// If not running in an AppImage, the path is `/usr/lib/${exe_name}`.
/// When running the app from `src-tauri/target/(debug|release)/`, the path is `${exe_dir}/../lib/${exe_name}`.
/// - **macOS:** Resolves to `${exe_dir}/../Resources` (inside .app).
/// - **iOS:** Resolves to `${exe_dir}/assets`.
/// - **Android:** Currently the resources are stored in the APK as assets so it's not a normal file system path,
/// we return a special URI prefix `asset://localhost/` here that can be used with the [file system plugin](https://tauri.app/plugin/file-system/),
/// with that, you can read the files through [`FsExt::fs`](https://docs.rs/tauri-plugin-fs/latest/tauri_plugin_fs/trait.FsExt.html#tymethod.fs)
/// like this: `app.fs().read_to_string(app.path().resource_dir().unwrap().join("resource"));`
pub fn resource_dir(&self) -> Result<PathBuf> {
crate::utils::platform::resource_dir(self.0.package_info(), &self.0.env())
.map_err(|_| Error::UnknownPath)
}
/// Returns the path to the suggested directory for your app's config files.
///
/// Resolves to [`config_dir`](Self::config_dir)`/${bundle_identifier}`.
pub fn app_config_dir(&self) -> Result<PathBuf> {
dirs::config_dir()
.ok_or(Error::UnknownPath)
.map(|dir| dir.join(&self.0.config().identifier))
}
/// Returns the path to the suggested directory for your app's data files.
///
/// Resolves to [`data_dir`](Self::data_dir)`/${bundle_identifier}`.
pub fn app_data_dir(&self) -> Result<PathBuf> {
dirs::data_dir()
.ok_or(Error::UnknownPath)
.map(|dir| dir.join(&self.0.config().identifier))
}
/// Returns the path to the suggested directory for your app's local data files.
///
/// Resolves to [`local_data_dir`](Self::local_data_dir)`/${bundle_identifier}`.
pub fn app_local_data_dir(&self) -> Result<PathBuf> {
dirs::data_local_dir()
.ok_or(Error::UnknownPath)
.map(|dir| dir.join(&self.0.config().identifier))
}
/// Returns the path to the suggested directory for your app's cache files.
///
/// Resolves to [`cache_dir`](Self::cache_dir)`/${bundle_identifier}`.
pub fn app_cache_dir(&self) -> Result<PathBuf> {
dirs::cache_dir()
.ok_or(Error::UnknownPath)
.map(|dir| dir.join(&self.0.config().identifier))
}
/// Returns the path to the suggested directory for your app's log files.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to [`local_data_dir`](Self::local_data_dir)`/${bundle_identifier}/logs`.
/// - **macOS:** Resolves to [`home_dir`](Self::home_dir)`/Library/Logs/${bundle_identifier}`
/// - **Windows:** Resolves to [`local_data_dir`](Self::local_data_dir)`/${bundle_identifier}/logs`.
pub fn app_log_dir(&self) -> Result<PathBuf> {
#[cfg(target_os = "macos")]
let path = dirs::home_dir()
.ok_or(Error::UnknownPath)
.map(|dir| dir.join("Library/Logs").join(&self.0.config().identifier));
#[cfg(not(target_os = "macos"))]
let path = dirs::data_local_dir()
.ok_or(Error::UnknownPath)
.map(|dir| dir.join(&self.0.config().identifier).join("logs"));
path
}
/// A temporary directory. Resolves to [`std::env::temp_dir`].
pub fn temp_dir(&self) -> Result<PathBuf> {
Ok(std::env::temp_dir())
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/path/plugin.rs | crates/tauri/src/path/plugin.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::path::{Component, Path, PathBuf, MAIN_SEPARATOR};
use serialize_to_javascript::{default_template, DefaultTemplate, Template};
use super::{BaseDirectory, Error, PathResolver, Result};
use crate::{
command,
plugin::{Builder, TauriPlugin},
AppHandle, Manager, Runtime, State,
};
/// Normalize a path, removing things like `.` and `..`, this snippet is taken from cargo's paths util.
/// <https://github.com/rust-lang/cargo/blob/46fa867ff7043e3a0545bf3def7be904e1497afd/crates/cargo-util/src/paths.rs#L73-L106>
fn normalize_path(path: &Path) -> PathBuf {
let mut components = path.components().peekable();
let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().copied() {
components.next();
PathBuf::from(c.as_os_str())
} else {
PathBuf::new()
};
for component in components {
match component {
Component::Prefix(..) => unreachable!(),
Component::RootDir => {
ret.push(component.as_os_str());
}
Component::CurDir => {}
Component::ParentDir => {
ret.pop();
}
Component::Normal(c) => {
ret.push(c);
}
}
}
ret
}
/// Normalize a path, removing things like `.` and `..`, this snippet is taken from cargo's paths util but
/// slightly modified to not resolve absolute paths.
/// <https://github.com/rust-lang/cargo/blob/46fa867ff7043e3a0545bf3def7be904e1497afd/crates/cargo-util/src/paths.rs#L73-L106>
fn normalize_path_no_absolute(path: &Path) -> PathBuf {
let mut components = path.components().peekable();
let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().copied() {
components.next();
PathBuf::from(c.as_os_str())
} else {
PathBuf::new()
};
for component in components {
match component {
Component::Prefix(..) => unreachable!(),
Component::RootDir => {
ret.push(component.as_os_str());
}
Component::CurDir => {}
Component::ParentDir => {
ret.pop();
}
Component::Normal(c) => {
// Using PathBuf::push here will replace the whole path if an absolute path is encountered
// which is not the intended behavior, so instead of that, convert the current resolved path
// to a string and do simple string concatenation with the current component then convert it
// back to a PathBuf
let mut p = ret.to_string_lossy().to_string();
// Only add a separator if it doesn't have one already or if current normalized path is empty,
// this ensures it won't have an unwanted leading separator
if !p.is_empty() && !p.ends_with('/') && !p.ends_with('\\') {
p.push(MAIN_SEPARATOR);
}
if let Some(c) = c.to_str() {
p.push_str(c);
}
ret = PathBuf::from(p);
}
}
}
ret
}
#[command(root = "crate")]
pub fn resolve_directory<R: Runtime>(
_app: AppHandle<R>,
resolver: State<'_, PathResolver<R>>,
directory: BaseDirectory,
path: Option<PathBuf>,
) -> Result<PathBuf> {
super::resolve_path(&resolver, directory, path).map(|p| dunce::simplified(&p).to_path_buf())
}
#[command(root = "crate")]
pub fn resolve(paths: Vec<String>) -> Result<PathBuf> {
// Start with current directory then start adding paths from the vector one by one using `PathBuf.push()` which
// will ensure that if an absolute path is encountered in the iteration, it will be used as the current full path.
//
// examples:
// 1. `vec!["."]` or `vec![]` will be equal to `std::env::current_dir()`
// 2. `vec!["/foo/bar", "/tmp/file", "baz"]` will be equal to `PathBuf::from("/tmp/file/baz")`
let mut path = std::env::current_dir().map_err(Error::CurrentDir)?;
for p in paths {
path.push(p);
}
Ok(dunce::simplified(&normalize_path(&path)).to_path_buf())
}
#[command(root = "crate")]
pub fn normalize(path: String) -> String {
let mut p = dunce::simplified(&normalize_path_no_absolute(Path::new(&path)))
.to_string_lossy()
.to_string();
// Node.js behavior is to return `".."` for `normalize("..")`
// and `"."` for `normalize("")` or `normalize(".")`
if p.is_empty() && path == ".." {
"..".into()
} else if p.is_empty() && path == "." {
".".into()
} else {
// Add a trailing separator if the path passed to this functions had a trailing separator. That's how Node.js behaves.
if (path.ends_with('/') || path.ends_with('\\')) && (!p.ends_with('/') || !p.ends_with('\\')) {
p.push(MAIN_SEPARATOR);
}
p
}
}
#[command(root = "crate")]
pub fn join(paths: Vec<String>) -> String {
let path = PathBuf::from(
paths
.into_iter()
.map(|mut p| {
// Add a `MAIN_SEPARATOR` if it doesn't already have one and is not an empty string.
// Doing this to ensure that the vector elements are separated in
// the resulting string so path.components() can work correctly when called
// in `normalize_path_no_absolute()` later on.
if !p.is_empty() && !p.ends_with('/') && !p.ends_with('\\') {
p.push(MAIN_SEPARATOR);
}
p
})
.collect::<String>(),
);
let p = dunce::simplified(&normalize_path_no_absolute(&path))
.to_string_lossy()
.to_string();
if p.is_empty() {
".".into()
} else {
p
}
}
#[command(root = "crate")]
pub fn dirname(path: String) -> Result<PathBuf> {
match Path::new(&path).parent() {
Some(p) => Ok(dunce::simplified(p).to_path_buf()),
None => Err(Error::NoParent),
}
}
#[command(root = "crate")]
pub fn extname<R: Runtime>(app: AppHandle<R>, path: String) -> Result<String> {
let file_name = app.path().file_name(&path).ok_or(Error::NoExtension)?;
match Path::new(&file_name)
.extension()
.and_then(std::ffi::OsStr::to_str)
{
Some(p) => Ok(p.to_string()),
None => Err(Error::NoExtension),
}
}
#[command(root = "crate")]
pub fn basename<R: Runtime>(app: AppHandle<R>, path: &str, ext: Option<&str>) -> Result<String> {
let file_name = app.path().file_name(path);
match file_name {
Some(p) => {
let maybe_stripped = if let Some(ext) = ext {
p.strip_suffix(ext).unwrap_or(&p).to_string()
} else {
p
};
Ok(maybe_stripped)
}
None => Err(Error::NoBasename),
}
}
#[command(root = "crate")]
pub fn is_absolute(path: String) -> bool {
Path::new(&path).is_absolute()
}
#[derive(Template)]
#[default_template("./init.js")]
struct InitJavascript {
sep: &'static str,
delimiter: &'static str,
}
/// Initializes the plugin.
pub(crate) fn init<R: Runtime>() -> TauriPlugin<R> {
#[cfg(windows)]
let (sep, delimiter) = ("\\", ";");
#[cfg(not(windows))]
let (sep, delimiter) = ("/", ":");
let init_js = InitJavascript { sep, delimiter }
.render_default(&Default::default())
// this will never fail with the above sep and delimiter values
.unwrap();
Builder::new("path")
.invoke_handler(crate::generate_handler![
#![plugin(path)]
resolve_directory,
resolve,
normalize,
join,
dirname,
extname,
basename,
is_absolute
])
.js_init_script(init_js.to_string())
.setup(|app, _api| {
#[cfg(target_os = "android")]
{
let handle = _api.register_android_plugin("app.tauri", "PathPlugin")?;
app.manage(PathResolver(handle));
}
#[cfg(not(target_os = "android"))]
{
app.manage(PathResolver(app.clone()));
}
Ok(())
})
.build()
}
#[cfg(test)]
mod tests {
use crate::test::mock_app;
#[test]
fn basename() {
let app = mock_app();
let path = "/path/to/some-json-file.json";
assert_eq!(
super::basename(app.handle().clone(), path, Some(".json")).unwrap(),
"some-json-file"
);
let path = "/path/to/some-json-file.json";
assert_eq!(
super::basename(app.handle().clone(), path, Some("json")).unwrap(),
"some-json-file."
);
let path = "/path/to/some-json-file.html.json";
assert_eq!(
super::basename(app.handle().clone(), path, Some(".json")).unwrap(),
"some-json-file.html"
);
let path = "/path/to/some-json-file.json.json";
assert_eq!(
super::basename(app.handle().clone(), path, Some(".json")).unwrap(),
"some-json-file.json"
);
let path = "/path/to/some-json-file.json.html";
assert_eq!(
super::basename(app.handle().clone(), path, Some(".json")).unwrap(),
"some-json-file.json.html"
);
}
#[test]
fn join() {
fn check(paths: Vec<&str>, expected_unix: &str, expected_windows: &str) {
let expected = if cfg!(windows) {
expected_windows
} else {
expected_unix
};
let paths = paths.into_iter().map(String::from).collect();
assert_eq!(super::join(paths), expected);
}
check(vec![""], ".", ".");
check(vec!["", ""], ".", ".");
check(vec!["a"], "a", "a");
check(vec!["", "a"], "a", "a");
check(vec!["a", "b"], "a/b", r"a\b");
check(vec!["a", "", "b"], "a/b", r"a\b");
check(vec!["a", "/b", "c"], "a/b/c", r"a\b\c");
check(vec!["a", "b/c", "d"], "a/b/c/d", r"a\b\c\d");
check(vec!["a/", "b"], "a/b", r"a\b");
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/resources/mod.rs | crates/tauri/src/resources/mod.rs | // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
// a modified version of https://github.com/denoland/deno/blob/0ae83847f498a2886ae32172e50fd5bdbab2f524/core/resources.rs#L220
pub(crate) mod plugin;
use std::{
any::{type_name, Any, TypeId},
borrow::Cow,
collections::BTreeMap,
sync::Arc,
};
/// Resources are Rust objects that are stored in [ResourceTable] and managed by tauri.
///
/// They are identified in JS by a numeric ID (the resource ID, or rid).
/// Resources can be created in commands. Resources can also be retrieved in commands by
/// their rid. Resources are thread-safe.
///
/// Resources are reference counted in Rust. This means that they can be
/// cloned and passed around. When the last reference is dropped, the resource
/// is automatically closed. As long as the resource exists in the resource
/// table, the reference count is at least 1.
pub trait Resource: Any + 'static + Send + Sync {
/// Returns a string representation of the resource. The default implementation
/// returns the Rust type name, but specific resource types may override this
/// trait method.
fn name(&self) -> Cow<'_, str> {
type_name::<Self>().into()
}
/// Resources may implement the `close()` trait method if they need to do
/// resource specific clean-ups, such as cancelling pending futures, after a
/// resource has been removed from the resource table.
fn close(self: Arc<Self>) {}
}
impl dyn Resource {
#[inline(always)]
fn is<T: Resource>(&self) -> bool {
self.type_id() == TypeId::of::<T>()
}
#[inline(always)]
pub(crate) fn downcast_arc<'a, T: Resource>(self: &'a Arc<Self>) -> Option<&'a Arc<T>> {
if self.is::<T>() {
// A resource is stored as `Arc<T>` in a BTreeMap
// and is safe to cast to `Arc<T>` because of the runtime
// check done in `self.is::<T>()`
let ptr = self as *const Arc<_> as *const Arc<T>;
Some(unsafe { &*ptr })
} else {
None
}
}
}
/// A `ResourceId` is an integer value referencing a resource. It could be
/// considered to be the tauri equivalent of a `file descriptor` in POSIX like
/// operating systems.
pub type ResourceId = u32;
/// Map-like data structure storing Tauri's resources (equivalent to file
/// descriptors).
///
/// Provides basic methods for element access. A resource can be of any type.
/// Different types of resources can be stored in the same map, and provided
/// with a name for description.
///
/// Each resource is identified through a _resource ID (rid)_, which acts as
/// the key in the map.
#[derive(Default)]
pub struct ResourceTable {
index: BTreeMap<ResourceId, Arc<dyn Resource>>,
}
impl ResourceTable {
fn new_random_rid() -> u32 {
let mut bytes = [0_u8; 4];
getrandom::fill(&mut bytes).expect("failed to get random bytes");
u32::from_ne_bytes(bytes)
}
/// Inserts resource into the resource table, which takes ownership of it.
///
/// The resource type is erased at runtime and must be statically known
/// when retrieving it through `get()`.
///
/// Returns a unique resource ID, which acts as a key for this resource.
pub fn add<T: Resource>(&mut self, resource: T) -> ResourceId {
self.add_arc(Arc::new(resource))
}
/// Inserts a `Arc`-wrapped resource into the resource table.
///
/// The resource type is erased at runtime and must be statically known
/// when retrieving it through `get()`.
///
/// Returns a unique resource ID, which acts as a key for this resource.
pub fn add_arc<T: Resource>(&mut self, resource: Arc<T>) -> ResourceId {
let resource = resource as Arc<dyn Resource>;
self.add_arc_dyn(resource)
}
/// Inserts a `Arc`-wrapped resource into the resource table.
///
/// The resource type is erased at runtime and must be statically known
/// when retrieving it through `get()`.
///
/// Returns a unique resource ID, which acts as a key for this resource.
pub fn add_arc_dyn(&mut self, resource: Arc<dyn Resource>) -> ResourceId {
let mut rid = Self::new_random_rid();
while self.index.contains_key(&rid) {
rid = Self::new_random_rid();
}
let removed_resource = self.index.insert(rid, resource);
assert!(removed_resource.is_none());
rid
}
/// Returns true if any resource with the given `rid` exists.
pub fn has(&self, rid: ResourceId) -> bool {
self.index.contains_key(&rid)
}
/// Returns a reference counted pointer to the resource of type `T` with the
/// given `rid`. If `rid` is not present or has a type different than `T`,
/// this function returns [`Error::BadResourceId`](crate::Error::BadResourceId).
pub fn get<T: Resource>(&self, rid: ResourceId) -> crate::Result<Arc<T>> {
self
.index
.get(&rid)
.and_then(|rc| rc.downcast_arc::<T>())
.cloned()
.ok_or_else(|| crate::Error::BadResourceId(rid))
}
/// Returns a reference counted pointer to the resource of the given `rid`.
/// If `rid` is not present, this function returns [`Error::BadResourceId`].
pub fn get_any(&self, rid: ResourceId) -> crate::Result<Arc<dyn Resource>> {
self
.index
.get(&rid)
.ok_or_else(|| crate::Error::BadResourceId(rid))
.cloned()
}
/// Replaces a resource with a new resource.
///
/// Panics if the resource does not exist.
pub fn replace<T: Resource>(&mut self, rid: ResourceId, resource: T) {
let result = self
.index
.insert(rid, Arc::new(resource) as Arc<dyn Resource>);
assert!(result.is_some());
}
/// Removes a resource of type `T` from the resource table and returns it.
/// If a resource with the given `rid` exists but its type does not match `T`,
/// it is not removed from the resource table. Note that the resource's
/// `close()` method is *not* called.
///
/// Also note that there might be a case where
/// the returned `Arc<T>` is referenced by other variables. That is, we cannot
/// assume that `Arc::strong_count(&returned_arc)` is always equal to 1 on success.
/// In particular, be really careful when you want to extract the inner value of
/// type `T` from `Arc<T>`.
pub fn take<T: Resource>(&mut self, rid: ResourceId) -> crate::Result<Arc<T>> {
let resource = self.get::<T>(rid)?;
self.index.remove(&rid);
Ok(resource)
}
/// Removes a resource from the resource table and returns it. Note that the
/// resource's `close()` method is *not* called.
///
/// Also note that there might be a
/// case where the returned `Arc<T>` is referenced by other variables. That is,
/// we cannot assume that `Arc::strong_count(&returned_arc)` is always equal to 1
/// on success. In particular, be really careful when you want to extract the
/// inner value of type `T` from `Arc<T>`.
pub fn take_any(&mut self, rid: ResourceId) -> crate::Result<Arc<dyn Resource>> {
self
.index
.remove(&rid)
.ok_or_else(|| crate::Error::BadResourceId(rid))
}
/// Returns an iterator that yields a `(id, name)` pair for every resource
/// that's currently in the resource table. This can be used for debugging
/// purposes. Note that the order in
/// which items appear is not specified.
pub fn names(&self) -> impl Iterator<Item = (ResourceId, Cow<'_, str>)> {
self
.index
.iter()
.map(|(&id, resource)| (id, resource.name()))
}
/// Removes the resource with the given `rid` from the resource table. If the
/// only reference to this resource existed in the resource table, this will
/// cause the resource to be dropped. However, since resources are reference
/// counted, therefore pending ops are not automatically cancelled. A resource
/// may implement the `close()` method to perform clean-ups such as canceling
/// ops.
pub fn close(&mut self, rid: ResourceId) -> crate::Result<()> {
self
.index
.remove(&rid)
.ok_or_else(|| crate::Error::BadResourceId(rid))
.map(|resource| resource.close())
}
/// Removes and frees all resources stored. Note that the
/// resource's `close()` method is *not* called.
pub(crate) fn clear(&mut self) {
self.index.clear()
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/resources/plugin.rs | crates/tauri/src/resources/plugin.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{
command,
plugin::{Builder, TauriPlugin},
Manager, Runtime, Webview,
};
use super::ResourceId;
#[command(root = "crate")]
fn close<R: Runtime>(webview: Webview<R>, rid: ResourceId) -> crate::Result<()> {
let mut result = webview.resources_table().close(rid);
if result.is_err() {
result = webview.window().resources_table().close(rid);
if result.is_err() {
result = webview.app_handle().resources_table().close(rid);
}
}
result
}
pub(crate) fn init<R: Runtime>() -> TauriPlugin<R> {
Builder::new("resources")
.invoke_handler(crate::generate_handler![
#![plugin(resources)]
close
])
.build()
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/protocol/tauri.rs | crates/tauri/src/protocol/tauri.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{borrow::Cow, sync::Arc};
use http::{header::CONTENT_TYPE, Request, Response as HttpResponse, StatusCode};
use tauri_utils::config::HeaderAddition;
use crate::{
manager::{webview::PROXY_DEV_SERVER, AppManager},
webview::{UriSchemeProtocolHandler, WebResourceRequestHandler},
Runtime,
};
#[cfg(all(dev, mobile))]
use std::{collections::HashMap, sync::Mutex};
#[cfg(all(dev, mobile))]
#[derive(Clone)]
struct CachedResponse {
status: http::StatusCode,
headers: http::HeaderMap,
body: bytes::Bytes,
}
pub fn get<R: Runtime>(
#[allow(unused_variables)] manager: Arc<AppManager<R>>,
window_origin: &str,
web_resource_request_handler: Option<Box<WebResourceRequestHandler>>,
) -> UriSchemeProtocolHandler {
#[cfg(all(dev, mobile))]
let url = {
let mut url = manager
.get_app_url(window_origin.starts_with("https"))
.as_str()
.to_string();
if url.ends_with('/') {
url.pop();
}
url
};
let window_origin = window_origin.to_string();
#[cfg(all(dev, mobile))]
let response_cache = Arc::new(Mutex::new(HashMap::new()));
Box::new(move |_, request, responder| {
match get_response(
request,
&manager,
&window_origin,
web_resource_request_handler.as_deref(),
#[cfg(all(dev, mobile))]
(&url, &response_cache),
) {
Ok(response) => responder.respond(response),
Err(e) => responder.respond(
HttpResponse::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.header(CONTENT_TYPE, mime::TEXT_PLAIN.essence_str())
.header("Access-Control-Allow-Origin", &window_origin)
.body(e.to_string().into_bytes())
.unwrap(),
),
}
})
}
fn get_response<R: Runtime>(
#[allow(unused_mut)] mut request: Request<Vec<u8>>,
#[allow(unused_variables)] manager: &AppManager<R>,
window_origin: &str,
web_resource_request_handler: Option<&WebResourceRequestHandler>,
#[cfg(all(dev, mobile))] (url, response_cache): (
&str,
&Arc<Mutex<HashMap<String, CachedResponse>>>,
),
) -> Result<HttpResponse<Cow<'static, [u8]>>, Box<dyn std::error::Error>> {
// use the entire URI as we are going to proxy the request
let path = if PROXY_DEV_SERVER {
request.uri().to_string()
} else {
// ignore query string and fragment
request
.uri()
.to_string()
.split(&['?', '#'][..])
.next()
.unwrap()
.into()
};
let path = path
.strip_prefix("tauri://localhost")
.map(|p| p.to_string())
// the `strip_prefix` only returns None when a request is made to `https://tauri.$P` on Windows and Android
// where `$P` is not `localhost/*`
.unwrap_or_default();
let mut builder = HttpResponse::builder()
.add_configured_headers(manager.config.app.security.headers.as_ref())
.header("Access-Control-Allow-Origin", window_origin);
#[cfg(all(dev, mobile))]
let mut response = {
let decoded_path = percent_encoding::percent_decode(path.as_bytes())
.decode_utf8_lossy()
.to_string();
let url = format!(
"{}/{}",
url.trim_end_matches('/'),
decoded_path.trim_start_matches('/')
);
let mut client = reqwest::ClientBuilder::new();
if url.starts_with("https://") {
// we can't load env vars at runtime, gotta embed them in the lib
if let Some(cert_pem) = option_env!("TAURI_DEV_ROOT_CERTIFICATE") {
#[cfg(any(
feature = "native-tls",
feature = "native-tls-vendored",
feature = "rustls-tls"
))]
{
log::info!("adding dev server root certificate");
client = client.add_root_certificate(
reqwest::Certificate::from_pem(cert_pem.as_bytes())
.expect("failed to parse TAURI_DEV_ROOT_CERTIFICATE"),
);
}
#[cfg(not(any(
feature = "native-tls",
feature = "native-tls-vendored",
feature = "rustls-tls"
)))]
{
log::warn!(
"the dev root-certificate-path option was provided, but you must enable one of the following Tauri features in Cargo.toml: native-tls, native-tls-vendored, rustls-tls"
);
}
} else {
log::warn!(
"loading HTTPS URL; you might need to provide a certificate via the `dev --root-certificate-path` option. You must enable one of the following Tauri features in Cargo.toml: native-tls, native-tls-vendored, rustls-tls"
);
}
}
let mut proxy_builder = client
.build()
.unwrap()
.request(request.method().clone(), &url);
proxy_builder = proxy_builder.body(std::mem::take(request.body_mut()));
for (name, value) in request.headers() {
proxy_builder = proxy_builder.header(name, value);
}
proxy_builder = proxy_builder.body(request.body().clone());
match crate::async_runtime::safe_block_on(proxy_builder.send()) {
Ok(r) => {
let mut response_cache_ = response_cache.lock().unwrap();
let mut response = None;
if r.status() == http::StatusCode::NOT_MODIFIED {
response = response_cache_.get(&url);
}
let response = if let Some(r) = response {
r
} else {
let status = r.status();
let headers = r.headers().clone();
let body = crate::async_runtime::safe_block_on(r.bytes())?;
let response = CachedResponse {
status,
headers,
body,
};
response_cache_.insert(url.clone(), response);
response_cache_.get(&url).unwrap()
};
for (name, value) in &response.headers {
builder = builder.header(name, value);
}
builder
.status(response.status)
.body(response.body.to_vec().into())?
}
Err(e) => {
let error_message = format!(
"Failed to request {}: {}{}",
url.as_str(),
e,
if let Some(s) = e.status() {
format!("status code: {}", s.as_u16())
} else if cfg!(target_os = "ios") {
", did you grant local network permissions? That is required to reach the development server. Please grant the permission via the prompt or in `Settings > Privacy & Security > Local Network` and restart the app. See https://support.apple.com/en-us/102229 for more information.".to_string()
} else {
"".to_string()
}
);
log::error!("{error_message}");
return Err(error_message.into());
}
}
};
#[cfg(not(all(dev, mobile)))]
let mut response = {
let use_https_scheme = request.uri().scheme() == Some(&http::uri::Scheme::HTTPS);
let asset = manager.get_asset(path, use_https_scheme)?;
builder = builder.header(CONTENT_TYPE, &asset.mime_type);
if let Some(csp) = &asset.csp_header {
builder = builder.header("Content-Security-Policy", csp);
}
builder.body(asset.bytes.into())?
};
if let Some(handler) = &web_resource_request_handler {
handler(request, &mut response);
}
Ok(response)
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/protocol/asset.rs | crates/tauri/src/protocol/asset.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{path::SafePathBuf, scope, webview::UriSchemeProtocolHandler};
use http::{header::*, status::StatusCode, Request, Response};
use http_range::HttpRange;
use std::{borrow::Cow, io::SeekFrom};
use tauri_utils::mime_type::MimeType;
use tokio::fs::File;
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
pub fn get(scope: scope::fs::Scope, window_origin: String) -> UriSchemeProtocolHandler {
Box::new(
move |_, request, responder| match get_response(request, &scope, &window_origin) {
Ok(response) => responder.respond(response),
Err(e) => responder.respond(
http::Response::builder()
.status(http::StatusCode::INTERNAL_SERVER_ERROR)
.header(CONTENT_TYPE, mime::TEXT_PLAIN.essence_str())
.header("Access-Control-Allow-Origin", &window_origin)
.body(e.to_string().into_bytes())
.unwrap(),
),
},
)
}
fn get_response(
request: Request<Vec<u8>>,
scope: &scope::fs::Scope,
window_origin: &str,
) -> Result<Response<Cow<'static, [u8]>>, Box<dyn std::error::Error>> {
// skip leading `/`
let path = percent_encoding::percent_decode(&request.uri().path().as_bytes()[1..])
.decode_utf8_lossy()
.to_string();
let mut resp = Response::builder().header("Access-Control-Allow-Origin", window_origin);
if let Err(e) = SafePathBuf::new(path.clone().into()) {
log::error!("asset protocol path \"{}\" is not valid: {}", path, e);
return resp.status(403).body(Vec::new().into()).map_err(Into::into);
}
if !scope.is_allowed(&path) {
log::error!("asset protocol not configured to allow the path: {}", path);
return resp.status(403).body(Vec::new().into()).map_err(Into::into);
}
let (mut file, len, mime_type, read_bytes) = crate::async_runtime::safe_block_on(async move {
let mut file = File::open(&path).await?;
// get file length
let len = {
let old_pos = file.stream_position().await?;
let len = file.seek(SeekFrom::End(0)).await?;
file.seek(SeekFrom::Start(old_pos)).await?;
len
};
// get file mime type
let (mime_type, read_bytes) = {
let nbytes = len.min(8192);
let mut magic_buf = Vec::with_capacity(nbytes as usize);
let old_pos = file.stream_position().await?;
(&mut file).take(nbytes).read_to_end(&mut magic_buf).await?;
file.seek(SeekFrom::Start(old_pos)).await?;
(
MimeType::parse(&magic_buf, &path),
// return the `magic_bytes` if we read the whole file
// to avoid reading it again later if this is not a range request
if len < 8192 { Some(magic_buf) } else { None },
)
};
Ok::<(File, u64, String, Option<Vec<u8>>), anyhow::Error>((file, len, mime_type, read_bytes))
})?;
resp = resp.header(CONTENT_TYPE, &mime_type);
// handle 206 (partial range) http requests
let response = if let Some(range_header) = request
.headers()
.get("range")
.and_then(|r| r.to_str().map(|r| r.to_string()).ok())
{
resp = resp.header(ACCEPT_RANGES, "bytes");
resp = resp.header(ACCESS_CONTROL_EXPOSE_HEADERS, "content-range");
let not_satisfiable = || {
Response::builder()
.status(StatusCode::RANGE_NOT_SATISFIABLE)
.header(CONTENT_RANGE, format!("bytes */{len}"))
.body(vec![].into())
.map_err(Into::into)
};
// parse range header
let ranges = if let Ok(ranges) = HttpRange::parse(&range_header, len) {
ranges
.iter()
// map the output to spec range <start-end>, example: 0-499
.map(|r| (r.start, r.start + r.length - 1))
.collect::<Vec<_>>()
} else {
return not_satisfiable();
};
/// The Maximum bytes we send in one range
const MAX_LEN: u64 = 1000 * 1024;
// single-part range header
if ranges.len() == 1 {
let &(start, mut end) = ranges.first().unwrap();
// check if a range is not satisfiable
//
// this should be already taken care of by the range parsing library
// but checking here again for extra assurance
if start >= len || end >= len || end < start {
return not_satisfiable();
}
// adjust end byte for MAX_LEN
end = start + (end - start).min(len - start).min(MAX_LEN - 1);
// calculate number of bytes needed to be read
let nbytes = end + 1 - start;
let buf = crate::async_runtime::safe_block_on(async move {
let mut buf = Vec::with_capacity(nbytes as usize);
file.seek(SeekFrom::Start(start)).await?;
file.take(nbytes).read_to_end(&mut buf).await?;
Ok::<Vec<u8>, anyhow::Error>(buf)
})?;
resp = resp.header(CONTENT_RANGE, format!("bytes {start}-{end}/{len}"));
resp = resp.header(CONTENT_LENGTH, end + 1 - start);
resp = resp.status(StatusCode::PARTIAL_CONTENT);
resp.body(buf.into())
} else {
let ranges = ranges
.iter()
.filter_map(|&(start, mut end)| {
// filter out unsatisfiable ranges
//
// this should be already taken care of by the range parsing library
// but checking here again for extra assurance
if start >= len || end >= len || end < start {
None
} else {
// adjust end byte for MAX_LEN
end = start + (end - start).min(len - start).min(MAX_LEN - 1);
Some((start, end))
}
})
.collect::<Vec<_>>();
let boundary = random_boundary();
let boundary_sep = format!("\r\n--{boundary}\r\n");
let boundary_closer = format!("\r\n--{boundary}\r\n");
resp = resp.header(
CONTENT_TYPE,
format!("multipart/byteranges; boundary={boundary}"),
);
let buf = crate::async_runtime::safe_block_on(async move {
// multi-part range header
let mut buf = Vec::new();
for (end, start) in ranges {
// a new range is being written, write the range boundary
buf.write_all(boundary_sep.as_bytes()).await?;
// write the needed headers `Content-Type` and `Content-Range`
buf
.write_all(format!("{CONTENT_TYPE}: {mime_type}\r\n").as_bytes())
.await?;
buf
.write_all(format!("{CONTENT_RANGE}: bytes {start}-{end}/{len}\r\n").as_bytes())
.await?;
// write the separator to indicate the start of the range body
buf.write_all("\r\n".as_bytes()).await?;
// calculate number of bytes needed to be read
let nbytes = end + 1 - start;
let mut local_buf = Vec::with_capacity(nbytes as usize);
file.seek(SeekFrom::Start(start)).await?;
(&mut file).take(nbytes).read_to_end(&mut local_buf).await?;
buf.extend_from_slice(&local_buf);
}
// all ranges have been written, write the closing boundary
buf.write_all(boundary_closer.as_bytes()).await?;
Ok::<Vec<u8>, anyhow::Error>(buf)
})?;
resp.body(buf.into())
}
} else if request.method() == http::Method::HEAD {
// if the HEAD method is used, we should not return a body
resp = resp.header(CONTENT_LENGTH, len);
resp.body(Vec::new().into())
} else {
// avoid reading the file if we already read it
// as part of mime type detection
let buf = if let Some(b) = read_bytes {
b
} else {
crate::async_runtime::safe_block_on(async move {
let mut local_buf = Vec::with_capacity(len as usize);
file.read_to_end(&mut local_buf).await?;
Ok::<Vec<u8>, anyhow::Error>(local_buf)
})?
};
resp = resp.header(CONTENT_LENGTH, len);
resp.body(buf.into())
};
response.map_err(Into::into)
}
fn random_boundary() -> String {
let mut x = [0_u8; 30];
getrandom::fill(&mut x).expect("failed to get random bytes");
(x[..])
.iter()
.map(|&x| format!("{x:x}"))
.fold(String::new(), |mut a, x| {
a.push_str(x.as_str());
a
})
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/protocol/mod.rs | crates/tauri/src/protocol/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Custom protocol handlers
#[cfg(feature = "protocol-asset")]
pub mod asset;
#[cfg(feature = "isolation")]
pub mod isolation;
pub mod tauri;
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri/src/protocol/isolation.rs | crates/tauri/src/protocol/isolation.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::Assets;
use http::header::CONTENT_TYPE;
use serialize_to_javascript::Template;
use tauri_utils::{
assets::EmbeddedAssets,
config::{Csp, HeaderAddition},
};
use std::sync::Arc;
use crate::{
manager::{set_csp, webview::PROCESS_IPC_MESSAGE_FN, AppManager},
webview::UriSchemeProtocolHandler,
Runtime,
};
pub fn get<R: Runtime>(
manager: Arc<AppManager<R>>,
schema: &str,
assets: Arc<EmbeddedAssets>,
aes_gcm_key: [u8; 32],
window_origin: String,
use_https_scheme: bool,
) -> UriSchemeProtocolHandler {
let frame_src = if cfg!(any(windows, target_os = "android")) {
let https = if use_https_scheme { "https" } else { "http" };
format!("{https}://{schema}.localhost")
} else {
format!("{schema}:")
};
let assets = assets as Arc<dyn Assets<R>>;
Box::new(move |_, request, responder| {
let response = match request_to_path(&request).as_str() {
"index.html" => match assets.get(&"index.html".into()) {
Some(asset) => {
let mut asset = String::from_utf8_lossy(asset.as_ref()).into_owned();
let csp_map = set_csp(
&mut asset,
&assets,
&"index.html".into(),
&manager,
Csp::Policy(format!("default-src 'none'; frame-src {frame_src}")),
);
let csp = Csp::DirectiveMap(csp_map).to_string();
let template = tauri_utils::pattern::isolation::IsolationJavascriptRuntime {
runtime_aes_gcm_key: &aes_gcm_key,
origin: window_origin.clone(),
process_ipc_message_fn: PROCESS_IPC_MESSAGE_FN,
};
match template.render(asset.as_ref(), &Default::default()) {
Ok(asset) => http::Response::builder()
.add_configured_headers(manager.config.app.security.headers.as_ref())
.header(CONTENT_TYPE, mime::TEXT_HTML.as_ref())
.header("Content-Security-Policy", csp)
.body(asset.into_string().into_bytes()),
Err(_) => http::Response::builder()
.status(http::StatusCode::INTERNAL_SERVER_ERROR)
.header(CONTENT_TYPE, mime::TEXT_PLAIN.as_ref())
.body(Vec::new()),
}
}
None => http::Response::builder()
.status(http::StatusCode::NOT_FOUND)
.header(CONTENT_TYPE, mime::TEXT_PLAIN.as_ref())
.body(Vec::new()),
},
_ => http::Response::builder()
.status(http::StatusCode::NOT_FOUND)
.header(CONTENT_TYPE, mime::TEXT_PLAIN.as_ref())
.body(Vec::new()),
};
if let Ok(r) = response {
responder.respond(r);
} else {
responder.respond(
http::Response::builder()
.status(http::StatusCode::INTERNAL_SERVER_ERROR)
.body("failed to get response".as_bytes())
.unwrap(),
);
}
})
}
fn request_to_path(request: &http::Request<Vec<u8>>) -> String {
let path = request
.uri()
.path()
.trim_start_matches('/')
.trim_end_matches('/');
let path = percent_encoding::percent_decode(path.as_bytes())
.decode_utf8_lossy()
.to_string();
if path.is_empty() {
// if the url has no path, we should load `index.html`
"index.html".to_string()
} else {
// skip leading `/`
path.chars().skip(1).collect()
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-bundler/src/lib.rs | crates/tauri-bundler/src/lib.rs | // Copyright 2016-2019 Cargo-Bundle developers <https://github.com/burtonageo/cargo-bundle>
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! The Tauri bundler is a tool that generates installers or app bundles for executables.
//! It supports auto updating through [tauri](https://docs.rs/tauri).
//!
//! # Platform support
//! - macOS
//! - DMG and App bundles
//! - Linux
//! - Appimage, Debian and RPM packages
//! - Windows
//! - MSI using WiX
#![doc(
html_logo_url = "https://github.com/tauri-apps/tauri/raw/dev/.github/icon.png",
html_favicon_url = "https://github.com/tauri-apps/tauri/raw/dev/.github/icon.png"
)]
#![warn(missing_docs, rust_2018_idioms)]
/// The bundle API.
pub mod bundle;
mod error;
mod utils;
pub use bundle::*;
pub use error::{Error, Result};
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-bundler/src/bundle.rs | crates/tauri-bundler/src/bundle.rs | // Copyright 2016-2019 Cargo-Bundle developers <https://github.com/burtonageo/cargo-bundle>
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
mod category;
#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
mod platform;
mod settings;
mod updater_bundle;
mod windows;
use tauri_utils::{display_path, platform::Target as TargetPlatform};
/// Patch a binary with bundle type information
fn patch_binary(binary: &PathBuf, package_type: &PackageType) -> crate::Result<()> {
match package_type {
#[cfg(target_os = "linux")]
PackageType::AppImage | PackageType::Deb | PackageType::Rpm => {
log::info!(
"Patching binary {:?} for type {}",
binary,
package_type.short_name()
);
linux::patch_binary(binary, package_type)?;
}
PackageType::Nsis | PackageType::WindowsMsi => {
log::info!(
"Patching binary {:?} for type {}",
binary,
package_type.short_name()
);
windows::patch_binary(binary, package_type)?;
}
_ => (),
}
Ok(())
}
pub use self::{
category::AppCategory,
settings::{
AppImageSettings, BundleBinary, BundleSettings, CustomSignCommandSettings, DebianSettings,
DmgSettings, Entitlements, IosSettings, MacOsSettings, PackageSettings, PackageType, PlistKind,
Position, RpmSettings, Settings, SettingsBuilder, Size, UpdaterSettings,
},
};
pub use settings::{NsisSettings, WindowsSettings, WixLanguage, WixLanguageConfig, WixSettings};
use std::{
fmt::Write,
io::{Seek, SeekFrom},
path::PathBuf,
};
/// Generated bundle metadata.
#[derive(Debug)]
pub struct Bundle {
/// The package type.
pub package_type: PackageType,
/// All paths for this package.
pub bundle_paths: Vec<PathBuf>,
}
/// Bundles the project.
/// Returns the list of paths where the bundles can be found.
pub fn bundle_project(settings: &Settings) -> crate::Result<Vec<Bundle>> {
let mut package_types = settings.package_types()?;
if package_types.is_empty() {
return Ok(Vec::new());
}
package_types.sort_by_key(|a| a.priority());
let target_os = settings.target_platform();
if *target_os != TargetPlatform::current() {
log::warn!("Cross-platform compilation is experimental and does not support all features. Please use a matching host system for full compatibility.");
}
// Sign windows binaries before the bundling step in case neither wix and nsis bundles are enabled
sign_binaries_if_needed(settings, target_os)?;
let main_binary = settings
.binaries()
.iter()
.find(|b| b.main())
.expect("Main binary missing in settings");
let main_binary_path = settings.binary_path(main_binary);
// When packaging multiple binary types, we make a copy of the unsigned main_binary so that we can
// restore it after each package_type step. This avoids two issues:
// - modifying a signed binary without updating its PE checksum can break signature verification
// - codesigning tools should handle calculating+updating this, we just need to ensure
// (re)signing is performed after every `patch_binary()` operation
// - signing an already-signed binary can result in multiple signatures, causing verification errors
let main_binary_reset_required = matches!(target_os, TargetPlatform::Windows)
&& settings.windows().can_sign()
&& package_types.len() > 1;
let mut unsigned_main_binary_copy = tempfile::tempfile()?;
if main_binary_reset_required {
let mut unsigned_main_binary = std::fs::File::open(&main_binary_path)?;
std::io::copy(&mut unsigned_main_binary, &mut unsigned_main_binary_copy)?;
}
let mut main_binary_signed = false;
let mut bundles = Vec::<Bundle>::new();
for package_type in &package_types {
// bundle was already built! e.g. DMG already built .app
if bundles.iter().any(|b| b.package_type == *package_type) {
continue;
}
if let Err(e) = patch_binary(&main_binary_path, package_type) {
log::warn!("Failed to add bundler type to the binary: {e}. Updater plugin may not be able to update this package. This shouldn't normally happen, please report it to https://github.com/tauri-apps/tauri/issues");
}
// sign main binary for every package type after patch
if matches!(target_os, TargetPlatform::Windows) && settings.windows().can_sign() {
if main_binary_signed && main_binary_reset_required {
let mut signed_main_binary = std::fs::OpenOptions::new()
.write(true)
.truncate(true)
.open(&main_binary_path)?;
unsigned_main_binary_copy.seek(SeekFrom::Start(0))?;
std::io::copy(&mut unsigned_main_binary_copy, &mut signed_main_binary)?;
}
windows::sign::try_sign(&main_binary_path, settings)?;
main_binary_signed = true;
}
let bundle_paths = match package_type {
#[cfg(target_os = "macos")]
PackageType::MacOsBundle => macos::app::bundle_project(settings)?,
#[cfg(target_os = "macos")]
PackageType::IosBundle => macos::ios::bundle_project(settings)?,
// dmg is dependent of MacOsBundle, we send our bundles to prevent rebuilding
#[cfg(target_os = "macos")]
PackageType::Dmg => {
let bundled = macos::dmg::bundle_project(settings, &bundles)?;
if !bundled.app.is_empty() {
bundles.push(Bundle {
package_type: PackageType::MacOsBundle,
bundle_paths: bundled.app,
});
}
bundled.dmg
}
#[cfg(target_os = "windows")]
PackageType::WindowsMsi => windows::msi::bundle_project(settings, false)?,
// note: don't restrict to windows as NSIS installers can be built in linux using cargo-xwin
PackageType::Nsis => windows::nsis::bundle_project(settings, false)?,
#[cfg(target_os = "linux")]
PackageType::Deb => linux::debian::bundle_project(settings)?,
#[cfg(target_os = "linux")]
PackageType::Rpm => linux::rpm::bundle_project(settings)?,
#[cfg(target_os = "linux")]
PackageType::AppImage => linux::appimage::bundle_project(settings)?,
_ => {
log::warn!("ignoring {}", package_type.short_name());
continue;
}
};
bundles.push(Bundle {
package_type: package_type.to_owned(),
bundle_paths,
});
}
if let Some(updater) = settings.updater() {
if package_types.iter().any(|package_type| {
if updater.v1_compatible {
matches!(
package_type,
PackageType::AppImage
| PackageType::MacOsBundle
| PackageType::Nsis
| PackageType::WindowsMsi
| PackageType::Deb
)
} else {
matches!(package_type, PackageType::MacOsBundle)
}
}) {
let updater_paths = updater_bundle::bundle_project(settings, &bundles)?;
bundles.push(Bundle {
package_type: PackageType::Updater,
bundle_paths: updater_paths,
});
} else if updater.v1_compatible
|| !package_types.iter().any(|package_type| {
// Self contained updater, no need to zip
matches!(
package_type,
PackageType::AppImage | PackageType::Nsis | PackageType::WindowsMsi | PackageType::Deb
)
})
{
log::warn!("The bundler was configured to create updater artifacts but no updater-enabled targets were built. Please enable one of these targets: app, appimage, msi, nsis");
}
if updater.v1_compatible {
log::warn!("Legacy v1 compatible updater is deprecated and will be removed in v3, change bundle > createUpdaterArtifacts to true when your users are updated to the version with v2 updater plugin");
}
}
#[cfg(target_os = "macos")]
{
// Clean up .app if only building dmg or updater
if !package_types.contains(&PackageType::MacOsBundle) {
if let Some(app_bundle_paths) = bundles
.iter()
.position(|b| b.package_type == PackageType::MacOsBundle)
.map(|i| bundles.remove(i))
.map(|b| b.bundle_paths)
{
for app_bundle_path in &app_bundle_paths {
use crate::error::ErrorExt;
log::info!(action = "Cleaning"; "{}", app_bundle_path.display());
match app_bundle_path.is_dir() {
true => std::fs::remove_dir_all(app_bundle_path),
false => std::fs::remove_file(app_bundle_path),
}
.fs_context(
"failed to clean the app bundle",
app_bundle_path.to_path_buf(),
)?;
}
}
}
}
if bundles.is_empty() {
return Ok(bundles);
}
let finished_bundles = bundles
.iter()
.filter(|b| b.package_type != PackageType::Updater)
.count();
let pluralised = if finished_bundles == 1 {
"bundle"
} else {
"bundles"
};
let mut printable_paths = String::new();
for bundle in &bundles {
for path in &bundle.bundle_paths {
let note = if bundle.package_type == crate::PackageType::Updater {
" (updater)"
} else {
""
};
let path_display = display_path(path);
writeln!(printable_paths, " {path_display}{note}").unwrap();
}
}
log::info!(action = "Finished"; "{finished_bundles} {pluralised} at:\n{printable_paths}");
Ok(bundles)
}
fn sign_binaries_if_needed(settings: &Settings, target_os: &TargetPlatform) -> crate::Result<()> {
if matches!(target_os, TargetPlatform::Windows) {
if settings.windows().can_sign() {
if settings.no_sign() {
log::warn!("Skipping binary signing due to --no-sign flag.");
return Ok(());
}
for bin in settings.binaries() {
if bin.main() {
// we will sign the main binary after patching per "package type"
continue;
}
let bin_path = settings.binary_path(bin);
windows::sign::try_sign(&bin_path, settings)?;
}
// Sign the sidecar binaries
for bin in settings.external_binaries() {
let path = bin?;
let skip = std::env::var("TAURI_SKIP_SIDECAR_SIGNATURE_CHECK").is_ok_and(|v| v == "true");
if skip {
continue;
}
#[cfg(windows)]
if windows::sign::verify(&path)? {
log::info!(
"sidecar at \"{}\" already signed. Skipping...",
path.display()
);
continue;
}
windows::sign::try_sign(&path, settings)?;
}
} else {
#[cfg(not(target_os = "windows"))]
log::warn!("Signing, by default, is only supported on Windows hosts, but you can specify a custom signing command in `bundler > windows > sign_command`, for now, skipping signing the installer...");
}
}
Ok(())
}
/// Check to see if there are icons in the settings struct
pub fn check_icons(settings: &Settings) -> crate::Result<bool> {
// make a peekable iterator of the icon_files
let mut iter = settings.icon_files().peekable();
// if iter's first value is a None then there are no Icon files in the settings struct
if iter.peek().is_none() {
Ok(false)
} else {
Ok(true)
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-bundler/src/error.rs | crates/tauri-bundler/src/error.rs | // Copyright 2016-2019 Cargo-Bundle developers <https://github.com/burtonageo/cargo-bundle>
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{
fmt::Display,
io, num,
path::{self, PathBuf},
};
use thiserror::Error as DeriveError;
/// Errors returned by the bundler.
#[derive(Debug, DeriveError)]
#[non_exhaustive]
pub enum Error {
/// Error with context. Created by the [`Context`] trait.
#[error("{0}: {1}")]
Context(String, Box<Self>),
/// File system error.
#[error("{context} {path}: {error}")]
Fs {
/// Context of the error.
context: &'static str,
/// Path that was accessed.
path: PathBuf,
/// Error that occurred.
error: io::Error,
},
/// Child process error.
#[error("failed to run command {command}: {error}")]
CommandFailed {
/// Command that failed.
command: String,
/// Error that occurred.
error: io::Error,
},
/// Error running tauri_utils API.
#[error("{0}")]
Resource(#[from] tauri_utils::Error),
/// Bundler error.
///
/// This variant is no longer used as this crate no longer uses anyhow.
// TODO(v3): remove this variant
#[error("{0:#}")]
BundlerError(#[from] anyhow::Error),
/// I/O error.
#[error("`{0}`")]
IoError(#[from] io::Error),
/// Image error.
#[error("`{0}`")]
ImageError(#[from] image::ImageError),
/// Error walking directory.
#[error("`{0}`")]
WalkdirError(#[from] walkdir::Error),
/// Strip prefix error.
#[error("`{0}`")]
StripError(#[from] path::StripPrefixError),
/// Number parse error.
#[error("`{0}`")]
ConvertError(#[from] num::TryFromIntError),
/// Zip error.
#[error("`{0}`")]
ZipError(#[from] zip::result::ZipError),
/// Hex error.
#[error("`{0}`")]
HexError(#[from] hex::FromHexError),
/// Handlebars template error.
#[error("`{0}`")]
HandleBarsError(#[from] handlebars::RenderError),
/// JSON error.
#[error("`{0}`")]
JsonError(#[from] serde_json::error::Error),
/// Regex error.
#[cfg(any(target_os = "macos", windows))]
#[error("`{0}`")]
RegexError(#[from] regex::Error),
/// Failed to perform HTTP request.
#[error("`{0}`")]
HttpError(#[from] Box<ureq::Error>),
/// Invalid glob pattern.
#[cfg(windows)]
#[error("{0}")]
GlobPattern(#[from] glob::PatternError),
/// Failed to use glob pattern.
#[cfg(windows)]
#[error("`{0}`")]
Glob(#[from] glob::GlobError),
/// Failed to parse the URL
#[error("`{0}`")]
UrlParse(#[from] url::ParseError),
/// Failed to validate downloaded file hash.
#[error("hash mismatch of downloaded file")]
HashError,
/// Failed to parse binary
#[error("Binary parse error: `{0}`")]
BinaryParseError(#[from] goblin::error::Error),
/// Package type is not supported by target platform
#[error("Wrong package type {0} for platform {1}")]
InvalidPackageType(String, String),
/// Bundle type symbol missing in binary
#[cfg_attr(
target_os = "linux",
error("__TAURI_BUNDLE_TYPE variable not found in binary. Make sure tauri crate and tauri-cli are up to date and that symbol stripping is disabled (https://doc.rust-lang.org/cargo/reference/profiles.html#strip)")
)]
#[cfg_attr(
not(target_os = "linux"),
error("__TAURI_BUNDLE_TYPE variable not found in binary. Make sure tauri crate and tauri-cli are up to date")
)]
MissingBundleTypeVar,
/// Failed to write binary file changed
#[error("Failed to write binary file changes: `{0}`")]
BinaryWriteError(String),
/// Invalid offset while patching binary file
#[error("Invalid offset while patching binary file")]
BinaryOffsetOutOfRange,
/// Unsupported architecture.
#[error("Architecture Error: `{0}`")]
ArchError(String),
/// Couldn't find icons.
#[error("Could not find Icon paths. Please make sure they exist in the tauri config JSON file")]
IconPathError,
/// Couldn't find background file.
#[error("Could not find background file. Make sure it exists in the tauri config JSON file and extension is png/jpg/gif")]
BackgroundPathError,
/// Error on path util operation.
#[error("Path Error:`{0}`")]
PathUtilError(String),
/// Error on shell script.
#[error("Shell Scripting Error:`{0}`")]
ShellScriptError(String),
/// Generic error.
#[error("`{0}`")]
GenericError(String),
/// No bundled project found for the updater.
#[error("Unable to find a bundled project for the updater")]
UnableToFindProject,
/// String is not UTF-8.
#[error("string is not UTF-8")]
Utf8(#[from] std::str::Utf8Error),
/// Windows SignTool not found.
#[error("SignTool not found")]
SignToolNotFound,
/// Failed to open Windows registry.
#[error("failed to open registry {0}")]
OpenRegistry(String),
/// Failed to get registry value.
#[error("failed to get {0} value on registry")]
GetRegistryValue(String),
/// Failed to enumerate registry keys.
#[error("failed to enumerate registry keys")]
FailedToEnumerateRegKeys,
/// Unsupported OS bitness.
#[error("unsupported OS bitness")]
UnsupportedBitness,
/// Failed to sign application.
#[error("failed to sign app: {0}")]
Sign(String),
/// time error.
#[cfg(target_os = "macos")]
#[error("`{0}`")]
TimeError(#[from] time::error::Error),
/// Plist error.
#[cfg(target_os = "macos")]
#[error(transparent)]
Plist(#[from] plist::Error),
/// Rpm error.
#[cfg(target_os = "linux")]
#[error("{0}")]
RpmError(#[from] rpm::Error),
/// Failed to notarize application.
#[cfg(target_os = "macos")]
#[error("failed to notarize app: {0}")]
AppleNotarization(#[from] NotarizeAuthError),
/// Failed to codesign application.
#[cfg(target_os = "macos")]
#[error("failed codesign application: {0}")]
AppleCodesign(#[from] Box<tauri_macos_sign::Error>),
/// Handlebars template error.
#[error(transparent)]
Template(#[from] handlebars::TemplateError),
/// Semver error.
#[error("`{0}`")]
SemverError(#[from] semver::Error),
}
#[cfg(target_os = "macos")]
#[allow(clippy::enum_variant_names)]
#[derive(Debug, thiserror::Error)]
pub enum NotarizeAuthError {
#[error(
"The team ID is now required for notarization with app-specific password as authentication. Please set the `APPLE_TEAM_ID` environment variable. You can find the team ID in https://developer.apple.com/account#MembershipDetailsCard."
)]
MissingTeamId,
#[error("could not find API key file. Please set the APPLE_API_KEY_PATH environment variables to the path to the {file_name} file")]
MissingApiKey { file_name: String },
#[error("no APPLE_ID & APPLE_PASSWORD & APPLE_TEAM_ID or APPLE_API_KEY & APPLE_API_ISSUER & APPLE_API_KEY_PATH environment variables found")]
MissingCredentials,
}
/// Convenient type alias of Result type.
pub type Result<T> = std::result::Result<T, Error>;
pub trait Context<T> {
// Required methods
fn context<C>(self, context: C) -> Result<T>
where
C: Display + Send + Sync + 'static;
fn with_context<C, F>(self, f: F) -> Result<T>
where
C: Display + Send + Sync + 'static,
F: FnOnce() -> C;
}
impl<T> Context<T> for Result<T> {
fn context<C>(self, context: C) -> Result<T>
where
C: Display + Send + Sync + 'static,
{
self.map_err(|e| Error::Context(context.to_string(), Box::new(e)))
}
fn with_context<C, F>(self, f: F) -> Result<T>
where
C: Display + Send + Sync + 'static,
F: FnOnce() -> C,
{
self.map_err(|e| Error::Context(f().to_string(), Box::new(e)))
}
}
impl<T> Context<T> for Option<T> {
fn context<C>(self, context: C) -> Result<T>
where
C: Display + Send + Sync + 'static,
{
self.ok_or_else(|| Error::GenericError(context.to_string()))
}
fn with_context<C, F>(self, f: F) -> Result<T>
where
C: Display + Send + Sync + 'static,
F: FnOnce() -> C,
{
self.ok_or_else(|| Error::GenericError(f().to_string()))
}
}
pub trait ErrorExt<T> {
fn fs_context(self, context: &'static str, path: impl Into<PathBuf>) -> Result<T>;
}
impl<T> ErrorExt<T> for std::result::Result<T, std::io::Error> {
fn fs_context(self, context: &'static str, path: impl Into<PathBuf>) -> Result<T> {
self.map_err(|error| Error::Fs {
context,
path: path.into(),
error,
})
}
}
#[allow(unused)]
macro_rules! bail {
($msg:literal $(,)?) => {
return Err(crate::Error::GenericError($msg.into()))
};
($err:expr $(,)?) => {
return Err(crate::Error::GenericError($err))
};
($fmt:expr, $($arg:tt)*) => {
return Err(crate::Error::GenericError(format!($fmt, $($arg)*)))
};
}
#[allow(unused)]
pub(crate) use bail;
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-bundler/src/utils/http_utils.rs | crates/tauri-bundler/src/utils/http_utils.rs | // Copyright 2016-2019 Cargo-Bundle developers <https://github.com/burtonageo/cargo-bundle>
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{
fs::{create_dir_all, File},
io::{Cursor, Read, Write},
path::Path,
};
use regex::Regex;
use sha2::Digest;
use url::Url;
use zip::ZipArchive;
const BUNDLER_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"),);
fn generate_github_mirror_url_from_template(github_url: &str) -> Option<String> {
std::env::var("TAURI_BUNDLER_TOOLS_GITHUB_MIRROR_TEMPLATE")
.ok()
.and_then(|template| {
let re =
Regex::new(r"https://github.com/([^/]+)/([^/]+)/releases/download/([^/]+)/(.*)").unwrap();
re.captures(github_url).map(|caps| {
template
.replace("<owner>", &caps[1])
.replace("<repo>", &caps[2])
.replace("<version>", &caps[3])
.replace("<asset>", &caps[4])
})
})
}
fn generate_github_mirror_url_from_base(github_url: &str) -> Option<String> {
std::env::var("TAURI_BUNDLER_TOOLS_GITHUB_MIRROR")
.ok()
.and_then(|cdn| Url::parse(&cdn).ok())
.map(|mut cdn| {
cdn.set_path(github_url);
cdn.to_string()
})
}
fn generate_github_alternative_url(url: &str) -> Option<(ureq::Agent, String)> {
if !url.starts_with("https://github.com/") {
return None;
}
generate_github_mirror_url_from_template(url)
.or_else(|| generate_github_mirror_url_from_base(url))
.map(|alt_url| {
(
ureq::Agent::config_builder()
.user_agent(BUNDLER_USER_AGENT)
.build()
.into(),
alt_url,
)
})
}
fn create_agent_and_url(url: &str) -> (ureq::Agent, String) {
generate_github_alternative_url(url).unwrap_or((base_ureq_agent(), url.to_owned()))
}
pub(crate) fn base_ureq_agent() -> ureq::Agent {
#[allow(unused_mut)]
let mut config_builder = ureq::Agent::config_builder()
.user_agent(BUNDLER_USER_AGENT)
.proxy(ureq::Proxy::try_from_env());
#[cfg(feature = "platform-certs")]
{
config_builder = config_builder.tls_config(
ureq::tls::TlsConfig::builder()
.root_certs(ureq::tls::RootCerts::PlatformVerifier)
.build(),
);
}
config_builder.build().into()
}
#[allow(dead_code)]
pub fn download(url: &str) -> crate::Result<Vec<u8>> {
let (agent, final_url) = create_agent_and_url(url);
log::info!(action = "Downloading"; "{}", final_url);
let response = agent.get(&final_url).call().map_err(Box::new)?;
let mut bytes = Vec::new();
response.into_body().into_reader().read_to_end(&mut bytes)?;
Ok(bytes)
}
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub enum HashAlgorithm {
#[cfg(target_os = "windows")]
Sha256,
Sha1,
}
/// Function used to download a file and checks SHA256 to verify the download.
#[allow(dead_code)]
pub fn download_and_verify(
url: &str,
hash: &str,
hash_algorithm: HashAlgorithm,
) -> crate::Result<Vec<u8>> {
let data = download(url)?;
log::info!("validating hash");
verify_hash(&data, hash, hash_algorithm)?;
Ok(data)
}
#[allow(dead_code)]
pub fn verify_hash(data: &[u8], hash: &str, hash_algorithm: HashAlgorithm) -> crate::Result<()> {
match hash_algorithm {
#[cfg(target_os = "windows")]
HashAlgorithm::Sha256 => {
let hasher = sha2::Sha256::new();
verify_data_with_hasher(data, hash, hasher)
}
HashAlgorithm::Sha1 => {
let hasher = sha1::Sha1::new();
verify_data_with_hasher(data, hash, hasher)
}
}
}
fn verify_data_with_hasher(data: &[u8], hash: &str, mut hasher: impl Digest) -> crate::Result<()> {
hasher.update(data);
let url_hash = hasher.finalize().to_vec();
let expected_hash = hex::decode(hash)?;
if expected_hash == url_hash {
Ok(())
} else {
Err(crate::Error::HashError)
}
}
#[allow(dead_code)]
pub fn verify_file_hash<P: AsRef<Path>>(
path: P,
hash: &str,
hash_algorithm: HashAlgorithm,
) -> crate::Result<()> {
let data = std::fs::read(path)?;
verify_hash(&data, hash, hash_algorithm)
}
/// Extracts the zips from memory into a usable path.
#[allow(dead_code)]
pub fn extract_zip(data: &[u8], path: &Path) -> crate::Result<()> {
let cursor = Cursor::new(data);
let mut zipa = ZipArchive::new(cursor)?;
for i in 0..zipa.len() {
let mut file = zipa.by_index(i)?;
if let Some(name) = file.enclosed_name() {
let dest_path = path.join(name);
if file.is_dir() {
create_dir_all(&dest_path)?;
continue;
}
let parent = dest_path.parent().expect("Failed to get parent");
if !parent.exists() {
create_dir_all(parent)?;
}
let mut buff: Vec<u8> = Vec::new();
file.read_to_end(&mut buff)?;
let mut fileout = File::create(dest_path).expect("Failed to open file");
fileout.write_all(&buff)?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::generate_github_mirror_url_from_template;
use std::env;
const GITHUB_ASSET_URL: &str =
"https://github.com/wixtoolset/wix3/releases/download/wix3112rtm/wix311-binaries.zip";
const NON_GITHUB_ASSET_URL: &str = "https://someotherwebsite.com/somefile.zip";
#[test]
fn test_generate_mirror_url_no_env_var() {
env::remove_var("TAURI_BUNDLER_TOOLS_GITHUB_MIRROR_TEMPLATE");
assert!(generate_github_mirror_url_from_template(GITHUB_ASSET_URL).is_none());
}
#[test]
fn test_generate_mirror_url_non_github_url() {
env::set_var(
"TAURI_BUNDLER_TOOLS_GITHUB_MIRROR_TEMPLATE",
"https://mirror.example.com/<owner>/<repo>/releases/download/<version>/<asset>",
);
assert!(generate_github_mirror_url_from_template(NON_GITHUB_ASSET_URL).is_none());
}
struct TestCase {
template: &'static str,
expected_url: &'static str,
}
#[test]
fn test_generate_mirror_url_correctly() {
let test_cases = vec![
TestCase {
template: "https://mirror.example.com/<owner>/<repo>/releases/download/<version>/<asset>",
expected_url: "https://mirror.example.com/wixtoolset/wix3/releases/download/wix3112rtm/wix311-binaries.zip",
},
TestCase {
template: "https://mirror.example.com/<asset>",
expected_url: "https://mirror.example.com/wix311-binaries.zip",
},
];
for case in test_cases {
env::set_var("TAURI_BUNDLER_TOOLS_GITHUB_MIRROR_TEMPLATE", case.template);
assert_eq!(
generate_github_mirror_url_from_template(GITHUB_ASSET_URL),
Some(case.expected_url.to_string())
);
}
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-bundler/src/utils/fs_utils.rs | crates/tauri-bundler/src/utils/fs_utils.rs | // Copyright 2016-2019 Cargo-Bundle developers <https://github.com/burtonageo/cargo-bundle>
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{
fs::{self, File},
io::{self, BufWriter},
path::Path,
};
/// Creates a new file at the given path, creating any parent directories as
/// needed.
pub fn create_file(path: &Path) -> crate::Result<BufWriter<File>> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let file = File::create(path)?;
Ok(BufWriter::new(file))
}
/// Creates the given directory path,
/// erasing it first if specified.
#[allow(dead_code)]
pub fn create_dir(path: &Path, erase: bool) -> crate::Result<()> {
if erase && path.exists() {
remove_dir_all(path)?;
}
Ok(fs::create_dir(path)?)
}
/// Creates all of the directories of the specified path,
/// erasing it first if specified.
#[allow(dead_code)]
pub fn create_dir_all(path: &Path, erase: bool) -> crate::Result<()> {
if erase && path.exists() {
remove_dir_all(path)?;
}
Ok(fs::create_dir_all(path)?)
}
/// Removes the directory and its contents if it exists.
#[allow(dead_code)]
pub fn remove_dir_all(path: &Path) -> crate::Result<()> {
if path.exists() {
Ok(fs::remove_dir_all(path)?)
} else {
Ok(())
}
}
/// Makes a symbolic link to a directory.
#[cfg(unix)]
#[allow(dead_code)]
fn symlink_dir(src: &Path, dst: &Path) -> io::Result<()> {
std::os::unix::fs::symlink(src, dst)
}
/// Makes a symbolic link to a directory.
#[cfg(windows)]
fn symlink_dir(src: &Path, dst: &Path) -> io::Result<()> {
std::os::windows::fs::symlink_dir(src, dst)
}
/// Makes a symbolic link to a file.
#[cfg(unix)]
#[allow(dead_code)]
fn symlink_file(src: &Path, dst: &Path) -> io::Result<()> {
std::os::unix::fs::symlink(src, dst)
}
/// Makes a symbolic link to a file.
#[cfg(windows)]
fn symlink_file(src: &Path, dst: &Path) -> io::Result<()> {
std::os::windows::fs::symlink_file(src, dst)
}
/// Copies a regular file from one path to another, creating any parent
/// directories of the destination path as necessary. Fails if the source path
/// is a directory or doesn't exist.
pub fn copy_file(from: &Path, to: &Path) -> crate::Result<()> {
if !from.exists() {
return Err(crate::Error::GenericError(format!(
"{from:?} does not exist"
)));
}
if !from.is_file() {
return Err(crate::Error::GenericError(format!(
"{from:?} is not a file"
)));
}
let dest_dir = to.parent().expect("No data in parent");
fs::create_dir_all(dest_dir)?;
fs::copy(from, to)?;
Ok(())
}
/// Recursively copies a directory file from one path to another, creating any
/// parent directories of the destination path as necessary. Fails if the
/// source path is not a directory or doesn't exist, or if the destination path
/// already exists.
#[allow(dead_code)]
pub fn copy_dir(from: &Path, to: &Path) -> crate::Result<()> {
if !from.exists() {
return Err(crate::Error::GenericError(format!(
"{from:?} does not exist"
)));
}
if !from.is_dir() {
return Err(crate::Error::GenericError(format!(
"{from:?} is not a Directory"
)));
}
let parent = to.parent().expect("No data in parent");
fs::create_dir_all(parent)?;
for entry in walkdir::WalkDir::new(from) {
let entry = entry?;
debug_assert!(entry.path().starts_with(from));
let rel_path = entry.path().strip_prefix(from)?;
let dest_path = to.join(rel_path);
if entry.file_type().is_symlink() {
let target = fs::read_link(entry.path())?;
if entry.path().is_dir() {
symlink_dir(&target, &dest_path)?;
} else {
symlink_file(&target, &dest_path)?;
}
} else if entry.file_type().is_dir() {
fs::create_dir_all(dest_path)?;
} else {
fs::copy(entry.path(), dest_path)?;
}
}
Ok(())
}
/// Copies user-defined files specified in the configuration file to the package.
///
/// The configuration object maps the path in the package to the path of the file on the filesystem,
/// relative to the tauri.conf.json file.
///
/// Expects a HashMap of PathBuf entries, representing destination and source paths,
/// and also a path of a directory. The files will be stored with respect to this directory.
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
pub fn copy_custom_files(
files_map: &std::collections::HashMap<std::path::PathBuf, std::path::PathBuf>,
data_dir: &Path,
) -> crate::Result<()> {
for (pkg_path, path) in files_map.iter() {
let pkg_path = if pkg_path.is_absolute() {
pkg_path.strip_prefix("/").unwrap()
} else {
pkg_path
};
if path.is_file() {
copy_file(path, &data_dir.join(pkg_path))?;
} else {
copy_dir(path, &data_dir.join(pkg_path))?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::create_file;
use std::io::Write;
#[test]
fn create_file_with_parent_dirs() {
let tmp = tempfile::tempdir().expect("Unable to create temp dir");
assert!(!tmp.path().join("parent").exists());
{
let mut file =
create_file(&tmp.path().join("parent/file.txt")).expect("Failed to create file");
writeln!(file, "Hello, world!").expect("unable to write file");
}
assert!(tmp.path().join("parent").is_dir());
assert!(tmp.path().join("parent/file.txt").is_file());
}
#[cfg(not(windows))]
#[test]
fn copy_dir_with_symlinks() {
use std::path::PathBuf;
// Create a directory structure that looks like this:
// ${TMP}/orig/
// sub/
// file.txt
// link -> sub/file.txt
let tmp = tempfile::tempdir().expect("unable to create tempdir");
{
let mut file =
create_file(&tmp.path().join("orig/sub/file.txt")).expect("Unable to create file");
writeln!(file, "Hello, world!").expect("Unable to write to file");
}
super::symlink_file(
&PathBuf::from("sub/file.txt"),
&tmp.path().join("orig/link"),
)
.expect("Failed to create symlink");
assert_eq!(
std::fs::read(tmp.path().join("orig/link"))
.expect("Failed to read file")
.as_slice(),
b"Hello, world!\n"
);
// Copy ${TMP}/orig to ${TMP}/parent/copy, and make sure that the
// directory structure, file, and symlink got copied correctly.
super::copy_dir(&tmp.path().join("orig"), &tmp.path().join("parent/copy"))
.expect("Failed to copy dir");
assert!(tmp.path().join("parent/copy").is_dir());
assert!(tmp.path().join("parent/copy/sub").is_dir());
assert!(tmp.path().join("parent/copy/sub/file.txt").is_file());
assert_eq!(
std::fs::read(tmp.path().join("parent/copy/sub/file.txt"))
.expect("Failed to read file")
.as_slice(),
b"Hello, world!\n"
);
assert!(tmp.path().join("parent/copy/link").exists());
assert_eq!(
std::fs::read_link(tmp.path().join("parent/copy/link")).expect("Failed to read from symlink"),
PathBuf::from("sub/file.txt")
);
assert_eq!(
std::fs::read(tmp.path().join("parent/copy/link"))
.expect("Failed to read from file")
.as_slice(),
b"Hello, world!\n"
);
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-bundler/src/utils/mod.rs | crates/tauri-bundler/src/utils/mod.rs | // Copyright 2016-2019 Cargo-Bundle developers <https://github.com/burtonageo/cargo-bundle>
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{
ffi::OsStr,
io::{BufRead, BufReader},
path::Path,
process::{Command, ExitStatus, Output, Stdio},
sync::{Arc, Mutex},
};
pub mod fs_utils;
pub mod http_utils;
/// Returns true if the path has a filename indicating that it is a high-density
/// "retina" icon. Specifically, returns true the file stem ends with
/// "@2x" (a convention specified by the [Apple developer docs](
/// <https://developer.apple.com/library/mac/documentation/GraphicsAnimation/Conceptual/HighResolutionOSX/Optimizing/Optimizing.html>)).
#[allow(dead_code)]
pub fn is_retina(path: &Path) -> bool {
path
.file_stem()
.and_then(OsStr::to_str)
.map(|stem| stem.ends_with("@2x"))
.unwrap_or(false)
}
pub trait CommandExt {
// The `pipe` function sets the stdout and stderr to properly
// show the command output in the Node.js wrapper.
fn piped(&mut self) -> std::io::Result<ExitStatus>;
fn output_ok(&mut self) -> crate::Result<Output>;
}
impl CommandExt for Command {
fn piped(&mut self) -> std::io::Result<ExitStatus> {
self.stdin(os_pipe::dup_stdin()?);
self.stdout(os_pipe::dup_stdout()?);
self.stderr(os_pipe::dup_stderr()?);
let program = self.get_program().to_string_lossy().into_owned();
log::debug!(action = "Running"; "Command `{} {}`", program, self.get_args().map(|arg| arg.to_string_lossy()).fold(String::new(), |acc, arg| format!("{acc} {arg}")));
self.status()
}
fn output_ok(&mut self) -> crate::Result<Output> {
let program = self.get_program().to_string_lossy().into_owned();
log::debug!(action = "Running"; "Command `{} {}`", program, self.get_args().map(|arg| arg.to_string_lossy()).fold(String::new(), |acc, arg| format!("{acc} {arg}")));
self.stdout(Stdio::piped());
self.stderr(Stdio::piped());
let mut child = self.spawn()?;
let mut stdout = child.stdout.take().map(BufReader::new).unwrap();
let stdout_lines = Arc::new(Mutex::new(Vec::new()));
let stdout_lines_ = stdout_lines.clone();
std::thread::spawn(move || {
let mut line = String::new();
let mut lines = stdout_lines_.lock().unwrap();
loop {
line.clear();
match stdout.read_line(&mut line) {
Ok(0) => break,
Ok(_) => {
log::debug!(action = "stdout"; "{}", line.trim_end());
lines.extend(line.as_bytes().to_vec());
}
Err(_) => (),
}
}
});
let mut stderr = child.stderr.take().map(BufReader::new).unwrap();
let stderr_lines = Arc::new(Mutex::new(Vec::new()));
let stderr_lines_ = stderr_lines.clone();
std::thread::spawn(move || {
let mut line = String::new();
let mut lines = stderr_lines_.lock().unwrap();
loop {
line.clear();
match stderr.read_line(&mut line) {
Ok(0) => break,
Ok(_) => {
log::debug!(action = "stderr"; "{}", line.trim_end());
lines.extend(line.as_bytes().to_vec());
}
Err(_) => (),
}
}
});
let status = child.wait()?;
let output = Output {
status,
stdout: std::mem::take(&mut *stdout_lines.lock().unwrap()),
stderr: std::mem::take(&mut *stderr_lines.lock().unwrap()),
};
if output.status.success() {
Ok(output)
} else {
Err(crate::Error::GenericError(format!(
"failed to run {program}"
)))
}
}
}
#[cfg(test)]
mod tests {
use std::path::{Path, PathBuf};
use tauri_utils::resources::resource_relpath;
use super::is_retina;
#[test]
fn retina_icon_paths() {
assert!(!is_retina(Path::new("data/icons/512x512.png")));
assert!(is_retina(Path::new("data/icons/512x512@2x.png")));
}
#[test]
fn resource_relative_paths() {
assert_eq!(
resource_relpath(Path::new("./data/images/button.png")),
PathBuf::from("data/images/button.png")
);
assert_eq!(
resource_relpath(Path::new("../../images/wheel.png")),
PathBuf::from("_up_/_up_/images/wheel.png")
);
assert_eq!(
resource_relpath(Path::new("/home/ferris/crab.png")),
PathBuf::from("_root_/home/ferris/crab.png")
);
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-bundler/src/bundle/settings.rs | crates/tauri-bundler/src/bundle/settings.rs | // Copyright 2016-2019 Cargo-Bundle developers <https://github.com/burtonageo/cargo-bundle>
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use super::category::AppCategory;
use crate::{bundle::platform::target_triple, error::Context, utils::fs_utils};
pub use tauri_utils::config::WebviewInstallMode;
use tauri_utils::{
config::{
BundleType, DeepLinkProtocol, FileAssociation, NSISInstallerMode, NsisCompression,
RpmCompression,
},
platform::Target as TargetPlatform,
resources::{external_binaries, ResourcePaths},
};
use std::{
collections::HashMap,
path::{Path, PathBuf},
};
/// The type of the package we're bundling.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum PackageType {
/// The macOS application bundle (.app).
MacOsBundle,
/// The iOS app bundle.
IosBundle,
/// The Windows bundle (.msi).
WindowsMsi,
/// The NSIS bundle (.exe).
Nsis,
/// The Linux Debian package bundle (.deb).
Deb,
/// The Linux RPM bundle (.rpm).
Rpm,
/// The Linux AppImage bundle (.AppImage).
AppImage,
/// The macOS DMG bundle (.dmg).
Dmg,
/// The Updater bundle.
Updater,
}
impl From<BundleType> for PackageType {
fn from(bundle: BundleType) -> Self {
match bundle {
BundleType::Deb => Self::Deb,
BundleType::Rpm => Self::Rpm,
BundleType::AppImage => Self::AppImage,
BundleType::Msi => Self::WindowsMsi,
BundleType::Nsis => Self::Nsis,
BundleType::App => Self::MacOsBundle,
BundleType::Dmg => Self::Dmg,
}
}
}
impl PackageType {
/// Maps a short name to a PackageType.
/// Possible values are "deb", "ios", "msi", "app", "rpm", "appimage", "dmg", "updater".
pub fn from_short_name(name: &str) -> Option<PackageType> {
// Other types we may eventually want to support: apk.
match name {
"deb" => Some(PackageType::Deb),
"ios" => Some(PackageType::IosBundle),
"msi" => Some(PackageType::WindowsMsi),
"nsis" => Some(PackageType::Nsis),
"app" => Some(PackageType::MacOsBundle),
"rpm" => Some(PackageType::Rpm),
"appimage" => Some(PackageType::AppImage),
"dmg" => Some(PackageType::Dmg),
"updater" => Some(PackageType::Updater),
_ => None,
}
}
/// Gets the short name of this PackageType.
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn short_name(&self) -> &'static str {
match *self {
PackageType::Deb => "deb",
PackageType::IosBundle => "ios",
PackageType::WindowsMsi => "msi",
PackageType::Nsis => "nsis",
PackageType::MacOsBundle => "app",
PackageType::Rpm => "rpm",
PackageType::AppImage => "appimage",
PackageType::Dmg => "dmg",
PackageType::Updater => "updater",
}
}
/// Gets the list of the possible package types.
pub fn all() -> &'static [PackageType] {
ALL_PACKAGE_TYPES
}
/// Gets a number representing priority which used to sort package types
/// in an order that guarantees that if a certain package type
/// depends on another (like Dmg depending on MacOsBundle), the dependency
/// will be built first
///
/// The lower the number, the higher the priority
pub fn priority(&self) -> u32 {
match self {
PackageType::MacOsBundle => 0,
PackageType::IosBundle => 0,
PackageType::WindowsMsi => 0,
PackageType::Nsis => 0,
PackageType::Deb => 0,
PackageType::Rpm => 0,
PackageType::AppImage => 0,
PackageType::Dmg => 1,
PackageType::Updater => 2,
}
}
}
const ALL_PACKAGE_TYPES: &[PackageType] = &[
#[cfg(target_os = "linux")]
PackageType::Deb,
#[cfg(target_os = "macos")]
PackageType::IosBundle,
#[cfg(target_os = "windows")]
PackageType::WindowsMsi,
#[cfg(target_os = "windows")]
PackageType::Nsis,
#[cfg(target_os = "macos")]
PackageType::MacOsBundle,
#[cfg(target_os = "linux")]
PackageType::Rpm,
#[cfg(target_os = "macos")]
PackageType::Dmg,
#[cfg(target_os = "linux")]
PackageType::AppImage,
PackageType::Updater,
];
/// The package settings.
#[derive(Debug, Clone)]
pub struct PackageSettings {
/// the package's product name.
pub product_name: String,
/// the package's version.
pub version: String,
/// the package's description.
pub description: String,
/// the package's homepage.
pub homepage: Option<String>,
/// the package's authors.
pub authors: Option<Vec<String>>,
/// the default binary to run.
pub default_run: Option<String>,
}
/// The updater settings.
#[derive(Debug, Default, Clone)]
pub struct UpdaterSettings {
/// Should generate v1 compatible zipped updater
pub v1_compatible: bool,
/// Signature public key.
pub pubkey: String,
/// Args to pass to `msiexec.exe` to run the updater on Windows.
pub msiexec_args: &'static [&'static str],
}
/// The Linux debian bundle settings.
#[derive(Clone, Debug, Default)]
pub struct DebianSettings {
// OS-specific settings:
/// the list of debian dependencies.
pub depends: Option<Vec<String>>,
/// the list of debian dependencies recommendations.
pub recommends: Option<Vec<String>>,
/// the list of dependencies the package provides.
pub provides: Option<Vec<String>>,
/// the list of package conflicts.
pub conflicts: Option<Vec<String>>,
/// the list of package replaces.
pub replaces: Option<Vec<String>>,
/// List of custom files to add to the deb package.
/// Maps the path on the debian package to the path of the file to include (relative to the current working directory).
pub files: HashMap<PathBuf, PathBuf>,
/// Path to a custom desktop file Handlebars template.
///
/// Available variables: `categories`, `comment` (optional), `exec`, `icon` and `name`.
///
/// Default file contents:
/// ```text
#[doc = include_str!("./linux/freedesktop/main.desktop")]
/// ```
pub desktop_template: Option<PathBuf>,
/// Define the section in Debian Control file. See : <https://www.debian.org/doc/debian-policy/ch-archive.html#s-subsections>
pub section: Option<String>,
/// Change the priority of the Debian Package. By default, it is set to `optional`.
/// Recognized Priorities as of now are : `required`, `important`, `standard`, `optional`, `extra`
pub priority: Option<String>,
/// Path of the uncompressed Changelog file, to be stored at /usr/share/doc/package-name/changelog.gz. See
/// <https://www.debian.org/doc/debian-policy/ch-docs.html#changelog-files-and-release-notes>
pub changelog: Option<PathBuf>,
/// Path to script that will be executed before the package is unpacked. See
/// <https://www.debian.org/doc/debian-policy/ch-maintainerscripts.html>
pub pre_install_script: Option<PathBuf>,
/// Path to script that will be executed after the package is unpacked. See
/// <https://www.debian.org/doc/debian-policy/ch-maintainerscripts.html>
pub post_install_script: Option<PathBuf>,
/// Path to script that will be executed before the package is removed. See
/// <https://www.debian.org/doc/debian-policy/ch-maintainerscripts.html>
pub pre_remove_script: Option<PathBuf>,
/// Path to script that will be executed after the package is removed. See
/// <https://www.debian.org/doc/debian-policy/ch-maintainerscripts.html>
pub post_remove_script: Option<PathBuf>,
}
/// The Linux AppImage bundle settings.
#[derive(Clone, Debug, Default)]
pub struct AppImageSettings {
/// The files to include in the Appimage Binary.
pub files: HashMap<PathBuf, PathBuf>,
/// Whether to include gstreamer plugins for audio/media support.
pub bundle_media_framework: bool,
/// Whether to include the `xdg-open` binary.
pub bundle_xdg_open: bool,
}
/// The RPM bundle settings.
#[derive(Clone, Debug, Default)]
pub struct RpmSettings {
/// The list of RPM dependencies your application relies on.
pub depends: Option<Vec<String>>,
/// the list of of RPM dependencies your application recommends.
pub recommends: Option<Vec<String>>,
/// The list of RPM dependencies your application provides.
pub provides: Option<Vec<String>>,
/// The list of RPM dependencies your application conflicts with. They must not be present
/// in order for the package to be installed.
pub conflicts: Option<Vec<String>>,
/// The list of RPM dependencies your application supersedes - if this package is installed,
/// packages listed as "obsoletes" will be automatically removed (if they are present).
pub obsoletes: Option<Vec<String>>,
/// The RPM release tag.
pub release: String,
/// The RPM epoch.
pub epoch: u32,
/// List of custom files to add to the RPM package.
/// Maps the path on the RPM package to the path of the file to include (relative to the current working directory).
pub files: HashMap<PathBuf, PathBuf>,
/// Path to a custom desktop file Handlebars template.
///
/// Available variables: `categories`, `comment` (optional), `exec`, `icon` and `name`.
///
/// Default file contents:
/// ```text
#[doc = include_str!("./linux/freedesktop/main.desktop")]
/// ```
pub desktop_template: Option<PathBuf>,
/// Path to script that will be executed before the package is unpacked. See
/// <http://ftp.rpm.org/max-rpm/s1-rpm-inside-scripts.html>
pub pre_install_script: Option<PathBuf>,
/// Path to script that will be executed after the package is unpacked. See
/// <http://ftp.rpm.org/max-rpm/s1-rpm-inside-scripts.html>
pub post_install_script: Option<PathBuf>,
/// Path to script that will be executed before the package is removed. See
/// <http://ftp.rpm.org/max-rpm/s1-rpm-inside-scripts.html>
pub pre_remove_script: Option<PathBuf>,
/// Path to script that will be executed after the package is removed. See
/// <http://ftp.rpm.org/max-rpm/s1-rpm-inside-scripts.html>
pub post_remove_script: Option<PathBuf>,
/// Compression algorithm and level. Defaults to `Gzip` with level 6.
pub compression: Option<RpmCompression>,
}
/// Position coordinates struct.
#[derive(Clone, Debug, Default)]
pub struct Position {
/// X coordinate.
pub x: u32,
/// Y coordinate.
pub y: u32,
}
/// Size of the window.
#[derive(Clone, Debug, Default)]
pub struct Size {
/// Width of the window.
pub width: u32,
/// Height of the window.
pub height: u32,
}
/// The DMG bundle settings.
#[derive(Clone, Debug, Default)]
pub struct DmgSettings {
/// Image to use as the background in dmg file. Accepted formats: `png`/`jpg`/`gif`.
pub background: Option<PathBuf>,
/// Position of volume window on screen.
pub window_position: Option<Position>,
/// Size of volume window.
pub window_size: Size,
/// Position of app file on window.
pub app_position: Position,
/// Position of application folder on window.
pub application_folder_position: Position,
}
/// The iOS bundle settings.
#[derive(Clone, Debug, Default)]
pub struct IosSettings {
/// The version of the build that identifies an iteration of the bundle.
pub bundle_version: Option<String>,
}
/// The macOS bundle settings.
#[derive(Clone, Debug, Default)]
pub struct MacOsSettings {
/// MacOS frameworks that need to be bundled with the app.
///
/// Each string can either be the name of a framework (without the `.framework` extension, e.g. `"SDL2"`),
/// in which case we will search for that framework in the standard install locations (`~/Library/Frameworks/`, `/Library/Frameworks/`, and `/Network/Library/Frameworks/`),
/// or a path to a specific framework bundle (e.g. `./data/frameworks/SDL2.framework`). Note that this setting just makes tauri-bundler copy the specified frameworks into the OS X app bundle
/// (under `Foobar.app/Contents/Frameworks/`); you are still responsible for:
///
/// - arranging for the compiled binary to link against those frameworks (e.g. by emitting lines like `cargo:rustc-link-lib=framework=SDL2` from your `build.rs` script)
///
/// - embedding the correct rpath in your binary (e.g. by running `install_name_tool -add_rpath "@executable_path/../Frameworks" path/to/binary` after compiling)
pub frameworks: Option<Vec<String>>,
/// List of custom files to add to the application bundle.
/// Maps the path in the Contents directory in the app to the path of the file to include (relative to the current working directory).
pub files: HashMap<PathBuf, PathBuf>,
/// The version of the build that identifies an iteration of the bundle.
pub bundle_version: Option<String>,
/// The name of the build that identifies a string of the bundle.
///
/// If not set, defaults to the package's product name.
pub bundle_name: Option<String>,
/// A version string indicating the minimum MacOS version that the bundled app supports (e.g. `"10.11"`).
/// If you are using this config field, you may also want have your `build.rs` script emit `cargo:rustc-env=MACOSX_DEPLOYMENT_TARGET=10.11`.
pub minimum_system_version: Option<String>,
/// The exception domain to use on the macOS .app bundle.
///
/// This allows communication to the outside world e.g. a web server you're shipping.
pub exception_domain: Option<String>,
/// Code signing identity.
pub signing_identity: Option<String>,
/// Whether to wait for notarization to finish and `staple` the ticket onto the app.
///
/// Gatekeeper will look for stapled tickets to tell whether your app was notarized without
/// reaching out to Apple's servers which is helpful in offline environments.
///
/// Enabling this option will also result in `tauri build` not waiting for notarization to finish
/// which is helpful for the very first time your app is notarized as this can take multiple hours.
/// On subsequent runs, it's recommended to disable this setting again.
pub skip_stapling: bool,
/// Preserve the hardened runtime version flag, see <https://developer.apple.com/documentation/security/hardened_runtime>
///
/// Settings this to `false` is useful when using an ad-hoc signature, making it less strict.
pub hardened_runtime: bool,
/// Provider short name for notarization.
pub provider_short_name: Option<String>,
/// Path or contents of the entitlements.plist file.
pub entitlements: Option<Entitlements>,
/// Path to the Info.plist file or raw plist value to merge with the bundle Info.plist.
pub info_plist: Option<PlistKind>,
}
/// Entitlements for macOS code signing.
#[derive(Debug, Clone)]
pub enum Entitlements {
/// Path to the entitlements.plist file.
Path(PathBuf),
/// Raw plist::Value.
Plist(plist::Value),
}
/// Plist format.
#[derive(Debug, Clone)]
pub enum PlistKind {
/// Path to a .plist file.
Path(PathBuf),
/// Raw plist value.
Plist(plist::Value),
}
/// Configuration for a target language for the WiX build.
#[derive(Debug, Clone, Default)]
pub struct WixLanguageConfig {
/// The path to a locale (`.wxl`) file. See <https://wixtoolset.org/documentation/manual/v3/howtos/ui_and_localization/build_a_localized_version.html>.
pub locale_path: Option<PathBuf>,
}
/// The languages to build using WiX.
#[derive(Debug, Clone)]
pub struct WixLanguage(pub Vec<(String, WixLanguageConfig)>);
impl Default for WixLanguage {
fn default() -> Self {
Self(vec![("en-US".into(), Default::default())])
}
}
/// Settings specific to the WiX implementation.
#[derive(Clone, Debug, Default)]
pub struct WixSettings {
/// MSI installer version in the format `major.minor.patch.build` (build is optional).
///
/// Because a valid version is required for MSI installer, it will be derived from [`PackageSettings::version`] if this field is not set.
///
/// The first field is the major version and has a maximum value of 255. The second field is the minor version and has a maximum value of 255.
/// The third and fourth fields have a maximum value of 65,535.
///
/// See <https://learn.microsoft.com/en-us/windows/win32/msi/productversion> for more info.
pub version: Option<String>,
/// A GUID upgrade code for MSI installer. This code **_must stay the same across all of your updates_**,
/// otherwise, Windows will treat your update as a different app and your users will have duplicate versions of your app.
///
/// By default, tauri generates this code by generating a Uuid v5 using the string `<productName>.exe.app.x64` in the DNS namespace.
/// You can use Tauri's CLI to generate and print this code for you by running `tauri inspect wix-upgrade-code`.
///
/// It is recommended that you set this value in your tauri config file to avoid accidental changes in your upgrade code
/// whenever you want to change your product name.
pub upgrade_code: Option<uuid::Uuid>,
/// The app languages to build. See <https://docs.microsoft.com/en-us/windows/win32/msi/localizing-the-error-and-actiontext-tables>.
pub language: WixLanguage,
/// By default, the bundler uses an internal template.
/// This option allows you to define your own wix file.
pub template: Option<PathBuf>,
/// A list of paths to .wxs files with WiX fragments to use.
pub fragment_paths: Vec<PathBuf>,
/// The ComponentGroup element ids you want to reference from the fragments.
pub component_group_refs: Vec<String>,
/// The Component element ids you want to reference from the fragments.
pub component_refs: Vec<String>,
/// The FeatureGroup element ids you want to reference from the fragments.
pub feature_group_refs: Vec<String>,
/// The Feature element ids you want to reference from the fragments.
pub feature_refs: Vec<String>,
/// The Merge element ids you want to reference from the fragments.
pub merge_refs: Vec<String>,
/// Create an elevated update task within Windows Task Scheduler.
pub enable_elevated_update_task: bool,
/// Path to a bitmap file to use as the installation user interface banner.
/// This bitmap will appear at the top of all but the first page of the installer.
///
/// The required dimensions are 493px × 58px.
pub banner_path: Option<PathBuf>,
/// Path to a bitmap file to use on the installation user interface dialogs.
/// It is used on the welcome and completion dialogs.
///
/// The required dimensions are 493px × 312px.
pub dialog_image_path: Option<PathBuf>,
/// Enables FIPS compliant algorithms.
pub fips_compliant: bool,
}
/// Settings specific to the NSIS implementation.
#[derive(Clone, Debug, Default)]
pub struct NsisSettings {
/// A custom .nsi template to use.
pub template: Option<PathBuf>,
/// The path to a bitmap file to display on the header of installers pages.
///
/// The recommended dimensions are 150px x 57px.
pub header_image: Option<PathBuf>,
/// The path to a bitmap file for the Welcome page and the Finish page.
///
/// The recommended dimensions are 164px x 314px.
pub sidebar_image: Option<PathBuf>,
/// The path to an icon file used as the installer icon.
pub installer_icon: Option<PathBuf>,
/// Whether the installation will be for all users or just the current user.
pub install_mode: NSISInstallerMode,
/// A list of installer languages.
/// By default the OS language is used. If the OS language is not in the list of languages, the first language will be used.
/// To allow the user to select the language, set `display_language_selector` to `true`.
///
/// See <https://github.com/kichik/nsis/tree/9465c08046f00ccb6eda985abbdbf52c275c6c4d/Contrib/Language%20files> for the complete list of languages.
pub languages: Option<Vec<String>>,
/// An key-value pair where the key is the language and the
/// value is the path to a custom `.nsi` file that holds the translated text for tauri's custom messages.
///
/// See <https://github.com/tauri-apps/tauri/blob/dev/crates/tauri-bundler/src/bundle/windows/nsis/languages/English.nsh> for an example `.nsi` file.
///
/// **Note**: the key must be a valid NSIS language and it must be added to [`NsisConfig`]languages array,
pub custom_language_files: Option<HashMap<String, PathBuf>>,
/// Whether to display a language selector dialog before the installer and uninstaller windows are rendered or not.
/// By default the OS language is selected, with a fallback to the first language in the `languages` array.
pub display_language_selector: bool,
/// Set compression algorithm used to compress files in the installer.
pub compression: NsisCompression,
/// Set the folder name for the start menu shortcut.
///
/// Use this option if you have multiple apps and wish to group their shortcuts under one folder
/// or if you generally prefer to set your shortcut inside a folder.
///
/// Examples:
/// - `AwesomePublisher`, shortcut will be placed in `%AppData%\Microsoft\Windows\Start Menu\Programs\AwesomePublisher\<your-app>.lnk`
/// - If unset, shortcut will be placed in `%AppData%\Microsoft\Windows\Start Menu\Programs\<your-app>.lnk`
pub start_menu_folder: Option<String>,
/// A path to a `.nsh` file that contains special NSIS macros to be hooked into the
/// main installer.nsi script.
///
/// Supported hooks are:
/// - `NSIS_HOOK_PREINSTALL`: This hook runs before copying files, setting registry key values and creating shortcuts.
/// - `NSIS_HOOK_POSTINSTALL`: This hook runs after the installer has finished copying all files, setting the registry keys and created shortcuts.
/// - `NSIS_HOOK_PREUNINSTALL`: This hook runs before removing any files, registry keys and shortcuts.
/// - `NSIS_HOOK_POSTUNINSTALL`: This hook runs after files, registry keys and shortcuts have been removed.
///
///
/// ### Example
///
/// ```nsh
/// !macro NSIS_HOOK_PREINSTALL
/// MessageBox MB_OK "PreInstall"
/// !macroend
///
/// !macro NSIS_HOOK_POSTINSTALL
/// MessageBox MB_OK "PostInstall"
/// !macroend
///
/// !macro NSIS_HOOK_PREUNINSTALL
/// MessageBox MB_OK "PreUnInstall"
/// !macroend
///
/// !macro NSIS_HOOK_POSTUNINSTALL
/// MessageBox MB_OK "PostUninstall"
/// !macroend
/// ```
pub installer_hooks: Option<PathBuf>,
/// Try to ensure that the WebView2 version is equal to or newer than this version,
/// if the user's WebView2 is older than this version,
/// the installer will try to trigger a WebView2 update.
pub minimum_webview2_version: Option<String>,
}
/// The Custom Signing Command Settings for Windows exe
#[derive(Clone, Debug)]
pub struct CustomSignCommandSettings {
/// The command to run to sign the binary.
pub cmd: String,
/// The arguments to pass to the command.
///
/// "%1" will be replaced with the path to the binary to be signed.
pub args: Vec<String>,
}
/// The Windows bundle settings.
#[derive(Clone, Debug)]
pub struct WindowsSettings {
/// The file digest algorithm to use for creating file signatures. Required for code signing. SHA-256 is recommended.
pub digest_algorithm: Option<String>,
/// The SHA1 hash of the signing certificate.
pub certificate_thumbprint: Option<String>,
/// Server to use during timestamping.
pub timestamp_url: Option<String>,
/// Whether to use Time-Stamp Protocol (TSP, a.k.a. RFC 3161) for the timestamp server. Your code signing provider may
/// use a TSP timestamp server, like e.g. SSL.com does. If so, enable TSP by setting to true.
pub tsp: bool,
/// WiX configuration.
pub wix: Option<WixSettings>,
/// Nsis configuration.
pub nsis: Option<NsisSettings>,
/// The path to the application icon. Defaults to `./icons/icon.ico`.
#[deprecated = "This is used for the MSI installer and will be removed in 3.0.0, use `BundleSettings::icon` field and make sure a `.ico` icon exists instead."]
pub icon_path: PathBuf,
/// The installation mode for the Webview2 runtime.
pub webview_install_mode: WebviewInstallMode,
/// Validates a second app installation, blocking the user from installing an older version if set to `false`.
///
/// For instance, if `1.2.1` is installed, the user won't be able to install app version `1.2.0` or `1.1.5`.
///
/// /// The default value of this flag is `true`.
pub allow_downgrades: bool,
/// Specify a custom command to sign the binaries.
/// This command needs to have a `%1` in it which is just a placeholder for the binary path,
/// which we will detect and replace before calling the command.
///
/// Example:
/// ```text
/// sign-cli --arg1 --arg2 %1
/// ```
///
/// By Default we use `signtool.exe` which can be found only on Windows so
/// if you are on another platform and want to cross-compile and sign you will
/// need to use another tool like `osslsigncode`.
pub sign_command: Option<CustomSignCommandSettings>,
}
impl WindowsSettings {
pub(crate) fn can_sign(&self) -> bool {
self.sign_command.is_some() || self.certificate_thumbprint.is_some()
}
}
#[allow(deprecated)]
mod _default {
use super::*;
impl Default for WindowsSettings {
fn default() -> Self {
Self {
digest_algorithm: None,
certificate_thumbprint: None,
timestamp_url: None,
tsp: false,
wix: None,
nsis: None,
icon_path: PathBuf::from("icons/icon.ico"),
webview_install_mode: Default::default(),
allow_downgrades: true,
sign_command: None,
}
}
}
}
/// The bundle settings of the BuildArtifact we're bundling.
#[derive(Clone, Debug, Default)]
pub struct BundleSettings {
/// the app's identifier.
pub identifier: Option<String>,
/// The app's publisher. Defaults to the second element in the identifier string.
///
/// Currently maps to the Manufacturer property of the Windows Installer
/// and the Maintainer field of debian packages if the Cargo.toml does not have the authors field.
pub publisher: Option<String>,
/// A url to the home page of your application. If None, will
/// fallback to [PackageSettings::homepage].
///
/// Supported bundle targets: `deb`, `rpm`, `nsis` and `msi`
pub homepage: Option<String>,
/// the app's icon list.
pub icon: Option<Vec<String>>,
/// the app's resources to bundle.
///
/// each item can be a path to a file or a path to a folder.
///
/// supports glob patterns.
pub resources: Option<Vec<String>>,
/// The app's resources to bundle. Takes precedence over `Self::resources` when specified.
///
/// Maps each resource path to its target directory in the bundle resources directory.
///
/// Supports glob patterns.
pub resources_map: Option<HashMap<String, String>>,
/// the app's copyright.
pub copyright: Option<String>,
/// The package's license identifier to be included in the appropriate bundles.
/// If not set, defaults to the license from the Cargo.toml file.
pub license: Option<String>,
/// The path to the license file to be included in the appropriate bundles.
pub license_file: Option<PathBuf>,
/// the app's category.
pub category: Option<AppCategory>,
/// the file associations
pub file_associations: Option<Vec<FileAssociation>>,
/// the app's short description.
pub short_description: Option<String>,
/// the app's long description.
pub long_description: Option<String>,
// Bundles for other binaries:
/// Configuration map for the apps to bundle.
pub bin: Option<HashMap<String, BundleSettings>>,
/// External binaries to add to the bundle.
///
/// Note that each binary name should have the target platform's target triple appended,
/// as well as `.exe` for Windows.
/// For example, if you're bundling a sidecar called `sqlite3`, the bundler expects
/// a binary named `sqlite3-x86_64-unknown-linux-gnu` on linux,
/// and `sqlite3-x86_64-pc-windows-gnu.exe` on windows.
///
/// Run `tauri build --help` for more info on targets.
///
/// If you are building a universal binary for MacOS, the bundler expects
/// your external binary to also be universal, and named after the target triple,
/// e.g. `sqlite3-universal-apple-darwin`. See
/// <https://developer.apple.com/documentation/apple-silicon/building-a-universal-macos-binary>
pub external_bin: Option<Vec<String>>,
/// Deep-link protocols.
pub deep_link_protocols: Option<Vec<DeepLinkProtocol>>,
/// Debian-specific settings.
pub deb: DebianSettings,
/// AppImage-specific settings.
pub appimage: AppImageSettings,
/// Rpm-specific settings.
pub rpm: RpmSettings,
/// DMG-specific settings.
pub dmg: DmgSettings,
/// iOS-specific settings.
pub ios: IosSettings,
/// MacOS-specific settings.
pub macos: MacOsSettings,
/// Updater configuration.
pub updater: Option<UpdaterSettings>,
/// Windows-specific settings.
pub windows: WindowsSettings,
}
/// A binary to bundle.
#[derive(Clone, Debug)]
pub struct BundleBinary {
name: String,
main: bool,
src_path: Option<String>,
}
impl BundleBinary {
/// Creates a new bundle binary.
pub fn new(name: String, main: bool) -> Self {
Self {
name,
main,
src_path: None,
}
}
/// Creates a new bundle binary with path.
pub fn with_path(name: String, main: bool, src_path: Option<String>) -> Self {
Self {
name,
src_path,
main,
}
}
/// Mark the binary as the main executable.
pub fn set_main(&mut self, main: bool) {
self.main = main;
}
/// Sets the binary name.
pub fn set_name(&mut self, name: String) {
self.name = name;
}
/// Sets the src path of the binary.
#[must_use]
pub fn set_src_path(mut self, src_path: Option<String>) -> Self {
self.src_path = src_path;
self
}
/// Returns the binary `main` flag.
pub fn main(&self) -> bool {
self.main
}
/// Returns the binary name.
pub fn name(&self) -> &str {
&self.name
}
/// Returns the binary source path.
pub fn src_path(&self) -> Option<&String> {
self.src_path.as_ref()
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Arch {
/// For the x86_64 / x64 / AMD64 instruction sets (64 bits).
X86_64,
/// For the x86 / i686 / i686 / 8086 instruction sets (32 bits).
X86,
/// For the AArch64 / ARM64 instruction sets (64 bits).
AArch64,
/// For the AArch32 / ARM32 instruction sets with hard-float (32 bits).
Armhf,
/// For the AArch32 / ARM32 instruction sets with soft-float (32 bits).
Armel,
/// For the RISC-V instruction sets (64 bits).
Riscv64,
/// For universal macOS applications.
Universal,
}
/// The Settings exposed by the module.
#[derive(Clone, Debug)]
pub struct Settings {
/// The log level.
log_level: log::Level,
/// the package settings.
package: PackageSettings,
/// the package types we're bundling.
///
/// if not present, we'll use the PackageType list for the target OS.
package_types: Option<Vec<PackageType>>,
/// the directory where the bundles will be placed.
project_out_directory: PathBuf,
/// the directory to place tools used by the bundler,
/// if `None`, tools are placed in the current user's platform-specific cache directory.
local_tools_directory: Option<PathBuf>,
/// the bundle settings.
bundle_settings: BundleSettings,
/// the binaries to bundle.
binaries: Vec<BundleBinary>,
/// The target platform.
target_platform: TargetPlatform,
/// The target triple.
target: String,
/// Whether to disable code signing during the bundling process.
no_sign: bool,
}
/// A builder for [`Settings`].
#[derive(Default)]
pub struct SettingsBuilder {
log_level: Option<log::Level>,
project_out_directory: Option<PathBuf>,
package_types: Option<Vec<PackageType>>,
package_settings: Option<PackageSettings>,
bundle_settings: BundleSettings,
binaries: Vec<BundleBinary>,
target: Option<String>,
local_tools_directory: Option<PathBuf>,
no_sign: bool,
}
impl SettingsBuilder {
/// Creates the default settings builder.
pub fn new() -> Self {
Default::default()
}
/// Sets the project output directory. It's used as current working directory.
#[must_use]
pub fn project_out_directory<P: AsRef<Path>>(mut self, path: P) -> Self {
self
.project_out_directory
.replace(path.as_ref().to_path_buf());
self
}
/// Sets the directory to place tools used by the bundler
/// when [`BundleSettings::use_local_tools_dir`] is true.
#[must_use]
pub fn local_tools_directory<P: AsRef<Path>>(mut self, path: P) -> Self {
self
.local_tools_directory
.replace(path.as_ref().to_path_buf());
self
}
/// Sets the package types to create.
#[must_use]
pub fn package_types(mut self, package_types: Vec<PackageType>) -> Self {
self.package_types = Some(package_types);
self
}
/// Sets the package settings.
#[must_use]
pub fn package_settings(mut self, settings: PackageSettings) -> Self {
self.package_settings.replace(settings);
self
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | true |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-bundler/src/bundle/platform.rs | crates/tauri-bundler/src/bundle/platform.rs | // Copyright 2016-2019 Cargo-Bundle developers <https://github.com/burtonageo/cargo-bundle>
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::utils::CommandExt;
use std::process::Command;
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
#[derive(Debug, PartialEq, Eq)]
struct RustCfg {
target_arch: Option<String>,
}
fn parse_rust_cfg(cfg: String) -> RustCfg {
let target_line = "target_arch=\"";
let mut target_arch = None;
for line in cfg.split('\n') {
if line.starts_with(target_line) {
let len = target_line.len();
let arch = line.chars().skip(len).take(line.len() - len - 1).collect();
target_arch.replace(arch);
}
}
RustCfg { target_arch }
}
/// Try to determine the current target triple.
///
/// Returns a target triple (e.g. `x86_64-unknown-linux-gnu` or `i686-pc-windows-msvc`) or an
/// `Error::Config` if the current config cannot be determined or is not some combination of the
/// following values:
/// `linux, mac, windows` -- `i686, x86, armv7` -- `gnu, musl, msvc`
///
/// * Errors:
/// * Unexpected system config
pub fn target_triple() -> Result<String, crate::Error> {
let arch_res = Command::new("rustc").args(["--print", "cfg"]).output_ok();
let arch = match arch_res {
Ok(output) => parse_rust_cfg(String::from_utf8_lossy(&output.stdout).into())
.target_arch
.expect("could not find `target_arch` when running `rustc --print cfg`."),
Err(err) => {
log::warn!(
"failed to determine target arch using rustc, error: `{}`. The fallback is the architecture of the machine that compiled this crate.",
err,
);
if cfg!(target_arch = "x86") {
"i686".into()
} else if cfg!(target_arch = "x86_64") {
"x86_64".into()
} else if cfg!(target_arch = "arm") {
"armv7".into()
} else if cfg!(target_arch = "aarch64") {
"aarch64".into()
} else if cfg!(target_arch = "riscv64") {
"riscv64".into()
} else {
return Err(crate::Error::ArchError(String::from(
"Unable to determine target-architecture",
)));
}
}
};
let os = if cfg!(target_os = "linux") {
"unknown-linux"
} else if cfg!(target_os = "macos") {
"apple-darwin"
} else if cfg!(target_os = "windows") {
"pc-windows"
} else if cfg!(target_os = "freebsd") {
"unknown-freebsd"
} else {
return Err(crate::Error::ArchError(String::from(
"Unable to determine target-os",
)));
};
let os = if cfg!(target_os = "macos") || cfg!(target_os = "freebsd") {
String::from(os)
} else {
let env = if cfg!(target_env = "gnu") {
"gnu"
} else if cfg!(target_env = "musl") {
"musl"
} else if cfg!(target_env = "msvc") {
"msvc"
} else {
return Err(crate::Error::ArchError(String::from(
"Unable to determine target-environment",
)));
};
format!("{os}-{env}")
};
Ok(format!("{arch}-{os}"))
}
#[cfg(test)]
mod tests {
use super::RustCfg;
#[test]
fn parse_rust_cfg() {
assert_eq!(
super::parse_rust_cfg("target_arch".into()),
RustCfg { target_arch: None }
);
assert_eq!(
super::parse_rust_cfg(
r#"debug_assertions
target_arch="aarch64"
target_endian="little"
target_env=""
target_family="unix"
target_os="macos"
target_pointer_width="64"
target_vendor="apple"
unix"#
.into()
),
RustCfg {
target_arch: Some("aarch64".into())
}
);
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-bundler/src/bundle/category.rs | crates/tauri-bundler/src/bundle/category.rs | // Copyright 2016-2019 Cargo-Bundle developers <https://github.com/burtonageo/cargo-bundle>
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{fmt, str::FromStr};
const CONFIDENCE_THRESHOLD: f64 = 0.8;
const MACOS_APP_CATEGORY_PREFIX: &str = "public.app-category.";
// TODO: RIght now, these categories correspond to LSApplicationCategoryType
// values for OS X. There are also some additional GNOME registered categories
// that don't fit these; we should add those here too.
/// The possible app categories.
/// Corresponds to `LSApplicationCategoryType` on macOS and the GNOME desktop categories on Debian.
#[allow(missing_docs)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum AppCategory {
Business,
DeveloperTool,
Education,
Entertainment,
Finance,
Game,
ActionGame,
AdventureGame,
ArcadeGame,
BoardGame,
CardGame,
CasinoGame,
DiceGame,
EducationalGame,
FamilyGame,
KidsGame,
MusicGame,
PuzzleGame,
RacingGame,
RolePlayingGame,
SimulationGame,
SportsGame,
StrategyGame,
TriviaGame,
WordGame,
GraphicsAndDesign,
HealthcareAndFitness,
Lifestyle,
Medical,
Music,
News,
Photography,
Productivity,
Reference,
SocialNetworking,
Sports,
Travel,
Utility,
Video,
Weather,
}
impl FromStr for AppCategory {
type Err = Option<&'static str>;
/// Given a string, returns the `AppCategory` it refers to, or the closest
/// string that the user might have intended (if any).
fn from_str(input: &str) -> Result<AppCategory, Self::Err> {
// Canonicalize input:
let mut input = input.to_ascii_lowercase();
if input.starts_with(MACOS_APP_CATEGORY_PREFIX) {
input = input
.split_at(MACOS_APP_CATEGORY_PREFIX.len())
.1
.to_string();
}
input = input.replace(' ', "");
input = input.replace('-', "");
// Find best match:
let mut best_confidence = 0.0;
let mut best_category: Option<AppCategory> = None;
for &(string, category) in CATEGORY_STRINGS.iter() {
if input == string {
return Ok(category);
}
let confidence = strsim::jaro_winkler(&input, string);
if confidence >= CONFIDENCE_THRESHOLD && confidence > best_confidence {
best_confidence = confidence;
best_category = Some(category);
}
}
Err(best_category.map(AppCategory::canonical))
}
}
impl AppCategory {
/// Map an AppCategory to the string we recommend to use in Cargo.toml if
/// the users misspells the category name.
fn canonical(self) -> &'static str {
match self {
AppCategory::Business => "Business",
AppCategory::DeveloperTool => "Developer Tool",
AppCategory::Education => "Education",
AppCategory::Entertainment => "Entertainment",
AppCategory::Finance => "Finance",
AppCategory::Game => "Game",
AppCategory::ActionGame => "Action Game",
AppCategory::AdventureGame => "Adventure Game",
AppCategory::ArcadeGame => "Arcade Game",
AppCategory::BoardGame => "Board Game",
AppCategory::CardGame => "Card Game",
AppCategory::CasinoGame => "Casino Game",
AppCategory::DiceGame => "Dice Game",
AppCategory::EducationalGame => "Educational Game",
AppCategory::FamilyGame => "Family Game",
AppCategory::KidsGame => "Kids Game",
AppCategory::MusicGame => "Music Game",
AppCategory::PuzzleGame => "Puzzle Game",
AppCategory::RacingGame => "Racing Game",
AppCategory::RolePlayingGame => "Role-Playing Game",
AppCategory::SimulationGame => "Simulation Game",
AppCategory::SportsGame => "Sports Game",
AppCategory::StrategyGame => "Strategy Game",
AppCategory::TriviaGame => "Trivia Game",
AppCategory::WordGame => "Word Game",
AppCategory::GraphicsAndDesign => "Graphics and Design",
AppCategory::HealthcareAndFitness => "Healthcare and Fitness",
AppCategory::Lifestyle => "Lifestyle",
AppCategory::Medical => "Medical",
AppCategory::Music => "Music",
AppCategory::News => "News",
AppCategory::Photography => "Photography",
AppCategory::Productivity => "Productivity",
AppCategory::Reference => "Reference",
AppCategory::SocialNetworking => "Social Networking",
AppCategory::Sports => "Sports",
AppCategory::Travel => "Travel",
AppCategory::Utility => "Utility",
AppCategory::Video => "Video",
AppCategory::Weather => "Weather",
}
}
/// Map an AppCategory to the closest set of Freedesktop registered
/// categories that matches that category.
///
/// Cf <https://specifications.freedesktop.org/menu-spec/latest/>
pub fn freedesktop_categories(self) -> &'static str {
match &self {
AppCategory::Business => "Office;",
AppCategory::DeveloperTool => "Development;",
AppCategory::Education => "Education;",
AppCategory::Entertainment => "Network;",
AppCategory::Finance => "Office;Finance;",
AppCategory::Game => "Game;",
AppCategory::ActionGame => "Game;ActionGame;",
AppCategory::AdventureGame => "Game;AdventureGame;",
AppCategory::ArcadeGame => "Game;ArcadeGame;",
AppCategory::BoardGame => "Game;BoardGame;",
AppCategory::CardGame => "Game;CardGame;",
AppCategory::CasinoGame => "Game;",
AppCategory::DiceGame => "Game;",
AppCategory::EducationalGame => "Game;Education;",
AppCategory::FamilyGame => "Game;",
AppCategory::KidsGame => "Game;KidsGame;",
AppCategory::MusicGame => "Game;",
AppCategory::PuzzleGame => "Game;LogicGame;",
AppCategory::RacingGame => "Game;",
AppCategory::RolePlayingGame => "Game;RolePlaying;",
AppCategory::SimulationGame => "Game;Simulation;",
AppCategory::SportsGame => "Game;SportsGame;",
AppCategory::StrategyGame => "Game;StrategyGame;",
AppCategory::TriviaGame => "Game;",
AppCategory::WordGame => "Game;",
AppCategory::GraphicsAndDesign => "Graphics;",
AppCategory::HealthcareAndFitness => "Science;",
AppCategory::Lifestyle => "Education;",
AppCategory::Medical => "Science;MedicalSoftware;",
AppCategory::Music => "AudioVideo;Audio;Music;",
AppCategory::News => "Network;News;",
AppCategory::Photography => "Graphics;Photography;",
AppCategory::Productivity => "Office;",
AppCategory::Reference => "Education;",
AppCategory::SocialNetworking => "Network;",
AppCategory::Sports => "Education;Sports;",
AppCategory::Travel => "Education;",
AppCategory::Utility => "Utility;",
AppCategory::Video => "AudioVideo;Video;",
AppCategory::Weather => "Science;",
}
}
/// Map an AppCategory to the closest LSApplicationCategoryType value that
/// matches that category.
pub fn macos_application_category_type(self) -> &'static str {
match &self {
AppCategory::Business => "public.app-category.business",
AppCategory::DeveloperTool => "public.app-category.developer-tools",
AppCategory::Education => "public.app-category.education",
AppCategory::Entertainment => "public.app-category.entertainment",
AppCategory::Finance => "public.app-category.finance",
AppCategory::Game => "public.app-category.games",
AppCategory::ActionGame => "public.app-category.action-games",
AppCategory::AdventureGame => "public.app-category.adventure-games",
AppCategory::ArcadeGame => "public.app-category.arcade-games",
AppCategory::BoardGame => "public.app-category.board-games",
AppCategory::CardGame => "public.app-category.card-games",
AppCategory::CasinoGame => "public.app-category.casino-games",
AppCategory::DiceGame => "public.app-category.dice-games",
AppCategory::EducationalGame => "public.app-category.educational-games",
AppCategory::FamilyGame => "public.app-category.family-games",
AppCategory::KidsGame => "public.app-category.kids-games",
AppCategory::MusicGame => "public.app-category.music-games",
AppCategory::PuzzleGame => "public.app-category.puzzle-games",
AppCategory::RacingGame => "public.app-category.racing-games",
AppCategory::RolePlayingGame => "public.app-category.role-playing-games",
AppCategory::SimulationGame => "public.app-category.simulation-games",
AppCategory::SportsGame => "public.app-category.sports-games",
AppCategory::StrategyGame => "public.app-category.strategy-games",
AppCategory::TriviaGame => "public.app-category.trivia-games",
AppCategory::WordGame => "public.app-category.word-games",
AppCategory::GraphicsAndDesign => "public.app-category.graphics-design",
AppCategory::HealthcareAndFitness => "public.app-category.healthcare-fitness",
AppCategory::Lifestyle => "public.app-category.lifestyle",
AppCategory::Medical => "public.app-category.medical",
AppCategory::Music => "public.app-category.music",
AppCategory::News => "public.app-category.news",
AppCategory::Photography => "public.app-category.photography",
AppCategory::Productivity => "public.app-category.productivity",
AppCategory::Reference => "public.app-category.reference",
AppCategory::SocialNetworking => "public.app-category.social-networking",
AppCategory::Sports => "public.app-category.sports",
AppCategory::Travel => "public.app-category.travel",
AppCategory::Utility => "public.app-category.utilities",
AppCategory::Video => "public.app-category.video",
AppCategory::Weather => "public.app-category.weather",
}
}
}
impl<'d> serde::Deserialize<'d> for AppCategory {
fn deserialize<D: serde::Deserializer<'d>>(deserializer: D) -> Result<AppCategory, D::Error> {
deserializer.deserialize_str(AppCategoryVisitor { did_you_mean: None })
}
}
struct AppCategoryVisitor {
did_you_mean: Option<&'static str>,
}
impl serde::de::Visitor<'_> for AppCategoryVisitor {
type Value = AppCategory;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.did_you_mean {
Some(string) => write!(
formatter,
"a valid app category string (did you mean \"{string}\"?)"
),
None => write!(formatter, "a valid app category string"),
}
}
fn visit_str<E: serde::de::Error>(mut self, value: &str) -> Result<AppCategory, E> {
match AppCategory::from_str(value) {
Ok(category) => Ok(category),
Err(did_you_mean) => {
self.did_you_mean = did_you_mean;
let unexp = serde::de::Unexpected::Str(value);
Err(serde::de::Error::invalid_value(unexp, &self))
}
}
}
}
const CATEGORY_STRINGS: &[(&str, AppCategory)] = &[
("actiongame", AppCategory::ActionGame),
("actiongames", AppCategory::ActionGame),
("adventuregame", AppCategory::AdventureGame),
("adventuregames", AppCategory::AdventureGame),
("arcadegame", AppCategory::ArcadeGame),
("arcadegames", AppCategory::ArcadeGame),
("boardgame", AppCategory::BoardGame),
("boardgames", AppCategory::BoardGame),
("business", AppCategory::Business),
("cardgame", AppCategory::CardGame),
("cardgames", AppCategory::CardGame),
("casinogame", AppCategory::CasinoGame),
("casinogames", AppCategory::CasinoGame),
("developer", AppCategory::DeveloperTool),
("developertool", AppCategory::DeveloperTool),
("developertools", AppCategory::DeveloperTool),
("development", AppCategory::DeveloperTool),
("dicegame", AppCategory::DiceGame),
("dicegames", AppCategory::DiceGame),
("education", AppCategory::Education),
("educationalgame", AppCategory::EducationalGame),
("educationalgames", AppCategory::EducationalGame),
("entertainment", AppCategory::Entertainment),
("familygame", AppCategory::FamilyGame),
("familygames", AppCategory::FamilyGame),
("finance", AppCategory::Finance),
("fitness", AppCategory::HealthcareAndFitness),
("game", AppCategory::Game),
("games", AppCategory::Game),
("graphicdesign", AppCategory::GraphicsAndDesign),
("graphicsanddesign", AppCategory::GraphicsAndDesign),
("graphicsdesign", AppCategory::GraphicsAndDesign),
("healthcareandfitness", AppCategory::HealthcareAndFitness),
("healthcarefitness", AppCategory::HealthcareAndFitness),
("kidsgame", AppCategory::KidsGame),
("kidsgames", AppCategory::KidsGame),
("lifestyle", AppCategory::Lifestyle),
("logicgame", AppCategory::PuzzleGame),
("medical", AppCategory::Medical),
("medicalsoftware", AppCategory::Medical),
("music", AppCategory::Music),
("musicgame", AppCategory::MusicGame),
("musicgames", AppCategory::MusicGame),
("news", AppCategory::News),
("photography", AppCategory::Photography),
("productivity", AppCategory::Productivity),
("puzzlegame", AppCategory::PuzzleGame),
("puzzlegames", AppCategory::PuzzleGame),
("racinggame", AppCategory::RacingGame),
("racinggames", AppCategory::RacingGame),
("reference", AppCategory::Reference),
("roleplaying", AppCategory::RolePlayingGame),
("roleplayinggame", AppCategory::RolePlayingGame),
("roleplayinggames", AppCategory::RolePlayingGame),
("rpg", AppCategory::RolePlayingGame),
("simulationgame", AppCategory::SimulationGame),
("simulationgames", AppCategory::SimulationGame),
("socialnetwork", AppCategory::SocialNetworking),
("socialnetworking", AppCategory::SocialNetworking),
("sports", AppCategory::Sports),
("sportsgame", AppCategory::SportsGame),
("sportsgames", AppCategory::SportsGame),
("strategygame", AppCategory::StrategyGame),
("strategygames", AppCategory::StrategyGame),
("travel", AppCategory::Travel),
("triviagame", AppCategory::TriviaGame),
("triviagames", AppCategory::TriviaGame),
("utilities", AppCategory::Utility),
("utility", AppCategory::Utility),
("video", AppCategory::Video),
("weather", AppCategory::Weather),
("wordgame", AppCategory::WordGame),
("wordgames", AppCategory::WordGame),
];
#[cfg(test)]
mod tests {
use super::AppCategory;
use std::str::FromStr;
#[test]
fn category_from_string_ok() {
// Canonical name of category works:
assert_eq!(
AppCategory::from_str("Education"),
Ok(AppCategory::Education)
);
assert_eq!(
AppCategory::from_str("Developer Tool"),
Ok(AppCategory::DeveloperTool)
);
// Lowercase, spaces, and hyphens are fine:
assert_eq!(
AppCategory::from_str(" puzzle game "),
Ok(AppCategory::PuzzleGame)
);
assert_eq!(
AppCategory::from_str("Role-playing game"),
Ok(AppCategory::RolePlayingGame)
);
// Using macOS LSApplicationCategoryType value is fine:
assert_eq!(
AppCategory::from_str("public.app-category.developer-tools"),
Ok(AppCategory::DeveloperTool)
);
assert_eq!(
AppCategory::from_str("public.app-category.role-playing-games"),
Ok(AppCategory::RolePlayingGame)
);
// Using GNOME category name is fine:
assert_eq!(
AppCategory::from_str("Development"),
Ok(AppCategory::DeveloperTool)
);
assert_eq!(
AppCategory::from_str("LogicGame"),
Ok(AppCategory::PuzzleGame)
);
// Using common abbreviations is fine:
assert_eq!(
AppCategory::from_str("RPG"),
Ok(AppCategory::RolePlayingGame)
);
}
#[test]
fn category_from_string_did_you_mean() {
assert_eq!(AppCategory::from_str("gaming"), Err(Some("Game")));
assert_eq!(AppCategory::from_str("photos"), Err(Some("Photography")));
assert_eq!(
AppCategory::from_str("strategery"),
Err(Some("Strategy Game"))
);
}
#[test]
fn category_from_string_totally_wrong() {
assert_eq!(AppCategory::from_str("fhqwhgads"), Err(None));
assert_eq!(AppCategory::from_str("WHARRGARBL"), Err(None));
}
#[test]
fn ls_application_category_type_round_trip() {
let values = &[
"public.app-category.business",
"public.app-category.developer-tools",
"public.app-category.education",
"public.app-category.entertainment",
"public.app-category.finance",
"public.app-category.games",
"public.app-category.action-games",
"public.app-category.adventure-games",
"public.app-category.arcade-games",
"public.app-category.board-games",
"public.app-category.card-games",
"public.app-category.casino-games",
"public.app-category.dice-games",
"public.app-category.educational-games",
"public.app-category.family-games",
"public.app-category.kids-games",
"public.app-category.music-games",
"public.app-category.puzzle-games",
"public.app-category.racing-games",
"public.app-category.role-playing-games",
"public.app-category.simulation-games",
"public.app-category.sports-games",
"public.app-category.strategy-games",
"public.app-category.trivia-games",
"public.app-category.word-games",
"public.app-category.graphics-design",
"public.app-category.healthcare-fitness",
"public.app-category.lifestyle",
"public.app-category.medical",
"public.app-category.music",
"public.app-category.news",
"public.app-category.photography",
"public.app-category.productivity",
"public.app-category.reference",
"public.app-category.social-networking",
"public.app-category.sports",
"public.app-category.travel",
"public.app-category.utilities",
"public.app-category.video",
"public.app-category.weather",
];
// Test that if the user uses an LSApplicationCategoryType string as
// the category string, they will get back that same string for the
// macOS app bundle LSApplicationCategoryType.
for &value in values.iter() {
let category = AppCategory::from_str(value).expect(value);
assert_eq!(category.macos_application_category_type(), value);
}
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-bundler/src/bundle/updater_bundle.rs | crates/tauri-bundler/src/bundle/updater_bundle.rs | // Copyright 2016-2019 Cargo-Bundle developers <https://github.com/burtonageo/cargo-bundle>
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{
bundle::{
windows::{
NSIS_OUTPUT_FOLDER_NAME, NSIS_UPDATER_OUTPUT_FOLDER_NAME, WIX_OUTPUT_FOLDER_NAME,
WIX_UPDATER_OUTPUT_FOLDER_NAME,
},
Bundle,
},
error::{Context, ErrorExt},
utils::fs_utils,
Settings,
};
use tauri_utils::{display_path, platform::Target as TargetPlatform};
use std::{
fs::{self, File},
io::prelude::*,
path::{Path, PathBuf},
};
use zip::write::SimpleFileOptions;
// Build update
pub fn bundle_project(settings: &Settings, bundles: &[Bundle]) -> crate::Result<Vec<PathBuf>> {
let target_os = settings.target_platform();
if matches!(target_os, TargetPlatform::Windows) {
return bundle_update_windows(settings, bundles);
}
#[cfg(target_os = "macos")]
return bundle_update_macos(bundles);
#[cfg(target_os = "linux")]
return bundle_update_linux(bundles);
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
{
log::error!("Current platform does not support updates");
Ok(vec![])
}
}
// Create simple update-macos.tar.gz
// This is the Mac OS App packaged
#[cfg(target_os = "macos")]
fn bundle_update_macos(bundles: &[Bundle]) -> crate::Result<Vec<PathBuf>> {
use std::ffi::OsStr;
// find our .app or rebuild our bundle
if let Some(source_path) = bundles
.iter()
.filter(|bundle| bundle.package_type == crate::PackageType::MacOsBundle)
.find_map(|bundle| {
bundle
.bundle_paths
.iter()
.find(|path| path.extension() == Some(OsStr::new("app")))
})
{
// add .tar.gz to our path
let osx_archived = format!("{}.tar.gz", source_path.display());
let osx_archived_path = PathBuf::from(&osx_archived);
// Create our gzip file (need to send parent)
// as we walk the source directory (source isnt added)
create_tar(source_path, &osx_archived_path)
.with_context(|| "Failed to tar.gz update directory")?;
log::info!(action = "Bundling"; "{} ({})", osx_archived, display_path(&osx_archived_path));
Ok(vec![osx_archived_path])
} else {
Err(crate::Error::UnableToFindProject)
}
}
// Create simple update-linux_<arch>.tar.gz
// Including the AppImage
// Right now in linux we hot replace the bin and request a restart
// No assets are replaced
#[cfg(target_os = "linux")]
fn bundle_update_linux(bundles: &[Bundle]) -> crate::Result<Vec<PathBuf>> {
use std::ffi::OsStr;
// build our app actually we support only appimage on linux
if let Some(source_path) = bundles
.iter()
.filter(|bundle| bundle.package_type == crate::PackageType::AppImage)
.find_map(|bundle| {
bundle
.bundle_paths
.iter()
.find(|path| path.extension() == Some(OsStr::new("AppImage")))
})
{
// add .tar.gz to our path
let appimage_archived = format!("{}.tar.gz", source_path.display());
let appimage_archived_path = PathBuf::from(&appimage_archived);
// Create our gzip file
create_tar(source_path, &appimage_archived_path)
.with_context(|| "Failed to tar.gz update directory")?;
log::info!(action = "Bundling"; "{} ({})", appimage_archived, display_path(&appimage_archived_path));
Ok(vec![appimage_archived_path])
} else {
Err(crate::Error::UnableToFindProject)
}
}
// Create simple update-win_<arch>.zip
// Including the binary as root
// Right now in windows we hot replace the bin and request a restart
// No assets are replaced
fn bundle_update_windows(settings: &Settings, bundles: &[Bundle]) -> crate::Result<Vec<PathBuf>> {
use crate::bundle::settings::WebviewInstallMode;
#[cfg(target_os = "windows")]
use crate::bundle::windows::msi;
use crate::bundle::windows::nsis;
use crate::PackageType;
// find our installers or rebuild
let mut bundle_paths = Vec::new();
let mut rebuild_installers = || -> crate::Result<()> {
for bundle in bundles {
match bundle.package_type {
#[cfg(target_os = "windows")]
PackageType::WindowsMsi => bundle_paths.extend(msi::bundle_project(settings, true)?),
PackageType::Nsis => bundle_paths.extend(nsis::bundle_project(settings, true)?),
_ => {}
};
}
Ok(())
};
if matches!(
settings.windows().webview_install_mode,
WebviewInstallMode::OfflineInstaller { .. } | WebviewInstallMode::EmbedBootstrapper { .. }
) {
rebuild_installers()?;
} else {
let paths = bundles
.iter()
.filter(|bundle| {
matches!(
bundle.package_type,
PackageType::WindowsMsi | PackageType::Nsis
)
})
.flat_map(|bundle| bundle.bundle_paths.clone())
.collect::<Vec<_>>();
// we expect our installer files to be on `bundle_paths`
if paths.is_empty() {
rebuild_installers()?;
} else {
bundle_paths.extend(paths);
}
};
let mut installers_archived_paths = Vec::new();
for source_path in bundle_paths {
// add .zip to our path
let (archived_path, bundle_name) =
source_path
.components()
.fold((PathBuf::new(), String::new()), |(mut p, mut b), c| {
if let std::path::Component::Normal(name) = c {
if let Some(name) = name.to_str() {
// installers bundled for updater should be put in a directory named `${bundle_name}-updater`
if name == WIX_UPDATER_OUTPUT_FOLDER_NAME || name == NSIS_UPDATER_OUTPUT_FOLDER_NAME {
b = name.strip_suffix("-updater").unwrap().to_string();
p.push(&b);
return (p, b);
}
if name == WIX_OUTPUT_FOLDER_NAME || name == NSIS_OUTPUT_FOLDER_NAME {
b = name.to_string();
}
}
}
p.push(c);
(p, b)
});
let archived_path = archived_path.with_extension(format!("{bundle_name}.zip"));
log::info!(action = "Bundling"; "{}", display_path(&archived_path));
// Create our gzip file
create_zip(&source_path, &archived_path).with_context(|| "Failed to zip update bundle")?;
installers_archived_paths.push(archived_path);
}
Ok(installers_archived_paths)
}
pub fn create_zip(src_file: &Path, dst_file: &Path) -> crate::Result<PathBuf> {
let parent_dir = dst_file.parent().expect("No data in parent");
fs::create_dir_all(parent_dir)?;
let writer = fs_utils::create_file(dst_file)?;
let file_name = src_file
.file_name()
.expect("Can't extract file name from path");
let mut zip = zip::ZipWriter::new(writer);
let options = SimpleFileOptions::default()
.compression_method(zip::CompressionMethod::Stored)
.unix_permissions(0o755);
zip.start_file(file_name.to_string_lossy(), options)?;
let mut f =
File::open(src_file).fs_context("failed to open updater ZIP file", src_file.to_path_buf())?;
let mut buffer = Vec::new();
f.read_to_end(&mut buffer)?;
zip.write_all(&buffer)?;
buffer.clear();
Ok(dst_file.to_owned())
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn create_tar(src_dir: &Path, dest_path: &Path) -> crate::Result<PathBuf> {
use flate2::{write::GzEncoder, Compression};
let dest_file = fs_utils::create_file(dest_path)?;
let gzip_encoder = GzEncoder::new(dest_file, Compression::default());
let gzip_encoder = create_tar_from_src(src_dir, gzip_encoder)?;
let mut dest_file = gzip_encoder.finish()?;
dest_file.flush()?;
Ok(dest_path.to_owned())
}
#[cfg(target_os = "macos")]
fn create_tar_from_src<P: AsRef<Path>, W: Write>(src_dir: P, dest_file: W) -> crate::Result<W> {
let src_dir = src_dir.as_ref();
let mut builder = tar::Builder::new(dest_file);
builder.follow_symlinks(false);
builder.append_dir_all(src_dir.file_name().expect("Path has no file_name"), src_dir)?;
builder.into_inner().map_err(Into::into)
}
#[cfg(target_os = "linux")]
fn create_tar_from_src<P: AsRef<Path>, W: Write>(src_dir: P, dest_file: W) -> crate::Result<W> {
let src_dir = src_dir.as_ref();
let mut tar_builder = tar::Builder::new(dest_file);
// validate source type
let file_type = fs::metadata(src_dir).expect("Can't read source directory");
// if it's a file don't need to walkdir
if file_type.is_file() {
let mut src_file = fs::File::open(src_dir)?;
let file_name = src_dir
.file_name()
.expect("Can't extract file name from path");
tar_builder.append_file(file_name, &mut src_file)?;
} else {
for entry in walkdir::WalkDir::new(src_dir) {
let entry = entry?;
let src_path = entry.path();
if src_path == src_dir {
continue;
}
// We add the .parent() because example if we send a path
// /dev/src-tauri/target/debug/bundle/osx/app.app
// We need a tar with app.app/<...> (source root folder should be included)
// safe to unwrap: the path has a parent
let dest_path = src_path.strip_prefix(src_dir.parent().unwrap())?;
if entry.file_type().is_dir() {
tar_builder.append_dir(dest_path, src_path)?;
} else {
let mut src_file = fs::File::open(src_path)?;
tar_builder.append_file(dest_path, &mut src_file)?;
}
}
}
let dest_file = tar_builder.into_inner()?;
Ok(dest_file)
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-bundler/src/bundle/linux/rpm.rs | crates/tauri-bundler/src/bundle/linux/rpm.rs | // Copyright 2016-2019 Cargo-Bundle developers <https://github.com/burtonageo/cargo-bundle>
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{bundle::settings::Arch, error::ErrorExt, Settings};
use rpm::{self, signature::pgp, Dependency, FileMode, FileOptions};
use std::{
env,
fs::{self, File},
path::{Path, PathBuf},
};
use tauri_utils::config::RpmCompression;
use super::freedesktop;
/// Bundles the project.
/// Returns a vector of PathBuf that shows where the RPM was created.
pub fn bundle_project(settings: &Settings) -> crate::Result<Vec<PathBuf>> {
let product_name = settings.product_name();
let version = settings.version_string();
let release = match settings.rpm().release.as_str() {
"" => "1", // Considered the default. If left empty, you get file with "-.".
v => v,
};
let epoch = settings.rpm().epoch;
let arch = match settings.binary_arch() {
Arch::X86_64 => "x86_64",
Arch::X86 => "i386",
Arch::AArch64 => "aarch64",
Arch::Armhf => "armhfp",
Arch::Armel => "armel",
Arch::Riscv64 => "riscv64",
target => {
return Err(crate::Error::ArchError(format!(
"Unsupported architecture: {target:?}"
)));
}
};
let summary = settings.short_description().trim();
let package_base_name = format!("{product_name}-{version}-{release}.{arch}");
let package_name = format!("{package_base_name}.rpm");
let base_dir = settings.project_out_directory().join("bundle/rpm");
let package_dir = base_dir.join(&package_base_name);
if package_dir.exists() {
fs::remove_dir_all(&package_dir).fs_context(
"Failed to remove old package directory",
package_dir.clone(),
)?;
}
fs::create_dir_all(&package_dir)
.fs_context("Failed to create package directory", package_dir.clone())?;
let package_path = base_dir.join(&package_name);
log::info!(action = "Bundling"; "{} ({})", package_name, package_path.display());
let license = settings.license().unwrap_or_default();
let name = heck::AsKebabCase(settings.product_name()).to_string();
let compression = settings
.rpm()
.compression
.map(|c| match c {
RpmCompression::Gzip { level } => rpm::CompressionWithLevel::Gzip(level),
RpmCompression::Zstd { level } => rpm::CompressionWithLevel::Zstd(level),
RpmCompression::Xz { level } => rpm::CompressionWithLevel::Xz(level),
RpmCompression::Bzip2 { level } => rpm::CompressionWithLevel::Bzip2(level),
_ => rpm::CompressionWithLevel::None,
})
// This matches .deb compression. On a 240MB source binary the bundle will be 100KB larger than rpm's default while reducing build times by ~25%.
// TODO: Default to Zstd in v3 to match rpm-rs new default in 0.16
.unwrap_or(rpm::CompressionWithLevel::Gzip(6));
let mut builder = rpm::PackageBuilder::new(&name, version, &license, arch, summary)
.epoch(epoch)
.release(release)
.compression(compression);
if let Some(description) = settings.long_description() {
builder = builder.description(description);
}
if let Some(homepage) = settings.homepage_url() {
builder = builder.url(homepage);
}
// Add requirements
for dep in settings.rpm().depends.as_ref().cloned().unwrap_or_default() {
builder = builder.requires(Dependency::any(dep));
}
// Add provides
for dep in settings
.rpm()
.provides
.as_ref()
.cloned()
.unwrap_or_default()
{
builder = builder.provides(Dependency::any(dep));
}
// Add recommends
for dep in settings
.rpm()
.recommends
.as_ref()
.cloned()
.unwrap_or_default()
{
builder = builder.recommends(Dependency::any(dep));
}
// Add conflicts
for dep in settings
.rpm()
.conflicts
.as_ref()
.cloned()
.unwrap_or_default()
{
builder = builder.conflicts(Dependency::any(dep));
}
// Add obsoletes
for dep in settings
.rpm()
.obsoletes
.as_ref()
.cloned()
.unwrap_or_default()
{
builder = builder.obsoletes(Dependency::any(dep));
}
// Add binaries
for bin in settings.binaries() {
let src = settings.binary_path(bin);
let dest = Path::new("/usr/bin").join(bin.name());
builder = builder.with_file(src, FileOptions::new(dest.to_string_lossy()))?;
}
// Add external binaries
for src in settings.external_binaries() {
let src = src?;
let dest = Path::new("/usr/bin").join(
src
.file_name()
.expect("failed to extract external binary filename")
.to_string_lossy()
.replace(&format!("-{}", settings.target()), ""),
);
builder = builder.with_file(&src, FileOptions::new(dest.to_string_lossy()))?;
}
// Add scripts
if let Some(script_path) = &settings.rpm().pre_install_script {
let script = fs::read_to_string(script_path)?;
builder = builder.pre_install_script(script);
}
if let Some(script_path) = &settings.rpm().post_install_script {
let script = fs::read_to_string(script_path)?;
builder = builder.post_install_script(script);
}
if let Some(script_path) = &settings.rpm().pre_remove_script {
let script = fs::read_to_string(script_path)?;
builder = builder.pre_uninstall_script(script);
}
if let Some(script_path) = &settings.rpm().post_remove_script {
let script = fs::read_to_string(script_path)?;
builder = builder.post_uninstall_script(script);
}
// Add resources
if settings.resource_files().count() > 0 {
let resource_dir = Path::new("/usr/lib").join(settings.product_name());
// Create an empty file, needed to add a directory to the RPM package
// (cf https://github.com/rpm-rs/rpm/issues/177)
let empty_file_path = &package_dir.join("empty");
File::create(empty_file_path)?;
// Then add the resource directory `/usr/lib/<product_name>` to the package.
builder = builder.with_file(
empty_file_path,
FileOptions::new(resource_dir.to_string_lossy()).mode(FileMode::Dir { permissions: 0o755 }),
)?;
// Then add the resources files in that directory
for resource in settings.resource_files().iter() {
let resource = resource?;
let dest = resource_dir.join(resource.target());
builder = builder.with_file(resource.path(), FileOptions::new(dest.to_string_lossy()))?;
}
}
// Add Desktop entry file
let (desktop_src_path, desktop_dest_path) =
freedesktop::generate_desktop_file(settings, &settings.rpm().desktop_template, &package_dir)?;
builder = builder.with_file(
desktop_src_path,
FileOptions::new(desktop_dest_path.to_string_lossy()),
)?;
// Add icons
for (icon, src) in &freedesktop::list_icon_files(settings, &PathBuf::from("/"))? {
builder = builder.with_file(src, FileOptions::new(icon.path.to_string_lossy()))?;
}
// Add custom files
for (rpm_path, src_path) in settings.rpm().files.iter() {
if src_path.is_file() {
builder = builder.with_file(src_path, FileOptions::new(rpm_path.to_string_lossy()))?;
} else {
for entry in walkdir::WalkDir::new(src_path) {
let entry_path = entry?.into_path();
if entry_path.is_file() {
let dest_path = rpm_path.join(entry_path.strip_prefix(src_path).unwrap());
builder =
builder.with_file(&entry_path, FileOptions::new(dest_path.to_string_lossy()))?;
}
}
}
}
let pkg = if let Ok(raw_secret_key) = env::var("TAURI_SIGNING_RPM_KEY") {
let mut signer = pgp::Signer::load_from_asc(&raw_secret_key)?;
if let Ok(passphrase) = env::var("TAURI_SIGNING_RPM_KEY_PASSPHRASE") {
signer = signer.with_key_passphrase(passphrase);
}
builder.build_and_sign(signer)?
} else {
builder.build()?
};
let mut f = fs::File::create(&package_path)?;
pkg.write(&mut f)?;
Ok(vec![package_path])
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-bundler/src/bundle/linux/util.rs | crates/tauri-bundler/src/bundle/linux/util.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
/// Change value of __TAURI_BUNDLE_TYPE static variable to mark which package type it was bundled in
#[cfg(target_os = "linux")]
pub fn patch_binary(
binary_path: &std::path::PathBuf,
package_type: &crate::PackageType,
) -> crate::Result<()> {
let mut file_data = std::fs::read(binary_path).expect("Could not read binary file.");
let elf = match goblin::Object::parse(&file_data)? {
goblin::Object::Elf(elf) => elf,
_ => return Err(crate::Error::GenericError("Not an ELF file".to_owned())),
};
let offset = find_bundle_type_symbol(elf).ok_or(crate::Error::MissingBundleTypeVar)?;
let offset = offset as usize;
if offset + 3 <= file_data.len() {
let chars = &mut file_data[offset..offset + 3];
match package_type {
crate::PackageType::Deb => chars.copy_from_slice(b"DEB"),
crate::PackageType::Rpm => chars.copy_from_slice(b"RPM"),
crate::PackageType::AppImage => chars.copy_from_slice(b"APP"),
_ => {
return Err(crate::Error::InvalidPackageType(
package_type.short_name().to_owned(),
"linux".to_owned(),
))
}
}
std::fs::write(binary_path, &file_data)
.map_err(|error| crate::Error::BinaryWriteError(error.to_string()))?;
} else {
return Err(crate::Error::BinaryOffsetOutOfRange);
}
Ok(())
}
/// Find address of a symbol in relocations table
#[cfg(target_os = "linux")]
fn find_bundle_type_symbol(elf: goblin::elf::Elf<'_>) -> Option<i64> {
for sym in elf.syms.iter() {
if let Some(name) = elf.strtab.get_at(sym.st_name) {
if name == "__TAURI_BUNDLE_TYPE" {
for reloc in elf.dynrelas.iter() {
if reloc.r_offset == sym.st_value {
return Some(reloc.r_addend.unwrap());
}
}
}
}
}
None
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-bundler/src/bundle/linux/mod.rs | crates/tauri-bundler/src/bundle/linux/mod.rs | // Copyright 2016-2019 Cargo-Bundle developers <https://github.com/burtonageo/cargo-bundle>
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
pub mod appimage;
pub mod debian;
pub mod freedesktop;
pub mod rpm;
mod util;
#[cfg(target_os = "linux")]
pub use util::patch_binary;
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-bundler/src/bundle/linux/debian.rs | crates/tauri-bundler/src/bundle/linux/debian.rs | // Copyright 2016-2019 Cargo-Bundle developers <https://github.com/burtonageo/cargo-bundle>
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
// The structure of a Debian package looks something like this:
//
// foobar_1.2.3_i386.deb # Actually an ar archive
// debian-binary # Specifies deb format version (2.0 in our case)
// control.tar.gz # Contains files controlling the installation:
// control # Basic package metadata
// md5sums # Checksums for files in data.tar.gz below
// postinst # Post-installation script (optional)
// prerm # Pre-uninstallation script (optional)
// data.tar.gz # Contains files to be installed:
// usr/bin/foobar # Binary executable file
// usr/share/applications/foobar.desktop # Desktop file (for apps)
// usr/share/icons/hicolor/... # Icon files (for apps)
// usr/lib/foobar/... # Other resource files
//
// For cargo-bundle, we put bundle resource files under /usr/lib/package_name/,
// and then generate the desktop file and control file from the bundle
// metadata, as well as generating the md5sums file. Currently we do not
// generate postinst or prerm files.
use super::freedesktop;
use crate::{
bundle::settings::Arch,
error::{Context, ErrorExt},
utils::fs_utils,
Settings,
};
use flate2::{write::GzEncoder, Compression};
use tar::HeaderMode;
use walkdir::WalkDir;
use std::{
fs::{self, File, OpenOptions},
io::{self, Write},
os::unix::fs::{MetadataExt, OpenOptionsExt},
path::{Path, PathBuf},
};
/// Bundles the project.
/// Returns a vector of PathBuf that shows where the DEB was created.
pub fn bundle_project(settings: &Settings) -> crate::Result<Vec<PathBuf>> {
let arch = match settings.binary_arch() {
Arch::X86_64 => "amd64",
Arch::X86 => "i386",
Arch::AArch64 => "arm64",
Arch::Armhf => "armhf",
Arch::Armel => "armel",
Arch::Riscv64 => "riscv64",
target => {
return Err(crate::Error::ArchError(format!(
"Unsupported architecture: {target:?}"
)));
}
};
let package_base_name = format!(
"{}_{}_{}",
settings.product_name(),
settings.version_string(),
arch
);
let package_name = format!("{package_base_name}.deb");
let base_dir = settings.project_out_directory().join("bundle/deb");
let package_dir = base_dir.join(&package_base_name);
if package_dir.exists() {
fs::remove_dir_all(&package_dir).fs_context(
"Failed to Remove old package directory",
package_dir.clone(),
)?;
}
let package_path = base_dir.join(&package_name);
log::info!(action = "Bundling"; "{} ({})", package_name, package_path.display());
let (data_dir, _) =
generate_data(settings, &package_dir).context("Failed to build data folders and files")?;
fs_utils::copy_custom_files(&settings.deb().files, &data_dir)
.context("Failed to copy custom files")?;
// Generate control files.
let control_dir = package_dir.join("control");
generate_control_file(settings, arch, &control_dir, &data_dir)
.context("Failed to create control file")?;
generate_scripts(settings, &control_dir).context("Failed to create control scripts")?;
generate_md5sums(&control_dir, &data_dir).context("Failed to create md5sums file")?;
// Generate `debian-binary` file; see
// http://www.tldp.org/HOWTO/Debian-Binary-Package-Building-HOWTO/x60.html#AEN66
let debian_binary_path = package_dir.join("debian-binary");
create_file_with_data(&debian_binary_path, "2.0\n")
.context("Failed to create debian-binary file")?;
// Apply tar/gzip/ar to create the final package file.
let control_tar_gz_path =
tar_and_gzip_dir(control_dir).with_context(|| "Failed to tar/gzip control directory")?;
let data_tar_gz_path =
tar_and_gzip_dir(data_dir).with_context(|| "Failed to tar/gzip data directory")?;
create_archive(
vec![debian_binary_path, control_tar_gz_path, data_tar_gz_path],
&package_path,
)
.with_context(|| "Failed to create package archive")?;
Ok(vec![package_path])
}
/// Generate the debian data folders and files.
pub fn generate_data(
settings: &Settings,
package_dir: &Path,
) -> crate::Result<(PathBuf, Vec<freedesktop::Icon>)> {
// Generate data files.
let data_dir = package_dir.join("data");
let bin_dir = data_dir.join("usr/bin");
for bin in settings.binaries() {
let bin_path = settings.binary_path(bin);
let trgt = bin_dir.join(bin.name());
fs_utils::copy_file(&bin_path, &trgt)
.with_context(|| format!("Failed to copy binary from {bin_path:?} to {trgt:?}"))?;
}
copy_resource_files(settings, &data_dir).with_context(|| "Failed to copy resource files")?;
settings
.copy_binaries(&bin_dir)
.with_context(|| "Failed to copy external binaries")?;
let icons = freedesktop::copy_icon_files(settings, &data_dir)
.with_context(|| "Failed to create icon files")?;
freedesktop::generate_desktop_file(settings, &settings.deb().desktop_template, &data_dir)
.with_context(|| "Failed to create desktop file")?;
generate_changelog_file(settings, &data_dir)
.with_context(|| "Failed to create changelog.gz file")?;
Ok((data_dir, icons))
}
/// Generate the Changelog file by compressing, to be stored at /usr/share/doc/package-name/changelog.gz. See
/// <https://www.debian.org/doc/debian-policy/ch-docs.html#changelog-files-and-release-notes>
fn generate_changelog_file(settings: &Settings, data_dir: &Path) -> crate::Result<()> {
if let Some(changelog_src_path) = &settings.deb().changelog {
let mut src_file = File::open(changelog_src_path)?;
let product_name = settings.product_name();
let dest_path = data_dir.join(format!("usr/share/doc/{product_name}/changelog.gz"));
let changelog_file = fs_utils::create_file(&dest_path)?;
let mut gzip_encoder = GzEncoder::new(changelog_file, Compression::new(9));
io::copy(&mut src_file, &mut gzip_encoder)?;
let mut changelog_file = gzip_encoder.finish()?;
changelog_file.flush()?;
}
Ok(())
}
/// Generates the debian control file and stores it under the `control_dir`.
fn generate_control_file(
settings: &Settings,
arch: &str,
control_dir: &Path,
data_dir: &Path,
) -> crate::Result<()> {
// For more information about the format of this file, see
// https://www.debian.org/doc/debian-policy/ch-controlfields.html
let dest_path = control_dir.join("control");
let mut file = fs_utils::create_file(&dest_path)?;
let package = heck::AsKebabCase(settings.product_name());
writeln!(file, "Package: {package}")?;
writeln!(file, "Version: {}", settings.version_string())?;
writeln!(file, "Architecture: {arch}")?;
// Installed-Size must be divided by 1024, see https://www.debian.org/doc/debian-policy/ch-controlfields.html#installed-size
writeln!(file, "Installed-Size: {}", total_dir_size(data_dir)? / 1024)?;
let authors = settings
.authors_comma_separated()
.or_else(|| settings.publisher().map(ToString::to_string))
.unwrap_or_else(|| {
settings
.bundle_identifier()
.split('.')
.nth(1)
.unwrap_or(settings.bundle_identifier())
.to_string()
});
writeln!(file, "Maintainer: {authors}")?;
if let Some(section) = &settings.deb().section {
writeln!(file, "Section: {section}")?;
}
if let Some(priority) = &settings.deb().priority {
writeln!(file, "Priority: {priority}")?;
} else {
writeln!(file, "Priority: optional")?;
}
if let Some(homepage) = settings.homepage_url() {
writeln!(file, "Homepage: {homepage}")?;
}
let dependencies = settings.deb().depends.as_ref().cloned().unwrap_or_default();
if !dependencies.is_empty() {
writeln!(file, "Depends: {}", dependencies.join(", "))?;
}
let dependencies = settings
.deb()
.recommends
.as_ref()
.cloned()
.unwrap_or_default();
if !dependencies.is_empty() {
writeln!(file, "Recommends: {}", dependencies.join(", "))?;
}
let provides = settings
.deb()
.provides
.as_ref()
.cloned()
.unwrap_or_default();
if !provides.is_empty() {
writeln!(file, "Provides: {}", provides.join(", "))?;
}
let conflicts = settings
.deb()
.conflicts
.as_ref()
.cloned()
.unwrap_or_default();
if !conflicts.is_empty() {
writeln!(file, "Conflicts: {}", conflicts.join(", "))?;
}
let replaces = settings
.deb()
.replaces
.as_ref()
.cloned()
.unwrap_or_default();
if !replaces.is_empty() {
writeln!(file, "Replaces: {}", replaces.join(", "))?;
}
let mut short_description = settings.short_description().trim();
if short_description.is_empty() {
short_description = "(none)";
}
let mut long_description = settings.long_description().unwrap_or("").trim();
if long_description.is_empty() {
long_description = "(none)";
}
writeln!(file, "Description: {short_description}")?;
for line in long_description.lines() {
let line = line.trim();
if line.is_empty() {
writeln!(file, " .")?;
} else {
writeln!(file, " {line}")?;
}
}
file.flush()?;
Ok(())
}
fn generate_scripts(settings: &Settings, control_dir: &Path) -> crate::Result<()> {
if let Some(script_path) = &settings.deb().pre_install_script {
let dest_path = control_dir.join("preinst");
create_script_file_from_path(script_path, &dest_path)?
}
if let Some(script_path) = &settings.deb().post_install_script {
let dest_path = control_dir.join("postinst");
create_script_file_from_path(script_path, &dest_path)?
}
if let Some(script_path) = &settings.deb().pre_remove_script {
let dest_path = control_dir.join("prerm");
create_script_file_from_path(script_path, &dest_path)?
}
if let Some(script_path) = &settings.deb().post_remove_script {
let dest_path = control_dir.join("postrm");
create_script_file_from_path(script_path, &dest_path)?
}
Ok(())
}
fn create_script_file_from_path(from: &PathBuf, to: &PathBuf) -> crate::Result<()> {
let mut from = File::open(from)?;
let mut file = OpenOptions::new()
.create(true)
.truncate(true)
.write(true)
.mode(0o755)
.open(to)?;
std::io::copy(&mut from, &mut file)?;
Ok(())
}
/// Create an `md5sums` file in the `control_dir` containing the MD5 checksums
/// for each file within the `data_dir`.
fn generate_md5sums(control_dir: &Path, data_dir: &Path) -> crate::Result<()> {
let md5sums_path = control_dir.join("md5sums");
let mut md5sums_file = fs_utils::create_file(&md5sums_path)?;
for entry in WalkDir::new(data_dir) {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
continue;
}
let mut file = File::open(path)?;
let mut hash = md5::Context::new();
io::copy(&mut file, &mut hash)?;
for byte in hash.finalize().iter() {
write!(md5sums_file, "{byte:02x}")?;
}
let rel_path = path.strip_prefix(data_dir)?;
let path_str = rel_path.to_str().ok_or_else(|| {
let msg = format!("Non-UTF-8 path: {rel_path:?}");
io::Error::new(io::ErrorKind::InvalidData, msg)
})?;
writeln!(md5sums_file, " {path_str}")?;
}
Ok(())
}
/// Copy the bundle's resource files into an appropriate directory under the
/// `data_dir`.
fn copy_resource_files(settings: &Settings, data_dir: &Path) -> crate::Result<()> {
let resource_dir = data_dir.join("usr/lib").join(settings.product_name());
settings.copy_resources(&resource_dir)
}
/// Create an empty file at the given path, creating any parent directories as
/// needed, then write `data` into the file.
fn create_file_with_data<P: AsRef<Path>>(path: P, data: &str) -> crate::Result<()> {
let mut file = fs_utils::create_file(path.as_ref())?;
file.write_all(data.as_bytes())?;
file.flush()?;
Ok(())
}
/// Computes the total size, in bytes, of the given directory and all of its
/// contents.
fn total_dir_size(dir: &Path) -> crate::Result<u64> {
let mut total: u64 = 0;
for entry in WalkDir::new(dir) {
total += entry?.metadata()?.len();
}
Ok(total)
}
/// Writes a tar file to the given writer containing the given directory.
fn create_tar_from_dir<P: AsRef<Path>, W: Write>(src_dir: P, dest_file: W) -> crate::Result<W> {
let src_dir = src_dir.as_ref();
let mut tar_builder = tar::Builder::new(dest_file);
for entry in WalkDir::new(src_dir) {
let entry = entry?;
let src_path = entry.path();
if src_path == src_dir {
continue;
}
let dest_path = src_path.strip_prefix(src_dir)?;
let stat = fs::metadata(src_path)?;
let mut header = tar::Header::new_gnu();
header.set_metadata_in_mode(&stat, HeaderMode::Deterministic);
header.set_mtime(stat.mtime() as u64);
if entry.file_type().is_dir() {
tar_builder.append_data(&mut header, dest_path, &mut io::empty())?;
} else {
let mut src_file = fs::File::open(src_path)?;
tar_builder.append_data(&mut header, dest_path, &mut src_file)?;
}
}
let dest_file = tar_builder.into_inner()?;
Ok(dest_file)
}
/// Creates a `.tar.gz` file from the given directory (placing the new file
/// within the given directory's parent directory), then deletes the original
/// directory and returns the path to the new file.
fn tar_and_gzip_dir<P: AsRef<Path>>(src_dir: P) -> crate::Result<PathBuf> {
let src_dir = src_dir.as_ref();
let dest_path = src_dir.with_extension("tar.gz");
let dest_file = fs_utils::create_file(&dest_path)?;
let gzip_encoder = GzEncoder::new(dest_file, Compression::default());
let gzip_encoder = create_tar_from_dir(src_dir, gzip_encoder)?;
let mut dest_file = gzip_encoder.finish()?;
dest_file.flush()?;
Ok(dest_path)
}
/// Creates an `ar` archive from the given source files and writes it to the
/// given destination path.
fn create_archive(srcs: Vec<PathBuf>, dest: &Path) -> crate::Result<()> {
let mut builder = ar::Builder::new(fs_utils::create_file(dest)?);
for path in &srcs {
builder.append_path(path)?;
}
builder.into_inner()?.flush()?;
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-bundler/src/bundle/linux/freedesktop/mod.rs | crates/tauri-bundler/src/bundle/linux/freedesktop/mod.rs | // Copyright 2016-2019 Cargo-Bundle developers <https://github.com/burtonageo/cargo-bundle>
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! This module provides utilities helping the packaging of desktop
//! applications for Linux:
//!
//! - Generation of [desktop entries] (`.desktop` files)
//! - Copy of icons in the [icons file hierarchy]
//!
//! The specifications are developed and hosted at [freedesktop.org].
//!
//! [freedesktop.org]: https://www.freedesktop.org
//! [desktop entries]: https://www.freedesktop.org/wiki/Specifications/desktop-entry-spec/
//! [icons file hierarchy]: https://specifications.freedesktop.org/icon-theme-spec/icon-theme-spec-latest.html#icon_lookup
use std::collections::BTreeMap;
use std::ffi::OsStr;
use std::fs::{read_to_string, File};
use std::io::BufReader;
use std::path::{Path, PathBuf};
use handlebars::Handlebars;
use image::{self, codecs::png::PngDecoder, ImageDecoder};
use serde::Serialize;
use crate::{
error::Context,
utils::{self, fs_utils},
Settings,
};
#[derive(PartialEq, Eq, PartialOrd, Ord)]
pub struct Icon {
pub width: u32,
pub height: u32,
pub is_high_density: bool,
pub path: PathBuf,
}
/// Generate the icon files, and returns a map where keys are the icons and
/// values are their current (source) path.
pub fn list_icon_files(
settings: &Settings,
data_dir: &Path,
) -> crate::Result<BTreeMap<Icon, PathBuf>> {
let base_dir = data_dir.join("usr/share/icons/hicolor");
let main_binary_name = settings.main_binary_name()?;
let get_dest_path = |width: u32, height: u32, is_high_density: bool| {
base_dir.join(format!(
"{}x{}{}/apps/{}.png",
width,
height,
if is_high_density { "@2" } else { "" },
main_binary_name
))
};
let mut icons = BTreeMap::new();
for icon_path in settings.icon_files() {
let icon_path = icon_path?;
if icon_path.extension() != Some(OsStr::new("png")) {
continue;
}
// Put file in scope so that it's closed when copying it
let icon = {
let decoder = PngDecoder::new(BufReader::new(File::open(&icon_path)?))?;
let width = decoder.dimensions().0;
let height = decoder.dimensions().1;
let is_high_density = utils::is_retina(&icon_path);
let dest_path = get_dest_path(width, height, is_high_density);
Icon {
width,
height,
is_high_density,
path: dest_path,
}
};
icons.entry(icon).or_insert(icon_path);
}
Ok(icons)
}
/// Generate the icon files and store them under the `data_dir`.
pub fn copy_icon_files(settings: &Settings, data_dir: &Path) -> crate::Result<Vec<Icon>> {
let icons = list_icon_files(settings, data_dir)?;
for (icon, src) in &icons {
fs_utils::copy_file(src, &icon.path)?;
}
Ok(icons.into_keys().collect())
}
/// Generate the application desktop file and store it under the `data_dir`.
/// Returns the path of the resulting file (source path) and the destination
/// path in the package.
pub fn generate_desktop_file(
settings: &Settings,
custom_template_path: &Option<PathBuf>,
data_dir: &Path,
) -> crate::Result<(PathBuf, PathBuf)> {
let bin_name = settings.main_binary_name()?;
let product_name = settings.product_name();
let desktop_file_name = format!("{product_name}.desktop");
let path = PathBuf::from("usr/share/applications").join(desktop_file_name);
let dest_path = PathBuf::from("/").join(&path);
let file_path = data_dir.join(&path);
let file = &mut fs_utils::create_file(&file_path)?;
let mut handlebars = Handlebars::new();
handlebars.register_escape_fn(handlebars::no_escape);
if let Some(template) = custom_template_path {
handlebars
.register_template_string("main.desktop", read_to_string(template)?)
.map_err(Into::into)
.context("Failed to setup custom handlebar template")?;
} else {
handlebars
.register_template_string("main.desktop", include_str!("./main.desktop"))
.map_err(Into::into)
.context("Failed to setup default handlebar template")?;
}
#[derive(Serialize)]
struct DesktopTemplateParams<'a> {
categories: &'a str,
comment: Option<&'a str>,
exec: &'a str,
icon: &'a str,
name: &'a str,
mime_type: Option<String>,
long_description: String,
}
let mut mime_type: Vec<String> = Vec::new();
if let Some(associations) = settings.file_associations() {
mime_type.extend(
associations
.iter()
.filter_map(|association| association.mime_type.clone()),
);
}
if let Some(protocols) = settings.deep_link_protocols() {
mime_type.extend(
protocols
.iter()
.flat_map(|protocol| &protocol.schemes)
.map(|s| format!("x-scheme-handler/{s}")),
);
}
let mime_type = (!mime_type.is_empty()).then_some(mime_type.join(";"));
let bin_name_exec = if bin_name.contains(' ') {
format!("\"{bin_name}\"")
} else {
bin_name.to_string()
};
handlebars.render_to_write(
"main.desktop",
&DesktopTemplateParams {
categories: settings
.app_category()
.map(|app_category| app_category.freedesktop_categories())
.unwrap_or(""),
comment: if !settings.short_description().is_empty() {
Some(settings.short_description())
} else {
None
},
exec: &bin_name_exec,
icon: bin_name,
name: settings.product_name(),
mime_type,
long_description: settings.long_description().unwrap_or_default().to_string(),
},
file,
)?;
Ok((file_path, dest_path))
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-bundler/src/bundle/linux/appimage/mod.rs | crates/tauri-bundler/src/bundle/linux/appimage/mod.rs | // Copyright 2016-2019 Cargo-Bundle developers <https://github.com/burtonageo/cargo-bundle>
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use super::debian;
use crate::{
bundle::settings::Arch,
error::{Context, ErrorExt},
utils::{fs_utils, http_utils::download, CommandExt},
Settings,
};
use std::{
fs,
path::{Path, PathBuf},
process::Command,
};
/// Bundles the project.
/// Returns a vector of PathBuf that shows where the AppImage was created.
pub fn bundle_project(settings: &Settings) -> crate::Result<Vec<PathBuf>> {
// generate the deb binary name
let appimage_arch: &str = match settings.binary_arch() {
Arch::X86_64 => "amd64",
Arch::X86 => "i386",
Arch::AArch64 => "aarch64",
Arch::Armhf => "armhf",
target => {
return Err(crate::Error::ArchError(format!(
"Unsupported architecture: {target:?}"
)));
}
};
let tools_arch = if settings.binary_arch() == Arch::Armhf {
"armhf"
} else {
settings.target().split('-').next().unwrap()
};
let output_path = settings.project_out_directory().join("bundle/appimage");
if output_path.exists() {
fs::remove_dir_all(&output_path)?;
}
let tools_path = settings
.local_tools_directory()
.map(|d| d.join(".tauri"))
.unwrap_or_else(|| {
dirs::cache_dir().map_or_else(|| output_path.to_path_buf(), |p| p.join("tauri"))
});
fs::create_dir_all(&tools_path)?;
let linuxdeploy_path = prepare_tools(
&tools_path,
tools_arch,
settings.log_level() != log::Level::Error,
)?;
let package_dir = settings.project_out_directory().join("bundle/appimage_deb");
let main_binary = settings.main_binary()?;
let product_name = settings.product_name();
let mut settings = settings.clone();
if main_binary.name().contains(' ') {
let main_binary_path = settings.binary_path(main_binary);
let project_out_directory = settings.project_out_directory();
let main_binary_name_kebab = heck::AsKebabCase(main_binary.name()).to_string();
let new_path = project_out_directory.join(&main_binary_name_kebab);
fs::copy(main_binary_path, new_path)?;
let main_binary = settings.main_binary_mut()?;
main_binary.set_name(main_binary_name_kebab);
}
// generate deb_folder structure
let (data_dir, icons) = debian::generate_data(&settings, &package_dir)
.with_context(|| "Failed to build data folders and files")?;
fs_utils::copy_custom_files(&settings.appimage().files, &data_dir)
.with_context(|| "Failed to copy custom files")?;
fs::create_dir_all(&output_path)?;
let app_dir_path = output_path.join(format!("{}.AppDir", settings.product_name()));
let appimage_filename = format!(
"{}_{}_{}.AppImage",
settings.product_name(),
settings.version_string(),
appimage_arch
);
let appimage_path = output_path.join(&appimage_filename);
fs_utils::create_dir(&app_dir_path, true)?;
fs::create_dir_all(&tools_path)?;
let larger_icon = icons
.iter()
.filter(|i| i.width == i.height)
.max_by_key(|i| i.width)
.expect("couldn't find a square icon to use as AppImage icon");
let larger_icon_path = larger_icon
.path
.strip_prefix(package_dir.join("data"))
.unwrap()
.to_string_lossy()
.to_string();
log::info!(action = "Bundling"; "{} ({})", appimage_filename, appimage_path.display());
let app_dir_usr = app_dir_path.join("usr/");
let app_dir_usr_bin = app_dir_usr.join("bin/");
let app_dir_usr_lib = app_dir_usr.join("lib/");
fs_utils::copy_dir(&data_dir.join("usr/"), &app_dir_usr)?;
// Using create_dir_all for a single dir so we don't get errors if the path already exists
fs::create_dir_all(&app_dir_usr_bin)?;
fs::create_dir_all(app_dir_usr_lib)?;
// Copy bins and libs that linuxdeploy doesn't know about
// we also check if the user may have provided their own copy already
// xdg-open will be handled by the `files` config instead
if settings.deep_link_protocols().is_some() && !app_dir_usr_bin.join("xdg-open").exists() {
fs::copy("/usr/bin/xdg-mime", app_dir_usr_bin.join("xdg-mime"))
.fs_context("xdg-mime binary not found", "/usr/bin/xdg-mime".to_string())?;
}
// we also check if the user may have provided their own copy already
if settings.appimage().bundle_xdg_open && !app_dir_usr_bin.join("xdg-open").exists() {
fs::copy("/usr/bin/xdg-open", app_dir_usr_bin.join("xdg-open"))
.fs_context("xdg-open binary not found", "/usr/bin/xdg-open".to_string())?;
}
let search_dirs = [
match settings.binary_arch() {
Arch::X86_64 => "/usr/lib/x86_64-linux-gnu/",
Arch::X86 => "/usr/lib/i386-linux-gnu/",
Arch::AArch64 => "/usr/lib/aarch64-linux-gnu/",
Arch::Armhf => "/usr/lib/arm-linux-gnueabihf/",
_ => unreachable!(),
},
"/usr/lib64",
"/usr/lib",
"/usr/libexec",
];
for file in [
"WebKitNetworkProcess",
"WebKitWebProcess",
"injected-bundle/libwebkit2gtkinjectedbundle.so",
] {
for source in search_dirs.map(PathBuf::from) {
// TODO: Check if it's the same dir name on all systems
let source = source.join("webkit2gtk-4.1").join(file);
if source.exists() {
fs_utils::copy_file(
&source,
&app_dir_path.join(source.strip_prefix("/").unwrap()),
)?;
}
}
}
fs::copy(
tools_path.join(format!("AppRun-{tools_arch}")),
app_dir_path.join("AppRun"),
)?;
fs::copy(
app_dir_path.join(larger_icon_path),
app_dir_path.join(format!("{product_name}.png")),
)?;
std::os::unix::fs::symlink(
app_dir_path.join(format!("{product_name}.png")),
app_dir_path.join(".DirIcon"),
)?;
std::os::unix::fs::symlink(
app_dir_path.join(format!("usr/share/applications/{product_name}.desktop")),
app_dir_path.join(format!("{product_name}.desktop")),
)?;
let log_level = match settings.log_level() {
log::Level::Error => "3",
log::Level::Warn => "2",
log::Level::Info => "1",
_ => "0",
};
let mut cmd = Command::new(linuxdeploy_path);
cmd.env("OUTPUT", &appimage_path);
cmd.env("ARCH", tools_arch);
// Looks like the cli arg isn't enough for the updated AppImage output-plugin.
cmd.env("APPIMAGE_EXTRACT_AND_RUN", "1");
cmd.args([
"--appimage-extract-and-run",
"--verbosity",
log_level,
"--appdir",
&app_dir_path.display().to_string(),
"--plugin",
"gtk",
]);
if settings.appimage().bundle_media_framework {
cmd.args(["--plugin", "gstreamer"]);
}
cmd.args(["--output", "appimage"]);
// Linuxdeploy logs everything into stderr so we have to ignore the output ourselves here
if settings.log_level() == log::Level::Error {
log::debug!(action = "Running"; "Command `linuxdeploy {}`", cmd.get_args().map(|arg| arg.to_string_lossy()).fold(String::new(), |acc, arg| format!("{acc} {arg}")));
if !cmd.output()?.status.success() {
return Err(crate::Error::GenericError(
"failed to run linuxdeploy".to_string(),
));
}
} else {
cmd.output_ok()?;
}
fs::remove_dir_all(&package_dir)?;
Ok(vec![appimage_path])
}
// returns the linuxdeploy path to keep linuxdeploy_arch contained
fn prepare_tools(tools_path: &Path, arch: &str, verbose: bool) -> crate::Result<PathBuf> {
let apprun = tools_path.join(format!("AppRun-{arch}"));
if !apprun.exists() {
let data = download(&format!(
"https://github.com/tauri-apps/binary-releases/releases/download/apprun-old/AppRun-{arch}"
))?;
write_and_make_executable(&apprun, &data)?;
}
let linuxdeploy_arch = if arch == "i686" { "i386" } else { arch };
let linuxdeploy = tools_path.join(format!("linuxdeploy-{linuxdeploy_arch}.AppImage"));
if !linuxdeploy.exists() {
let data = download(&format!("https://github.com/tauri-apps/binary-releases/releases/download/linuxdeploy/linuxdeploy-{linuxdeploy_arch}.AppImage"))?;
write_and_make_executable(&linuxdeploy, &data)?;
}
let gtk = tools_path.join("linuxdeploy-plugin-gtk.sh");
if !gtk.exists() {
let data = include_bytes!("./linuxdeploy-plugin-gtk.sh");
write_and_make_executable(>k, data)?;
}
let gstreamer = tools_path.join("linuxdeploy-plugin-gstreamer.sh");
if !gstreamer.exists() {
let data = include_bytes!("./linuxdeploy-plugin-gstreamer.sh");
write_and_make_executable(&gstreamer, data)?;
}
let appimage = tools_path.join("linuxdeploy-plugin-appimage.AppImage");
if !appimage.exists() {
// This is optional, linuxdeploy will fall back to its built-in version if the download failed.
let data = download(&format!("https://github.com/linuxdeploy/linuxdeploy-plugin-appimage/releases/download/continuous/linuxdeploy-plugin-appimage-{arch}.AppImage"));
match data {
Ok(data) => write_and_make_executable(&appimage, &data)?,
Err(err) => {
log::error!("Download of AppImage plugin failed. Using older built-in version instead.");
if verbose {
log::debug!("{err:?}");
}
}
}
}
// This should prevent linuxdeploy to be detected by appimage integration tools
let _ = Command::new("dd")
.args([
"if=/dev/zero",
"bs=1",
"count=3",
"seek=8",
"conv=notrunc",
&format!("of={}", linuxdeploy.display()),
])
.output();
Ok(linuxdeploy)
}
fn write_and_make_executable(path: &Path, data: &[u8]) -> std::io::Result<()> {
use std::os::unix::fs::PermissionsExt;
fs::write(path, data)?;
fs::set_permissions(path, fs::Permissions::from_mode(0o770))?;
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-bundler/src/bundle/windows/sign.rs | crates/tauri-bundler/src/bundle/windows/sign.rs | // Copyright 2016-2019 Cargo-Bundle developers <https://github.com/burtonageo/cargo-bundle>
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::bundle::settings::CustomSignCommandSettings;
#[cfg(windows)]
use crate::bundle::windows::util;
use crate::{utils::CommandExt, Settings};
#[cfg(windows)]
use std::path::PathBuf;
#[cfg(windows)]
use std::sync::OnceLock;
use std::{path::Path, process::Command};
impl Settings {
pub(crate) fn sign_params(&self) -> SignParams {
SignParams {
product_name: self.product_name().into(),
digest_algorithm: self
.windows()
.digest_algorithm
.as_ref()
.map(|algorithm| algorithm.to_string())
.unwrap_or_else(|| "sha256".to_string()),
certificate_thumbprint: self
.windows()
.certificate_thumbprint
.clone()
.unwrap_or_default(),
timestamp_url: self
.windows()
.timestamp_url
.as_ref()
.map(|url| url.to_string()),
tsp: self.windows().tsp,
sign_command: self.windows().sign_command.clone(),
}
}
}
#[cfg_attr(not(windows), allow(dead_code))]
pub struct SignParams {
pub product_name: String,
pub digest_algorithm: String,
pub certificate_thumbprint: String,
pub timestamp_url: Option<String>,
pub tsp: bool,
pub sign_command: Option<CustomSignCommandSettings>,
}
#[cfg(windows)]
fn signtool() -> Option<PathBuf> {
// sign code forked from https://github.com/forbjok/rust-codesign
static SIGN_TOOL: OnceLock<crate::Result<PathBuf>> = OnceLock::new();
SIGN_TOOL
.get_or_init(|| {
if let Some(signtool) = std::env::var_os("TAURI_WINDOWS_SIGNTOOL_PATH") {
return Ok(PathBuf::from(signtool));
}
const INSTALLED_ROOTS_REGKEY_PATH: &str = r"SOFTWARE\Microsoft\Windows Kits\Installed Roots";
const KITS_ROOT_REGVALUE_NAME: &str = r"KitsRoot10";
// Open 32-bit HKLM "Installed Roots" key
let installed_roots_key = windows_registry::LOCAL_MACHINE
.open(INSTALLED_ROOTS_REGKEY_PATH)
.map_err(|_| crate::Error::OpenRegistry(INSTALLED_ROOTS_REGKEY_PATH.to_string()))?;
// Get the Windows SDK root path
let kits_root_10_path: String = installed_roots_key
.get_string(KITS_ROOT_REGVALUE_NAME)
.map_err(|_| crate::Error::GetRegistryValue(KITS_ROOT_REGVALUE_NAME.to_string()))?;
// Construct Windows SDK bin path
let kits_root_10_bin_path = Path::new(&kits_root_10_path).join("bin");
let mut installed_kits: Vec<String> = installed_roots_key
.keys()
.map_err(|_| crate::Error::FailedToEnumerateRegKeys)?
.collect();
// Sort installed kits
installed_kits.sort();
/* Iterate through installed kit version keys in reverse (from newest to oldest),
adding their bin paths to the list.
Windows SDK 10 v10.0.15063.468 and later will have their signtools located there. */
let mut kit_bin_paths: Vec<PathBuf> = installed_kits
.iter()
.rev()
.map(|kit| kits_root_10_bin_path.join(kit))
.collect();
/* Add kits root bin path.
For Windows SDK 10 versions earlier than v10.0.15063.468, signtool will be located there. */
kit_bin_paths.push(kits_root_10_bin_path);
// Choose which version of SignTool to use based on OS bitness
let arch_dir = util::os_bitness().ok_or(crate::Error::UnsupportedBitness)?;
/* Iterate through all bin paths, checking for existence of a SignTool executable. */
for kit_bin_path in &kit_bin_paths {
/* Construct SignTool path. */
let signtool_path = kit_bin_path.join(arch_dir).join("signtool.exe");
/* Check if SignTool exists at this location. */
if signtool_path.exists() {
// SignTool found. Return it.
return Ok(signtool_path);
}
}
Err(crate::Error::SignToolNotFound)
})
.as_ref()
.ok()
.cloned()
}
/// Check if binary is already signed.
/// Used to skip sidecar binaries that are already signed.
#[cfg(windows)]
pub fn verify(path: &Path) -> crate::Result<bool> {
let signtool = signtool().ok_or(crate::Error::SignToolNotFound)?;
let mut cmd = Command::new(signtool);
cmd.arg("verify");
cmd.arg("/pa");
cmd.arg(path);
Ok(cmd.status()?.success())
}
pub fn sign_command_custom<P: AsRef<Path>>(
path: P,
command: &CustomSignCommandSettings,
) -> crate::Result<Command> {
let path = path.as_ref();
let cwd = std::env::current_dir()?;
let mut cmd = Command::new(&command.cmd);
for arg in &command.args {
if arg == "%1" {
cmd.arg(path);
} else {
let path = Path::new(arg);
// turn relative paths into absolute paths - so the uninstall command can use them
// since the !uninstfinalize NSIS hook runs in a different directory
if path.exists() && path.is_relative() {
cmd.arg(cwd.join(path));
} else {
cmd.arg(arg);
}
}
}
Ok(cmd)
}
#[cfg(windows)]
pub fn sign_command_default<P: AsRef<Path>>(
path: P,
params: &SignParams,
) -> crate::Result<Command> {
let signtool = signtool().ok_or(crate::Error::SignToolNotFound)?;
let mut cmd = Command::new(signtool);
cmd.arg("sign");
cmd.args(["/fd", ¶ms.digest_algorithm]);
cmd.args(["/sha1", ¶ms.certificate_thumbprint]);
cmd.args(["/d", ¶ms.product_name]);
if let Some(ref timestamp_url) = params.timestamp_url {
if params.tsp {
cmd.args(["/tr", timestamp_url]);
cmd.args(["/td", ¶ms.digest_algorithm]);
} else {
cmd.args(["/t", timestamp_url]);
}
}
cmd.arg(path.as_ref());
Ok(cmd)
}
pub fn sign_command<P: AsRef<Path>>(path: P, params: &SignParams) -> crate::Result<Command> {
match ¶ms.sign_command {
Some(custom_command) => sign_command_custom(path, custom_command),
#[cfg(windows)]
None => sign_command_default(path, params),
// should not be reachable
#[cfg(not(windows))]
None => Ok(Command::new("")),
}
}
pub fn sign_custom<P: AsRef<Path>>(
path: P,
custom_command: &CustomSignCommandSettings,
) -> crate::Result<()> {
let path = path.as_ref();
log::info!(action = "Signing";"{} with a custom signing command", tauri_utils::display_path(path));
let mut cmd = sign_command_custom(path, custom_command)?;
let output = cmd.output_ok()?;
let stdout = String::from_utf8_lossy(output.stdout.as_slice()).into_owned();
log::info!(action = "Signing";"Output of signing command:\n{}", stdout.trim());
Ok(())
}
#[cfg(windows)]
pub fn sign_default<P: AsRef<Path>>(path: P, params: &SignParams) -> crate::Result<()> {
let signtool = signtool().ok_or(crate::Error::SignToolNotFound)?;
let path = path.as_ref();
log::info!(action = "Signing"; "{} with identity \"{}\"", tauri_utils::display_path(path), params.certificate_thumbprint);
let mut cmd = sign_command_default(path, params)?;
log::debug!("Running signtool {:?}", signtool);
// Execute SignTool command
let output = cmd.output_ok()?;
let stdout = String::from_utf8_lossy(output.stdout.as_slice()).into_owned();
log::info!(action = "Signing";"Output of signing command:\n{}", stdout.trim());
Ok(())
}
pub fn sign<P: AsRef<Path>>(path: P, params: &SignParams) -> crate::Result<()> {
match ¶ms.sign_command {
Some(custom_command) => sign_custom(path, custom_command),
#[cfg(windows)]
None => sign_default(path, params),
// should not be reachable, as user should either use Windows
// or specify a custom sign_command but we succeed anyways
#[cfg(not(windows))]
None => Ok(()),
}
}
pub fn try_sign<P: AsRef<Path>>(file_path: P, settings: &Settings) -> crate::Result<()> {
if settings.no_sign() {
log::warn!(
"Skipping signing for {} due to --no-sign flag.",
tauri_utils::display_path(file_path.as_ref())
);
return Ok(());
}
if settings.windows().can_sign() {
log::info!(action = "Signing"; "{}", tauri_utils::display_path(file_path.as_ref()));
sign(file_path, &settings.sign_params())?;
}
Ok(())
}
/// If the file is signable (is a binary file) and not signed already
/// (will skip the verification if not on Windows since we can't verify it)
pub fn should_sign(file_path: &Path) -> crate::Result<bool> {
let is_binary = file_path
.extension()
.is_some_and(|ext| ext == "exe" || ext == "dll");
if !is_binary {
return Ok(false);
}
#[cfg(windows)]
{
let already_signed = verify(file_path)?;
Ok(!already_signed)
}
// Skip verification if not on Windows since we can't verify it
#[cfg(not(windows))]
{
Ok(true)
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-bundler/src/bundle/windows/util.rs | crates/tauri-bundler/src/bundle/windows/util.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{
fs::create_dir_all,
path::{Path, PathBuf},
};
use ureq::ResponseExt;
use crate::utils::http_utils::{base_ureq_agent, download};
pub const WEBVIEW2_BOOTSTRAPPER_URL: &str = "https://go.microsoft.com/fwlink/p/?LinkId=2124703";
pub const WEBVIEW2_OFFLINE_INSTALLER_X86_URL: &str =
"https://go.microsoft.com/fwlink/?linkid=2099617";
pub const WEBVIEW2_OFFLINE_INSTALLER_X64_URL: &str =
"https://go.microsoft.com/fwlink/?linkid=2124701";
pub const WEBVIEW2_URL_PREFIX: &str =
"https://msedge.sf.dl.delivery.mp.microsoft.com/filestreamingservice/files/";
pub const NSIS_OUTPUT_FOLDER_NAME: &str = "nsis";
pub const NSIS_UPDATER_OUTPUT_FOLDER_NAME: &str = "nsis-updater";
pub const WIX_OUTPUT_FOLDER_NAME: &str = "msi";
pub const WIX_UPDATER_OUTPUT_FOLDER_NAME: &str = "msi-updater";
pub fn webview2_guid_path(url: &str) -> crate::Result<(String, String)> {
let agent = base_ureq_agent();
let response = agent.head(url).call().map_err(Box::new)?;
let final_url = response.get_uri().to_string();
let remaining_url = final_url.strip_prefix(WEBVIEW2_URL_PREFIX).ok_or_else(|| {
crate::Error::GenericError(format!(
"WebView2 URL prefix mismatch. Expected `{WEBVIEW2_URL_PREFIX}`, found `{final_url}`."
))
})?;
let (guid, filename) = remaining_url.split_once('/').ok_or_else(|| {
crate::Error::GenericError(format!(
"WebView2 URL format mismatch. Expected `<GUID>/<FILENAME>`, found `{remaining_url}`."
))
})?;
Ok((guid.into(), filename.into()))
}
pub fn download_webview2_bootstrapper(base_path: &Path) -> crate::Result<PathBuf> {
let file_path = base_path.join("MicrosoftEdgeWebview2Setup.exe");
if !file_path.exists() {
std::fs::write(&file_path, download(WEBVIEW2_BOOTSTRAPPER_URL)?)?;
}
Ok(file_path)
}
pub fn download_webview2_offline_installer(base_path: &Path, arch: &str) -> crate::Result<PathBuf> {
let url = if arch == "x64" {
WEBVIEW2_OFFLINE_INSTALLER_X64_URL
} else {
WEBVIEW2_OFFLINE_INSTALLER_X86_URL
};
let (guid, filename) = webview2_guid_path(url)?;
let dir_path = base_path.join(guid);
let file_path = dir_path.join(filename);
if !file_path.exists() {
create_dir_all(dir_path)?;
std::fs::write(&file_path, download(url)?)?;
}
Ok(file_path)
}
#[cfg(target_os = "windows")]
pub fn os_bitness<'a>() -> Option<&'a str> {
use windows_sys::Win32::System::SystemInformation::{
GetNativeSystemInfo, PROCESSOR_ARCHITECTURE_AMD64, PROCESSOR_ARCHITECTURE_INTEL, SYSTEM_INFO,
};
let mut system_info: SYSTEM_INFO = unsafe { std::mem::zeroed() };
unsafe { GetNativeSystemInfo(&mut system_info) };
match unsafe { system_info.Anonymous.Anonymous.wProcessorArchitecture } {
PROCESSOR_ARCHITECTURE_INTEL => Some("x86"),
PROCESSOR_ARCHITECTURE_AMD64 => Some("x64"),
_ => None,
}
}
pub fn patch_binary(binary_path: &PathBuf, package_type: &crate::PackageType) -> crate::Result<()> {
let mut file_data = std::fs::read(binary_path)?;
let pe = match goblin::Object::parse(&file_data)? {
goblin::Object::PE(pe) => pe,
_ => {
return Err(crate::Error::BinaryParseError(
std::io::Error::new(std::io::ErrorKind::InvalidInput, "binary is not a PE file").into(),
));
}
};
let tauri_bundle_section = pe
.sections
.iter()
.find(|s| s.name().unwrap_or_default() == ".taubndl")
.ok_or(crate::Error::MissingBundleTypeVar)?;
let data_offset = tauri_bundle_section.pointer_to_raw_data as usize;
let pointer_size = if pe.is_64 { 8 } else { 4 };
let ptr_bytes = file_data
.get(data_offset..data_offset + pointer_size)
.ok_or(crate::Error::BinaryOffsetOutOfRange)?;
// `try_into` is safe to `unwrap` here because we have already checked the slice's size through `get`
let ptr_value = if pe.is_64 {
u64::from_le_bytes(ptr_bytes.try_into().unwrap())
} else {
u32::from_le_bytes(ptr_bytes.try_into().unwrap()).into()
};
let rdata_section = pe
.sections
.iter()
.find(|s| s.name().unwrap_or_default() == ".rdata")
.ok_or_else(|| {
crate::Error::BinaryParseError(
std::io::Error::new(std::io::ErrorKind::InvalidInput, ".rdata section not found").into(),
)
})?;
let rva = ptr_value.checked_sub(pe.image_base as u64).ok_or_else(|| {
crate::Error::BinaryParseError(
std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid RVA offset").into(),
)
})?;
// see "Relative virtual address (RVA)" for explanation of offset arithmetic here:
// https://learn.microsoft.com/en-us/windows/win32/debug/pe-format#general-concepts
let file_offset = rdata_section.pointer_to_raw_data as usize
+ (rva as usize).saturating_sub(rdata_section.virtual_address as usize);
// Overwrite the string at that offset
let string_bytes = file_data
.get_mut(file_offset..file_offset + 3)
.ok_or(crate::Error::BinaryOffsetOutOfRange)?;
match package_type {
crate::PackageType::Nsis => string_bytes.copy_from_slice(b"NSS"),
crate::PackageType::WindowsMsi => string_bytes.copy_from_slice(b"MSI"),
_ => {
return Err(crate::Error::InvalidPackageType(
package_type.short_name().to_owned(),
"windows".to_owned(),
));
}
}
std::fs::write(binary_path, &file_data)
.map_err(|e| crate::Error::BinaryWriteError(e.to_string()))?;
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-bundler/src/bundle/windows/mod.rs | crates/tauri-bundler/src/bundle/windows/mod.rs | // Copyright 2016-2019 Cargo-Bundle developers <https://github.com/burtonageo/cargo-bundle>
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
#[cfg(target_os = "windows")]
pub mod msi;
pub mod nsis;
pub mod sign;
mod util;
pub use util::{
NSIS_OUTPUT_FOLDER_NAME, NSIS_UPDATER_OUTPUT_FOLDER_NAME, WIX_OUTPUT_FOLDER_NAME,
WIX_UPDATER_OUTPUT_FOLDER_NAME,
};
pub use util::patch_binary;
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.