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 |
|---|---|---|---|---|---|---|---|---|
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/interpreter/build.rs | packages/interpreter/build.rs | fn main() {
// If any TS files change, re-run the build script
lazy_js_bundle::LazyTypeScriptBindings::new()
.with_watching("./src/ts")
.with_binding("./src/ts/set_attribute.ts", "./src/js/set_attribute.js")
.with_binding("./src/ts/native.ts", "./src/js/native.js")
.with_binding("./src/ts/core.ts", "./src/js/core.js")
.with_binding("./src/ts/hydrate.ts", "./src/js/hydrate.js")
.with_binding("./src/ts/patch_console.ts", "./src/js/patch_console.js")
.with_binding(
"./src/ts/initialize_streaming.ts",
"./src/js/initialize_streaming.js",
)
.run();
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/interpreter/src/lib.rs | packages/interpreter/src/lib.rs | #![allow(clippy::empty_docs)]
#![doc = include_str!("../README.md")]
#![doc(html_logo_url = "https://avatars.githubusercontent.com/u/79236386")]
#![doc(html_favicon_url = "https://avatars.githubusercontent.com/u/79236386")]
/// The base class that the JS channel will extend
pub static INTERPRETER_JS: &str = include_str!("./js/core.js");
/// The code explicitly for desktop/liveview that bridges the eval gap between the two
pub static NATIVE_JS: &str = include_str!("./js/native.js");
/// The code that handles initializing data used for fullstack data streaming
pub static INITIALIZE_STREAMING_JS: &str = include_str!("./js/initialize_streaming.js");
#[cfg(all(feature = "binary-protocol", feature = "sledgehammer"))]
mod write_native_mutations;
#[cfg(all(feature = "binary-protocol", feature = "sledgehammer"))]
pub use write_native_mutations::*;
#[cfg(feature = "sledgehammer")]
pub mod unified_bindings;
#[cfg(feature = "sledgehammer")]
pub use unified_bindings::*;
// Common bindings for minimal usage.
#[cfg(all(feature = "minimal_bindings", feature = "webonly"))]
pub mod minimal_bindings {
use wasm_bindgen::{prelude::wasm_bindgen, JsValue};
/// Some useful snippets that we use to share common functionality between the different platforms we support.
///
/// This maintains some sort of consistency between web, desktop, and liveview
#[wasm_bindgen(module = "/src/js/set_attribute.js")]
extern "C" {
/// Set the attribute of the node
pub fn setAttributeInner(node: JsValue, name: &str, value: JsValue, ns: Option<&str>);
}
#[wasm_bindgen(module = "/src/js/hydrate.js")]
extern "C" {
/// Register a callback that that will be called to hydrate a node at the given id with data from the server
pub fn register_rehydrate_chunk_for_streaming(
closure: &wasm_bindgen::closure::Closure<dyn FnMut(Vec<u32>, js_sys::Uint8Array)>,
);
/// Register a callback that that will be called to hydrate a node at the given id with data from the server
pub fn register_rehydrate_chunk_for_streaming_debug(
closure: &wasm_bindgen::closure::Closure<
dyn FnMut(Vec<u32>, js_sys::Uint8Array, Option<Vec<String>>, Option<Vec<String>>),
>,
);
}
#[wasm_bindgen(module = "/src/js/patch_console.js")]
extern "C" {
pub fn monkeyPatchConsole(ws: JsValue);
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/interpreter/src/unified_bindings.rs | packages/interpreter/src/unified_bindings.rs | #[cfg(feature = "webonly")]
use web_sys::Node;
pub const SLEDGEHAMMER_JS: &str = GENERATED_JS;
#[cfg(feature = "webonly")]
#[wasm_bindgen::prelude::wasm_bindgen]
extern "C" {
pub type BaseInterpreter;
#[wasm_bindgen(method)]
pub fn initialize(this: &BaseInterpreter, root: Node, handler: &js_sys::Function);
#[wasm_bindgen(method, js_name = "saveTemplate")]
pub fn save_template(this: &BaseInterpreter, nodes: Vec<Node>, tmpl_id: u16);
#[wasm_bindgen(method)]
pub fn hydrate(this: &BaseInterpreter, ids: Vec<u32>, under: Vec<Node>);
#[wasm_bindgen(method, js_name = "getNode")]
pub fn get_node(this: &BaseInterpreter, id: u32) -> Node;
#[wasm_bindgen(method, js_name = "pushRoot")]
pub fn push_root(this: &BaseInterpreter, node: Node);
}
// Note that this impl is for the sledgehammer interpreter to allow us dropping down to the base interpreter
// During hydration and initialization we need to the base interpreter methods
#[cfg(feature = "webonly")]
impl Interpreter {
/// Convert the interpreter to its baseclass, giving
pub fn base(&self) -> &BaseInterpreter {
use wasm_bindgen::prelude::JsCast;
self.js_channel().unchecked_ref()
}
}
#[sledgehammer_bindgen::bindgen(module)]
mod js {
// Extend the web base class
const BASE: &str = "./src/js/core.js";
/// The interpreter extends the core interpreter which contains the state for the interpreter along with some functions that all platforms use like `AppendChildren`.
#[extends(BaseInterpreter)]
pub struct Interpreter;
fn push_root(root: u32) {
"{this.pushRoot(this.nodes[$root$]);}"
}
fn append_children(id: u32, many: u16) {
"{this.appendChildren($id$, $many$);}"
}
fn pop_root() {
"{this.stack.pop();}"
}
fn replace_with(id: u32, n: u16) {
"{const root = this.nodes[$id$]; let els = this.stack.splice(this.stack.length-$n$); if (root.listening) { this.removeAllNonBubblingListeners(root); } root.replaceWith(...els);}"
}
fn insert_after(id: u32, n: u16) {
"{let node = this.nodes[$id$];node.after(...this.stack.splice(this.stack.length-$n$));}"
}
fn insert_before(id: u32, n: u16) {
"{let node = this.nodes[$id$];node.before(...this.stack.splice(this.stack.length-$n$));}"
}
fn remove(id: u32) {
"{let node = this.nodes[$id$]; if (node !== undefined) { if (node.listening) { this.removeAllNonBubblingListeners(node); } node.remove(); }}"
}
fn create_raw_text(text: &str) {
"{this.stack.push(document.createTextNode($text$));}"
}
fn create_text_node(text: &str, id: u32) {
"{let node = document.createTextNode($text$); this.nodes[$id$] = node; this.stack.push(node);}"
}
fn create_placeholder(id: u32) {
"{let node = document.createComment('placeholder'); this.stack.push(node); this.nodes[$id$] = node;}"
}
fn new_event_listener(event_name: &str<u8, evt>, id: u32, bubbles: u8) {
r#"
const node = this.nodes[id];
if(node.listening){node.listening += 1;}else{node.listening = 1;}
node.setAttribute('data-dioxus-id', `\${id}`);
this.createListener($event_name$, node, $bubbles$);
"#
}
fn remove_event_listener(event_name: &str<u8, evt>, id: u32, bubbles: u8) {
"{let node = this.nodes[$id$]; node.listening -= 1; node.removeAttribute('data-dioxus-id'); this.removeListener(node, $event_name$, $bubbles$);}"
}
fn set_text(id: u32, text: &str) {
"{this.nodes[$id$].textContent = $text$;}"
}
fn set_attribute(id: u32, field: &str<u8, attr>, value: &str, ns: &str<u8, ns_cache>) {
"{let node = this.nodes[$id$]; this.setAttributeInner(node, $field$, $value$, $ns$);}"
}
fn remove_attribute(id: u32, field: &str<u8, attr>, ns: &str<u8, ns_cache>) {
r#"{
let node = this.nodes[$id$];
if (!ns) {
switch (field) {
case "value":
node.value = "";
node.removeAttribute("value");
break;
case "checked":
node.checked = false;
break;
case "selected":
node.selected = false;
break;
case "dangerous_inner_html":
node.innerHTML = "";
break;
default:
node.removeAttribute(field);
break;
}
} else if (ns == "style") {
node.style.removeProperty(field);
} else {
node.removeAttributeNS(ns, field);
}
}"#
}
fn assign_id(ptr: u32, len: u8, id: u32) {
"{this.nodes[$id$] = this.loadChild($ptr$, $len$);}"
}
fn replace_placeholder(ptr: u32, len: u8, n: u16) {
"{let els = this.stack.splice(this.stack.length - $n$); let node = this.loadChild($ptr$, $len$); node.replaceWith(...els);}"
}
fn load_template(tmpl_id: u16, index: u16, id: u32) {
"{let node = this.templates[$tmpl_id$][$index$].cloneNode(true); this.nodes[$id$] = node; this.stack.push(node);}"
}
#[cfg(feature = "binary-protocol")]
fn append_children_to_top(many: u16) {
"{
let root = this.stack[this.stack.length-many-1];
let els = this.stack.splice(this.stack.length-many);
for (let k = 0; k < many; k++) {
root.appendChild(els[k]);
}
}"
}
#[cfg(feature = "binary-protocol")]
fn set_top_attribute(field: &str<u8, attr>, value: &str, ns: &str<u8, ns_cache>) {
"{this.setAttributeInner(this.stack[this.stack.length-1], $field$, $value$, $ns$);}"
}
#[cfg(feature = "binary-protocol")]
fn add_placeholder() {
"{let node = document.createComment('placeholder'); this.stack.push(node);}"
}
#[cfg(feature = "binary-protocol")]
fn create_element(element: &'static str<u8, el>) {
"{this.stack.push(document.createElement($element$))}"
}
#[cfg(feature = "binary-protocol")]
fn create_element_ns(element: &'static str<u8, el>, ns: &'static str<u8, namespace>) {
"{this.stack.push(document.createElementNS($ns$, $element$))}"
}
#[cfg(feature = "binary-protocol")]
fn add_templates(tmpl_id: u16, len: u16) {
"{this.templates[$tmpl_id$] = this.stack.splice(this.stack.length-$len$);}"
}
#[cfg(feature = "binary-protocol")]
fn foreign_event_listener(event: &str<u8, evt>, id: u32, bubbles: u8) {
r#"
bubbles = bubbles == 1;
let this_node = this.nodes[id];
if(this_node.listening){
this_node.listening += 1;
} else {
this_node.listening = 1;
}
this_node.setAttribute('data-dioxus-id', `\${id}`);
const event_name = $event$;
// if this is a mounted listener, we send the event immediately
if (event_name === "mounted") {
window.ipc.postMessage(
this.sendSerializedEvent({
name: event_name,
element: id,
data: null,
bubbles,
})
);
} else {
this.createListener(event_name, this_node, bubbles, (event) => {
this.handler(event, event_name, bubbles);
});
}"#
}
/// Assign the ID
#[cfg(feature = "binary-protocol")]
fn assign_id_ref(array: &[u8], id: u32) {
"{this.nodes[$id$] = this.loadChild($array$);}"
}
#[cfg(feature = "binary-protocol")]
fn replace_placeholder_ref(array: &[u8], n: u16) {
"{let els = this.stack.splice(this.stack.length - $n$); let node = this.loadChild($array$); node.replaceWith(...els);}"
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/interpreter/src/write_native_mutations.rs | packages/interpreter/src/write_native_mutations.rs | use crate::unified_bindings::Interpreter as Channel;
use dioxus_core::{Template, TemplateAttribute, TemplateNode, WriteMutations};
use dioxus_core_types::event_bubbles;
use rustc_hash::FxHashMap;
/// The state needed to apply mutations to a channel. This state should be kept across all mutations for the app
#[derive(Default)]
pub struct MutationState {
/// The currently registered templates with the template ids
templates: FxHashMap<Template, u16>,
/// The channel that we are applying mutations to
channel: Channel,
}
impl MutationState {
pub fn new() -> Self {
Self::default()
}
pub fn export_memory(&mut self) -> Vec<u8> {
let bytes: Vec<_> = self.channel.export_memory().collect();
self.channel.reset();
bytes
}
pub fn write_memory_into(&mut self, buffer: &mut Vec<u8>) {
buffer.extend(self.channel.export_memory());
self.channel.reset();
}
pub fn channel(&mut self) -> &mut Channel {
&mut self.channel
}
pub fn channel_mut(&mut self) -> &mut Channel {
&mut self.channel
}
fn create_template_node(&mut self, node: &'static TemplateNode) {
use TemplateNode::*;
match node {
Element {
tag,
namespace,
attrs,
children,
..
} => {
// Push the current node onto the stack
match namespace {
Some(ns) => self.channel.create_element_ns(tag, ns),
None => self.channel.create_element(tag),
}
// Set attributes on the current node
for attr in *attrs {
if let TemplateAttribute::Static {
name,
value,
namespace,
} = attr
{
self.channel
.set_top_attribute(name, value, namespace.unwrap_or_default())
}
}
// Add each child to the stack
for child in *children {
self.create_template_node(child);
}
// Add all children to the parent
self.channel.append_children_to_top(children.len() as u16);
}
Text { text } => self.channel.create_raw_text(text),
Dynamic { .. } => self.channel.add_placeholder(),
}
}
}
impl WriteMutations for MutationState {
fn append_children(&mut self, id: dioxus_core::ElementId, m: usize) {
self.channel.append_children(id.0 as u32, m as u16);
}
fn assign_node_id(&mut self, path: &'static [u8], id: dioxus_core::ElementId) {
self.channel.assign_id_ref(path, id.0 as u32);
}
fn create_placeholder(&mut self, id: dioxus_core::ElementId) {
self.channel.create_placeholder(id.0 as u32);
}
fn create_text_node(&mut self, value: &str, id: dioxus_core::ElementId) {
self.channel.create_text_node(value, id.0 as u32);
}
fn load_template(&mut self, template: Template, index: usize, id: dioxus_core::ElementId) {
// Get the template or create it if we haven't seen it before
let tmpl_id = self.templates.get(&template).cloned().unwrap_or_else(|| {
let tmpl_id = self.templates.len() as u16;
self.templates.insert(template, tmpl_id);
for root in template.roots.iter() {
self.create_template_node(root);
}
let len = template.roots.len() as u16;
self.channel.add_templates(tmpl_id, len);
tmpl_id
});
self.channel
.load_template(tmpl_id, index as u16, id.0 as u32);
}
fn replace_node_with(&mut self, id: dioxus_core::ElementId, m: usize) {
self.channel.replace_with(id.0 as u32, m as u16);
}
fn replace_placeholder_with_nodes(&mut self, path: &'static [u8], m: usize) {
self.channel.replace_placeholder_ref(path, m as u16);
}
fn insert_nodes_after(&mut self, id: dioxus_core::ElementId, m: usize) {
self.channel.insert_after(id.0 as u32, m as u16);
}
fn insert_nodes_before(&mut self, id: dioxus_core::ElementId, m: usize) {
self.channel.insert_before(id.0 as u32, m as u16);
}
fn set_attribute(
&mut self,
name: &'static str,
ns: Option<&'static str>,
value: &dioxus_core::AttributeValue,
id: dioxus_core::ElementId,
) {
match value {
dioxus_core::AttributeValue::Text(txt) => {
self.channel
.set_attribute(id.0 as u32, name, txt, ns.unwrap_or_default())
}
dioxus_core::AttributeValue::Float(f) => self.channel.set_attribute(
id.0 as u32,
name,
&f.to_string(),
ns.unwrap_or_default(),
),
dioxus_core::AttributeValue::Int(n) => self.channel.set_attribute(
id.0 as u32,
name,
&n.to_string(),
ns.unwrap_or_default(),
),
dioxus_core::AttributeValue::Bool(b) => self.channel.set_attribute(
id.0 as u32,
name,
if *b { "true" } else { "false" },
ns.unwrap_or_default(),
),
dioxus_core::AttributeValue::None => {
self.channel
.remove_attribute(id.0 as u32, name, ns.unwrap_or_default())
}
_ => unreachable!("Any attributes are not supported by the current renderer"),
}
}
fn set_node_text(&mut self, value: &str, id: dioxus_core::ElementId) {
self.channel.set_text(id.0 as u32, value);
}
fn create_event_listener(&mut self, name: &'static str, id: dioxus_core::ElementId) {
// note that we use the foreign event listener here instead of the native one
// the native method assumes we have direct access to the dom, which we don't.
self.channel
.foreign_event_listener(name, id.0 as u32, event_bubbles(name) as u8);
}
fn remove_event_listener(&mut self, name: &'static str, id: dioxus_core::ElementId) {
self.channel
.remove_event_listener(name, id.0 as u32, event_bubbles(name) as u8);
}
fn remove_node(&mut self, id: dioxus_core::ElementId) {
self.channel.remove(id.0 as u32);
}
fn push_root(&mut self, id: dioxus_core::ElementId) {
self.channel.push_root(id.0 as _);
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/interpreter/tests/serialize.rs | packages/interpreter/tests/serialize.rs | //! Ensure that events are serialized and deserialized correctly.
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/interpreter/tests/e2e.rs | packages/interpreter/tests/e2e.rs | //! Ensure that the interpreter loads, has no errors, and writes mutations
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/config-macros/src/lib.rs | packages/config-macros/src/lib.rs | /// A macro for deciding whether or not to split the wasm bundle.
/// Used by the internal router-macro code. The contents here are considered to be semver exempt.
///
/// Only on wasm with the wasm-split feature will we prefer the `maybe_wasm_split` variant that emits
/// the "lefthand" tokens. Otherwise, we emit the non-wasm_split tokens
#[doc(hidden)]
#[cfg(all(feature = "wasm-split", target_arch = "wasm32"))]
#[macro_export]
macro_rules! maybe_wasm_split {
(
if wasm_split {
$left:tt
} else {
$right:tt
}
) => {
$left
};
}
/// A macro for deciding whether or not to split the wasm bundle.
/// Used by the internal router-macro code. The contents here are considered to be semver exempt.
///
/// Only on wasm with the wasm-split feature will we prefer the `maybe_wasm_split` variant that emits
/// the "lefthand" tokens. Otherwise, we emit the non-wasm_split tokens
#[doc(hidden)]
#[cfg(any(not(feature = "wasm-split"), not(target_arch = "wasm32")))]
#[macro_export]
macro_rules! maybe_wasm_split {
(
if wasm_split {
$left:tt
} else {
$right:tt
}
) => {
$right
};
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx/src/attribute.rs | packages/rsx/src/attribute.rs | //! Parser for the attribute shared both by elements and components
//!
//! ```rust, ignore
//! rsx! {
//! div {
//! class: "my-class",
//! onclick: move |_| println!("clicked")
//! }
//!
//! Component {
//! class: "my-class",
//! onclick: move |_| println!("clicked")
//! }
//! }
//! ```
use super::literal::HotLiteral;
use crate::{innerlude::*, partial_closure::PartialClosure};
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::{quote, quote_spanned, ToTokens, TokenStreamExt};
use std::fmt::Display;
use syn::{
ext::IdentExt,
parse::{Parse, ParseStream},
parse_quote,
spanned::Spanned,
Block, Expr, ExprBlock, ExprClosure, ExprIf, Ident, Lit, LitBool, LitFloat, LitInt, LitStr,
Stmt, Token,
};
/// A property value in the from of a `name: value` pair with an optional comma.
/// Note that the colon and value are optional in the case of shorthand attributes. We keep them around
/// to support "lossless" parsing in case that ever might be useful.
#[derive(PartialEq, Eq, Clone, Debug, Hash)]
pub struct Attribute {
/// The name of the attribute (ident or custom)
///
/// IE `class` or `onclick`
pub name: AttributeName,
/// The colon that separates the name and value - keep this for lossless parsing
pub colon: Option<Token![:]>,
/// The value of the attribute
///
/// IE `class="my-class"` or `onclick: move |_| println!("clicked")`
pub value: AttributeValue,
/// The comma that separates this attribute from the next one
/// Used for more accurate completions
pub comma: Option<Token![,]>,
/// The dynamic index of this attribute - used by the template system
pub dyn_idx: DynIdx,
/// The element name of this attribute if it is bound to an element.
/// When parsed for components or freestanding, this will be None
pub el_name: Option<ElementName>,
}
impl Parse for Attribute {
fn parse(content: ParseStream) -> syn::Result<Self> {
// if there's an ident not followed by a colon, it's a shorthand attribute
if content.peek(Ident::peek_any) && !content.peek2(Token![:]) {
let ident = parse_raw_ident(content)?;
let comma = content.parse().ok();
return Ok(Attribute {
name: AttributeName::BuiltIn(ident.clone()),
colon: None,
value: AttributeValue::Shorthand(ident),
comma,
dyn_idx: DynIdx::default(),
el_name: None,
});
}
// Parse the name as either a known or custom attribute
let name = match content.peek(LitStr) {
true => AttributeName::Custom(content.parse::<LitStr>()?),
false => AttributeName::BuiltIn(parse_raw_ident(content)?),
};
// Ensure there's a colon
let colon = Some(content.parse::<Token![:]>()?);
// todo: make this cleaner please
// if statements in attributes get automatic closing in some cases
// we shouldn't be handling it any differently.
let value = AttributeValue::parse(content)?;
let comma = content.parse::<Token![,]>().ok();
let attr = Attribute {
name,
value,
colon,
comma,
dyn_idx: DynIdx::default(),
el_name: None,
};
Ok(attr)
}
}
impl Attribute {
/// Create a new attribute from a name and value
pub fn from_raw(name: AttributeName, value: AttributeValue) -> Self {
Self {
name,
colon: Default::default(),
value,
comma: Default::default(),
dyn_idx: Default::default(),
el_name: None,
}
}
/// Set the dynamic index of this attribute
pub fn set_dyn_idx(&self, idx: usize) {
self.dyn_idx.set(idx);
}
/// Get the dynamic index of this attribute
pub fn get_dyn_idx(&self) -> usize {
self.dyn_idx.get()
}
pub fn span(&self) -> proc_macro2::Span {
self.name.span()
}
pub fn as_lit(&self) -> Option<&HotLiteral> {
match &self.value {
AttributeValue::AttrLiteral(lit) => Some(lit),
_ => None,
}
}
/// Run this closure against the attribute if it's hotreloadable
pub fn with_literal(&self, f: impl FnOnce(&HotLiteral)) {
if let AttributeValue::AttrLiteral(ifmt) = &self.value {
f(ifmt);
}
}
pub fn ifmt(&self) -> Option<&IfmtInput> {
match &self.value {
AttributeValue::AttrLiteral(HotLiteral::Fmted(input)) => Some(input),
_ => None,
}
}
pub fn as_static_str_literal(&self) -> Option<(&AttributeName, &IfmtInput)> {
match &self.value {
AttributeValue::AttrLiteral(lit) => match &lit {
HotLiteral::Fmted(input) if input.is_static() => Some((&self.name, input)),
_ => None,
},
_ => None,
}
}
pub fn is_static_str_literal(&self) -> bool {
self.as_static_str_literal().is_some()
}
pub fn rendered_as_dynamic_attr(&self) -> TokenStream2 {
// Shortcut out with spreads
if let AttributeName::Spread(_) = self.name {
let AttributeValue::AttrExpr(expr) = &self.value else {
unreachable!("Spread attributes should always be expressions")
};
return quote_spanned! { expr.span() => {#expr}.into_boxed_slice() };
}
let el_name = self
.el_name
.as_ref()
.expect("el_name rendered as a dynamic attribute should always have an el_name set");
let ns = |name: &AttributeName| match (el_name, name) {
(ElementName::Ident(i), AttributeName::BuiltIn(_)) => {
quote! { dioxus_elements::#i::#name.1 }
}
_ => quote! { None },
};
let volatile = |name: &AttributeName| match (el_name, name) {
(ElementName::Ident(i), AttributeName::BuiltIn(_)) => {
quote! { dioxus_elements::#i::#name.2 }
}
_ => quote! { false },
};
let attribute = |name: &AttributeName| match name {
AttributeName::BuiltIn(name) => match el_name {
ElementName::Ident(_) => quote! { dioxus_elements::#el_name::#name.0 },
ElementName::Custom(_) => {
let as_string = name.to_string();
quote!(#as_string)
}
},
AttributeName::Custom(s) => quote! { #s },
AttributeName::Spread(_) => unreachable!("Spread attributes are handled elsewhere"),
};
let attribute = {
let value = &self.value;
let name = &self.name;
let is_not_event = !self.name.is_likely_event();
match &self.value {
AttributeValue::AttrLiteral(_)
| AttributeValue::AttrExpr(_)
| AttributeValue::Shorthand(_)
| AttributeValue::IfExpr { .. }
if is_not_event =>
{
let name = &self.name;
let ns = ns(name);
let volatile = volatile(name);
let attribute = attribute(name);
let value = quote! { #value };
quote! {
dioxus_core::Attribute::new(
#attribute,
#value,
#ns,
#volatile
)
}
}
AttributeValue::EventTokens(_) | AttributeValue::AttrExpr(_) => {
let (tokens, span) = match &self.value {
AttributeValue::EventTokens(tokens) => {
(tokens.to_token_stream(), tokens.span())
}
AttributeValue::AttrExpr(tokens) => {
(tokens.to_token_stream(), tokens.span())
}
_ => unreachable!(),
};
fn check_tokens_is_closure(tokens: &TokenStream2) -> bool {
if syn::parse2::<ExprClosure>(tokens.to_token_stream()).is_ok() {
return true;
}
let Ok(block) = syn::parse2::<ExprBlock>(tokens.to_token_stream()) else {
return false;
};
let mut block = █
loop {
match block.block.stmts.last() {
Some(Stmt::Expr(Expr::Closure(_), _)) => return true,
Some(Stmt::Expr(Expr::Block(b), _)) => {
block = b;
continue;
}
_ => return false,
}
}
}
match &self.name {
AttributeName::BuiltIn(name) => {
let event_tokens_is_closure = check_tokens_is_closure(&tokens);
let function_name =
quote_spanned! { span => dioxus_elements::events::#name };
let function = if event_tokens_is_closure {
// If we see an explicit closure, we can call the `call_with_explicit_closure` version of the event for better type inference
quote_spanned! { span => #function_name::call_with_explicit_closure }
} else {
function_name
};
quote_spanned! { span =>
#function(#tokens)
}
}
AttributeName::Custom(_) => unreachable!("Handled elsewhere in the macro"),
AttributeName::Spread(_) => unreachable!("Handled elsewhere in the macro"),
}
}
_ => {
quote_spanned! { value.span() => dioxus_elements::events::#name(#value) }
}
}
};
let attr_span = attribute.span();
let completion_hints = self.completion_hints();
quote_spanned! { attr_span =>
Box::new([
{
#completion_hints
#attribute
}
])
}
.to_token_stream()
}
pub fn can_be_shorthand(&self) -> bool {
// If it's a shorthand...
if matches!(self.value, AttributeValue::Shorthand(_)) {
return true;
}
// Or if it is a builtin attribute with a single ident value
if let (AttributeName::BuiltIn(name), AttributeValue::AttrExpr(expr)) =
(&self.name, &self.value)
{
if let Ok(Expr::Path(path)) = expr.as_expr() {
if path.path.get_ident() == Some(name) {
return true;
}
}
}
false
}
/// If this is the last attribute of an element and it doesn't have a tailing comma,
/// we add hints so that rust analyzer completes it either as an attribute or element
fn completion_hints(&self) -> TokenStream2 {
let Attribute {
name,
value,
comma,
el_name,
..
} = self;
// If there is a trailing comma, rust analyzer does a good job of completing the attribute by itself
if comma.is_some() {
return quote! {};
}
// Only add hints if the attribute is:
// - a built in attribute (not a literal)
// - an build in element (not a custom element)
// - a shorthand attribute
let (
Some(ElementName::Ident(el)),
AttributeName::BuiltIn(name),
AttributeValue::Shorthand(_),
) = (&el_name, &name, &value)
else {
return quote! {};
};
// If the attribute is a shorthand attribute, but it is an event handler, rust analyzer already does a good job of completing the attribute by itself
if name.to_string().starts_with("on") {
return quote! {};
}
quote! {
{
#[allow(dead_code)]
#[doc(hidden)]
mod __completions {
// Autocomplete as an attribute
pub use super::dioxus_elements::#el::*;
// Autocomplete as an element
pub use super::dioxus_elements::elements::completions::CompleteWithBraces::*;
fn ignore() {
#name;
}
}
}
}
}
}
#[derive(PartialEq, Eq, Clone, Debug, Hash)]
pub enum AttributeName {
Spread(Token![..]),
/// an attribute in the form of `name: value`
BuiltIn(Ident),
/// an attribute in the form of `"name": value` - notice that the name is a string literal
/// this is to allow custom attributes in the case of missing built-in attributes
///
/// we might want to change this one day to be ticked or something and simply a boolean
Custom(LitStr),
}
impl AttributeName {
pub fn is_likely_event(&self) -> bool {
matches!(self, Self::BuiltIn(ident) if ident.to_string().starts_with("on"))
}
pub fn is_likely_key(&self) -> bool {
matches!(self, Self::BuiltIn(ident) if ident == "key")
}
pub fn span(&self) -> proc_macro2::Span {
match self {
Self::Custom(lit) => lit.span(),
Self::BuiltIn(ident) => ident.span(),
Self::Spread(dots) => dots.span(),
}
}
}
impl Display for AttributeName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Custom(lit) => write!(f, "{}", lit.value()),
Self::BuiltIn(ident) => write!(f, "{}", ident),
Self::Spread(_) => write!(f, ".."),
}
}
}
impl ToTokens for AttributeName {
fn to_tokens(&self, tokens: &mut TokenStream2) {
match self {
Self::Custom(lit) => lit.to_tokens(tokens),
Self::BuiltIn(ident) => ident.to_tokens(tokens),
Self::Spread(dots) => dots.to_tokens(tokens),
}
}
}
// ..spread attribute
#[derive(PartialEq, Eq, Clone, Debug, Hash)]
pub struct Spread {
pub dots: Token![..],
pub expr: Expr,
pub dyn_idx: DynIdx,
pub comma: Option<Token![,]>,
}
impl Spread {
pub fn span(&self) -> proc_macro2::Span {
self.dots.span()
}
}
#[derive(PartialEq, Eq, Clone, Debug, Hash)]
pub enum AttributeValue {
/// Just a regular shorthand attribute - an ident. Makes our parsing a bit more opaque.
/// attribute,
Shorthand(Ident),
/// Any attribute that's a literal. These get hotreloading super powers
///
/// attribute: "value"
/// attribute: bool,
/// attribute: 1,
AttrLiteral(HotLiteral),
/// A series of tokens that represent an event handler
///
/// We use a special type here so we can get autocomplete in the closure using partial expansion.
/// We also do some extra wrapping for improved type hinting since rust sometimes has trouble with
/// generics and closures.
EventTokens(PartialClosure),
/// Conditional expression
///
/// attribute: if bool { "value" } else if bool { "other value" } else { "default value" }
///
/// Currently these don't get hotreloading super powers, but they could, depending on how far
/// we want to go with it
IfExpr(IfAttributeValue),
/// attribute: some_expr
/// attribute: {some_expr} ?
AttrExpr(PartialExpr),
}
impl Parse for AttributeValue {
fn parse(content: ParseStream) -> syn::Result<Self> {
// Attempt to parse the unterminated if statement
if content.peek(Token![if]) {
return Ok(Self::IfExpr(content.parse::<IfAttributeValue>()?));
}
// Use the move and/or bars as an indicator that we have an event handler
if content.peek(Token![move]) || content.peek(Token![|]) {
let value = content.parse()?;
return Ok(AttributeValue::EventTokens(value));
}
if content.peek(LitStr)
|| content.peek(LitBool)
|| content.peek(LitFloat)
|| content.peek(LitInt)
{
let fork = content.fork();
_ = fork.parse::<Lit>().unwrap();
if content.peek2(Token![,]) || fork.is_empty() {
let value = content.parse()?;
return Ok(AttributeValue::AttrLiteral(value));
}
}
let value = content.parse::<PartialExpr>()?;
Ok(AttributeValue::AttrExpr(value))
}
}
impl ToTokens for AttributeValue {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
match self {
Self::Shorthand(ident) => ident.to_tokens(tokens),
Self::AttrLiteral(ifmt) => ifmt.to_tokens(tokens),
Self::IfExpr(if_expr) => if_expr.to_tokens(tokens),
Self::AttrExpr(expr) => expr.to_tokens(tokens),
Self::EventTokens(closure) => closure.to_tokens(tokens),
}
}
}
impl AttributeValue {
pub fn span(&self) -> proc_macro2::Span {
match self {
Self::Shorthand(ident) => ident.span(),
Self::AttrLiteral(ifmt) => ifmt.span(),
Self::IfExpr(if_expr) => if_expr.span(),
Self::AttrExpr(expr) => expr.span(),
Self::EventTokens(closure) => closure.span(),
}
}
}
/// A if else chain attribute value
#[derive(PartialEq, Eq, Clone, Debug, Hash)]
pub struct IfAttributeValue {
pub if_expr: ExprIf,
pub condition: Expr,
pub then_value: Box<AttributeValue>,
pub else_value: Option<Box<AttributeValue>>,
}
impl IfAttributeValue {
/// Convert the if expression to an expression that returns a string. If the unterminated case is hit, it returns an empty string
pub(crate) fn quote_as_string(&self, diagnostics: &mut Diagnostics) -> Expr {
let mut expression = quote! {};
let mut current_if_value = self;
let mut non_string_diagnostic = |span: proc_macro2::Span| -> Expr {
Element::add_merging_non_string_diagnostic(diagnostics, span);
parse_quote! { ::std::string::String::new() }
};
loop {
let AttributeValue::AttrLiteral(lit) = current_if_value.then_value.as_ref() else {
return non_string_diagnostic(current_if_value.span());
};
let HotLiteral::Fmted(HotReloadFormattedSegment {
formatted_input: new,
..
}) = &lit
else {
return non_string_diagnostic(current_if_value.span());
};
let condition = ¤t_if_value.if_expr.cond;
expression.extend(quote! {
if #condition {
#new.to_string()
} else
});
match current_if_value.else_value.as_deref() {
// If the else value is another if expression, then we need to continue the loop
Some(AttributeValue::IfExpr(else_value)) => {
current_if_value = else_value;
}
// If the else value is a literal, then we need to append it to the expression and break
Some(AttributeValue::AttrLiteral(lit)) => {
if let HotLiteral::Fmted(new) = &lit {
let fmted = &new.formatted_input;
expression.extend(quote! { { #fmted.to_string() } });
break;
} else {
return non_string_diagnostic(current_if_value.span());
}
}
// If it is the end of the if expression without an else, then we need to append the default value and break
None => {
expression.extend(quote! { { ::std::string::String::new() } });
break;
}
_ => {
return non_string_diagnostic(current_if_value.else_value.span());
}
}
}
parse_quote! {
{
#expression
}
}
}
fn span(&self) -> Span {
self.if_expr.span()
}
fn is_terminated(&self) -> bool {
match &self.else_value {
Some(attribute) => match attribute.as_ref() {
AttributeValue::IfExpr(if_expr) => if_expr.is_terminated(),
_ => true,
},
None => false,
}
}
fn contains_expression(&self) -> bool {
fn attribute_value_contains_expression(expr: &AttributeValue) -> bool {
match expr {
AttributeValue::IfExpr(if_expr) => if_expr.contains_expression(),
AttributeValue::AttrLiteral(_) => false,
_ => true,
}
}
attribute_value_contains_expression(&self.then_value)
|| self
.else_value
.as_deref()
.is_some_and(attribute_value_contains_expression)
}
fn parse_attribute_value_from_block(block: &Block) -> syn::Result<Box<AttributeValue>> {
let stmts = &block.stmts;
if stmts.len() != 1 {
return Err(syn::Error::new(
block.span(),
"Expected a single statement in the if block",
));
}
// either an ifmt or an expr in the block
let stmt = &stmts[0];
// Either it's a valid ifmt or an expression
match stmt {
syn::Stmt::Expr(exp, None) => {
// Try parsing the statement as an IfmtInput by passing it through tokens
let value: Result<HotLiteral, syn::Error> = syn::parse2(exp.to_token_stream());
Ok(match value {
Ok(res) => Box::new(AttributeValue::AttrLiteral(res)),
Err(_) => Box::new(AttributeValue::AttrExpr(PartialExpr::from_expr(exp))),
})
}
_ => Err(syn::Error::new(stmt.span(), "Expected an expression")),
}
}
fn to_tokens_with_terminated(
&self,
tokens: &mut TokenStream2,
terminated: bool,
contains_expression: bool,
) {
let IfAttributeValue {
if_expr,
then_value,
else_value,
..
} = self;
// Quote an attribute value and convert the value to a string if it is formatted
// We always quote formatted segments as strings inside if statements so they have a consistent type
// This fixes https://github.com/DioxusLabs/dioxus/issues/2997
fn quote_attribute_value_string(
value: &AttributeValue,
contains_expression: bool,
) -> TokenStream2 {
if let AttributeValue::AttrLiteral(HotLiteral::Fmted(fmted)) = value {
if let Some(str) = fmted.to_static().filter(|_| contains_expression) {
// If this is actually a static string, the user may be using a static string expression in another branch
// use into to convert the string to whatever the other branch is using
quote! {
{
#[allow(clippy::useless_conversion)]
#str.into()
}
}
} else {
quote! { #value.to_string() }
}
} else {
value.to_token_stream()
}
}
let then_value = quote_attribute_value_string(then_value, contains_expression);
let then_value = if terminated {
quote! { #then_value }
}
// Otherwise we need to return an Option and a None if the else value is None
else {
quote! { Some(#then_value) }
};
let else_value = match else_value.as_deref() {
Some(AttributeValue::IfExpr(else_value)) => {
let mut tokens = TokenStream2::new();
else_value.to_tokens_with_terminated(&mut tokens, terminated, contains_expression);
tokens
}
Some(other) => {
let other = quote_attribute_value_string(other, contains_expression);
if terminated {
other
} else {
quote_spanned! { other.span() => Some(#other) }
}
}
None => quote! { None },
};
let condition = &if_expr.cond;
tokens.append_all(quote_spanned! { if_expr.span()=>
if #condition {
#then_value
} else {
#else_value
}
});
}
}
impl Parse for IfAttributeValue {
fn parse(input: ParseStream) -> syn::Result<Self> {
let if_expr = input.parse::<ExprIf>()?;
let stmts = &if_expr.then_branch.stmts;
if stmts.len() != 1 {
return Err(syn::Error::new(
if_expr.then_branch.span(),
"Expected a single statement in the if block",
));
}
// Parse the then branch into a single attribute value
let then_value = Self::parse_attribute_value_from_block(&if_expr.then_branch)?;
// If there's an else branch, parse it as a single attribute value or an if expression
let else_value = match if_expr.else_branch.as_ref() {
Some((_, else_branch)) => {
// The else branch if either a block or another if expression
let attribute_value = match else_branch.as_ref() {
// If it is a block, then the else is terminated
Expr::Block(block) => Self::parse_attribute_value_from_block(&block.block)?,
// Otherwise try to parse it as an if expression
_ => Box::new(syn::parse2(else_branch.to_token_stream())?),
};
Some(attribute_value)
}
None => None,
};
Ok(Self {
condition: *if_expr.cond.clone(),
if_expr,
then_value,
else_value,
})
}
}
impl ToTokens for IfAttributeValue {
fn to_tokens(&self, tokens: &mut TokenStream2) {
// If the if expression is terminated, we can just return the then value
let terminated = self.is_terminated();
let contains_expression = self.contains_expression();
self.to_tokens_with_terminated(tokens, terminated, contains_expression)
}
}
#[cfg(test)]
mod tests {
use super::*;
use quote::quote;
use syn::parse2;
#[test]
fn parse_attrs() {
let _parsed: Attribute = parse2(quote! { name: "value" }).unwrap();
let _parsed: Attribute = parse2(quote! { name: value }).unwrap();
let _parsed: Attribute = parse2(quote! { name: "value {fmt}" }).unwrap();
let _parsed: Attribute = parse2(quote! { name: 123 }).unwrap();
let _parsed: Attribute = parse2(quote! { name: false }).unwrap();
let _parsed: Attribute = parse2(quote! { "custom": false }).unwrap();
let _parsed: Attribute = parse2(quote! { prop: "blah".to_string() }).unwrap();
// with commas
let _parsed: Attribute = parse2(quote! { "custom": false, }).unwrap();
let _parsed: Attribute = parse2(quote! { name: false, }).unwrap();
// with if chains
let parsed: Attribute = parse2(quote! { name: if true { "value" } }).unwrap();
assert!(matches!(parsed.value, AttributeValue::IfExpr(_)));
let parsed: Attribute =
parse2(quote! { name: if true { "value" } else { "other" } }).unwrap();
assert!(matches!(parsed.value, AttributeValue::IfExpr(_)));
let parsed: Attribute =
parse2(quote! { name: if true { "value" } else if false { "other" } }).unwrap();
assert!(matches!(parsed.value, AttributeValue::IfExpr(_)));
// with shorthand
let _parsed: Attribute = parse2(quote! { name }).unwrap();
let _parsed: Attribute = parse2(quote! { name, }).unwrap();
// Events - make sure they get partial expansion
let parsed: Attribute = parse2(quote! { onclick: |e| {} }).unwrap();
assert!(matches!(parsed.value, AttributeValue::EventTokens(_)));
let parsed: Attribute = parse2(quote! { onclick: |e| { "value" } }).unwrap();
assert!(matches!(parsed.value, AttributeValue::EventTokens(_)));
let parsed: Attribute = parse2(quote! { onclick: |e| { value. } }).unwrap();
assert!(matches!(parsed.value, AttributeValue::EventTokens(_)));
let parsed: Attribute = parse2(quote! { onclick: move |e| { value. } }).unwrap();
assert!(matches!(parsed.value, AttributeValue::EventTokens(_)));
let parsed: Attribute = parse2(quote! { onclick: move |e| value }).unwrap();
assert!(matches!(parsed.value, AttributeValue::EventTokens(_)));
let parsed: Attribute = parse2(quote! { onclick: |e| value, }).unwrap();
assert!(matches!(parsed.value, AttributeValue::EventTokens(_)));
}
#[test]
fn merge_attrs() {
let _a: Attribute = parse2(quote! { class: "value1" }).unwrap();
let _b: Attribute = parse2(quote! { class: "value2" }).unwrap();
let _b: Attribute = parse2(quote! { class: "value2 {something}" }).unwrap();
let _b: Attribute = parse2(quote! { class: if value { "other thing" } }).unwrap();
let _b: Attribute = parse2(quote! { class: if value { some_expr } }).unwrap();
let _b: Attribute = parse2(quote! { class: if value { "some_expr" } }).unwrap();
dbg!(_b);
}
#[test]
fn static_literals() {
let a: Attribute = parse2(quote! { class: "value1" }).unwrap();
let b: Attribute = parse2(quote! { class: "value {some}" }).unwrap();
assert!(a.is_static_str_literal());
assert!(!b.is_static_str_literal());
}
#[test]
fn partial_eqs() {
// Basics
let a: Attribute = parse2(quote! { class: "value1" }).unwrap();
let b: Attribute = parse2(quote! { class: "value1" }).unwrap();
assert_eq!(a, b);
// Exprs
let a: Attribute = parse2(quote! { class: var }).unwrap();
let b: Attribute = parse2(quote! { class: var }).unwrap();
assert_eq!(a, b);
// Events
let a: Attribute = parse2(quote! { onclick: |e| {} }).unwrap();
let b: Attribute = parse2(quote! { onclick: |e| {} }).unwrap();
let c: Attribute = parse2(quote! { onclick: move |e| {} }).unwrap();
let d: Attribute = parse2(quote! { onclick: { |e| {} } }).unwrap();
assert_eq!(a, b);
assert_ne!(a, c);
assert_ne!(a, d);
}
#[test]
fn call_with_explicit_closure() {
let mut a: Attribute = parse2(quote! { onclick: |e| {} }).unwrap();
a.el_name = Some(parse_quote!(button));
assert!(a
.rendered_as_dynamic_attr()
.to_string()
.contains("call_with_explicit_closure"));
let mut a: Attribute = parse2(quote! { onclick: { let a = 1; |e| {} } }).unwrap();
a.el_name = Some(parse_quote!(button));
assert!(a
.rendered_as_dynamic_attr()
.to_string()
.contains("call_with_explicit_closure"));
let mut a: Attribute = parse2(quote! { onclick: { let b = 2; { |e| { b } } } }).unwrap();
a.el_name = Some(parse_quote!(button));
assert!(a
.rendered_as_dynamic_attr()
.to_string()
.contains("call_with_explicit_closure"));
let mut a: Attribute = parse2(quote! { onclick: { let r = |e| { b }; r } }).unwrap();
a.el_name = Some(parse_quote!(button));
assert!(!a
.rendered_as_dynamic_attr()
.to_string()
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | true |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx/src/node.rs | packages/rsx/src/node.rs | use crate::innerlude::*;
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::ToTokens;
use syn::{
ext::IdentExt,
parse::{Parse, ParseStream},
spanned::Spanned,
token::{self},
Ident, LitStr, Result, Token,
};
#[derive(PartialEq, Eq, Clone, Debug)]
pub enum BodyNode {
/// div {}
Element(Element),
/// Component {}
Component(Component),
/// "text {formatted}"
Text(TextNode),
/// {expr}
RawExpr(ExprNode),
/// for item in items {}
ForLoop(ForLoop),
/// if cond {} else if cond {} (else {}?)
IfChain(IfChain),
}
impl Parse for BodyNode {
fn parse(stream: ParseStream) -> Result<Self> {
if stream.peek(LitStr) {
return Ok(BodyNode::Text(stream.parse()?));
}
// Transform for loops into into_iter calls
if stream.peek(Token![for]) {
return Ok(BodyNode::ForLoop(stream.parse()?));
}
// Transform unterminated if statements into terminated optional if statements
if stream.peek(Token![if]) {
return Ok(BodyNode::IfChain(stream.parse()?));
}
// Match statements are special but have no special arm syntax
// we could allow arm syntax if we wanted.
//
// And it might even backwards compatible? - I think it is with the right fallback
// -> parse as bodynode (BracedRawExpr will kick in on multiline arms)
// -> if that fails parse as an expr, since that arm might be a one-liner
//
// ```
// match expr {
// val => rsx! { div {} },
// other_val => rsx! { div {} }
// }
// ```
if stream.peek(Token![match]) {
return Ok(BodyNode::RawExpr(stream.parse()?));
}
// Raw expressions need to be wrapped in braces - let RawBracedExpr handle partial expansion
if stream.peek(token::Brace) {
return Ok(BodyNode::RawExpr(stream.parse()?));
}
// If there's an ident immediately followed by a dash, it's a web component
// Web components support no namespacing, so just parse it as an element directly
if stream.peek(Ident::peek_any) && stream.peek2(Token![-]) {
return Ok(BodyNode::Element(stream.parse::<Element>()?));
}
// this is an Element if the path is:
//
// - one ident
// - 1st char is lowercase
// - no underscores (reserved for components)
// And it is not:
// - the start of a path with components
//
// example:
// div {}
if stream.peek(Ident::peek_any) && !stream.peek2(Token![::]) {
let ident = parse_raw_ident(&stream.fork()).unwrap();
let el_name = ident.to_string();
let first_char = el_name.chars().next().unwrap();
if first_char.is_ascii_lowercase() && !el_name.contains('_') {
return Ok(BodyNode::Element(stream.parse::<Element>()?));
}
}
// Otherwise this should be Component, allowed syntax:
// - syn::Path
// - PathArguments can only apper in last segment
// - followed by `{` or `(`, note `(` cannot be used with one ident
//
// example
// Div {}
// ::Div {}
// crate::Div {}
// component {} <-- already handled by elements
// ::component {}
// crate::component{}
// Input::<InputProps<'_, i32> {}
// crate::Input::<InputProps<'_, i32> {}
Ok(BodyNode::Component(stream.parse()?))
}
}
impl ToTokens for BodyNode {
fn to_tokens(&self, tokens: &mut TokenStream2) {
match self {
BodyNode::Element(ela) => ela.to_tokens(tokens),
BodyNode::RawExpr(exp) => exp.to_tokens(tokens),
BodyNode::Text(txt) => txt.to_tokens(tokens),
BodyNode::ForLoop(floop) => floop.to_tokens(tokens),
BodyNode::Component(comp) => comp.to_tokens(tokens),
BodyNode::IfChain(ifchain) => ifchain.to_tokens(tokens),
}
}
}
impl BodyNode {
pub fn get_dyn_idx(&self) -> usize {
match self {
BodyNode::Text(text) => text.dyn_idx.get(),
BodyNode::RawExpr(exp) => exp.dyn_idx.get(),
BodyNode::Component(comp) => comp.dyn_idx.get(),
BodyNode::ForLoop(floop) => floop.dyn_idx.get(),
BodyNode::IfChain(chain) => chain.dyn_idx.get(),
BodyNode::Element(_) => panic!("Cannot get dyn_idx for this node"),
}
}
pub fn set_dyn_idx(&self, idx: usize) {
match self {
BodyNode::Text(text) => text.dyn_idx.set(idx),
BodyNode::RawExpr(exp) => exp.dyn_idx.set(idx),
BodyNode::Component(comp) => comp.dyn_idx.set(idx),
BodyNode::ForLoop(floop) => floop.dyn_idx.set(idx),
BodyNode::IfChain(chain) => chain.dyn_idx.set(idx),
BodyNode::Element(_) => panic!("Cannot set dyn_idx for this node"),
}
}
pub fn is_litstr(&self) -> bool {
matches!(self, BodyNode::Text { .. })
}
pub fn span(&self) -> Span {
match self {
BodyNode::Element(el) => el.name.span(),
BodyNode::Component(component) => component.name.span(),
BodyNode::Text(text) => text.input.span(),
BodyNode::RawExpr(exp) => exp.span(),
BodyNode::ForLoop(fl) => fl.for_token.span(),
BodyNode::IfChain(f) => f.if_token.span(),
}
}
pub fn element_children(&self) -> &[BodyNode] {
match self {
BodyNode::Element(el) => &el.children,
_ => panic!("Children not available for this node"),
}
}
pub fn el_name(&self) -> &ElementName {
match self {
BodyNode::Element(el) => &el.name,
_ => panic!("Element name not available for this node"),
}
}
pub(crate) fn key(&self) -> Option<&AttributeValue> {
match self {
Self::Element(el) => el.key(),
Self::Component(comp) => comp.get_key(),
_ => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use quote::quote;
#[test]
fn parsing_matches() {
let element = quote! { div { class: "inline-block mr-4", icons::icon_14 {} } };
assert!(matches!(
syn::parse2::<BodyNode>(element).unwrap(),
BodyNode::Element(_)
));
let text = quote! { "Hello, world!" };
assert!(matches!(
syn::parse2::<BodyNode>(text).unwrap(),
BodyNode::Text(_)
));
let component = quote! { Component {} };
assert!(matches!(
syn::parse2::<BodyNode>(component).unwrap(),
BodyNode::Component(_)
));
let raw_expr = quote! { { 1 + 1 } };
assert!(matches!(
syn::parse2::<BodyNode>(raw_expr).unwrap(),
BodyNode::RawExpr(_)
));
let for_loop = quote! { for item in items {} };
assert!(matches!(
syn::parse2::<BodyNode>(for_loop).unwrap(),
BodyNode::ForLoop(_)
));
let if_chain = quote! { if cond {} else if cond {} };
assert!(matches!(
syn::parse2::<BodyNode>(if_chain).unwrap(),
BodyNode::IfChain(_)
));
let match_expr = quote! {
match blah {
val => rsx! { div {} },
other_val => rsx! { div {} }
}
};
assert!(matches!(
syn::parse2::<BodyNode>(match_expr).unwrap(),
BodyNode::RawExpr(_)
),);
let incomplete_component = quote! {
some::cool::Component
};
assert!(matches!(
syn::parse2::<BodyNode>(incomplete_component).unwrap(),
BodyNode::Component(_)
),);
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx/src/element.rs | packages/rsx/src/element.rs | use crate::innerlude::*;
use proc_macro2::{Span, TokenStream as TokenStream2};
use proc_macro2_diagnostics::SpanDiagnosticExt;
use quote::{quote, ToTokens, TokenStreamExt};
use std::fmt::{Display, Formatter};
use syn::{
parse::{Parse, ParseStream},
punctuated::Punctuated,
spanned::Spanned,
token::Brace,
Ident, LitStr, Result, Token,
};
/// Parse the VNode::Element type
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Element {
/// div { } -> div
pub name: ElementName,
/// The actual attributes that were parsed
pub raw_attributes: Vec<Attribute>,
/// The attributes after merging - basically the formatted version of the combined attributes
/// where possible.
///
/// These are the actual attributes that get rendered out
pub merged_attributes: Vec<Attribute>,
/// The `...` spread attributes.
pub spreads: Vec<Spread>,
// /// Elements can have multiple, unlike components which can only have one
// pub spreads: Vec<Spread>,
/// The children of the element
pub children: Vec<BodyNode>,
/// the brace of the `div { }`
pub brace: Option<Brace>,
/// A list of diagnostics that were generated during parsing. This element might be a valid rsx_block
/// but not technically a valid element - these diagnostics tell us what's wrong and then are used
/// when rendering
pub diagnostics: Diagnostics,
}
impl Parse for Element {
fn parse(stream: ParseStream) -> Result<Self> {
let name = stream.parse::<ElementName>()?;
// We very liberally parse elements - they might not even have a brace!
// This is designed such that we can throw a compile error but still give autocomplete
// ... partial completions mean we do some weird parsing to get the right completions
let mut brace = None;
let mut block = RsxBlock::default();
match stream.peek(Brace) {
// If the element is followed by a brace, it is complete. Parse the body
true => {
block = stream.parse::<RsxBlock>()?;
brace = Some(block.brace);
}
// Otherwise, it is incomplete. Add a diagnostic
false => block.diagnostics.push(
name.span()
.error("Elements must be followed by braces")
.help("Did you forget a brace?"),
),
}
// Make sure these attributes have an el_name set for completions and Template generation
for attr in block.attributes.iter_mut() {
attr.el_name = Some(name.clone());
}
// Assemble the new element from the contents of the block
let mut element = Element {
brace,
name: name.clone(),
raw_attributes: block.attributes,
children: block.children,
diagnostics: block.diagnostics,
spreads: block.spreads.clone(),
merged_attributes: Vec::new(),
};
// And then merge the various attributes together
// The original raw_attributes are kept for lossless parsing used by hotreload/autofmt
element.merge_attributes();
// And then merge the spreads *after* the attributes are merged. This ensures walking the
// merged attributes in path order stops before we hit the spreads, but spreads are still
// counted as dynamic attributes
for spread in block.spreads.iter() {
element.merged_attributes.push(Attribute {
name: AttributeName::Spread(spread.dots),
colon: None,
value: AttributeValue::AttrExpr(PartialExpr::from_expr(&spread.expr)),
comma: spread.comma,
dyn_idx: spread.dyn_idx.clone(),
el_name: Some(name.clone()),
});
}
Ok(element)
}
}
impl ToTokens for Element {
fn to_tokens(&self, tokens: &mut TokenStream2) {
let el = self;
let el_name = &el.name;
let ns = |name| match el_name {
ElementName::Ident(i) => quote! { dioxus_elements::#i::#name },
ElementName::Custom(_) => quote! { None },
};
let static_attrs = el
.merged_attributes
.iter()
.map(|attr| {
// Rendering static attributes requires a bit more work than just a dynamic attrs
// Early return for dynamic attributes
let Some((name, value)) = attr.as_static_str_literal() else {
let id = attr.dyn_idx.get();
return quote! { dioxus_core::TemplateAttribute::Dynamic { id: #id } };
};
let ns = match name {
AttributeName::BuiltIn(name) => ns(quote!(#name.1)),
AttributeName::Custom(_) => quote!(None),
AttributeName::Spread(_) => {
unreachable!("spread attributes should not be static")
}
};
let name = match (el_name, name) {
(ElementName::Ident(_), AttributeName::BuiltIn(_)) => {
quote! { dioxus_elements::#el_name::#name.0 }
}
//hmmmm I think we could just totokens this, but the to_string might be inserting quotes
_ => {
let as_string = name.to_string();
quote! { #as_string }
}
};
let value = value.to_static().unwrap();
quote! {
dioxus_core::TemplateAttribute::Static {
name: #name,
namespace: #ns,
value: #value,
}
}
})
.collect::<Vec<_>>();
// Render either the child
let children = el.children.iter().map(|c| match c {
BodyNode::Element(el) => quote! { #el },
BodyNode::Text(text) if text.is_static() => {
let text = text.input.to_static().unwrap();
quote! { dioxus_core::TemplateNode::Text { text: #text } }
}
BodyNode::Text(text) => {
let id = text.dyn_idx.get();
quote! { dioxus_core::TemplateNode::Dynamic { id: #id } }
}
BodyNode::ForLoop(floop) => {
let id = floop.dyn_idx.get();
quote! { dioxus_core::TemplateNode::Dynamic { id: #id } }
}
BodyNode::RawExpr(exp) => {
let id = exp.dyn_idx.get();
quote! { dioxus_core::TemplateNode::Dynamic { id: #id } }
}
BodyNode::Component(exp) => {
let id = exp.dyn_idx.get();
quote! { dioxus_core::TemplateNode::Dynamic { id: #id } }
}
BodyNode::IfChain(exp) => {
let id = exp.dyn_idx.get();
quote! { dioxus_core::TemplateNode::Dynamic { id: #id } }
}
});
let ns = ns(quote!(NAME_SPACE));
let el_name = el_name.tag_name();
let diagnostics = &el.diagnostics;
let completion_hints = &el.completion_hints();
// todo: generate less code if there's no diagnostics by not including the curlies
tokens.append_all(quote! {
{
#completion_hints
#diagnostics
dioxus_core::TemplateNode::Element {
tag: #el_name,
namespace: #ns,
attrs: &[ #(#static_attrs),* ],
children: &[ #(#children),* ],
}
}
})
}
}
impl Element {
pub(crate) fn add_merging_non_string_diagnostic(diagnostics: &mut Diagnostics, span: Span) {
diagnostics.push(span.error("Cannot merge non-fmt literals").help(
"Only formatted strings can be merged together. If you want to merge literals, you can use a format string.",
));
}
/// Collapses ifmt attributes into a single dynamic attribute using a space or `;` as a delimiter
///
/// ```ignore,
/// div {
/// class: "abc-def",
/// class: if some_expr { "abc" },
/// }
/// ```
fn merge_attributes(&mut self) {
let mut attrs: Vec<&Attribute> = vec![];
for attr in &self.raw_attributes {
if attrs.iter().any(|old_attr| old_attr.name == attr.name) {
continue;
}
attrs.push(attr);
}
for attr in attrs {
if attr.name.is_likely_key() {
continue;
}
// Collect all the attributes with the same name
let matching_attrs = self
.raw_attributes
.iter()
.filter(|a| a.name == attr.name)
.collect::<Vec<_>>();
// if there's only one attribute with this name, then we don't need to merge anything
if matching_attrs.len() == 1 {
self.merged_attributes.push(attr.clone());
continue;
}
// If there are multiple attributes with the same name, then we need to merge them
// This will be done by creating an ifmt attribute that combines all the segments
// We might want to throw a diagnostic of trying to merge things together that might not
// make a whole lot of sense - like merging two exprs together
let mut out = IfmtInput::new(attr.span());
for (idx, matching_attr) in matching_attrs.iter().enumerate() {
// If this is the first attribute, then we don't need to add a delimiter
if idx != 0 {
// FIXME: I don't want to special case anything - but our delimiter is special cased to a space
// We really don't want to special case anything in the macro, but the hope here is that
// multiline strings can be merged with a space
out.push_raw_str(" ".to_string());
}
// Merge raw literals into the output
if let AttributeValue::AttrLiteral(HotLiteral::Fmted(lit)) = &matching_attr.value {
out.push_ifmt(lit.formatted_input.clone());
continue;
}
// Merge `if cond { "abc" } else if ...` into the output
if let AttributeValue::IfExpr(value) = &matching_attr.value {
out.push_expr(value.quote_as_string(&mut self.diagnostics));
continue;
}
Self::add_merging_non_string_diagnostic(
&mut self.diagnostics,
matching_attr.span(),
);
}
let out_lit = HotLiteral::Fmted(out.into());
self.merged_attributes.push(Attribute {
name: attr.name.clone(),
value: AttributeValue::AttrLiteral(out_lit),
colon: attr.colon,
dyn_idx: attr.dyn_idx.clone(),
comma: matching_attrs.last().unwrap().comma,
el_name: attr.el_name.clone(),
});
}
}
pub(crate) fn key(&self) -> Option<&AttributeValue> {
self.raw_attributes
.iter()
.find(|attr| attr.name.is_likely_key())
.map(|attr| &attr.value)
}
fn completion_hints(&self) -> TokenStream2 {
// If there is already a brace, we don't need any completion hints
if self.brace.is_some() {
return quote! {};
}
let ElementName::Ident(name) = &self.name else {
return quote! {};
};
quote! {
{
#[allow(dead_code)]
#[doc(hidden)]
mod __completions {
fn ignore() {
super::dioxus_elements::elements::completions::CompleteWithBraces::#name
}
}
}
}
}
}
#[derive(PartialEq, Eq, Clone, Debug, Hash)]
pub enum ElementName {
Ident(Ident),
Custom(LitStr),
}
impl ToTokens for ElementName {
fn to_tokens(&self, tokens: &mut TokenStream2) {
match self {
ElementName::Ident(i) => tokens.append_all(quote! { #i }),
ElementName::Custom(s) => s.to_tokens(tokens),
}
}
}
impl Parse for ElementName {
fn parse(stream: ParseStream) -> Result<Self> {
let raw =
Punctuated::<Ident, Token![-]>::parse_separated_nonempty_with(stream, parse_raw_ident)?;
if raw.len() == 1 {
Ok(ElementName::Ident(raw.into_iter().next().unwrap()))
} else {
let span = raw.span();
let tag = raw
.into_iter()
.map(|ident| ident.to_string())
.collect::<Vec<_>>()
.join("-");
let tag = LitStr::new(&tag, span);
Ok(ElementName::Custom(tag))
}
}
}
impl ElementName {
pub(crate) fn tag_name(&self) -> TokenStream2 {
match self {
ElementName::Ident(i) => quote! { dioxus_elements::elements::#i::TAG_NAME },
ElementName::Custom(s) => quote! { #s },
}
}
pub fn span(&self) -> Span {
match self {
ElementName::Ident(i) => i.span(),
ElementName::Custom(s) => s.span(),
}
}
}
impl PartialEq<&str> for ElementName {
fn eq(&self, other: &&str) -> bool {
match self {
ElementName::Ident(i) => i == *other,
ElementName::Custom(s) => s.value() == *other,
}
}
}
impl Display for ElementName {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
ElementName::Ident(i) => write!(f, "{}", i),
ElementName::Custom(s) => write!(f, "{}", s.value()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use prettier_please::PrettyUnparse;
#[test]
fn parses_name() {
let _parsed: ElementName = syn::parse2(quote::quote! { div }).unwrap();
let _parsed: ElementName = syn::parse2(quote::quote! { some-cool-element }).unwrap();
let _parsed: Element = syn::parse2(quote::quote! { div {} }).unwrap();
let _parsed: Element = syn::parse2(quote::quote! { some-cool-element {} }).unwrap();
let parsed: Element = syn::parse2(quote::quote! {
some-cool-div {
id: "hi",
id: "hi {abc}",
id: "hi {def}",
class: 123,
something: bool,
data_attr: "data",
data_attr: "data2",
data_attr: "data3",
exp: { some_expr },
something: {cool},
something: bool,
something: 123,
onclick: move |_| {
println!("hello world");
},
"some-attr": "hello world",
onclick: move |_| {},
class: "hello world",
id: "my-id",
data_attr: "data",
data_attr: "data2",
data_attr: "data3",
"somte_attr3": "hello world",
something: {cool},
something: bool,
something: 123,
onclick: move |_| {
println!("hello world");
},
..attrs1,
..attrs2,
..attrs3
}
})
.unwrap();
dbg!(parsed);
}
#[test]
fn parses_variety() {
let input = quote::quote! {
div {
class: "hello world",
id: "my-id",
data_attr: "data",
data_attr: "data2",
data_attr: "data3",
"somte_attr3": "hello world",
something: {cool},
something: bool,
something: 123,
onclick: move |_| {
println!("hello world");
},
..attrs,
..attrs2,
..attrs3
}
};
let parsed: Element = syn::parse2(input).unwrap();
dbg!(parsed);
}
#[test]
fn to_tokens_properly() {
let input = quote::quote! {
div {
class: "hello world",
class2: "hello {world}",
class3: "goodbye {world}",
class4: "goodbye world",
"something": "cool {blah}",
"something2": "cooler",
div {
div {
h1 { class: "h1 col" }
h2 { class: "h2 col" }
h3 { class: "h3 col" }
div {}
}
}
}
};
let parsed: Element = syn::parse2(input).unwrap();
println!("{}", parsed.to_token_stream().pretty_unparse());
}
#[test]
fn to_tokens_with_diagnostic() {
let input = quote::quote! {
div {
class: "hello world",
id: "my-id",
..attrs,
div {
..attrs,
class: "hello world",
id: "my-id",
}
}
};
let parsed: Element = syn::parse2(input).unwrap();
println!("{}", parsed.to_token_stream().pretty_unparse());
}
#[test]
fn merge_trivial_attributes() {
let input = quote::quote! {
div {
class: "foo",
class: "bar",
}
};
let parsed: Element = syn::parse2(input).unwrap();
assert_eq!(parsed.diagnostics.len(), 0);
assert_eq!(parsed.merged_attributes.len(), 1);
assert_eq!(
parsed.merged_attributes[0].name.to_string(),
"class".to_string()
);
let attr = &parsed.merged_attributes[0].value;
assert_eq!(
attr.to_token_stream().pretty_unparse().as_str(),
"\"foo bar\""
);
if let AttributeValue::AttrLiteral(_) = attr {
} else {
panic!("expected literal")
}
}
#[test]
fn merge_formatted_attributes() {
let input = quote::quote! {
div {
class: "foo",
class: "{bar}",
}
};
let parsed: Element = syn::parse2(input).unwrap();
assert_eq!(parsed.diagnostics.len(), 0);
assert_eq!(parsed.merged_attributes.len(), 1);
assert_eq!(
parsed.merged_attributes[0].name.to_string(),
"class".to_string()
);
let attr = &parsed.merged_attributes[0].value;
assert_eq!(
attr.to_token_stream().pretty_unparse().as_str(),
"::std::format!(\"foo {0:}\", bar)"
);
if let AttributeValue::AttrLiteral(_) = attr {
} else {
panic!("expected literal")
}
}
#[test]
fn merge_conditional_attributes() {
let input = quote::quote! {
div {
class: "foo",
class: if true { "bar" },
class: if false { "baz" } else { "qux" }
}
};
let parsed: Element = syn::parse2(input).unwrap();
assert_eq!(parsed.diagnostics.len(), 0);
assert_eq!(parsed.merged_attributes.len(), 1);
assert_eq!(
parsed.merged_attributes[0].name.to_string(),
"class".to_string()
);
let attr = &parsed.merged_attributes[0].value;
assert_eq!(
attr.to_token_stream().pretty_unparse().as_str(),
"::std::format!(\n \
\"foo {0:} {1:}\",\n \
{ if true { \"bar\".to_string() } else { ::std::string::String::new() } },\n \
{ if false { \"baz\".to_string() } else { \"qux\".to_string() } },\n\
)"
);
if let AttributeValue::AttrLiteral(_) = attr {
} else {
panic!("expected literal")
}
}
#[test]
fn merge_all_attributes() {
let input = quote::quote! {
div {
class: "foo",
class: "{bar}",
class: if true { "baz" },
class: if false { "{qux}" } else { "quux" }
}
};
let parsed: Element = syn::parse2(input).unwrap();
assert_eq!(parsed.diagnostics.len(), 0);
assert_eq!(parsed.merged_attributes.len(), 1);
assert_eq!(
parsed.merged_attributes[0].name.to_string(),
"class".to_string()
);
let attr = &parsed.merged_attributes[0].value;
if cfg!(debug_assertions) {
assert_eq!(
attr.to_token_stream().pretty_unparse().as_str(),
"::std::format!(\n \
\"foo {0:} {1:} {2:}\",\n \
bar,\n \
{ if true { \"baz\".to_string() } else { ::std::string::String::new() } },\n \
{ if false { ::std::format!(\"{qux}\").to_string() } else { \"quux\".to_string() } },\n\
)"
);
} else {
assert_eq!(
attr.to_token_stream().pretty_unparse().as_str(),
"::std::format!(\n \
\"foo {0:} {1:} {2:}\",\n \
bar,\n \
{ if true { \"baz\".to_string() } else { ::std::string::String::new() } },\n \
{ if false { (qux).to_string().to_string() } else { \"quux\".to_string() } },\n\
)"
);
}
if let AttributeValue::AttrLiteral(_) = attr {
} else {
panic!("expected literal")
}
}
/// There are a number of cases where merging attributes doesn't make sense
/// - merging two expressions together
/// - merging two literals together
/// - merging a literal and an expression together
///
/// etc
///
/// We really only want to merge formatted things together
///
/// IE
/// class: "hello world ",
/// class: if some_expr { "abc" }
///
/// Some open questions - should the delimiter be explicit?
#[test]
fn merging_weird_fails() {
let input = quote::quote! {
div {
class: "hello world",
class: if some_expr { 123 },
style: "color: red;",
style: "color: blue;",
width: "1px",
width: 1,
width: false,
contenteditable: true,
}
};
let parsed: Element = syn::parse2(input).unwrap();
assert_eq!(parsed.merged_attributes.len(), 4);
assert_eq!(parsed.diagnostics.len(), 3);
// style should not generate a diagnostic
assert!(!parsed
.diagnostics
.diagnostics
.into_iter()
.any(|f| f.emit_as_item_tokens().to_string().contains("style")));
}
#[test]
fn diagnostics() {
let input = quote::quote! {
p {
class: "foo bar"
"Hello world"
}
};
let _parsed: Element = syn::parse2(input).unwrap();
}
#[test]
fn parses_raw_elements() {
let input = quote::quote! {
use {
"hello"
}
};
let _parsed: Element = syn::parse2(input).unwrap();
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx/src/diagnostics.rs | packages/rsx/src/diagnostics.rs | use proc_macro2_diagnostics::Diagnostic;
use quote::ToTokens;
/// A collection of diagnostics
///
/// This is a wrapper type since we want it to be transparent in terms of PartialEq and Eq.
/// This also lets us choose the expansion strategy for the diagnostics.
#[derive(Debug, Clone, Default)]
pub struct Diagnostics {
pub diagnostics: Vec<Diagnostic>,
}
impl Diagnostics {
pub fn new() -> Self {
Self {
diagnostics: vec![],
}
}
pub fn push(&mut self, diagnostic: Diagnostic) {
self.diagnostics.push(diagnostic);
}
pub fn extend(&mut self, diagnostics: Vec<Diagnostic>) {
self.diagnostics.extend(diagnostics);
}
pub fn is_empty(&self) -> bool {
self.diagnostics.is_empty()
}
pub fn into_diagnostics(self) -> Vec<Diagnostic> {
self.diagnostics
}
pub fn len(&self) -> usize {
self.diagnostics.len()
}
}
impl PartialEq for Diagnostics {
fn eq(&self, _other: &Self) -> bool {
true
}
}
impl Eq for Diagnostics {}
impl ToTokens for Diagnostics {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
for diagnostic in &self.diagnostics {
tokens.extend(diagnostic.clone().emit_as_expr_tokens());
}
}
}
// TODO: Ideally this would be integrated into the existing diagnostics struct, but currently all fields are public so adding
// new fields would be a breaking change. Diagnostics also doesn't expose the message directly so we can't just modify
// the expansion
pub(crate) mod new_diagnostics {
use proc_macro2_diagnostics::SpanDiagnosticExt;
use std::fmt::Display;
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::quote_spanned;
pub(crate) fn warning_diagnostic(span: Span, message: impl Display) -> TokenStream2 {
let note = message.to_string();
// If we are compiling on nightly, use diagnostics directly which supports proper warnings through new span apis
if rustversion::cfg!(nightly) {
return span.warning(note).emit_as_item_tokens();
}
quote_spanned! { span =>
const _: () = {
#[deprecated(note = #note)]
struct Warning;
_ = Warning;
};
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx/src/text_node.rs | packages/rsx/src/text_node.rs | use crate::{literal::HotLiteral, location::DynIdx, HotReloadFormattedSegment, IfmtInput};
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::ToTokens;
use quote::{quote, TokenStreamExt};
use syn::Result;
use syn::{
parse::{Parse, ParseStream},
LitStr,
};
#[derive(PartialEq, Eq, Clone, Debug, Hash)]
pub struct TextNode {
pub input: HotReloadFormattedSegment,
pub dyn_idx: DynIdx,
}
impl Parse for TextNode {
fn parse(input: ParseStream) -> Result<Self> {
Ok(Self {
input: input.parse()?,
dyn_idx: DynIdx::default(),
})
}
}
impl ToTokens for TextNode {
fn to_tokens(&self, tokens: &mut TokenStream2) {
let txt = &self.input;
if txt.is_static() {
tokens.append_all(quote! {
dioxus_core::DynamicNode::Text(dioxus_core::VText::new(#txt.to_string()))
})
} else {
// todo:
// Use the RsxLiteral implementation to spit out a hotreloadable variant of this string
// This is not super efficient since we're doing a bit of cloning
let as_lit = HotLiteral::Fmted(txt.clone());
tokens.append_all(quote! {
dioxus_core::DynamicNode::Text(dioxus_core::VText::new( #as_lit ))
})
}
}
}
impl TextNode {
pub fn from_text(text: &str) -> Self {
let ifmt = IfmtInput {
source: LitStr::new(text, Span::call_site()),
segments: vec![],
};
Self {
input: ifmt.into(),
dyn_idx: Default::default(),
}
}
pub fn is_static(&self) -> bool {
self.input.is_static()
}
}
#[cfg(test)]
mod tests {
use super::*;
use prettier_please::PrettyUnparse;
#[test]
fn parses() {
let input = syn::parse2::<TextNode>(quote! { "hello world" }).unwrap();
assert_eq!(input.input.source.value(), "hello world");
}
#[test]
fn to_tokens_with_hr() {
let lit = syn::parse2::<TextNode>(quote! { "hi {world1} {world2} {world3}" }).unwrap();
println!("{}", lit.to_token_stream().pretty_unparse());
}
#[test]
fn raw_str() {
let input = syn::parse2::<TextNode>(quote! { r#"hello world"# }).unwrap();
println!("{}", input.input.source.to_token_stream());
assert_eq!(input.input.source.value(), "hello world");
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx/src/lib.rs | packages/rsx/src/lib.rs | #![doc(html_logo_url = "https://avatars.githubusercontent.com/u/79236386")]
#![doc(html_favicon_url = "https://avatars.githubusercontent.com/u/79236386")]
//! Parse the root tokens in the rsx! { } macro
//! =========================================
//!
//! This parsing path emerges directly from the macro call, with `RsxRender` being the primary entrance into parsing.
//! This feature must support:
//! - [x] Optionally rendering if the `in XYZ` pattern is present
//! - [x] Fragments as top-level element (through ambiguous)
//! - [x] Components as top-level element (through ambiguous)
//! - [x] Tags as top-level elements (through ambiguous)
//! - [x] Good errors if parsing fails
//!
//! Any errors in using rsx! will likely occur when people start using it, so the first errors must be really helpful.
//!
//! # Completions
//! Rust analyzer completes macros by looking at the expansion of the macro and trying to match the start of identifiers in the macro to identifiers in the current scope
//!
//! Eg, if a macro expands to this:
//! ```rust, ignore
//! struct MyStruct;
//!
//! // macro expansion
//! My
//! ```
//! Then the analyzer will try to match the start of the identifier "My" to an identifier in the current scope (MyStruct in this case).
//!
//! In dioxus, our macros expand to the completions module if we know the identifier is incomplete:
//! ```rust, ignore
//! // In the root of the macro, identifiers must be elements
//! // rsx! { di }
//! dioxus_elements::elements::di
//!
//! // Before the first child element, every following identifier is either an attribute or an element
//! // rsx! { div { ta } }
//! // Isolate completions scope
//! mod completions__ {
//! // import both the attributes and elements this could complete to
//! use dioxus_elements::elements::div::*;
//! use dioxus_elements::elements::*;
//! fn complete() {
//! ta;
//! }
//! }
//!
//! // After the first child element, every following identifier is another element
//! // rsx! { div { attribute: value, child {} di } }
//! dioxus_elements::elements::di
//! ```
mod assign_dyn_ids;
mod attribute;
mod component;
mod element;
mod forloop;
mod ifchain;
mod node;
mod raw_expr;
mod rsx_block;
mod rsx_call;
mod template_body;
mod text_node;
mod diagnostics;
mod expr_node;
mod ifmt;
mod literal;
mod location;
mod partial_closure;
mod util;
// Re-export the namespaces into each other
pub use diagnostics::Diagnostics;
pub use ifmt::*;
pub use node::*;
pub use partial_closure::PartialClosure;
pub use rsx_call::*;
pub use template_body::TemplateBody;
use quote::{quote, ToTokens, TokenStreamExt};
use syn::{
parse::{Parse, ParseStream},
Result, Token,
};
pub use innerlude::*;
pub(crate) mod innerlude {
pub use crate::attribute::*;
pub use crate::component::*;
pub use crate::element::*;
pub use crate::expr_node::*;
pub use crate::forloop::*;
pub use crate::ifchain::*;
pub use crate::location::*;
pub use crate::node::*;
pub use crate::raw_expr::*;
pub use crate::rsx_block::*;
pub use crate::template_body::*;
pub use crate::text_node::*;
pub use crate::diagnostics::*;
pub use crate::ifmt::*;
pub use crate::literal::*;
pub use crate::util::*;
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx/src/expr_node.rs | packages/rsx/src/expr_node.rs | use crate::{DynIdx, PartialExpr};
use quote::{quote, ToTokens, TokenStreamExt};
use syn::parse::Parse;
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ExprNode {
pub expr: PartialExpr,
pub dyn_idx: DynIdx,
}
impl ExprNode {
pub fn span(&self) -> proc_macro2::Span {
self.expr.span()
}
}
impl Parse for ExprNode {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
// // If it's a single-line expression, we want to parse it without braces, fixing some issues with rust 2024 lifetimes
// use syn::braced;
// let forked = input.fork();
// if forked.peek(syn::token::Brace) {
// let content;
// let _brace = braced!(content in forked);
// let as_expr: Result<syn::Expr, syn::Error> = content.parse();
// if as_expr.is_ok() && content.is_empty() {
// let content;
// let _brace = braced!(content in input);
// return Ok(Self {
// expr: content.parse()?,
// dyn_idx: DynIdx::default(),
// });
// }
// }
Ok(Self {
expr: input.parse()?,
dyn_idx: DynIdx::default(),
})
}
}
impl ToTokens for ExprNode {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
let expr = &self.expr;
tokens.append_all(quote! {
{
#[allow(unused_braces)]
let ___nodes = dioxus_core::IntoDynNode::into_dyn_node(#expr);
___nodes
}
})
}
}
#[test]
fn no_commas() {
use prettier_please::PrettyUnparse;
let input = quote! {
div {
{label("Hello, world!")},
}
};
let _expr: crate::BodyNode = syn::parse2(input).unwrap();
println!("{}", _expr.to_token_stream().pretty_unparse());
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx/src/raw_expr.rs | packages/rsx/src/raw_expr.rs | use proc_macro2::{Delimiter, TokenStream as TokenStream2, TokenTree};
use quote::ToTokens;
use std::hash;
use syn::{parse::Parse, spanned::Spanned, token::Brace, Expr};
/// A raw expression potentially wrapped in curly braces that is parsed from the input stream.
///
/// If there are no braces, it tries to parse as an expression without partial expansion. If there
/// are braces, it parses the contents as a `TokenStream2` and stores it as such.
#[derive(Clone, Debug)]
pub struct PartialExpr {
pub brace: Option<Brace>,
pub expr: TokenStream2,
}
impl Parse for PartialExpr {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
// Input is a braced expression if it's a braced group
// followed by either of the following:
// - the end of the stream
// - a comma
// - another braced group
// - an identifier
// - a string literal
let mut is_braced = false;
if let Some((TokenTree::Group(group), next)) = input.fork().cursor().token_tree() {
let next_char_is_a_comma = next.punct().is_some_and(|(tt, _)| tt.as_char() == ',');
let next_is_a_braced_exp = next.group(Delimiter::Brace).is_some();
let next_is_an_ident = next.ident().is_some();
let next_is_a_string_literal = next.literal().is_some();
if group.delimiter() == Delimiter::Brace
&& (next.eof()
|| next_char_is_a_comma
|| next_is_a_braced_exp
|| next_is_an_ident
|| next_is_a_string_literal)
{
is_braced = true
}
};
// Parse as an expression if it's not braced
if !is_braced {
let expr = input.parse::<syn::Expr>()?;
return Ok(Self {
brace: None,
expr: expr.to_token_stream(),
});
}
let content;
let brace = Some(syn::braced!(content in input));
let expr: TokenStream2 = content.parse()?;
Ok(Self { brace, expr })
}
}
impl ToTokens for PartialExpr {
fn to_tokens(&self, tokens: &mut TokenStream2) {
match &self.brace {
Some(brace) => brace.surround(tokens, |tokens| self.expr.to_tokens(tokens)),
_ => self.expr.to_tokens(tokens),
}
}
}
impl PartialExpr {
pub fn as_expr(&self) -> syn::Result<syn::Expr> {
// very important: make sure to include the brace in the span of the expr
// otherwise autofmt will freak out since it will use the inner span
if let Some(brace) = &self.brace {
let mut tokens = TokenStream2::new();
let f = |tokens: &mut TokenStream2| self.expr.to_tokens(tokens);
brace.surround(&mut tokens, f);
return syn::parse2(tokens);
}
let expr = self.expr.clone();
syn::parse2(expr.to_token_stream())
}
pub fn from_expr(expr: &Expr) -> Self {
Self {
brace: None,
expr: expr.to_token_stream(),
}
}
pub fn span(&self) -> proc_macro2::Span {
if let Some(brace) = &self.brace {
brace.span.span()
} else {
self.expr.span()
}
}
}
impl PartialEq for PartialExpr {
fn eq(&self, other: &Self) -> bool {
self.expr.to_string() == other.expr.to_string()
}
}
impl Eq for PartialExpr {}
impl hash::Hash for PartialExpr {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.expr.to_string().hash(state);
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx/src/rsx_block.rs | packages/rsx/src/rsx_block.rs | //! An arbitrary block parser.
//!
//! Is meant to parse the contents of a block that is either a component or an element.
//! We put these together to cut down on code duplication and make the parsers a bit more resilient.
//!
//! This involves custom structs for name, attributes, and children, as well as a custom parser for the block itself.
//! It also bubbles out diagnostics if it can to give better errors.
use crate::innerlude::*;
use proc_macro2::Span;
use proc_macro2_diagnostics::SpanDiagnosticExt;
use syn::{
ext::IdentExt,
parse::{Parse, ParseBuffer, ParseStream},
spanned::Spanned,
token::{self, Brace},
Expr, Ident, LitStr, Token,
};
/// An item in the form of
///
/// {
/// attributes,
/// ..spreads,
/// children
/// }
///
/// Does not make any guarantees about the contents of the block - this is meant to be verified by the
/// element/component impls themselves.
///
/// The name of the block is expected to be parsed by the parent parser. It will accept items out of
/// order if possible and then bubble up diagnostics to the parent. This lets us give better errors
/// and autocomplete
#[derive(PartialEq, Eq, Clone, Debug, Default)]
pub struct RsxBlock {
pub brace: token::Brace,
pub attributes: Vec<Attribute>,
pub spreads: Vec<Spread>,
pub children: Vec<BodyNode>,
pub diagnostics: Diagnostics,
}
impl Parse for RsxBlock {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let content: ParseBuffer;
let brace = syn::braced!(content in input);
RsxBlock::parse_inner(&content, brace)
}
}
impl RsxBlock {
/// Only parse the children of the block - all others will be rejected
pub fn parse_children(content: &ParseBuffer) -> syn::Result<Self> {
let mut nodes = vec![];
let mut diagnostics = Diagnostics::new();
while !content.is_empty() {
nodes.push(Self::parse_body_node_with_comma_diagnostics(
content,
&mut diagnostics,
)?);
}
Ok(Self {
children: nodes,
diagnostics,
..Default::default()
})
}
pub fn parse_inner(content: &ParseBuffer, brace: token::Brace) -> syn::Result<Self> {
let mut items = vec![];
let mut diagnostics = Diagnostics::new();
// If we are after attributes, we can try to provide better completions and diagnostics
// by parsing the following nodes as body nodes if they are ambiguous, we can parse them as body nodes
let mut after_attributes = false;
// Lots of manual parsing but it's important to do it all here to give the best diagnostics possible
// We can do things like lookaheads, peeking, etc. to give better errors and autocomplete
// We allow parsing in any order but complain if its done out of order.
// Autofmt will fortunately fix this for us in most cases
//
// We do this by parsing the unambiguous cases first and then do some clever lookahead to parse the rest
while !content.is_empty() {
// Parse spread attributes
if content.peek(Token![..]) {
let dots = content.parse::<Token![..]>()?;
// in case someone tries to do ...spread which is not valid
if let Ok(extra) = content.parse::<Token![.]>() {
diagnostics.push(
extra
.span()
.error("Spread expressions only take two dots - not 3! (..spread)"),
);
}
let expr = content.parse::<Expr>()?;
let attr = Spread {
expr,
dots,
dyn_idx: DynIdx::default(),
comma: content.parse().ok(),
};
if !content.is_empty() && attr.comma.is_none() {
diagnostics.push(
attr.span()
.error("Attributes must be separated by commas")
.help("Did you forget a comma?"),
);
}
items.push(RsxItem::Spread(attr));
after_attributes = true;
continue;
}
// Parse unambiguous attributes - these can't be confused with anything
if (content.peek(LitStr) || content.peek(Ident::peek_any))
&& content.peek2(Token![:])
&& !content.peek3(Token![:])
{
let attr = content.parse::<Attribute>()?;
if !content.is_empty() && attr.comma.is_none() {
diagnostics.push(
attr.span()
.error("Attributes must be separated by commas")
.help("Did you forget a comma?"),
);
}
items.push(RsxItem::Attribute(attr));
continue;
}
// Eagerly match on completed children, generally
if content.peek(LitStr)
| content.peek(Token![for])
| content.peek(Token![if])
| content.peek(Token![match])
| content.peek(token::Brace)
// web components
| (content.peek(Ident::peek_any) && content.peek2(Token![-]))
// elements
| (content.peek(Ident::peek_any) && (after_attributes || content.peek2(token::Brace)))
// components
| (content.peek(Ident::peek_any) && (after_attributes || content.peek2(token::Brace) || content.peek2(Token![::])))
{
items.push(RsxItem::Child(
Self::parse_body_node_with_comma_diagnostics(content, &mut diagnostics)?,
));
if !content.is_empty() && content.peek(Token![,]) {
let comma = content.parse::<Token![,]>()?;
diagnostics.push(
comma.span().warning(
"Elements and text nodes do not need to be separated by commas.",
),
);
}
after_attributes = true;
continue;
}
// Parse shorthand attributes
// todo: this might cause complications with partial expansion... think more about the cases
// where we can imagine expansion and what better diagnostics we can provide
if Self::peek_lowercase_ident(&content)
&& !content.peek2(Brace)
&& !content.peek2(Token![:]) // regular attributes / components with generics
&& !content.peek2(Token![-]) // web components
&& !content.peek2(Token![<]) // generics on components
// generics on components
&& !content.peek2(Token![::])
{
let attribute = content.parse::<Attribute>()?;
if !content.is_empty() && attribute.comma.is_none() {
diagnostics.push(
attribute
.span()
.error("Attributes must be separated by commas")
.help("Did you forget a comma?"),
);
}
items.push(RsxItem::Attribute(attribute));
continue;
}
// Finally just attempt a bodynode parse
items.push(RsxItem::Child(
Self::parse_body_node_with_comma_diagnostics(content, &mut diagnostics)?,
))
}
// Validate the order of the items
RsxBlock::validate(&items, &mut diagnostics);
// todo: maybe make this a method such that the rsxblock is lossless
// Decompose into attributes, spreads, and children
let mut attributes = vec![];
let mut spreads = vec![];
let mut children = vec![];
for item in items {
match item {
RsxItem::Attribute(attr) => attributes.push(attr),
RsxItem::Spread(spread) => spreads.push(spread),
RsxItem::Child(child) => children.push(child),
}
}
Ok(Self {
attributes,
children,
spreads,
brace,
diagnostics,
})
}
// Parse a body node with diagnostics for unnecessary trailing commas
fn parse_body_node_with_comma_diagnostics(
content: &ParseBuffer,
_diagnostics: &mut Diagnostics,
) -> syn::Result<BodyNode> {
let body_node = content.parse::<BodyNode>()?;
if !content.is_empty() && content.peek(Token![,]) {
let _comma = content.parse::<Token![,]>()?;
// todo: we would've pushed a warning here but proc-macro-2 emits them as errors, which we
// dont' want. There's no built-in cfg way for checking if we're on nightly, and adding
// that would require a build script, so for the interest of compile times, we won't throw
// any warning at all.
//
// Whenever the user formats their code with `dx fmt`, the comma will be removed, so active
// projects will implicitly be fixed.
//
// Whenever the issue is resolved or diagnostics are added, we can re-add this warning.
//
// - https://github.com/SergioBenitez/proc-macro2-diagnostics/issues/9
// - https://github.com/DioxusLabs/dioxus/issues/2807
//
// diagnostics.push(
// comma
// .span()
// .warning("Elements and text nodes do not need to be separated by commas."),
// );
}
Ok(body_node)
}
fn peek_lowercase_ident(stream: &ParseStream) -> bool {
let Ok(ident) = stream.fork().call(Ident::parse_any) else {
return false;
};
ident
.to_string()
.chars()
.next()
.unwrap()
.is_ascii_lowercase()
}
/// Ensure the ordering of the items is correct
/// - Attributes must come before children
/// - Spreads must come before children
/// - Spreads must come after attributes
///
/// div {
/// key: "value",
/// ..props,
/// "Hello, world!"
/// }
fn validate(items: &[RsxItem], diagnostics: &mut Diagnostics) {
#[derive(Debug, PartialEq, Eq)]
enum ValidationState {
Attributes,
Spreads,
Children,
}
use ValidationState::*;
let mut state = ValidationState::Attributes;
for item in items.iter() {
match item {
RsxItem::Attribute(_) => {
if state == Children || state == Spreads {
diagnostics.push(
item.span()
.error("Attributes must come before children in an element"),
);
}
state = Attributes;
}
RsxItem::Spread(_) => {
if state == Children {
diagnostics.push(
item.span()
.error("Spreads must come before children in an element"),
);
}
state = Spreads;
}
RsxItem::Child(_) => {
state = Children;
}
}
}
}
}
pub enum RsxItem {
Attribute(Attribute),
Spread(Spread),
Child(BodyNode),
}
impl RsxItem {
pub fn span(&self) -> Span {
match self {
RsxItem::Attribute(attr) => attr.span(),
RsxItem::Spread(spread) => spread.dots.span(),
RsxItem::Child(child) => child.span(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use quote::quote;
#[test]
fn basic_cases() {
let input = quote! {
{ "Hello, world!" }
};
let block: RsxBlock = syn::parse2(input).unwrap();
assert_eq!(block.attributes.len(), 0);
assert_eq!(block.children.len(), 1);
let input = quote! {
{
key: "value",
onclick: move |_| {
"Hello, world!"
},
..spread,
"Hello, world!"
}
};
let block: RsxBlock = syn::parse2(input).unwrap();
dbg!(block);
let complex_element = quote! {
{
key: "value",
onclick2: move |_| {
"Hello, world!"
},
thing: if true { "value" },
otherthing: if true { "value" } else { "value" },
onclick: move |_| {
"Hello, world!"
},
..spread,
..spread1
..spread2,
"Hello, world!"
}
};
let _block: RsxBlock = syn::parse2(complex_element).unwrap();
let complex_component = quote! {
{
key: "value",
onclick2: move |_| {
"Hello, world!"
},
..spread,
"Hello, world!"
}
};
let _block: RsxBlock = syn::parse2(complex_component).unwrap();
}
/// Some tests of partial expansion to give better autocomplete
#[test]
fn partial_cases() {
let with_handler = quote! {
{
onclick: move |_| {
some.
}
}
};
let _block: RsxBlock = syn::parse2(with_handler).unwrap();
}
/// Ensure the hotreload scoring algorithm works as expected
#[test]
fn hr_score() {
let _block = quote! {
{
a: "value {cool}",
b: "{cool} value",
b: "{cool} {thing} value",
b: "{thing} value",
}
};
// loop { accumulate perfect matches }
// stop when all matches are equally valid
//
// Remove new attr one by one as we find its perfect match. If it doesn't have a perfect match, we
// score it instead.
quote! {
// start with
div {
div { class: "other {abc} {def} {hij}" } // 1, 1, 1
div { class: "thing {abc} {def}" } // 1, 1, 1
// div { class: "thing {abc}" } // 1, 0, 1
}
// end with
div {
h1 {
class: "thing {abc}" // 1, 1, MAX
}
h1 {
class: "thing {hij}" // 1, 1, MAX
}
// h2 {
// class: "thing {def}" // 1, 1, 0
// }
// h3 {
// class: "thing {def}" // 1, 1, 0
// }
}
// how about shuffling components, for, if, etc
Component {
class: "thing {abc}",
other: "other {abc} {def}",
}
Component {
class: "thing",
other: "other",
}
Component {
class: "thing {abc}",
other: "other",
}
Component {
class: "thing {abc}",
other: "other {abc} {def}",
}
};
}
#[test]
fn kitchen_sink_parse() {
let input = quote! {
// Elements
{
class: "hello",
id: "node-{node_id}",
..props,
// Text Nodes
"Hello, world!"
// Exprs
{rsx! { "hi again!" }}
for item in 0..10 {
// "Second"
div { "cool-{item}" }
}
Link {
to: "/home",
class: "link {is_ready}",
"Home"
}
if false {
div { "hi again!?" }
} else if true {
div { "its cool?" }
} else {
div { "not nice !" }
}
}
};
let _parsed: RsxBlock = syn::parse2(input).unwrap();
}
#[test]
fn simple_comp_syntax() {
let input = quote! {
{ class: "inline-block mr-4", icons::icon_14 {} }
};
let _parsed: RsxBlock = syn::parse2(input).unwrap();
}
#[test]
fn with_sutter() {
let input = quote! {
{
div {}
d
div {}
}
};
let _parsed: RsxBlock = syn::parse2(input).unwrap();
}
#[test]
fn looks_like_prop_but_is_expr() {
let input = quote! {
{
a: "asd".to_string(),
// b can be omitted, and it will be filled with its default value
c: "asd".to_string(),
d: Some("asd".to_string()),
e: Some("asd".to_string()),
}
};
let _parsed: RsxBlock = syn::parse2(input).unwrap();
}
#[test]
fn no_comma_diagnostics() {
let input = quote! {
{ a, ..ComponentProps { a: 1, b: 2, c: 3, children: VNode::empty(), onclick: Default::default() } }
};
let parsed: RsxBlock = syn::parse2(input).unwrap();
assert!(parsed.diagnostics.is_empty());
}
#[test]
fn proper_attributes() {
let input = quote! {
{
onclick: action,
href,
onmounted: onmounted,
prevent_default,
class,
rel,
target: tag_target,
aria_current,
..attributes,
{children}
}
};
let parsed: RsxBlock = syn::parse2(input).unwrap();
dbg!(parsed.attributes);
}
#[test]
fn reserved_attributes() {
let input = quote! {
{
label {
for: "blah",
}
}
};
let parsed: RsxBlock = syn::parse2(input).unwrap();
dbg!(parsed.attributes);
}
#[test]
fn diagnostics_check() {
let input = quote::quote! {
{
class: "foo bar"
"Hello world"
}
};
let _parsed: RsxBlock = syn::parse2(input).unwrap();
}
#[test]
fn incomplete_components() {
let input = quote::quote! {
{
some::cool::Component
}
};
let _parsed: RsxBlock = syn::parse2(input).unwrap();
}
#[test]
fn incomplete_root_elements() {
use syn::parse::Parser;
let input = quote::quote! {
di
};
let parsed = RsxBlock::parse_children.parse2(input).unwrap();
let children = parsed.children;
assert_eq!(children.len(), 1);
if let BodyNode::Element(parsed) = &children[0] {
assert_eq!(
parsed.name,
ElementName::Ident(Ident::new("di", Span::call_site()))
);
} else {
panic!("expected element, got {:?}", children);
}
assert!(parsed.diagnostics.is_empty());
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx/src/ifchain.rs | packages/rsx/src/ifchain.rs | use crate::location::DynIdx;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use quote::{ToTokens, TokenStreamExt};
use syn::{
parse::{Parse, ParseStream},
token::Brace,
Expr, Result, Token,
};
use crate::TemplateBody;
#[non_exhaustive]
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct IfChain {
pub if_token: Token![if],
pub cond: Box<Expr>,
pub then_brace: Brace,
pub then_branch: TemplateBody,
pub else_if_branch: Option<Box<IfChain>>,
pub else_brace: Option<Brace>,
pub else_branch: Option<TemplateBody>,
pub dyn_idx: DynIdx,
}
impl IfChain {
pub fn for_each_branch(&self, f: &mut impl FnMut(&TemplateBody)) {
f(&self.then_branch);
if let Some(else_if) = &self.else_if_branch {
else_if.for_each_branch(f);
}
if let Some(else_branch) = &self.else_branch {
f(else_branch);
}
}
}
impl Parse for IfChain {
fn parse(input: ParseStream) -> Result<Self> {
let if_token: Token![if] = input.parse()?;
// stolen from ExprIf
let cond = Box::new(input.call(Expr::parse_without_eager_brace)?);
let content;
let then_brace = syn::braced!(content in input);
let then_branch = content.parse()?;
let mut else_brace = None;
let mut else_branch = None;
let mut else_if_branch = None;
// if the next token is `else`, set the else branch as the next if chain
if input.peek(Token![else]) {
input.parse::<Token![else]>()?;
if input.peek(Token![if]) {
else_if_branch = Some(Box::new(input.parse::<IfChain>()?));
} else {
let content;
else_brace = Some(syn::braced!(content in input));
else_branch = Some(content.parse()?);
}
}
Ok(Self {
cond,
if_token,
then_branch,
else_if_branch,
else_branch,
then_brace,
else_brace,
dyn_idx: DynIdx::default(),
})
}
}
impl ToTokens for IfChain {
fn to_tokens(&self, tokens: &mut TokenStream2) {
let mut body = TokenStream2::new();
let mut terminated = false;
let mut elif = Some(self);
while let Some(chain) = elif {
let IfChain {
if_token,
cond,
then_branch,
else_if_branch,
else_branch,
..
} = chain;
body.append_all(quote! {
#if_token #cond {
{ #then_branch }
}
});
if let Some(next) = else_if_branch {
body.append_all(quote! {
else
});
elif = Some(next);
} else if let Some(else_branch) = else_branch {
body.append_all(quote! {
else {
{#else_branch}
}
});
terminated = true;
break;
} else {
elif = None;
}
}
if !terminated {
body.append_all(quote! {
else { dioxus_core::VNode::empty() }
});
}
tokens.append_all(quote! {
{
let ___nodes = dioxus_core::IntoDynNode::into_dyn_node(#body);
___nodes
}
})
}
}
#[test]
fn parses_if_chain() {
let input = quote! {
if true {
"one"
} else if false {
"two"
} else {
"three"
}
};
let _chain: IfChain = syn::parse2(input).unwrap();
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx/src/literal.rs | packages/rsx/src/literal.rs | use proc_macro2::Span;
use quote::quote;
use quote::ToTokens;
use std::fmt::Display;
use std::ops::Deref;
use syn::{
parse::{Parse, ParseStream},
Lit, LitBool, LitFloat, LitInt, LitStr,
};
use crate::{location::DynIdx, IfmtInput, Segment};
use proc_macro2::TokenStream as TokenStream2;
/// A literal value in the rsx! macro
///
/// These get hotreloading super powers, making them a bit more complex than a normal literal.
/// In debug mode we need to generate a bunch of extra code to support hotreloading.
///
/// Eventually we want to remove this notion of hot literals since we're generating different code
/// in debug than in release, which is harder to maintain and can lead to bugs.
#[derive(PartialEq, Eq, Clone, Debug, Hash)]
pub enum HotLiteral {
/// A *formatted* string literal
/// We know this will generate a String, not an &'static str
///
/// The raw str type will generate a &'static str, but we need to distinguish the two for component props
///
/// "hello {world}"
Fmted(HotReloadFormattedSegment),
/// A float literal
///
/// 1.0
Float(LitFloat),
/// An int literal
///
/// 1
Int(LitInt),
/// A bool literal
///
/// true
Bool(LitBool),
}
impl HotLiteral {
pub fn quote_as_hot_reload_literal(&self) -> TokenStream2 {
match &self {
HotLiteral::Fmted(f) => quote! { dioxus_core::internal::HotReloadLiteral::Fmted(#f) },
HotLiteral::Float(f) => {
quote! { dioxus_core::internal::HotReloadLiteral::Float(#f as _) }
}
HotLiteral::Int(f) => quote! { dioxus_core::internal::HotReloadLiteral::Int(#f as _) },
HotLiteral::Bool(f) => quote! { dioxus_core::internal::HotReloadLiteral::Bool(#f) },
}
}
}
impl Parse for HotLiteral {
fn parse(input: ParseStream) -> syn::Result<Self> {
let raw = input.parse::<Lit>()?;
let value = match raw.clone() {
Lit::Int(a) => HotLiteral::Int(a),
Lit::Bool(a) => HotLiteral::Bool(a),
Lit::Float(a) => HotLiteral::Float(a),
Lit::Str(a) => HotLiteral::Fmted(IfmtInput::new_litstr(a)?.into()),
_ => {
return Err(syn::Error::new(
raw.span(),
"Only string, int, float, and bool literals are supported",
))
}
};
Ok(value)
}
}
impl ToTokens for HotLiteral {
fn to_tokens(&self, out: &mut proc_macro2::TokenStream) {
match &self {
HotLiteral::Fmted(f) => {
f.formatted_input.to_tokens(out);
}
HotLiteral::Float(f) => f.to_tokens(out),
HotLiteral::Int(f) => f.to_tokens(out),
HotLiteral::Bool(f) => f.to_tokens(out),
}
}
}
impl HotLiteral {
pub fn span(&self) -> Span {
match self {
HotLiteral::Fmted(f) => f.span(),
HotLiteral::Float(f) => f.span(),
HotLiteral::Int(f) => f.span(),
HotLiteral::Bool(f) => f.span(),
}
}
}
impl HotLiteral {
// We can only handle a few types of literals - the rest need to be expressions
// todo on adding more of course - they're not hard to support, just work
pub fn peek(input: ParseStream) -> bool {
if input.peek(Lit) {
let lit = input.fork().parse::<Lit>().unwrap();
matches!(
lit,
Lit::Str(_) | Lit::Int(_) | Lit::Float(_) | Lit::Bool(_)
)
} else {
false
}
}
pub fn is_static(&self) -> bool {
match &self {
HotLiteral::Fmted(fmt) => fmt.is_static(),
_ => false,
}
}
pub fn from_raw_text(text: &str) -> Self {
HotLiteral::Fmted(HotReloadFormattedSegment::from(IfmtInput {
source: LitStr::new(text, Span::call_site()),
segments: vec![],
}))
}
}
impl Display for HotLiteral {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self {
HotLiteral::Fmted(l) => l.to_string_with_quotes().fmt(f),
HotLiteral::Float(l) => l.fmt(f),
HotLiteral::Int(l) => l.fmt(f),
HotLiteral::Bool(l) => l.value().fmt(f),
}
}
}
/// A formatted segment that can be hot reloaded
#[derive(PartialEq, Eq, Clone, Debug, Hash)]
pub struct HotReloadFormattedSegment {
pub formatted_input: IfmtInput,
pub dynamic_node_indexes: Vec<DynIdx>,
}
impl HotReloadFormattedSegment {
/// This method is very important!
/// Deref + Spanned + .span() methods leads to name collisions
pub fn span(&self) -> Span {
self.formatted_input.span()
}
}
impl Deref for HotReloadFormattedSegment {
type Target = IfmtInput;
fn deref(&self) -> &Self::Target {
&self.formatted_input
}
}
impl From<IfmtInput> for HotReloadFormattedSegment {
fn from(input: IfmtInput) -> Self {
let mut dynamic_node_indexes = Vec::new();
for segment in &input.segments {
if let Segment::Formatted { .. } = segment {
dynamic_node_indexes.push(DynIdx::default());
}
}
Self {
formatted_input: input,
dynamic_node_indexes,
}
}
}
impl Parse for HotReloadFormattedSegment {
fn parse(input: ParseStream) -> syn::Result<Self> {
let ifmt: IfmtInput = input.parse()?;
Ok(Self::from(ifmt))
}
}
impl ToTokens for HotReloadFormattedSegment {
fn to_tokens(&self, tokens: &mut TokenStream2) {
let mut idx = 0_usize;
let segments = self.segments.iter().map(|s| match s {
Segment::Literal(lit) => quote! {
dioxus_core::internal::FmtSegment::Literal { value: #lit }
},
Segment::Formatted(_fmt) => {
// increment idx for the dynamic segment so we maintain the mapping
let _idx = self.dynamic_node_indexes[idx].get();
idx += 1;
quote! {
dioxus_core::internal::FmtSegment::Dynamic { id: #_idx }
}
}
});
// The static segments with idxs for locations
tokens.extend(quote! {
dioxus_core::internal::FmtedSegments::new( vec![ #(#segments),* ], )
});
}
}
#[cfg(test)]
mod tests {
use super::*;
use prettier_please::PrettyUnparse;
#[test]
fn parses_lits() {
let _ = syn::parse2::<HotLiteral>(quote! { "hello" }).unwrap();
let _ = syn::parse2::<HotLiteral>(quote! { "hello {world}" }).unwrap();
let _ = syn::parse2::<HotLiteral>(quote! { 1 }).unwrap();
let _ = syn::parse2::<HotLiteral>(quote! { 1.0 }).unwrap();
let _ = syn::parse2::<HotLiteral>(quote! { false }).unwrap();
let _ = syn::parse2::<HotLiteral>(quote! { true }).unwrap();
// Refuses the other unsupported types - we could add them if we wanted to
assert!(syn::parse2::<HotLiteral>(quote! { b"123" }).is_err());
assert!(syn::parse2::<HotLiteral>(quote! { 'a' }).is_err());
let lit = syn::parse2::<HotLiteral>(quote! { "hello" }).unwrap();
assert!(matches!(lit, HotLiteral::Fmted(_)));
let lit = syn::parse2::<HotLiteral>(quote! { "hello {world}" }).unwrap();
assert!(matches!(lit, HotLiteral::Fmted(_)));
}
#[test]
fn outputs_a_signal() {
// Should output a type of f64 which we convert into whatever the expected type is via "into"
// todo: hmmmmmmmmmmmm might not always work
let lit = syn::parse2::<HotLiteral>(quote! { 1.0 }).unwrap();
println!("{}", lit.to_token_stream().pretty_unparse());
let lit = syn::parse2::<HotLiteral>(quote! { "hi" }).unwrap();
println!("{}", lit.to_token_stream().pretty_unparse());
let lit = syn::parse2::<HotLiteral>(quote! { "hi {world}" }).unwrap();
println!("{}", lit.to_token_stream().pretty_unparse());
}
#[test]
fn static_str_becomes_str() {
let lit = syn::parse2::<HotLiteral>(quote! { "hello" }).unwrap();
let HotLiteral::Fmted(segments) = &lit else {
panic!("expected a formatted string");
};
assert!(segments.is_static());
assert_eq!(r##""hello""##, segments.to_string_with_quotes());
println!("{}", lit.to_token_stream().pretty_unparse());
}
#[test]
fn formatted_prints_as_formatted() {
let lit = syn::parse2::<HotLiteral>(quote! { "hello {world}" }).unwrap();
let HotLiteral::Fmted(segments) = &lit else {
panic!("expected a formatted string");
};
assert!(!segments.is_static());
assert_eq!(r##""hello {world}""##, segments.to_string_with_quotes());
println!("{}", lit.to_token_stream().pretty_unparse());
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx/src/util.rs | packages/rsx/src/util.rs | #![allow(unused)]
use proc_macro2::TokenStream as TokenStream2;
use std::{fmt::Debug, hash::Hash};
use syn::{
ext::IdentExt,
parse::{Parse, ParseBuffer},
Ident,
};
/// Parse a raw ident and return a new ident with the r# prefix added
pub fn parse_raw_ident(parse_buffer: &ParseBuffer) -> syn::Result<Ident> {
// First try to parse as a normal ident
if let Ok(ident) = Ident::parse(parse_buffer) {
return Ok(ident);
}
// If that fails, try to parse as a raw ident
let ident = Ident::parse_any(parse_buffer)?;
Ok(Ident::new_raw(&ident.to_string(), ident.span()))
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx/src/template_body.rs | packages/rsx/src/template_body.rs | //! I'm so sorry this is so complicated. Here's my best to simplify and explain it:
//!
//! The `Callbody` is the contents of the rsx! macro - this contains all the information about every
//! node that rsx! directly knows about. For loops, if statements, etc.
//!
//! However, there are multiple *templates* inside a callbody - due to how core clones templates and
//! just generally rationalize the concept of a template, nested bodies like for loops and if statements
//! and component children are all templates, contained within the same Callbody.
//!
//! This gets confusing fast since there's lots of IDs bouncing around.
//!
//! The IDs at play:
//! - The id of the template itself so we can find it and apply it to the dom.
//! This is challenging since all calls to file/line/col/id are relative to the macro invocation,
//! so they will have to share the same base ID and we need to give each template a new ID.
//! The id of the template will be something like file!():line!():col!():ID where ID increases for
//! each nested template.
//!
//! - The IDs of dynamic nodes relative to the template they live in. This is somewhat easy to track
//! but needs to happen on a per-template basis.
//!
//! - The IDs of formatted strings in debug mode only. Any formatted segments like "{x:?}" get pulled out
//! into a pool so we can move them around during hot reloading on a per-template basis.
//!
//! - The IDs of component property literals in debug mode only. Any component property literals like
//! 1234 get pulled into the pool so we can hot reload them with the context of the literal pool.
//!
//! We solve this by parsing the structure completely and then doing a second pass that fills in IDs
//! by walking the structure.
//!
//! This means you can't query the ID of any node "in a vacuum" - these are assigned once - but at
//! least they're stable enough for the purposes of hotreloading
//!
//! ```text
//! rsx! {
//! div {
//! class: "hello",
//! id: "node-{node_id}", <--- {node_id} has the formatted segment id 0 in the literal pool
//! ..props, <--- spreads are not reloadable
//!
//! "Hello, world!" <--- not tracked but reloadable in the template since it's just a string
//!
//! for item in 0..10 { <--- both 0 and 10 are technically reloadable, but we don't hot reload them today...
//! div { "cool-{item}" } <--- {item} has the formatted segment id 1 in the literal pool
//! }
//!
//! Link {
//! to: "/home", <--- hotreloadable since its a component prop literal (with component literal id 0)
//! class: "link {is_ready}", <--- {is_ready} has the formatted segment id 2 in the literal pool and the property has the component literal id 1
//! "Home" <--- hotreloadable since its a component child (via template)
//! }
//! }
//! }
//! ```
use self::location::DynIdx;
use crate::innerlude::Attribute;
use crate::*;
use proc_macro2::{Span, TokenStream as TokenStream2};
use proc_macro2_diagnostics::SpanDiagnosticExt;
use syn::parse_quote;
type NodePath = Vec<u8>;
type AttributePath = Vec<u8>;
/// A set of nodes in a template position
///
/// this could be:
/// - The root of a callbody
/// - The children of a component
/// - The children of a for loop
/// - The children of an if chain
///
/// The TemplateBody when needs to be parsed into a surrounding `Body` to be correctly re-indexed
/// By default every body has a `0` default index
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct TemplateBody {
pub roots: Vec<BodyNode>,
pub template_idx: DynIdx,
pub node_paths: Vec<NodePath>,
pub attr_paths: Vec<(AttributePath, usize)>,
pub dynamic_text_segments: Vec<FormattedSegment>,
pub diagnostics: Diagnostics,
}
impl Parse for TemplateBody {
/// Parse the nodes of the callbody as `Body`.
fn parse(input: ParseStream) -> Result<Self> {
let children = RsxBlock::parse_children(input)?;
let mut myself = Self::new(children.children);
myself
.diagnostics
.extend(children.diagnostics.into_diagnostics());
Ok(myself)
}
}
/// Our ToTokens impl here just defers to rendering a template out like any other `Body`.
/// This is because the parsing phase filled in all the additional metadata we need
impl ToTokens for TemplateBody {
fn to_tokens(&self, tokens: &mut TokenStream2) {
// First normalize the template body for rendering
let node = self.normalized();
// If we have an implicit key, then we need to write its tokens
let key_tokens = match node.implicit_key() {
Some(tok) => quote! { Some( #tok.to_string() ) },
None => quote! { None },
};
let key_warnings = self.check_for_duplicate_keys();
let roots = node.quote_roots();
// Print paths is easy - just print the paths
let node_paths = node.node_paths.iter().map(|it| quote!(&[#(#it),*]));
let attr_paths = node.attr_paths.iter().map(|(it, _)| quote!(&[#(#it),*]));
// For printing dynamic nodes, we rely on the ToTokens impl
// Elements have a weird ToTokens - they actually are the entrypoint for Template creation
let dynamic_nodes: Vec<_> = node.dynamic_nodes().collect();
let dynamic_nodes_len = dynamic_nodes.len();
// We could add a ToTokens for Attribute but since we use that for both components and elements
// They actually need to be different, so we just localize that here
let dyn_attr_printer: Vec<_> = node
.dynamic_attributes()
.map(|attr| attr.rendered_as_dynamic_attr())
.collect();
let dynamic_attr_len = dyn_attr_printer.len();
let dynamic_text = node.dynamic_text_segments.iter();
let diagnostics = &node.diagnostics;
let index = node.template_idx.get();
let hot_reload_mapping = node.hot_reload_mapping();
tokens.append_all(quote! {
dioxus_core::Element::Ok({
#diagnostics
#key_warnings
// Components pull in the dynamic literal pool and template in debug mode, so they need to be defined before dynamic nodes
#[cfg(debug_assertions)]
fn __original_template() -> &'static dioxus_core::internal::HotReloadedTemplate {
static __ORIGINAL_TEMPLATE: ::std::sync::OnceLock<dioxus_core::internal::HotReloadedTemplate> = ::std::sync::OnceLock::new();
if __ORIGINAL_TEMPLATE.get().is_none() {
_ = __ORIGINAL_TEMPLATE.set(#hot_reload_mapping);
}
__ORIGINAL_TEMPLATE.get().unwrap()
}
#[cfg(debug_assertions)]
let __template_read = {
use dioxus_signals::ReadableExt;
static __NORMALIZED_FILE: &'static str = {
const PATH: &str = dioxus_core::const_format::str_replace!(file!(), "\\\\", "/");
dioxus_core::const_format::str_replace!(PATH, '\\', "/")
};
// The key is important here - we're creating a new GlobalSignal each call to this
// But the key is what's keeping it stable
static __TEMPLATE: dioxus_signals::GlobalSignal<Option<dioxus_core::internal::HotReloadedTemplate>> = dioxus_signals::GlobalSignal::with_location(
|| None::<dioxus_core::internal::HotReloadedTemplate>,
__NORMALIZED_FILE,
line!(),
column!(),
#index
);
dioxus_core::Runtime::try_current().map(|_| __TEMPLATE.read())
};
// If the template has not been hot reloaded, we always use the original template
// Templates nested within macros may be merged because they have the same file-line-column-index
// They cannot be hot reloaded, so this prevents incorrect rendering
#[cfg(debug_assertions)]
let __template_read = match __template_read.as_ref().map(|__template_read| __template_read.as_ref()) {
Some(Some(__template_read)) => &__template_read,
_ => __original_template(),
};
#[cfg(debug_assertions)]
let mut __dynamic_literal_pool = dioxus_core::internal::DynamicLiteralPool::new(
vec![ #( #dynamic_text.to_string() ),* ],
);
// The key needs to be created before the dynamic nodes as it might depend on a borrowed value which gets moved into the dynamic nodes
#[cfg(not(debug_assertions))]
let __key = #key_tokens;
// These items are used in both the debug and release expansions of rsx. Pulling them out makes the expansion
// slightly smaller and easier to understand. Rust analyzer also doesn't autocomplete well when it sees an ident show up twice in the expansion
let __dynamic_nodes: [dioxus_core::DynamicNode; #dynamic_nodes_len] = [ #( #dynamic_nodes ),* ];
let __dynamic_attributes: [Box<[dioxus_core::Attribute]>; #dynamic_attr_len] = [ #( #dyn_attr_printer ),* ];
#[doc(hidden)]
static __TEMPLATE_ROOTS: &[dioxus_core::TemplateNode] = &[ #( #roots ),* ];
#[cfg(debug_assertions)]
{
let mut __dynamic_value_pool = dioxus_core::internal::DynamicValuePool::new(
Vec::from(__dynamic_nodes),
Vec::from(__dynamic_attributes),
__dynamic_literal_pool
);
__dynamic_value_pool.render_with(__template_read)
}
#[cfg(not(debug_assertions))]
{
#[doc(hidden)] // vscode please stop showing these in symbol search
static ___TEMPLATE: dioxus_core::Template = dioxus_core::Template {
roots: __TEMPLATE_ROOTS,
node_paths: &[ #( #node_paths ),* ],
attr_paths: &[ #( #attr_paths ),* ],
};
// NOTE: Allocating a temporary is important to make reads within rsx drop before the value is returned
#[allow(clippy::let_and_return)]
let __vnodes = dioxus_core::VNode::new(
__key,
___TEMPLATE,
Box::new(__dynamic_nodes),
Box::new(__dynamic_attributes),
);
__vnodes
}
})
});
}
}
impl TemplateBody {
/// Create a new TemplateBody from a set of nodes
///
/// This will fill in all the necessary path information for the nodes in the template and will
/// overwrite data like dynamic indexes.
pub fn new(nodes: Vec<BodyNode>) -> Self {
let mut body = Self {
roots: vec![],
template_idx: DynIdx::default(),
node_paths: Vec::new(),
attr_paths: Vec::new(),
dynamic_text_segments: Vec::new(),
diagnostics: Diagnostics::new(),
};
// Assign paths to all nodes in the template
body.assign_paths_inner(&nodes);
// And then save the roots
body.roots = nodes;
// Finally, validate the key
body.validate_key();
body
}
/// Normalize the Template body for rendering. If the body is completely empty, insert a placeholder node
pub fn normalized(&self) -> Self {
// If the nodes are completely empty, insert a placeholder node
// Core expects at least one node in the template to make it easier to replace
if self.is_empty() {
// Create an empty template body with a placeholder and diagnostics + the template index from the original
let empty = Self::new(vec![BodyNode::RawExpr(parse_quote! {()})]);
let default = Self {
diagnostics: self.diagnostics.clone(),
template_idx: self.template_idx.clone(),
..empty
};
return default;
}
self.clone()
}
pub fn is_empty(&self) -> bool {
self.roots.is_empty()
}
pub fn implicit_key(&self) -> Option<&AttributeValue> {
self.roots.first().and_then(BodyNode::key)
}
/// Ensure only one key and that the key is not a static str
///
/// todo: we want to allow arbitrary exprs for keys provided they impl hash / eq
fn validate_key(&mut self) {
let key = self.implicit_key();
if let Some(attr) = key {
let diagnostic = match &attr {
AttributeValue::AttrLiteral(ifmt) => {
if ifmt.is_static() {
ifmt.span().error("Key must not be a static string. Make sure to use a formatted string like `key: \"{value}\"")
} else {
return;
}
}
_ => attr
.span()
.error("Key must be in the form of a formatted string like `key: \"{value}\""),
};
self.diagnostics.push(diagnostic);
}
}
fn check_for_duplicate_keys(&self) -> TokenStream2 {
let mut warnings = TokenStream2::new();
// Make sure there are not multiple keys or keys on nodes other than the first in the block
for root in self.roots.iter().skip(1) {
if let Some(key) = root.key() {
warnings.extend(new_diagnostics::warning_diagnostic(
key.span(),
"Keys are only allowed on the first node in the block.",
));
}
}
warnings
}
pub fn get_dyn_node(&self, path: &[u8]) -> &BodyNode {
let mut node = self.roots.get(path[0] as usize).unwrap();
for idx in path.iter().skip(1) {
node = node.element_children().get(*idx as usize).unwrap();
}
node
}
pub fn get_dyn_attr(&self, path: &AttributePath, idx: usize) -> &Attribute {
match self.get_dyn_node(path) {
BodyNode::Element(el) => &el.merged_attributes[idx],
_ => unreachable!(),
}
}
pub fn dynamic_attributes(&self) -> impl DoubleEndedIterator<Item = &Attribute> {
self.attr_paths
.iter()
.map(|(path, idx)| self.get_dyn_attr(path, *idx))
}
pub fn dynamic_nodes(&self) -> impl DoubleEndedIterator<Item = &BodyNode> {
self.node_paths.iter().map(|path| self.get_dyn_node(path))
}
fn quote_roots(&self) -> impl Iterator<Item = TokenStream2> + '_ {
self.roots.iter().map(|node| match node {
BodyNode::Element(el) => quote! { #el },
BodyNode::Text(text) if text.is_static() => {
let text = text.input.to_static().unwrap();
quote! { dioxus_core::TemplateNode::Text { text: #text } }
}
_ => {
let id = node.get_dyn_idx();
quote! { dioxus_core::TemplateNode::Dynamic { id: #id } }
}
})
}
/// Iterate through the literal component properties of this rsx call in depth-first order
pub fn literal_component_properties(&self) -> impl Iterator<Item = &HotLiteral> + '_ {
self.dynamic_nodes()
.filter_map(|node| {
if let BodyNode::Component(component) = node {
Some(component)
} else {
None
}
})
.flat_map(|component| {
component.component_props().filter_map(|field| {
if let AttributeValue::AttrLiteral(literal) = &field.value {
Some(literal)
} else {
None
}
})
})
}
fn hot_reload_mapping(&self) -> TokenStream2 {
let key = if let Some(AttributeValue::AttrLiteral(HotLiteral::Fmted(key))) =
self.implicit_key()
{
quote! { Some(#key) }
} else {
quote! { None }
};
let dynamic_nodes = self.dynamic_nodes().map(|node| {
let id = node.get_dyn_idx();
quote! { dioxus_core::internal::HotReloadDynamicNode::Dynamic(#id) }
});
let dyn_attr_printer = self.dynamic_attributes().map(|attr| {
let id = attr.get_dyn_idx();
quote! { dioxus_core::internal::HotReloadDynamicAttribute::Dynamic(#id) }
});
let component_values = self
.literal_component_properties()
.map(|literal| literal.quote_as_hot_reload_literal());
quote! {
dioxus_core::internal::HotReloadedTemplate::new(
#key,
vec![ #( #dynamic_nodes ),* ],
vec![ #( #dyn_attr_printer ),* ],
vec![ #( #component_values ),* ],
__TEMPLATE_ROOTS,
)
}
}
/// Get the span of the first root of this template
pub(crate) fn first_root_span(&self) -> Span {
match self.roots.first() {
Some(root) => root.span(),
_ => Span::call_site(),
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx/src/partial_closure.rs | packages/rsx/src/partial_closure.rs | use crate::PartialExpr;
use proc_macro2::TokenStream;
use quote::ToTokens;
use std::hash::{Hash, Hasher};
use syn::{
parse::{Parse, ParseStream},
punctuated::Punctuated,
Attribute, Expr, Pat, PatType, Result, ReturnType, Token, Type,
};
use syn::{BoundLifetimes, ExprClosure};
/// A closure whose body might not be valid rust code but we want to interpret it regardless.
/// This lets us provide expansions in way more cases than normal closures at the expense of an
/// increased mainteance burden and complexity.
///
/// We do our best to reuse the same logic from partial exprs for the body of the PartialClosure.
/// The code here is simply stolen from `syn::ExprClosure` and lightly modified to work with
/// PartialExprs. We only removed the attrs field and changed the body to be a PartialExpr.
/// Otherwise, it's a direct copy of the original.
#[derive(Debug, Clone)]
pub struct PartialClosure {
pub lifetimes: Option<BoundLifetimes>,
pub constness: Option<Token![const]>,
pub movability: Option<Token![static]>,
pub asyncness: Option<Token![async]>,
pub capture: Option<Token![move]>,
pub or1_token: Token![|],
pub inputs: Punctuated<Pat, Token![,]>,
pub or2_token: Token![|],
pub output: ReturnType,
pub body: PartialExpr,
}
impl Parse for PartialClosure {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let lifetimes: Option<BoundLifetimes> = input.parse()?;
let constness: Option<Token![const]> = input.parse()?;
let movability: Option<Token![static]> = input.parse()?;
let asyncness: Option<Token![async]> = input.parse()?;
let capture: Option<Token![move]> = input.parse()?;
let or1_token: Token![|] = input.parse()?;
let mut inputs = Punctuated::new();
loop {
if input.peek(Token![|]) {
break;
}
let value = closure_arg(input)?;
inputs.push_value(value);
if input.peek(Token![|]) {
break;
}
let punct: Token![,] = input.parse()?;
inputs.push_punct(punct);
}
let or2_token: Token![|] = input.parse()?;
let output = if input.peek(Token![->]) {
let arrow_token: Token![->] = input.parse()?;
let ty: Type = input.parse()?;
ReturnType::Type(arrow_token, Box::new(ty))
} else {
ReturnType::Default
};
let body = PartialExpr::parse(input)?;
Ok(PartialClosure {
lifetimes,
constness,
movability,
asyncness,
capture,
or1_token,
inputs,
or2_token,
output,
body,
})
}
}
impl ToTokens for PartialClosure {
fn to_tokens(&self, tokens: &mut TokenStream) {
self.lifetimes.to_tokens(tokens);
self.constness.to_tokens(tokens);
self.movability.to_tokens(tokens);
self.asyncness.to_tokens(tokens);
self.capture.to_tokens(tokens);
self.or1_token.to_tokens(tokens);
self.inputs.to_tokens(tokens);
self.or2_token.to_tokens(tokens);
self.output.to_tokens(tokens);
self.body.to_tokens(tokens);
}
}
impl PartialEq for PartialClosure {
fn eq(&self, other: &Self) -> bool {
self.lifetimes == other.lifetimes
&& self.constness == other.constness
&& self.movability == other.movability
&& self.asyncness == other.asyncness
&& self.capture == other.capture
&& self.or1_token == other.or1_token
&& self.inputs == other.inputs
&& self.or2_token == other.or2_token
&& self.output == other.output
&& self.body == other.body
}
}
impl Eq for PartialClosure {}
impl Hash for PartialClosure {
fn hash<H: Hasher>(&self, state: &mut H) {
self.lifetimes.hash(state);
self.constness.hash(state);
self.movability.hash(state);
self.asyncness.hash(state);
self.capture.hash(state);
self.or1_token.hash(state);
self.inputs.hash(state);
self.or2_token.hash(state);
self.output.hash(state);
self.body.hash(state);
}
}
impl PartialClosure {
/// Convert this partial closure into a full closure if it is valid
/// Returns err if the internal tokens can't be parsed as a closure
pub fn as_expr(&self) -> Result<Expr> {
let expr_closure = ExprClosure {
attrs: Vec::new(),
asyncness: self.asyncness,
capture: self.capture,
inputs: self.inputs.clone(),
output: self.output.clone(),
lifetimes: self.lifetimes.clone(),
constness: self.constness,
movability: self.movability,
or1_token: self.or1_token,
or2_token: self.or2_token,
// try to lower the body to an expression - if might fail if it can't
body: Box::new(self.body.as_expr()?),
};
Ok(Expr::Closure(expr_closure))
}
}
/// This might look complex but it is just a ripoff of the `syn::ExprClosure` implementation. AFAIK
/// This code is not particularly accessible from outside syn... so it lives here. sorry
fn closure_arg(input: ParseStream) -> Result<Pat> {
let attrs = input.call(Attribute::parse_outer)?;
let mut pat = Pat::parse_single(input)?;
if input.peek(Token![:]) {
Ok(Pat::Type(PatType {
attrs,
pat: Box::new(pat),
colon_token: input.parse()?,
ty: input.parse()?,
}))
} else {
match &mut pat {
Pat::Const(pat) => pat.attrs = attrs,
Pat::Ident(pat) => pat.attrs = attrs,
Pat::Lit(pat) => pat.attrs = attrs,
Pat::Macro(pat) => pat.attrs = attrs,
Pat::Or(pat) => pat.attrs = attrs,
Pat::Paren(pat) => pat.attrs = attrs,
Pat::Path(pat) => pat.attrs = attrs,
Pat::Range(pat) => pat.attrs = attrs,
Pat::Reference(pat) => pat.attrs = attrs,
Pat::Rest(pat) => pat.attrs = attrs,
Pat::Slice(pat) => pat.attrs = attrs,
Pat::Struct(pat) => pat.attrs = attrs,
Pat::Tuple(pat) => pat.attrs = attrs,
Pat::TupleStruct(pat) => pat.attrs = attrs,
Pat::Wild(pat) => pat.attrs = attrs,
Pat::Type(_) => unreachable!(),
Pat::Verbatim(_) => {}
_ => {}
}
Ok(pat)
}
}
#[cfg(test)]
mod tests {
use super::*;
use quote::quote;
#[test]
fn parses() {
let doesnt_parse: Result<ExprClosure> = syn::parse2(quote! {
|a, b| { method. }
});
// regular closures can't parse as partial closures
assert!(doesnt_parse.is_err());
let parses: Result<PartialClosure> = syn::parse2(quote! {
|a, b| { method. }
});
// but ours can - we just can't format it out
let parses = parses.unwrap();
dbg!(parses.to_token_stream().to_string());
}
#[test]
fn parses_real_world() {
let parses: Result<PartialClosure> = syn::parse2(quote! {
move |_| {
let mut sidebar = SHOW_SIDEBAR.write();
*sidebar = !*sidebar;
}
});
// but ours can - we just can't format it out
let parses = parses.unwrap();
dbg!(parses.to_token_stream().to_string());
parses.as_expr().unwrap();
let parses: Result<PartialClosure> = syn::parse2(quote! {
move |_| {
rsx! {
div { class: "max-w-lg lg:max-w-2xl mx-auto mb-16 text-center",
"gomg"
"hi!!"
"womh"
}
};
println!("hi")
}
});
parses.unwrap().as_expr().unwrap();
}
#[test]
fn partial_eqs() {
let a: PartialClosure = syn::parse2(quote! {
move |e| {
println!("clicked!");
}
})
.unwrap();
let b: PartialClosure = syn::parse2(quote! {
move |e| {
println!("clicked!");
}
})
.unwrap();
let c: PartialClosure = syn::parse2(quote! {
move |e| {
println!("unclicked");
}
})
.unwrap();
assert_eq!(a, b);
assert_ne!(a, c);
}
/// Ensure our ToTokens impl is the same as the one in syn
#[test]
fn same_to_tokens() {
let a: PartialClosure = syn::parse2(quote! {
move |e| {
println!("clicked!");
}
})
.unwrap();
let b: PartialClosure = syn::parse2(quote! {
move |e| {
println!("clicked!");
}
})
.unwrap();
let c: ExprClosure = syn::parse2(quote! {
move |e| {
println!("clicked!");
}
})
.unwrap();
assert_eq!(
a.to_token_stream().to_string(),
b.to_token_stream().to_string()
);
assert_eq!(
a.to_token_stream().to_string(),
c.to_token_stream().to_string()
);
let a: PartialClosure = syn::parse2(quote! {
move |e| println!("clicked!")
})
.unwrap();
let b: ExprClosure = syn::parse2(quote! {
move |e| println!("clicked!")
})
.unwrap();
assert_eq!(
a.to_token_stream().to_string(),
b.to_token_stream().to_string()
);
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx/src/location.rs | packages/rsx/src/location.rs | use std::{cell::Cell, hash::Hash};
/// A simple idx in the code that can be used to track back to the original source location
///
/// Used in two places:
/// - In the `CallBody` to track the location of hotreloadable literals
/// - In the `Body` to track the ID of each template
///
/// We need an ID system, unfortunately, to properly disambiguate between different templates since
/// rustc assigns them all the same line!() and column!() information. Before, we hashed spans but
/// that has collision issues and is eventually relied on specifics of proc macros that aren't available
/// in testing (like snapshot testing). So, we just need an ID for each of these items, hence this struct.
///
/// This is "transparent" to partialeq and eq, so it will always return true when compared to another DynIdx.
#[derive(Clone, Debug, Default)]
pub struct DynIdx {
idx: Cell<Option<usize>>,
}
impl PartialEq for DynIdx {
fn eq(&self, _other: &Self) -> bool {
true
}
}
impl Eq for DynIdx {}
impl DynIdx {
pub fn set(&self, idx: usize) {
self.idx.set(Some(idx));
}
pub fn get(&self) -> usize {
self.idx.get().unwrap_or(usize::MAX)
}
}
impl Hash for DynIdx {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.idx.get().hash(state);
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx/src/rsx_call.rs | packages/rsx/src/rsx_call.rs | //! The actual rsx! macro implementation.
//!
//! This mostly just defers to the root TemplateBody with some additional tooling to provide better errors.
//! Currently the additional tooling doesn't do much.
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::ToTokens;
use std::{cell::Cell, fmt::Debug};
use syn::{
parse::{Parse, ParseStream},
Result,
};
use crate::{BodyNode, TemplateBody};
/// The Callbody is the contents of the rsx! macro
///
/// It is a list of BodyNodes, which are the different parts of the template.
/// The Callbody contains no information about how the template will be rendered, only information about the parsed tokens.
///
/// Every callbody should be valid, so you can use it to build a template.
/// To generate the code used to render the template, use the ToTokens impl on the Callbody, or with the `render_with_location` method.
///
/// Ideally we don't need the metadata here and can bake the idx-es into the templates themselves but I haven't figured out how to do that yet.
#[derive(Debug, Clone)]
pub struct CallBody {
pub body: TemplateBody,
pub template_idx: Cell<usize>,
pub span: Option<Span>,
}
impl Parse for CallBody {
fn parse(input: ParseStream) -> Result<Self> {
// Defer to the `new` method such that we can wire up hotreload information
let mut body = CallBody::new(input.parse()?);
body.span = Some(input.span());
Ok(body)
}
}
impl ToTokens for CallBody {
fn to_tokens(&self, out: &mut TokenStream2) {
self.body.to_tokens(out)
}
}
impl CallBody {
/// Create a new CallBody from a TemplateBody
///
/// This will overwrite all internal metadata regarding hotreloading.
pub fn new(body: TemplateBody) -> Self {
let body = CallBody {
body,
template_idx: Cell::new(0),
span: None,
};
body.body.template_idx.set(body.next_template_idx());
body.cascade_hotreload_info(&body.body.roots);
body
}
/// Parse a stream into a CallBody. Return all error immediately instead of trying to partially expand the macro
///
/// This should be preferred over `parse` if you are outside of a macro
pub fn parse_strict(input: ParseStream) -> Result<Self> {
// todo: actually throw warnings if there are any
Self::parse(input)
}
/// With the entire knowledge of the macro call, wire up location information for anything hotreloading
/// specific. It's a little bit simpler just to have a global id per callbody than to try and track it
/// relative to each template, though we could do that if we wanted to.
///
/// For now this is just information for ifmts and templates so that when they generate, they can be
/// tracked back to the original location in the source code, to support formatted string hotreloading.
///
/// Note that there are some more complex cases we could in theory support, but have bigger plans
/// to enable just pure rust hotreloading that would make those tricks moot. So, manage more of
/// the simple cases until that proper stuff ships.
///
/// We need to make sure to wire up:
/// - subtemplate IDs
/// - ifmt IDs
/// - dynamic node IDs
/// - dynamic attribute IDs
/// - paths for dynamic nodes and attributes
///
/// Lots of wiring!
///
/// However, here, we only need to wire up template IDs since TemplateBody will handle the rest.
///
/// This is better though since we can save the relevant data on the structures themselves.
fn cascade_hotreload_info(&self, nodes: &[BodyNode]) {
for node in nodes.iter() {
match node {
BodyNode::Element(el) => {
self.cascade_hotreload_info(&el.children);
}
BodyNode::Component(comp) => {
comp.children.template_idx.set(self.next_template_idx());
self.cascade_hotreload_info(&comp.children.roots);
}
BodyNode::ForLoop(floop) => {
floop.body.template_idx.set(self.next_template_idx());
self.cascade_hotreload_info(&floop.body.roots);
}
BodyNode::IfChain(chain) => chain.for_each_branch(&mut |body| {
body.template_idx.set(self.next_template_idx());
self.cascade_hotreload_info(&body.roots)
}),
_ => {}
}
}
}
fn next_template_idx(&self) -> usize {
let idx = self.template_idx.get();
self.template_idx.set(idx + 1);
idx
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx/src/ifmt.rs | packages/rsx/src/ifmt.rs | use proc_macro2::{Span, TokenStream};
use quote::{quote, quote_spanned, ToTokens, TokenStreamExt};
use std::collections::HashMap;
use syn::{
parse::{Parse, ParseStream},
*,
};
/// A hot-reloadable formatted string, boolean, number or other literal
///
/// This wraps LitStr with some extra goodies like inline expressions and hot-reloading.
/// Originally this was intended to provide named inline string interpolation but eventually Rust
/// actually shipped this!
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub struct IfmtInput {
pub source: LitStr,
pub segments: Vec<Segment>,
}
impl IfmtInput {
pub fn new(span: Span) -> Self {
Self {
source: LitStr::new("", span),
segments: Vec::new(),
}
}
pub fn new_litstr(source: LitStr) -> Result<Self> {
let segments = IfmtInput::from_raw(&source.value()).map_err(|e| {
// If there is an error creating the formatted string, attribute it to the litstr span
let span = source.span();
syn::Error::new(span, e)
})?;
Ok(Self { segments, source })
}
pub fn span(&self) -> Span {
self.source.span()
}
pub fn push_raw_str(&mut self, other: String) {
self.segments.push(Segment::Literal(other.to_string()))
}
pub fn push_ifmt(&mut self, other: IfmtInput) {
self.segments.extend(other.segments);
}
pub fn push_expr(&mut self, expr: Expr) {
self.segments.push(Segment::Formatted(FormattedSegment {
format_args: String::new(),
segment: FormattedSegmentType::Expr(Box::new(expr)),
}));
}
pub fn is_static(&self) -> bool {
self.segments
.iter()
.all(|seg| matches!(seg, Segment::Literal(_)))
}
pub fn to_static(&self) -> Option<String> {
self.segments
.iter()
.try_fold(String::new(), |acc, segment| {
if let Segment::Literal(seg) = segment {
Some(acc + seg)
} else {
None
}
})
}
pub fn dynamic_segments(&self) -> Vec<&FormattedSegment> {
self.segments
.iter()
.filter_map(|seg| match seg {
Segment::Formatted(seg) => Some(seg),
_ => None,
})
.collect::<Vec<_>>()
}
pub fn dynamic_seg_frequency_map(&self) -> HashMap<&FormattedSegment, usize> {
let mut map = HashMap::new();
for seg in self.dynamic_segments() {
*map.entry(seg).or_insert(0) += 1;
}
map
}
fn is_simple_expr(&self) -> bool {
// If there are segments but the source is empty, it's not a simple expression.
if !self.segments.is_empty() && self.source.span().byte_range().is_empty() {
return false;
}
self.segments.iter().all(|seg| match seg {
Segment::Literal(_) => true,
Segment::Formatted(FormattedSegment { segment, .. }) => {
matches!(segment, FormattedSegmentType::Ident(_))
}
})
}
/// Try to convert this into a single _.to_string() call if possible
///
/// Using "{single_expression}" is pretty common, but you don't need to go through the whole format! machinery for that, so we optimize it here.
fn try_to_string(&self) -> Option<TokenStream> {
let mut single_dynamic = None;
for segment in &self.segments {
match segment {
Segment::Literal(literal) => {
if !literal.is_empty() {
return None;
}
}
Segment::Formatted(FormattedSegment {
segment,
format_args,
}) => {
if format_args.is_empty() {
match single_dynamic {
Some(current_string) => {
single_dynamic =
Some(quote!(#current_string + &(#segment).to_string()));
}
None => {
single_dynamic = Some(quote!((#segment).to_string()));
}
}
} else {
return None;
}
}
}
}
single_dynamic
}
/// print the original source string - this handles escapes and stuff for us
pub fn to_string_with_quotes(&self) -> String {
self.source.to_token_stream().to_string()
}
/// Parse the source into segments
fn from_raw(input: &str) -> Result<Vec<Segment>> {
let mut chars = input.chars().peekable();
let mut segments = Vec::new();
let mut current_literal = String::new();
while let Some(c) = chars.next() {
if c == '{' {
if let Some(c) = chars.next_if(|c| *c == '{') {
current_literal.push(c);
continue;
}
if !current_literal.is_empty() {
segments.push(Segment::Literal(current_literal));
}
current_literal = String::new();
let mut current_captured = String::new();
while let Some(c) = chars.next() {
if c == ':' {
// two :s in a row is a path, not a format arg
if chars.next_if(|c| *c == ':').is_some() {
current_captured.push_str("::");
continue;
}
let mut current_format_args = String::new();
for c in chars.by_ref() {
if c == '}' {
segments.push(Segment::Formatted(FormattedSegment {
format_args: current_format_args,
segment: FormattedSegmentType::parse(¤t_captured)?,
}));
break;
}
current_format_args.push(c);
}
break;
}
if c == '}' {
segments.push(Segment::Formatted(FormattedSegment {
format_args: String::new(),
segment: FormattedSegmentType::parse(¤t_captured)?,
}));
break;
}
current_captured.push(c);
}
} else {
if '}' == c {
if let Some(c) = chars.next_if(|c| *c == '}') {
current_literal.push(c);
continue;
} else {
return Err(Error::new(
Span::call_site(),
"unmatched closing '}' in format string",
));
}
}
current_literal.push(c);
}
}
if !current_literal.is_empty() {
segments.push(Segment::Literal(current_literal));
}
Ok(segments)
}
}
impl ToTokens for IfmtInput {
fn to_tokens(&self, tokens: &mut TokenStream) {
// If the input is a string literal, we can just return it
if let Some(static_str) = self.to_static() {
return quote_spanned! { self.span() => #static_str }.to_tokens(tokens);
}
// Try to turn it into a single _.to_string() call
if !cfg!(debug_assertions) {
if let Some(single_dynamic) = self.try_to_string() {
tokens.extend(single_dynamic);
return;
}
}
// If the segments are not complex exprs, we can just use format! directly to take advantage of RA rename/expansion
if self.is_simple_expr() {
let raw = &self.source;
return quote_spanned! { raw.span() => ::std::format!(#raw) }.to_tokens(tokens);
}
// build format_literal
let mut format_literal = String::new();
let mut expr_counter = 0;
for segment in self.segments.iter() {
match segment {
Segment::Literal(s) => format_literal += &s.replace('{', "{{").replace('}', "}}"),
Segment::Formatted(FormattedSegment { format_args, .. }) => {
format_literal += "{";
format_literal += &expr_counter.to_string();
expr_counter += 1;
format_literal += ":";
format_literal += format_args;
format_literal += "}";
}
}
}
let span = self.span();
let positional_args = self.segments.iter().filter_map(|seg| {
if let Segment::Formatted(FormattedSegment { segment, .. }) = seg {
let mut segment = segment.clone();
// We set the span of the ident here, so that we can use it in diagnostics
if let FormattedSegmentType::Ident(ident) = &mut segment {
ident.set_span(span);
}
Some(segment)
} else {
None
}
});
quote_spanned! {
span =>
::std::format!(
#format_literal
#(, #positional_args)*
)
}
.to_tokens(tokens)
}
}
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub enum Segment {
Literal(String),
Formatted(FormattedSegment),
}
impl Segment {
pub fn is_literal(&self) -> bool {
matches!(self, Segment::Literal(_))
}
pub fn is_formatted(&self) -> bool {
matches!(self, Segment::Formatted(_))
}
}
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub struct FormattedSegment {
pub format_args: String,
pub segment: FormattedSegmentType,
}
impl ToTokens for FormattedSegment {
fn to_tokens(&self, tokens: &mut TokenStream) {
let (fmt, seg) = (&self.format_args, &self.segment);
let fmt = format!("{{0:{fmt}}}");
tokens.append_all(quote! {
format!(#fmt, #seg)
});
}
}
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub enum FormattedSegmentType {
Expr(Box<Expr>),
Ident(Ident),
}
impl FormattedSegmentType {
fn parse(input: &str) -> Result<Self> {
if let Ok(ident) = parse_str::<Ident>(input) {
if ident == input {
return Ok(Self::Ident(ident));
}
}
if let Ok(expr) = parse_str(input) {
Ok(Self::Expr(Box::new(expr)))
} else {
Err(Error::new(
Span::call_site(),
"Failed to parse formatted segment: Expected Ident or Expression",
))
}
}
}
impl ToTokens for FormattedSegmentType {
fn to_tokens(&self, tokens: &mut TokenStream) {
match self {
Self::Expr(expr) => expr.to_tokens(tokens),
Self::Ident(ident) => ident.to_tokens(tokens),
}
}
}
impl Parse for IfmtInput {
fn parse(input: ParseStream) -> Result<Self> {
let source: LitStr = input.parse()?;
Self::new_litstr(source)
}
}
#[cfg(test)]
mod tests {
use super::*;
use prettier_please::PrettyUnparse;
#[test]
fn raw_tokens() {
let input = syn::parse2::<IfmtInput>(quote! { r#"hello world"# }).unwrap();
println!("{}", input.to_token_stream().pretty_unparse());
assert_eq!(input.source.value(), "hello world");
assert_eq!(input.to_string_with_quotes(), "r#\"hello world\"#");
}
#[test]
fn segments_parse() {
let input: IfmtInput = parse_quote! { "blah {abc} {def}" };
assert_eq!(
input.segments,
vec![
Segment::Literal("blah ".to_string()),
Segment::Formatted(FormattedSegment {
format_args: String::new(),
segment: FormattedSegmentType::Ident(Ident::new("abc", Span::call_site()))
}),
Segment::Literal(" ".to_string()),
Segment::Formatted(FormattedSegment {
format_args: String::new(),
segment: FormattedSegmentType::Ident(Ident::new("def", Span::call_site()))
}),
]
);
}
#[test]
fn printing_raw() {
let input = syn::parse2::<IfmtInput>(quote! { "hello {world}" }).unwrap();
println!("{}", input.to_string_with_quotes());
let input = syn::parse2::<IfmtInput>(quote! { "hello {world} {world} {world}" }).unwrap();
println!("{}", input.to_string_with_quotes());
let input = syn::parse2::<IfmtInput>(quote! { "hello {world} {world} {world()}" }).unwrap();
println!("{}", input.to_string_with_quotes());
let input =
syn::parse2::<IfmtInput>(quote! { r#"hello {world} {world} {world()}"# }).unwrap();
println!("{}", input.to_string_with_quotes());
assert!(!input.is_static());
let input = syn::parse2::<IfmtInput>(quote! { r#"hello"# }).unwrap();
println!("{}", input.to_string_with_quotes());
assert!(input.is_static());
}
#[test]
fn to_static() {
let input = syn::parse2::<IfmtInput>(quote! { "body {{ background: red; }}" }).unwrap();
assert_eq!(
input.to_static(),
Some("body { background: red; }".to_string())
);
}
#[test]
fn error_spans() {
let input = syn::parse2::<IfmtInput>(quote! { "body {{ background: red; }" }).unwrap_err();
assert_eq!(input.span().byte_range(), 0..28);
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx/src/assign_dyn_ids.rs | packages/rsx/src/assign_dyn_ids.rs | use crate::attribute::Attribute;
use crate::{
AttributeValue, BodyNode, HotLiteral, HotReloadFormattedSegment, Segment, TemplateBody,
};
/// A visitor that assigns dynamic ids to nodes and attributes and accumulates paths to dynamic nodes and attributes
struct DynIdVisitor<'a> {
body: &'a mut TemplateBody,
current_path: Vec<u8>,
dynamic_text_index: usize,
component_literal_index: usize,
}
impl<'a> DynIdVisitor<'a> {
fn new(body: &'a mut TemplateBody) -> Self {
Self {
body,
current_path: Vec::new(),
dynamic_text_index: 0,
component_literal_index: 0,
}
}
fn visit_children(&mut self, children: &[BodyNode]) {
for (idx, node) in children.iter().enumerate() {
self.current_path.push(idx as u8);
self.visit(node);
self.current_path.pop();
}
}
fn visit(&mut self, node: &BodyNode) {
match node {
// Just descend into elements - they're not dynamic
BodyNode::Element(el) => {
for (idx, attr) in el.merged_attributes.iter().enumerate() {
if !attr.is_static_str_literal() {
self.assign_path_to_attribute(attr, idx);
if let AttributeValue::AttrLiteral(HotLiteral::Fmted(lit)) = &attr.value {
self.assign_formatted_segment(lit);
}
}
}
// Assign formatted segments to the key which is not included in the merged_attributes
if let Some(AttributeValue::AttrLiteral(HotLiteral::Fmted(fmted))) = el.key() {
self.assign_formatted_segment(fmted);
}
self.visit_children(&el.children);
}
// Text nodes are dynamic if they contain dynamic segments
BodyNode::Text(txt) => {
if !txt.is_static() {
self.assign_path_to_node(node);
self.assign_formatted_segment(&txt.input);
}
}
// Raw exprs are always dynamic
BodyNode::RawExpr(_) | BodyNode::ForLoop(_) | BodyNode::IfChain(_) => {
self.assign_path_to_node(node)
}
BodyNode::Component(component) => {
self.assign_path_to_node(node);
let mut index = 0;
for property in &component.fields {
if let AttributeValue::AttrLiteral(literal) = &property.value {
if let HotLiteral::Fmted(segments) = literal {
self.assign_formatted_segment(segments);
}
// Don't include keys in the component dynamic pool
if !property.name.is_likely_key() {
component.component_literal_dyn_idx[index]
.set(self.component_literal_index);
self.component_literal_index += 1;
index += 1;
}
}
}
}
};
}
/// Assign ids to a formatted segment
fn assign_formatted_segment(&mut self, segments: &HotReloadFormattedSegment) {
let mut dynamic_node_indexes = segments.dynamic_node_indexes.iter();
for segment in &segments.segments {
if let Segment::Formatted(segment) = segment {
dynamic_node_indexes
.next()
.unwrap()
.set(self.dynamic_text_index);
self.dynamic_text_index += 1;
self.body.dynamic_text_segments.push(segment.clone());
}
}
}
/// Assign a path to a node and give it its dynamic index
/// This simplifies the ToTokens implementation for the macro to be a little less centralized
fn assign_path_to_node(&mut self, node: &BodyNode) {
// Assign the TemplateNode::Dynamic index to the node
node.set_dyn_idx(self.body.node_paths.len());
// And then save the current path as the corresponding path
self.body.node_paths.push(self.current_path.clone());
}
/// Assign a path to a attribute and give it its dynamic index
/// This simplifies the ToTokens implementation for the macro to be a little less centralized
pub(crate) fn assign_path_to_attribute(
&mut self,
attribute: &Attribute,
attribute_index: usize,
) {
// Assign the dynamic index to the attribute
attribute.set_dyn_idx(self.body.attr_paths.len());
// And then save the current path as the corresponding path
self.body
.attr_paths
.push((self.current_path.clone(), attribute_index));
}
}
impl TemplateBody {
/// Cascade down path information into the children of this template
///
/// This provides the necessary path and index information for the children of this template
/// so that they can render out their dynamic nodes correctly. Also does plumbing for things like
/// hotreloaded literals which need to be tracked on a per-template basis.
///
/// This can only operate with knowledge of this template, not the surrounding callbody. Things like
/// wiring of ifmt literals need to be done at the callbody level since those final IDs need to
/// be unique to the entire app.
pub(crate) fn assign_paths_inner(&mut self, nodes: &[BodyNode]) {
let mut visitor = DynIdVisitor::new(self);
visitor.visit_children(nodes);
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx/src/forloop.rs | packages/rsx/src/forloop.rs | use super::*;
use location::DynIdx;
use proc_macro2::TokenStream as TokenStream2;
use syn::{braced, token::Brace, Expr, Pat};
#[non_exhaustive]
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ForLoop {
pub for_token: Token![for],
pub pat: Pat,
pub in_token: Token![in],
pub expr: Box<Expr>,
pub brace: Brace,
pub body: TemplateBody,
pub dyn_idx: DynIdx,
}
impl Parse for ForLoop {
fn parse(input: ParseStream) -> Result<Self> {
// todo: better partial parsing
// A bit stolen from `ExprForLoop` in the `syn` crate
let for_token = input.parse()?;
let pat = input.call(Pat::parse_single)?;
let in_token = input.parse()?;
let expr = input.call(Expr::parse_without_eager_brace)?;
let content;
let brace = braced!(content in input);
let body = content.parse()?;
Ok(Self {
for_token,
pat,
in_token,
brace,
expr: Box::new(expr),
body,
dyn_idx: DynIdx::default(),
})
}
}
impl ToTokens for ForLoop {
fn to_tokens(&self, tokens: &mut TokenStream2) {
let ForLoop {
pat, expr, body, ..
} = self;
// the temporary is important so we create a lifetime binding
tokens.append_all(quote! {
{
let ___nodes = dioxus_core::IntoDynNode::into_dyn_node((#expr).into_iter().map(|#pat| { #body }));
___nodes
}
});
}
}
#[test]
fn parses_for_loop() {
let toks = quote! {
for item in 0..10 {
div { "cool-{item}" }
div { "cool-{item}" }
div { "cool-{item}" }
}
};
let for_loop: ForLoop = syn::parse2(toks).unwrap();
assert!(for_loop.body.roots.len() == 3);
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx/src/component.rs | packages/rsx/src/component.rs | //! Parse components into the VNode::Component variant
//!
//! Uses the regular robust RsxBlock parser and then validates the component, emitting errors as
//! diagnostics. This was refactored from a straightforward parser to this validation approach so
//! that we can emit errors as diagnostics instead of returning results.
//!
//! Using this approach we can provide *much* better errors as well as partial expansion wherever
//! possible.
//!
//! It does lead to the code actually being larger than it was before, but it should be much easier
//! to work with and extend. To add new syntax, we add it to the RsxBlock parser and then add a
//! validation step here. This does make using the component as a source of truth not as good, but
//! oddly enoughly, we want the tree to actually be capable of being technically invalid. This is not
//! usual for building in Rust - you want strongly typed things to be valid - but in this case, we
//! want to accept all sorts of malformed input and then provide the best possible error messages.
//!
//! If you're generally parsing things, you'll just want to parse and then check if it's valid.
use crate::innerlude::*;
use proc_macro2::TokenStream as TokenStream2;
use proc_macro2_diagnostics::SpanDiagnosticExt;
use quote::{quote, quote_spanned, ToTokens, TokenStreamExt};
use std::{collections::HashSet, vec};
use syn::{
parse::{Parse, ParseStream},
spanned::Spanned,
token, AngleBracketedGenericArguments, Expr, Ident, PathArguments, Result,
};
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Component {
pub name: syn::Path,
pub generics: Option<AngleBracketedGenericArguments>,
pub fields: Vec<Attribute>,
pub component_literal_dyn_idx: Vec<DynIdx>,
pub spreads: Vec<Spread>,
pub brace: Option<token::Brace>,
pub children: TemplateBody,
pub dyn_idx: DynIdx,
pub diagnostics: Diagnostics,
}
impl Parse for Component {
fn parse(input: ParseStream) -> Result<Self> {
let mut name = input.parse::<syn::Path>()?;
let generics = normalize_path(&mut name);
if !input.peek(token::Brace) {
return Ok(Self::empty(name, generics));
};
let RsxBlock {
attributes: fields,
children,
brace,
spreads,
diagnostics,
} = input.parse::<RsxBlock>()?;
let literal_properties_count = fields
.iter()
.filter(|attr| matches!(attr.value, AttributeValue::AttrLiteral(_)))
.count();
let component_literal_dyn_idx = vec![DynIdx::default(); literal_properties_count];
let mut component = Self {
dyn_idx: DynIdx::default(),
children: TemplateBody::new(children),
name,
generics,
fields,
brace: Some(brace),
component_literal_dyn_idx,
spreads,
diagnostics,
};
// We've received a valid rsx block, but it's not necessarily a valid component
// validating it will dump diagnostics into the output
component.validate_component_path();
component.validate_fields();
component.validate_component_spread();
Ok(component)
}
}
impl ToTokens for Component {
fn to_tokens(&self, tokens: &mut TokenStream2) {
let Self { name, generics, .. } = self;
// Create props either from manual props or from the builder approach
let props = self.create_props();
// Make sure we emit any errors
let diagnostics = &self.diagnostics;
tokens.append_all(quote! {
dioxus_core::DynamicNode::Component({
// todo: ensure going through the trait actually works
// we want to avoid importing traits
use dioxus_core::Properties;
let __comp = ({
#props
}).into_vcomponent(
#name #generics,
);
#diagnostics
__comp
})
})
}
}
impl Component {
// Make sure this a proper component path (uppercase ident, a path, or contains an underscorea)
// This should be validated by the RsxBlock parser when it peeks bodynodes
fn validate_component_path(&mut self) {
let path = &self.name;
// First, ensure the path is not a single lowercase ident with no underscores
if path.segments.len() == 1 {
let seg = path.segments.first().unwrap();
if seg.ident.to_string().chars().next().unwrap().is_lowercase()
&& !seg.ident.to_string().contains('_')
{
self.diagnostics.push(seg.ident.span().error(
"Component names must be uppercase, contain an underscore, or abe a path.",
));
}
}
// ensure path segments doesn't have PathArguments, only the last
// segment is allowed to have one.
if path
.segments
.iter()
.take(path.segments.len() - 1)
.any(|seg| seg.arguments != PathArguments::None)
{
self.diagnostics.push(path.span().error(
"Component names must not have path arguments. Only the last segment is allowed to have one.",
));
}
// ensure last segment only have value of None or AngleBracketed
if !matches!(
path.segments.last().unwrap().arguments,
PathArguments::None | PathArguments::AngleBracketed(_)
) {
self.diagnostics.push(
path.span()
.error("Component names must have no arguments or angle bracketed arguments."),
);
}
}
// Make sure the spread argument is being used as props spreading
fn validate_component_spread(&mut self) {
// Next, ensure that there's only one spread argument in the attributes *and* it's the last one
for spread in self.spreads.iter().skip(1) {
self.diagnostics.push(
spread
.expr
.span()
.error("Only one set of manual props is allowed for a component."),
);
}
}
pub fn get_key(&self) -> Option<&AttributeValue> {
self.fields
.iter()
.find(|attr| attr.name.is_likely_key())
.map(|attr| &attr.value)
}
/// Ensure there's no duplicate props - this will be a compile error but we can move it to a
/// diagnostic, thankfully
fn validate_fields(&mut self) {
let mut seen = HashSet::new();
for field in self.fields.iter() {
match &field.name {
AttributeName::Custom(_) => {}
AttributeName::BuiltIn(k) => {
if !seen.contains(k) {
seen.insert(k);
} else {
self.diagnostics.push(k.span().error(
"Duplicate prop field found. Only one prop field per name is allowed.",
));
}
}
AttributeName::Spread(_) => {
unreachable!(
"Spread attributes should be handled in the spread validation step."
)
}
}
}
}
/// Create the tokens we'll use for the props of the component
///
/// todo: don't create the tokenstream from scratch and instead dump it into the existing streama
fn create_props(&self) -> TokenStream2 {
let manual_props = self.manual_props();
let name = &self.name;
let generics = &self.generics;
let inner_scope_span = self
.brace
.as_ref()
.map(|b| b.span.join())
.unwrap_or(self.name.span());
let mut tokens = if let Some(props) = manual_props.as_ref() {
quote_spanned! { props.span() => let mut __manual_props = #props; }
} else {
// we only want to span the name and generics, not the `fc_to_builder` call so jump-to-def
// only finds the single entry (#name)
let spanned = quote_spanned! { self.name.span() => #name #generics };
quote! { dioxus_core::fc_to_builder(#spanned) }
};
tokens.append_all(self.add_fields_to_builder(
manual_props.map(|_| Ident::new("__manual_props", proc_macro2::Span::call_site())),
));
if !self.children.is_empty() {
let children = &self.children;
// If the props don't accept children, attach the error to the first child
if manual_props.is_some() {
tokens.append_all(
quote_spanned! { children.first_root_span() => __manual_props.children = #children; },
)
} else {
tokens.append_all(
quote_spanned! { children.first_root_span() => .children( #children ) },
)
}
}
if manual_props.is_some() {
tokens.append_all(quote! { __manual_props })
} else {
// If this does fail to build, point the compiler error at the Prop braces
tokens.append_all(quote_spanned! { inner_scope_span => .build() })
}
tokens
}
fn manual_props(&self) -> Option<&Expr> {
self.spreads.first().map(|spread| &spread.expr)
}
// Iterate over the props of the component (without spreads, key, and custom attributes)
pub fn component_props(&self) -> impl Iterator<Item = &Attribute> {
self.fields
.iter()
.filter(move |attr| !attr.name.is_likely_key())
}
fn add_fields_to_builder(&self, manual_props: Option<Ident>) -> TokenStream2 {
let mut dynamic_literal_index = 0;
let mut tokens = TokenStream2::new();
for attribute in self.component_props() {
let release_value = attribute.value.to_token_stream();
// In debug mode, we try to grab the value from the dynamic literal pool if possible
let value = if let AttributeValue::AttrLiteral(literal) = &attribute.value {
let idx = self.component_literal_dyn_idx[dynamic_literal_index].get();
dynamic_literal_index += 1;
let debug_value = quote! { __dynamic_literal_pool.component_property(#idx, &*__template_read, #literal) };
quote! {
{
#[cfg(debug_assertions)]
{
#debug_value
}
#[cfg(not(debug_assertions))]
{
#release_value
}
}
}
} else {
release_value
};
match &attribute.name {
AttributeName::BuiltIn(name) => {
if let Some(manual_props) = &manual_props {
tokens.append_all(quote! { #manual_props.#name = #value; })
} else {
tokens.append_all(quote! { .#name(#value) })
}
}
AttributeName::Custom(name) => {
if manual_props.is_some() {
tokens.append_all(name.span().error(
"Custom attributes are not supported for components that are spread",
).emit_as_expr_tokens());
} else {
// tokens = quote! {
// dioxus_core::HasAttributes::push_attribute(
// #tokens,
// #name,
// None,
// #value,
// false
// )
// };
tokens.append_all(quote! {
.push_attribute(#name, None, #value, false)
})
}
}
// spreads are handled elsewhere
AttributeName::Spread(_) => {}
}
}
tokens
}
fn empty(name: syn::Path, generics: Option<AngleBracketedGenericArguments>) -> Self {
let mut diagnostics = Diagnostics::new();
diagnostics.push(
name.span()
.error("Components must have a body")
.help("Components must have a body, for example `Component {}`"),
);
Component {
name,
generics,
brace: None,
fields: vec![],
spreads: vec![],
children: TemplateBody::new(vec![]),
component_literal_dyn_idx: vec![],
dyn_idx: DynIdx::default(),
diagnostics,
}
}
}
/// Normalize the generics of a path
///
/// Ensure there's a `::` after the last segment if there are generics
fn normalize_path(name: &mut syn::Path) -> Option<AngleBracketedGenericArguments> {
let seg = name.segments.last_mut()?;
let mut generics = match seg.arguments.clone() {
PathArguments::AngleBracketed(args) => {
seg.arguments = PathArguments::None;
Some(args)
}
_ => None,
};
if let Some(generics) = generics.as_mut() {
generics.colon2_token = Some(syn::Token));
}
generics
}
#[cfg(test)]
mod tests {
use super::*;
use prettier_please::PrettyUnparse;
use syn::parse_quote;
/// Ensure we can parse a component
#[test]
fn parses() {
let input = quote! {
MyComponent {
key: "value {something}",
prop: "value",
..props,
div {
"Hello, world!"
}
}
};
let component: Component = syn::parse2(input).unwrap();
dbg!(component);
let input_without_manual_props = quote! {
MyComponent {
key: "value {something}",
prop: "value",
div { "Hello, world!" }
}
};
let component: Component = syn::parse2(input_without_manual_props).unwrap();
dbg!(component);
}
/// Ensure we reject invalid forms
///
/// Maybe want to snapshot the errors?
#[test]
fn rejects() {
let input = quote! {
myComponent {
key: "value",
prop: "value",
prop: "other",
..props,
..other_props,
div {
"Hello, world!"
}
}
};
let component: Component = syn::parse2(input).unwrap();
dbg!(component.diagnostics);
}
#[test]
fn to_tokens_properly() {
let input = quote! {
MyComponent {
key: "value {something}",
prop: "value",
prop: "value",
prop: "value",
prop: "value",
prop: 123,
..props,
div { "Hello, world!" }
}
};
let component: Component = syn::parse2(input).unwrap();
println!("{}", component.to_token_stream());
}
#[test]
fn to_tokens_no_manual_props() {
let input_without_manual_props = quote! {
MyComponent {
key: "value {something}",
named: "value {something}",
prop: "value",
count: 1,
div { "Hello, world!" }
}
};
let component: Component = syn::parse2(input_without_manual_props).unwrap();
println!("{}", component.to_token_stream().pretty_unparse());
}
#[test]
fn generics_params() {
let input_without_children = quote! {
Outlet::<R> {}
};
let component: crate::CallBody = syn::parse2(input_without_children).unwrap();
println!("{}", component.to_token_stream().pretty_unparse());
}
#[test]
fn generics_no_fish() {
let name = quote! { Outlet<R> };
let mut p = syn::parse2::<syn::Path>(name).unwrap();
let generics = normalize_path(&mut p);
assert!(generics.is_some());
let input_without_children = quote! {
div {
Component<Generic> {}
}
};
let component: BodyNode = syn::parse2(input_without_children).unwrap();
println!("{}", component.to_token_stream().pretty_unparse());
}
#[test]
fn fmt_passes_properly() {
let input = quote! {
Link { to: Route::List, class: "pure-button", "Go back" }
};
let component: Component = syn::parse2(input).unwrap();
println!("{}", component.to_token_stream().pretty_unparse());
}
#[test]
fn incomplete_components() {
let input = quote::quote! {
some::cool::Component
};
let _parsed: Component = syn::parse2(input).unwrap();
let input = quote::quote! {
some::cool::C
};
let _parsed: syn::Path = syn::parse2(input).unwrap();
}
#[test]
fn identifies_key() {
let input = quote! {
Link { key: "{value}", to: Route::List, class: "pure-button", "Go back" }
};
let component: Component = syn::parse2(input).unwrap();
// The key should exist
assert_eq!(component.get_key(), Some(&parse_quote!("{value}")));
// The key should not be included in the properties
let properties = component
.component_props()
.map(|attr| attr.name.to_string())
.collect::<Vec<_>>();
assert_eq!(properties, ["to", "class"]);
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx/tests/parsing.rs | packages/rsx/tests/parsing.rs | use dioxus_rsx::CallBody;
use quote::ToTokens;
use prettier_please::PrettyUnparse;
#[test]
fn callbody_ctx() {
let item = quote::quote! {
div {
h1 {
id: "Some cool attribute {cool}"
}
for item in items {
"Something {cool}"
}
Component {
"Something {elseish}"
}
Component2 {
"Something {Body}"
Component3 {
prop: "Something {Body3}",
"Something {Body4}"
}
}
something-cool {
"Something {cool}ish"
}
if true {
div {
"hi! {cool}"
}
}
"hi!"
"goodbye!"
}
{some_expr}
};
let cb: CallBody = syn::parse2(item).unwrap();
dbg!(cb.template_idx.get());
}
#[test]
fn simple_case() {
let item = quote::quote! {
div {
something: "cool",
id: "Some cool attribute {cool}",
class: "Some cool attribute {cool2}",
"hi!"
{some_expr}
Component {
boolish: true,
otherish: 123,
otherish2: 123.0,
otherish3: "dang!",
otherish3: "dang! {cool}",
}
}
};
let cb: CallBody = syn::parse2(item).unwrap();
println!("{}", cb.to_token_stream().pretty_unparse());
}
#[test]
fn complex_kitchen_sink() {
let item = quote::quote! {
// complex_carry
button {
class: "flex items-center pl-3 py-3 pr-2 text-gray-500 hover:bg-indigo-50 rounded",
width: {"100%"}.to_string(),
onclick: move |evt| {
show_user_menu.set(!show_user_menu.get());
evt.cancel_bubble();
},
onmousedown: move |evt| show_user_menu.set(!show_user_menu.get()),
span { class: "inline-block mr-4", icons::icon_14 {} }
span { "Settings" }
}
// Complex nesting with handlers
li {
Link {
class: "flex items-center pl-3 py-3 pr-4 {active_class} rounded",
to: "{to}",
span { class: "inline-block mr-3", icons::icon_0 {} }
span { "{name}" }
{children.is_some().then(|| rsx! {
span {
class: "inline-block ml-auto hover:bg-gray-500",
onclick: move |evt| {
// open.set(!open.get());
evt.cancel_bubble();
},
icons::icon_8 {}
}
})}
}
div { class: "px-4", {is_current.then(|| rsx! { children })} }
}
// No nesting
Component {
adsasd: "asd",
onclick: move |_| {
let blah = 120;
}
}
// No nesting
Component {
adsasd: "asd",
onclick: {
let a = 1;
move |_| {
let blah = 120;
}
}
}
// Component path
my::thing::Component {
adsasd: "asd",
onclick: move |_| {
let blah = 120;
}
}
for i in 0..10 {
Component { key: "{i}", blah: 120 }
}
for i in 0..10 {
Component { key: "{i}" }
}
for i in 0..10 {
div { key: "{i}", blah: 120 }
}
for i in 0..10 {
div { key: "{i}" }
}
div {
"asdbascasdbasd"
"asbdasbdabsd"
{asbdabsdbasdbas}
}
};
let _cb: CallBody = syn::parse2(item).unwrap();
}
#[test]
fn key_must_be_formatted() {
let item = quote::quote! {
div {
key: value
}
};
let parsed = syn::parse2::<CallBody>(item).unwrap();
println!("{:?}", parsed.body.diagnostics);
assert!(!parsed.body.diagnostics.is_empty());
}
#[test]
fn key_cannot_be_static() {
let item = quote::quote! {
div {
key: "hello world"
}
};
let parsed = syn::parse2::<CallBody>(item).unwrap();
println!("{:?}", parsed.body.diagnostics);
assert!(!parsed.body.diagnostics.is_empty());
}
#[test]
fn braced_expressions() {
let item = quote::quote! {
div {
width: {100} - 50,
width: {"100%"}.to_string(),
width: {|| "100%"}(),
}
// Partial expressions in braces rsx should be allowed and output as-is
// for autocomplete
{partial.}
div {}
{partial.}
// Comments should be ignored
div {}
{partial.}
"hello world"
{partial.}
if true {}
};
let _cb: CallBody = syn::parse2(item).unwrap();
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/bench/src/run_benchmark.rs | bench/src/run_benchmark.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! This Rust binary runs on CI and provides internal metrics results of Tauri.
//! To learn more see [benchmark_results](https://github.com/tauri-apps/benchmark_results) repository.
//!
//! ***_Internal use only_***
#![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 anyhow::{Context, Result};
use std::{
collections::{HashMap, HashSet},
env,
path::Path,
process::{Command, Stdio},
};
mod utils;
/// The list of examples for benchmarks
fn get_all_benchmarks(target: &str) -> Vec<(String, String)> {
vec![
(
"tauri_hello_world".into(),
format!("../target/{target}/release/bench_helloworld"),
),
(
"tauri_cpu_intensive".into(),
format!("../target/{target}/release/bench_cpu_intensive"),
),
(
"tauri_3mb_transfer".into(),
format!("../target/{target}/release/bench_files_transfer"),
),
]
}
fn run_strace_benchmarks(new_data: &mut utils::BenchResult, target: &str) -> Result<()> {
use std::io::Read;
let mut thread_count = HashMap::<String, u64>::new();
let mut syscall_count = HashMap::<String, u64>::new();
for (name, example_exe) in get_all_benchmarks(target) {
let mut file = tempfile::NamedTempFile::new()
.context("failed to create temporary file for strace output")?;
let exe_path = utils::bench_root_path().join(&example_exe);
let exe_path_str = exe_path
.to_str()
.context("executable path contains invalid UTF-8")?;
let temp_path_str = file
.path()
.to_str()
.context("temporary file path contains invalid UTF-8")?;
Command::new("strace")
.args(["-c", "-f", "-o", temp_path_str, exe_path_str])
.stdout(Stdio::inherit())
.spawn()
.context("failed to spawn strace process")?
.wait()
.context("failed to wait for strace process")?;
let mut output = String::new();
file
.as_file_mut()
.read_to_string(&mut output)
.context("failed to read strace output")?;
let strace_result = utils::parse_strace_output(&output);
// Count clone/clone3 syscalls as thread creation indicators
let clone_calls = strace_result.get("clone").map(|d| d.calls).unwrap_or(0)
+ strace_result.get("clone3").map(|d| d.calls).unwrap_or(0);
if let Some(total) = strace_result.get("total") {
thread_count.insert(name.clone(), clone_calls);
syscall_count.insert(name, total.calls);
}
}
new_data.thread_count = thread_count;
new_data.syscall_count = syscall_count;
Ok(())
}
fn run_max_mem_benchmark(target: &str) -> Result<HashMap<String, u64>> {
let mut results = HashMap::<String, u64>::new();
for (name, example_exe) in get_all_benchmarks(target) {
let benchmark_file = utils::target_dir().join(format!("mprof{name}_.dat"));
let benchmark_file_str = benchmark_file
.to_str()
.context("benchmark file path contains invalid UTF-8")?;
let exe_path = utils::bench_root_path().join(&example_exe);
let exe_path_str = exe_path
.to_str()
.context("executable path contains invalid UTF-8")?;
let proc = Command::new("mprof")
.args(["run", "-C", "-o", benchmark_file_str, exe_path_str])
.stdout(Stdio::null())
.stderr(Stdio::piped())
.spawn()
.with_context(|| format!("failed to spawn mprof for benchmark {name}"))?;
let proc_result = proc
.wait_with_output()
.with_context(|| format!("failed to wait for mprof {name}"))?;
if !proc_result.status.success() {
eprintln!(
"mprof failed for {name}: {}",
String::from_utf8_lossy(&proc_result.stderr)
);
}
if let Some(mem) = utils::parse_max_mem(benchmark_file_str)
.with_context(|| format!("failed to parse mprof data for {name}"))?
{
results.insert(name, mem);
}
// Clean up the temporary file
if let Err(e) = std::fs::remove_file(&benchmark_file) {
eprintln!("Warning: failed to remove temporary file {benchmark_file_str}: {e}");
}
}
Ok(results)
}
fn rlib_size(target_dir: &Path, prefix: &str) -> Result<u64> {
let mut size = 0;
let mut seen = HashSet::new();
let deps_dir = target_dir.join("deps");
for entry in std::fs::read_dir(&deps_dir).with_context(|| {
format!(
"failed to read target deps directory: {}",
deps_dir.display()
)
})? {
let entry = entry.context("failed to read directory entry")?;
let name = entry.file_name().to_string_lossy().to_string();
if name.starts_with(prefix) && name.ends_with(".rlib") {
if let Some(start) = name.split('-').next() {
if seen.insert(start.to_string()) {
size += entry
.metadata()
.context("failed to read file metadata")?
.len();
}
}
}
}
if size == 0 {
anyhow::bail!(
"no rlib files found for prefix {prefix} in {}",
deps_dir.display()
);
}
Ok(size)
}
fn get_binary_sizes(target_dir: &Path, target: &str) -> Result<HashMap<String, u64>> {
let mut sizes = HashMap::<String, u64>::new();
let wry_size = rlib_size(target_dir, "libwry")?;
sizes.insert("wry_rlib".to_string(), wry_size);
for (name, example_exe) in get_all_benchmarks(target) {
let exe_path = utils::bench_root_path().join(&example_exe);
let meta = std::fs::metadata(&exe_path)
.with_context(|| format!("failed to read metadata for {}", exe_path.display()))?;
sizes.insert(name, meta.len());
}
Ok(sizes)
}
/// (target OS, target triple)
const TARGETS: &[(&str, &[&str])] = &[
(
"Windows",
&[
"x86_64-pc-windows-gnu",
"i686-pc-windows-gnu",
"i686-pc-windows-msvc",
"x86_64-pc-windows-msvc",
],
),
(
"Linux",
&[
"x86_64-unknown-linux-gnu",
"i686-unknown-linux-gnu",
"aarch64-unknown-linux-gnu",
],
),
("macOS", &["x86_64-apple-darwin", "aarch64-apple-darwin"]),
];
fn cargo_deps() -> HashMap<String, usize> {
let mut results = HashMap::new();
for (os, targets) in TARGETS {
for target in *targets {
let mut cmd = Command::new("cargo");
cmd.arg("tree");
cmd.arg("--no-dedupe");
cmd.args(["--edges", "normal"]);
cmd.args(["--prefix", "none"]);
cmd.args(["--target", target]);
cmd.current_dir(utils::tauri_root_path());
match cmd.output() {
Ok(output) if output.status.success() => {
let full_deps = String::from_utf8_lossy(&output.stdout);
let count = full_deps
.lines()
.collect::<HashSet<_>>()
.len()
.saturating_sub(1); // output includes wry itself
// set the count to the highest count seen for this OS
let existing = results.entry(os.to_string()).or_default();
*existing = count.max(*existing);
if count <= 10 {
eprintln!("Warning: dependency count for {target} seems low: {count}");
}
}
Ok(output) => {
eprintln!(
"cargo tree failed for {target}: {}",
String::from_utf8_lossy(&output.stderr)
);
}
Err(e) => {
eprintln!("Failed to run cargo tree for {target}: {e}");
}
}
}
}
results
}
const RESULT_KEYS: &[&str] = &["mean", "stddev", "user", "system", "min", "max"];
fn run_exec_time(target: &str) -> Result<HashMap<String, HashMap<String, f64>>> {
let target_dir = utils::target_dir();
let benchmark_file = target_dir.join("hyperfine_results.json");
let benchmark_file_str = benchmark_file
.to_str()
.context("benchmark file path contains invalid UTF-8")?;
let mut command = vec![
"hyperfine",
"--export-json",
benchmark_file_str,
"--show-output",
"--warmup",
"3",
];
let benchmarks = get_all_benchmarks(target);
let mut benchmark_paths = Vec::new();
for (_, example_exe) in &benchmarks {
let exe_path = utils::bench_root_path().join(example_exe);
let exe_path_str = exe_path
.to_str()
.context("executable path contains invalid UTF-8")?;
benchmark_paths.push(exe_path_str.to_string());
}
for path in &benchmark_paths {
command.push(path.as_str());
}
utils::run(&command)?;
let mut results = HashMap::<String, HashMap<String, f64>>::new();
let hyperfine_results = utils::read_json(benchmark_file_str)?;
if let Some(results_array) = hyperfine_results
.as_object()
.and_then(|obj| obj.get("results"))
.and_then(|val| val.as_array())
{
for ((name, _), data) in benchmarks.iter().zip(results_array.iter()) {
if let Some(data_obj) = data.as_object() {
let filtered_data: HashMap<String, f64> = data_obj
.iter()
.filter(|(key, _)| RESULT_KEYS.contains(&key.as_str()))
.filter_map(|(key, val)| val.as_f64().map(|v| (key.clone(), v)))
.collect();
results.insert(name.clone(), filtered_data);
}
}
}
Ok(results)
}
fn main() -> Result<()> {
let json_3mb = utils::home_path().join(".tauri_3mb.json");
if !json_3mb.exists() {
println!("Downloading test data...");
utils::download_file(
"https://github.com/lemarier/tauri-test/releases/download/v2.0.0/json_3mb.json",
json_3mb,
)
.context("failed to download test data")?;
}
println!("Starting tauri benchmark");
let target_dir = utils::target_dir();
let target = utils::get_target();
env::set_current_dir(utils::bench_root_path())
.context("failed to set working directory to bench root")?;
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.context("failed to get current time")?;
let timestamp = format!("{}", now.as_secs());
println!("Running execution time benchmarks...");
let exec_time = run_exec_time(target)?;
println!("Getting binary sizes...");
let binary_size = get_binary_sizes(&target_dir, target)?;
println!("Analyzing cargo dependencies...");
let cargo_deps = cargo_deps();
let mut new_data = utils::BenchResult {
created_at: timestamp,
sha1: {
let output = utils::run_collect(&["git", "rev-parse", "HEAD"])?;
output.0.trim().to_string()
},
exec_time,
binary_size,
cargo_deps,
..Default::default()
};
if cfg!(target_os = "linux") {
println!("Running Linux-specific benchmarks...");
run_strace_benchmarks(&mut new_data, target)?;
new_data.max_memory = run_max_mem_benchmark(target)?;
}
println!("===== <BENCHMARK RESULTS>");
serde_json::to_writer_pretty(std::io::stdout(), &new_data)
.context("failed to serialize benchmark results")?;
println!("\n===== </BENCHMARK RESULTS>");
let bench_file = target_dir.join("bench.json");
if let Some(filename) = bench_file.to_str() {
utils::write_json(filename, &serde_json::to_value(&new_data)?)
.context("failed to write benchmark results to file")?;
println!("Results written to: {filename}");
} else {
eprintln!("Cannot write bench.json, path contains invalid UTF-8");
}
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/bench/src/utils.rs | bench/src/utils.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Utility functions for benchmarking tasks in the Tauri project.
//!
//! This module provides helpers for:
//! - Paths to project directories and targets
//! - Running and collecting process outputs
//! - Parsing memory profiler (`mprof`) and syscall profiler (`strace`) outputs
//! - JSON read/write utilities
//! - File download utilities (via `curl` or file copy)
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::{
collections::HashMap,
fs,
io::{BufRead, BufReader},
path::PathBuf,
process::{Command, Output, Stdio},
};
/// Holds the results of a benchmark run.
#[derive(Default, Clone, Serialize, Deserialize, Debug)]
pub struct BenchResult {
pub created_at: String,
pub sha1: String,
pub exec_time: HashMap<String, HashMap<String, f64>>,
pub binary_size: HashMap<String, u64>,
pub max_memory: HashMap<String, u64>,
pub thread_count: HashMap<String, u64>,
pub syscall_count: HashMap<String, u64>,
pub cargo_deps: HashMap<String, usize>,
}
/// Represents a single line of parsed `strace` output.
#[derive(Debug, Clone, Serialize)]
pub struct StraceOutput {
pub percent_time: f64,
pub seconds: f64,
pub usecs_per_call: Option<u64>,
pub calls: u64,
pub errors: u64,
}
/// Get the compilation target triple for the current platform.
pub fn get_target() -> &'static str {
#[cfg(target_os = "macos")]
return if cfg!(target_arch = "aarch64") {
"aarch64-apple-darwin"
} else {
"x86_64-apple-darwin"
};
#[cfg(target_os = "ios")]
return if cfg!(target_arch = "aarch64") {
"aarch64-apple-ios"
} else {
"x86_64-apple-ios"
};
#[cfg(target_os = "linux")]
return "x86_64-unknown-linux-gnu";
#[cfg(target_os = "windows")]
unimplemented!("Windows target not implemented yet");
}
/// Get the `target/release` directory path for benchmarks.
pub fn target_dir() -> PathBuf {
bench_root_path()
.join("..")
.join("target")
.join(get_target())
.join("release")
}
/// Get the root path of the current benchmark crate.
pub fn bench_root_path() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
}
/// Get the home directory of the current user.
pub fn home_path() -> PathBuf {
#[cfg(any(target_os = "macos", target_os = "ios", target_os = "linux"))]
{
PathBuf::from(std::env::var("HOME").unwrap_or_default())
}
#[cfg(target_os = "windows")]
{
PathBuf::from(std::env::var("USERPROFILE").unwrap_or_default())
}
}
/// Get the root path of the Tauri repository.
pub fn tauri_root_path() -> PathBuf {
bench_root_path().parent().map(|p| p.to_path_buf()).unwrap()
}
/// Run a command and collect its stdout and stderr as strings.
/// Returns an error if the command fails or exits with a non-zero status.
pub fn run_collect(cmd: &[&str]) -> Result<(String, String)> {
let output: Output = Command::new(cmd[0])
.args(&cmd[1..])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()
.with_context(|| format!("failed to execute command: {cmd:?}"))?;
if !output.status.success() {
bail!(
"Command {:?} exited with {:?}\nstdout:\n{}\nstderr:\n{}",
cmd,
output.status.code(),
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}
Ok((
String::from_utf8_lossy(&output.stdout).to_string(),
String::from_utf8_lossy(&output.stderr).to_string(),
))
}
/// Parse a memory profiler (`mprof`) output file and return the maximum
/// memory usage in bytes. Returns `None` if no values are found.
pub fn parse_max_mem(file_path: &str) -> Result<Option<u64>> {
let file = fs::File::open(file_path)
.with_context(|| format!("failed to open mprof output file {file_path}"))?;
let output = BufReader::new(file);
let mut highest: u64 = 0;
for line in output.lines().map_while(Result::ok) {
let split: Vec<&str> = line.split(' ').collect();
if split.len() == 3 {
if let Ok(mb) = split[1].parse::<f64>() {
let current_bytes = (mb * 1024.0 * 1024.0) as u64;
highest = highest.max(current_bytes);
}
}
}
// Best-effort cleanup
let _ = fs::remove_file(file_path);
Ok(if highest > 0 { Some(highest) } else { None })
}
/// Parse the output of `strace -c` and return a summary of syscalls.
pub fn parse_strace_output(output: &str) -> HashMap<String, StraceOutput> {
let mut summary = HashMap::new();
let mut lines = output
.lines()
.filter(|line| !line.is_empty() && !line.contains("detached ..."));
let count = lines.clone().count();
if count < 4 {
return summary;
}
let total_line = lines.next_back().unwrap();
lines.next_back(); // Drop separator
let data_lines = lines.skip(2);
for line in data_lines {
let syscall_fields: Vec<&str> = line.split_whitespace().collect();
let len = syscall_fields.len();
if let Some(&syscall_name) = syscall_fields.last() {
if (5..=6).contains(&len) {
let output = StraceOutput {
percent_time: syscall_fields[0].parse().unwrap_or(0.0),
seconds: syscall_fields[1].parse().unwrap_or(0.0),
usecs_per_call: syscall_fields[2].parse().ok(),
calls: syscall_fields[3].parse().unwrap_or(0),
errors: if len < 6 {
0
} else {
syscall_fields[4].parse().unwrap_or(0)
},
};
summary.insert(syscall_name.to_string(), output);
}
}
}
let total_fields: Vec<&str> = total_line.split_whitespace().collect();
let total = match total_fields.len() {
5 => StraceOutput {
percent_time: total_fields[0].parse().unwrap_or(0.0),
seconds: total_fields[1].parse().unwrap_or(0.0),
usecs_per_call: None,
calls: total_fields[2].parse().unwrap_or(0),
errors: total_fields[3].parse().unwrap_or(0),
},
6 => StraceOutput {
percent_time: total_fields[0].parse().unwrap_or(0.0),
seconds: total_fields[1].parse().unwrap_or(0.0),
usecs_per_call: total_fields[2].parse().ok(),
calls: total_fields[3].parse().unwrap_or(0),
errors: total_fields[4].parse().unwrap_or(0),
},
_ => {
panic!("Unexpected total field count: {}", total_fields.len());
}
};
summary.insert("total".to_string(), total);
summary
}
/// Run a command and wait for completion.
/// Returns an error if the command fails.
pub fn run(cmd: &[&str]) -> Result<()> {
let status = Command::new(cmd[0])
.args(&cmd[1..])
.stdin(Stdio::piped())
.status()
.with_context(|| format!("failed to execute command: {cmd:?}"))?;
if !status.success() {
bail!("Command {:?} exited with {:?}", cmd, status.code());
}
Ok(())
}
/// Read a JSON file into a [`serde_json::Value`].
pub fn read_json(filename: &str) -> Result<Value> {
let f =
fs::File::open(filename).with_context(|| format!("failed to open JSON file {filename}"))?;
Ok(serde_json::from_reader(f)?)
}
/// Write a [`serde_json::Value`] into a JSON file.
pub fn write_json(filename: &str, value: &Value) -> Result<()> {
let f =
fs::File::create(filename).with_context(|| format!("failed to create JSON file {filename}"))?;
serde_json::to_writer(f, value)?;
Ok(())
}
/// Download a file from either a local path or an HTTP/HTTPS URL.
/// Falls back to copying the file if the URL does not start with http/https.
pub fn download_file(url: &str, filename: PathBuf) -> Result<()> {
if !url.starts_with("http:") && !url.starts_with("https:") {
fs::copy(url, &filename).with_context(|| format!("failed to copy from {url}"))?;
return Ok(());
}
println!("Downloading {url}");
let status = Command::new("curl")
.arg("-L")
.arg("-s")
.arg("-o")
.arg(&filename)
.arg(url)
.status()
.with_context(|| format!("failed to execute curl for {url}"))?;
if !status.success() {
bail!("curl failed with exit code {:?}", status.code());
}
if !filename.exists() {
bail!("expected file {:?} to exist after download", filename);
}
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/bench/src/build_benchmark_jsons.rs | bench/src/build_benchmark_jsons.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! This Rust binary runs on CI and provides internal metrics results of Tauri. To learn more see [benchmark_results](https://github.com/tauri-apps/benchmark_results) repository.
//!
//! ***_Internal use only_**
#![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"
)]
// file is used by multiple binaries
#![allow(dead_code)]
use std::{fs::File, io::BufReader};
mod utils;
fn main() {
let tauri_data = &utils::tauri_root_path()
.join("gh-pages")
.join("tauri-data.json");
let tauri_recent = &utils::tauri_root_path()
.join("gh-pages")
.join("tauri-recent.json");
// current data
let current_data_buffer = BufReader::new(
File::open(utils::target_dir().join("bench.json")).expect("Unable to read current data file"),
);
let current_data: utils::BenchResult =
serde_json::from_reader(current_data_buffer).expect("Unable to read current data buffer");
// all data's
let all_data_buffer =
BufReader::new(File::open(tauri_data).expect("Unable to read all data file"));
let mut all_data: Vec<utils::BenchResult> =
serde_json::from_reader(all_data_buffer).expect("Unable to read all data buffer");
// add current data to all data
all_data.push(current_data);
// use only latest 20 elements from all data
let recent: Vec<utils::BenchResult> = if all_data.len() > 20 {
all_data[all_data.len() - 20..].to_vec()
} else {
all_data.clone()
};
// write json's
utils::write_json(
tauri_data
.to_str()
.expect("Something wrong with tauri_data"),
&serde_json::to_value(all_data).expect("Unable to build final json (all)"),
)
.unwrap_or_else(|_| panic!("Unable to write {tauri_data:?}"));
utils::write_json(
tauri_recent
.to_str()
.expect("Something wrong with tauri_recent"),
&serde_json::to_value(recent).expect("Unable to build final json (recent)"),
)
.unwrap_or_else(|_| panic!("Unable to write {tauri_recent:?}"));
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/bench/tests/cpu_intensive/src-tauri/build.rs | bench/tests/cpu_intensive/src-tauri/build.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
fn main() {
tauri_build::build()
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/bench/tests/cpu_intensive/src-tauri/src/main.rs | bench/tests/cpu_intensive/src-tauri/src/main.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
#[tauri::command]
fn app_completed_successfully() {
std::process::exit(0);
}
fn main() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![app_completed_successfully])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/bench/tests/files_transfer/src-tauri/build.rs | bench/tests/files_transfer/src-tauri/build.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
fn main() {
tauri_build::build()
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/bench/tests/files_transfer/src-tauri/src/main.rs | bench/tests/files_transfer/src-tauri/src/main.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use std::fs::read;
use tauri::{command, ipc::Response, path::BaseDirectory, AppHandle, Manager, Runtime};
#[command]
fn app_should_close(exit_code: i32) {
std::process::exit(exit_code);
}
#[command]
async fn read_file<R: Runtime>(app: AppHandle<R>) -> Result<Response, String> {
let path = app
.path()
.resolve(".tauri_3mb.json", BaseDirectory::Home)
.map_err(|e| e.to_string())?;
let contents = read(path).map_err(|e| e.to_string())?;
Ok(Response::new(contents))
}
fn main() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![app_should_close, read_file])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/bench/tests/helloworld/src-tauri/build.rs | bench/tests/helloworld/src-tauri/build.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
fn main() {
tauri_build::build()
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/bench/tests/helloworld/src-tauri/src/main.rs | bench/tests/helloworld/src-tauri/src/main.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
#[tauri::command]
fn app_loaded_successfully() {
std::process::exit(0);
}
fn main() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![app_loaded_successfully])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
| 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-plugin/src/lib.rs | crates/tauri-plugin/src/lib.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Interface for building Tauri plugins.
#![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"
)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#[cfg(feature = "build")]
mod build;
#[cfg(feature = "runtime")]
mod runtime;
#[cfg(feature = "build")]
#[cfg_attr(docsrs, doc(feature = "build"))]
pub use build::*;
#[cfg(feature = "runtime")]
#[cfg_attr(docsrs, doc(feature = "runtime"))]
#[allow(unused)]
pub use runtime::*;
| 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-plugin/src/runtime.rs | crates/tauri-plugin/src/runtime.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
| 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-plugin/src/build/mobile.rs | crates/tauri-plugin/src/build/mobile.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Mobile-specific build utilities.
use std::{
env::var_os,
fs::{copy, create_dir, create_dir_all, read_to_string, remove_dir_all, write},
path::{Path, PathBuf},
};
use anyhow::{Context, Result};
use super::{build_var, cfg_alias};
#[cfg(target_os = "macos")]
pub fn update_entitlements<F: FnOnce(&mut plist::Dictionary)>(f: F) -> Result<()> {
if let (Some(project_path), Ok(app_name)) = (
var_os("TAURI_IOS_PROJECT_PATH").map(PathBuf::from),
std::env::var("TAURI_IOS_APP_NAME"),
) {
update_plist_file(
project_path
.join(format!("{app_name}_iOS"))
.join(format!("{app_name}_iOS.entitlements")),
f,
)?;
}
Ok(())
}
#[cfg(target_os = "macos")]
pub fn update_info_plist<F: FnOnce(&mut plist::Dictionary)>(f: F) -> Result<()> {
if let (Some(project_path), Ok(app_name)) = (
var_os("TAURI_IOS_PROJECT_PATH").map(PathBuf::from),
std::env::var("TAURI_IOS_APP_NAME"),
) {
update_plist_file(
project_path
.join(format!("{app_name}_iOS"))
.join("Info.plist"),
f,
)?;
}
Ok(())
}
pub fn update_android_manifest(block_identifier: &str, parent: &str, insert: String) -> Result<()> {
if let Some(project_path) = var_os("TAURI_ANDROID_PROJECT_PATH").map(PathBuf::from) {
let manifest_path = project_path.join("app/src/main/AndroidManifest.xml");
let manifest = read_to_string(&manifest_path)?;
let rewritten = insert_into_xml(&manifest, block_identifier, parent, &insert);
if rewritten != manifest {
write(manifest_path, rewritten)?;
}
}
Ok(())
}
pub(crate) fn setup(
android_path: Option<PathBuf>,
#[allow(unused_variables)] ios_path: Option<PathBuf>,
) -> Result<()> {
let target_os = build_var("CARGO_CFG_TARGET_OS")?;
let mobile = target_os == "android" || target_os == "ios";
cfg_alias("mobile", mobile);
cfg_alias("desktop", !mobile);
match target_os.as_str() {
"android" => {
if let Some(path) = android_path {
let manifest_dir = build_var("CARGO_MANIFEST_DIR").map(PathBuf::from)?;
let source = manifest_dir.join(path);
let tauri_library_path = std::env::var("DEP_TAURI_ANDROID_LIBRARY_PATH")
.expect("missing `DEP_TAURI_ANDROID_LIBRARY_PATH` environment variable. Make sure `tauri` is a dependency of the plugin.");
println!("cargo:rerun-if-env-changed=DEP_TAURI_ANDROID_LIBRARY_PATH");
create_dir_all(source.join(".tauri")).context("failed to create .tauri directory")?;
copy_folder(
Path::new(&tauri_library_path),
&source.join(".tauri").join("tauri-api"),
&[],
)
.context("failed to copy tauri-api to the plugin project")?;
println!("cargo:android_library_path={}", source.display());
}
}
#[cfg(target_os = "macos")]
"ios" => {
if let Some(path) = ios_path {
let manifest_dir = std::env::var("CARGO_MANIFEST_DIR")
.map(PathBuf::from)
.unwrap();
let tauri_library_path = std::env::var("DEP_TAURI_IOS_LIBRARY_PATH")
.expect("missing `DEP_TAURI_IOS_LIBRARY_PATH` environment variable. Make sure `tauri` is a dependency of the plugin.");
let tauri_dep_path = path.parent().unwrap().join(".tauri");
create_dir_all(&tauri_dep_path).context("failed to create .tauri directory")?;
copy_folder(
Path::new(&tauri_library_path),
&tauri_dep_path.join("tauri-api"),
&[".build", "Package.resolved", "Tests"],
)
.context("failed to copy tauri-api to the plugin project")?;
tauri_utils::build::link_apple_library(
&std::env::var("CARGO_PKG_NAME").unwrap(),
manifest_dir.join(path),
);
}
}
_ => (),
}
Ok(())
}
fn copy_folder(source: &Path, target: &Path, ignore_paths: &[&str]) -> Result<()> {
let _ = remove_dir_all(target);
for entry in walkdir::WalkDir::new(source) {
let entry = entry?;
let rel_path = entry.path().strip_prefix(source)?;
let rel_path_str = rel_path.to_string_lossy();
if ignore_paths
.iter()
.any(|path| rel_path_str.starts_with(path))
{
continue;
}
let dest_path = target.join(rel_path);
if entry.file_type().is_dir() {
create_dir(&dest_path)
.with_context(|| format!("failed to create directory {}", dest_path.display()))?;
} else {
copy(entry.path(), &dest_path).with_context(|| {
format!(
"failed to copy {} to {}",
entry.path().display(),
dest_path.display()
)
})?;
println!("cargo:rerun-if-changed={}", entry.path().display());
}
}
Ok(())
}
#[cfg(target_os = "macos")]
fn update_plist_file<P: AsRef<Path>, F: FnOnce(&mut plist::Dictionary)>(
path: P,
f: F,
) -> Result<()> {
use std::io::Cursor;
let path = path.as_ref();
if path.exists() {
let plist_str = read_to_string(path)?;
let mut plist = plist::Value::from_reader(Cursor::new(&plist_str))?;
if let Some(dict) = plist.as_dictionary_mut() {
f(dict);
let mut plist_buf = Vec::new();
let writer = Cursor::new(&mut plist_buf);
plist::to_writer_xml(writer, &plist)?;
let new_plist_str = String::from_utf8(plist_buf)?;
if new_plist_str != plist_str {
write(path, new_plist_str)?;
}
}
}
Ok(())
}
fn xml_block_comment(id: &str) -> String {
format!("<!-- {id}. AUTO-GENERATED. DO NOT REMOVE. -->")
}
fn insert_into_xml(xml: &str, block_identifier: &str, parent_tag: &str, contents: &str) -> String {
let block_comment = xml_block_comment(block_identifier);
let mut rewritten = Vec::new();
let mut found_block = false;
let parent_closing_tag = format!("</{parent_tag}>");
for line in xml.split('\n') {
if line.contains(&block_comment) {
found_block = !found_block;
continue;
}
// found previous block which should be removed
if found_block {
continue;
}
if let Some(index) = line.find(&parent_closing_tag) {
let indentation = " ".repeat(index + 4);
rewritten.push(format!("{indentation}{block_comment}"));
for l in contents.split('\n') {
rewritten.push(format!("{indentation}{l}"));
}
rewritten.push(format!("{indentation}{block_comment}"));
}
rewritten.push(line.to_string());
}
rewritten.join("\n")
}
#[cfg(test)]
mod tests {
#[test]
fn insert_into_xml() {
let manifest = r#"<manifest>
<application>
<intent-filter>
</intent-filter>
</application>
</manifest>"#;
let id = "tauritest";
let new = super::insert_into_xml(manifest, id, "application", "<something></something>");
let block_id_comment = super::xml_block_comment(id);
let expected = format!(
r#"<manifest>
<application>
<intent-filter>
</intent-filter>
{block_id_comment}
<something></something>
{block_id_comment}
</application>
</manifest>"#
);
assert_eq!(new, expected);
// assert it's still the same after an empty update
let new = super::insert_into_xml(&expected, id, "application", "<something></something>");
assert_eq!(new, expected);
}
}
| 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-plugin/src/build/mod.rs | crates/tauri-plugin/src/build/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{
collections::BTreeMap,
path::{Path, PathBuf},
};
use anyhow::Result;
use tauri_utils::acl::{self, Error};
pub mod mobile;
use serde::de::DeserializeOwned;
use std::{env, io::Cursor};
const RESERVED_PLUGIN_NAMES: &[&str] = &["core", "tauri"];
pub fn plugin_config<T: DeserializeOwned>(name: &str) -> Option<T> {
let config_env_var_name = format!(
"TAURI_{}_PLUGIN_CONFIG",
name.to_uppercase().replace('-', "_")
);
if let Ok(config_str) = env::var(&config_env_var_name) {
println!("cargo:rerun-if-env-changed={config_env_var_name}");
serde_json::from_reader(Cursor::new(config_str))
.map(Some)
.expect("failed to parse configuration")
} else {
None
}
}
pub struct Builder<'a> {
commands: &'a [&'static str],
global_scope_schema: Option<schemars::schema::RootSchema>,
global_api_script_path: Option<PathBuf>,
android_path: Option<PathBuf>,
ios_path: Option<PathBuf>,
}
impl<'a> Builder<'a> {
pub fn new(commands: &'a [&'static str]) -> Self {
Self {
commands,
global_scope_schema: None,
global_api_script_path: None,
android_path: None,
ios_path: None,
}
}
/// Sets the global scope JSON schema.
pub fn global_scope_schema(mut self, schema: schemars::schema::RootSchema) -> Self {
self.global_scope_schema.replace(schema);
self
}
/// Sets the path to the script that is injected in the webview when the `withGlobalTauri` configuration is set to true.
///
/// This is usually an IIFE that injects the plugin API JavaScript bindings to `window.__TAURI__`.
pub fn global_api_script_path<P: Into<PathBuf>>(mut self, path: P) -> Self {
self.global_api_script_path.replace(path.into());
self
}
/// Sets the Android project path.
pub fn android_path<P: Into<PathBuf>>(mut self, android_path: P) -> Self {
self.android_path.replace(android_path.into());
self
}
/// Sets the iOS project path.
pub fn ios_path<P: Into<PathBuf>>(mut self, ios_path: P) -> Self {
self.ios_path.replace(ios_path.into());
self
}
/// [`Self::try_build`] but will exit automatically if an error is found.
pub fn build(self) {
if let Err(error) = self.try_build() {
println!("{}: {error:#}", env!("CARGO_PKG_NAME"));
std::process::exit(1);
}
}
/// Ensure this crate is properly configured to be a Tauri plugin.
///
/// # Errors
///
/// Errors will occur if environmental variables expected to be set inside of [build scripts]
/// are not found, or if the crate violates Tauri plugin conventions.
pub fn try_build(self) -> Result<()> {
// convention: plugin names should not use underscores
let name = build_var("CARGO_PKG_NAME")?;
if name.contains('_') {
anyhow::bail!("plugin names cannot contain underscores");
}
if RESERVED_PLUGIN_NAMES.contains(&name.as_str()) {
anyhow::bail!("plugin name `{name}` is reserved");
}
let out_dir = PathBuf::from(build_var("OUT_DIR")?);
// requirement: links MUST be set and MUST match the name
let _links = std::env::var("CARGO_MANIFEST_LINKS").map_err(|_| Error::LinksMissing)?;
let autogenerated = Path::new("permissions").join(acl::build::AUTOGENERATED_FOLDER_NAME);
std::fs::create_dir_all(&autogenerated).expect("unable to create permissions dir");
let commands_dir = autogenerated.join("commands");
if !self.commands.is_empty() {
acl::build::autogenerate_command_permissions(&commands_dir, self.commands, "", true);
}
println!("cargo:rerun-if-changed=permissions");
let permissions =
acl::build::define_permissions("./permissions/**/*.*", &name, &out_dir, |_| true)?;
if permissions.is_empty() {
let _ = std::fs::remove_file(format!(
"./permissions/{}/{}",
acl::PERMISSION_SCHEMAS_FOLDER_NAME,
acl::PERMISSION_SCHEMA_FILE_NAME
));
let _ = std::fs::remove_file(autogenerated.join(acl::build::PERMISSION_DOCS_FILE_NAME));
} else {
acl::schema::generate_permissions_schema(&permissions, "./permissions")?;
acl::build::generate_docs(
&permissions,
&autogenerated,
name.strip_prefix("tauri-plugin-").unwrap_or(&name),
)?;
}
let mut permissions_map = BTreeMap::new();
permissions_map.insert(name.clone(), permissions);
tauri_utils::acl::build::generate_allowed_commands(&out_dir, None, permissions_map)?;
if let Some(global_scope_schema) = self.global_scope_schema {
acl::build::define_global_scope_schema(global_scope_schema, &name, &out_dir)?;
}
if let Some(path) = self.global_api_script_path {
tauri_utils::plugin::define_global_api_script_path(&path);
}
mobile::setup(self.android_path, self.ios_path)?;
Ok(())
}
}
fn cfg_alias(alias: &str, has_feature: bool) {
println!("cargo:rustc-check-cfg=cfg({alias})");
if has_feature {
println!("cargo:rustc-cfg={alias}");
}
}
/// Grab an env var that is expected to be set inside of build scripts.
fn build_var(key: &'static str) -> Result<String, Error> {
std::env::var(key).map_err(|_| Error::BuildVar(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-driver/src/cli.rs | crates/tauri-driver/src/cli.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::path::PathBuf;
const HELP: &str = "\
USAGE: tauri-driver [FLAGS] [OPTIONS]
FLAGS:
-h, --help Prints help information
OPTIONS:
--port NUMBER Sets the tauri-driver intermediary port
--native-port NUMBER Sets the port of the underlying WebDriver
--native-host HOST Sets the host of the underlying WebDriver (Linux only)
--native-driver PATH Sets the path to the native WebDriver binary
";
#[derive(Debug, Clone)]
pub struct Args {
pub port: u16,
pub native_port: u16,
pub native_host: String,
pub native_driver: Option<PathBuf>,
}
impl From<pico_args::Arguments> for Args {
fn from(mut args: pico_args::Arguments) -> Self {
// if the user wanted help, we don't care about parsing the rest of the args
if args.contains(["-h", "--help"]) {
println!("{HELP}");
std::process::exit(0);
}
let native_driver = match args.opt_value_from_str("--native-driver") {
Ok(native_driver) => native_driver,
Err(e) => {
eprintln!("Error while parsing option --native-driver: {e}");
std::process::exit(1);
}
};
let parsed = Args {
port: args.value_from_str("--port").unwrap_or(4444),
native_port: args.value_from_str("--native-port").unwrap_or(4445),
native_host: args
.value_from_str("--native-host")
.unwrap_or(String::from("127.0.0.1")),
native_driver,
};
// be strict about accepting args, error for anything extraneous
let rest = args.finish();
if !rest.is_empty() {
eprintln!("Error: unused arguments left: {rest:?}");
eprintln!("{HELP}");
std::process::exit(1);
}
parsed
}
}
| 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-driver/src/webdriver.rs | crates/tauri-driver/src/webdriver.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::cli::Args;
use std::{env::current_dir, process::Command};
// the name of the binary to find in $PATH
#[cfg(target_os = "linux")]
const DRIVER_BINARY: &str = "WebKitWebDriver";
#[cfg(target_os = "windows")]
const DRIVER_BINARY: &str = "msedgedriver.exe";
/// Find the native driver binary in the PATH, or exits the process with an error.
pub fn native(args: &Args) -> Command {
let native_binary = match args.native_driver.as_deref() {
Some(custom) => {
if custom.exists() {
custom.to_owned()
} else {
eprintln!(
"can not find the supplied binary path {}. This is currently required.",
custom.display()
);
match current_dir() {
Ok(cwd) => eprintln!("current working directory: {}", cwd.display()),
Err(error) => eprintln!("can not find current working directory: {error}"),
}
std::process::exit(1);
}
}
None => match which::which(DRIVER_BINARY) {
Ok(binary) => binary,
Err(error) => {
eprintln!(
"can not find binary {DRIVER_BINARY} in the PATH. This is currently required.\
You can also pass a custom path with --native-driver"
);
eprintln!("{error:?}");
std::process::exit(1);
}
},
};
let mut cmd = Command::new(native_binary);
cmd.env("TAURI_AUTOMATION", "true"); // 1.x
cmd.env("TAURI_WEBVIEW_AUTOMATION", "true"); // 2.x
cmd.arg(format!("--port={}", args.native_port));
cmd.arg(format!("--host={}", args.native_host));
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-driver/src/server.rs | crates/tauri-driver/src/server.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::cli::Args;
use anyhow::Error;
use futures_util::TryFutureExt;
use http_body_util::{BodyExt, Full};
use hyper::{
body::{Bytes, Incoming},
header::CONTENT_LENGTH,
http::uri::Authority,
service::service_fn,
Method, Request, Response,
};
use hyper_util::{
client::legacy::{connect::HttpConnector, Client},
rt::{TokioExecutor, TokioIo},
server::conn::auto,
};
use serde::Deserialize;
use serde_json::{json, Map, Value};
use std::path::PathBuf;
use std::process::Child;
use tokio::net::TcpListener;
const TAURI_OPTIONS: &str = "tauri:options";
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct TauriOptions {
application: PathBuf,
#[serde(default)]
args: Vec<String>,
#[cfg(target_os = "windows")]
#[serde(default)]
webview_options: Option<Value>,
}
impl TauriOptions {
#[cfg(target_os = "linux")]
fn into_native_object(self) -> Map<String, Value> {
let mut map = Map::new();
map.insert(
"webkitgtk:browserOptions".into(),
json!({"binary": self.application, "args": self.args}),
);
map
}
#[cfg(target_os = "windows")]
fn into_native_object(self) -> Map<String, Value> {
let mut ms_edge_options = Map::new();
ms_edge_options.insert(
"binary".into(),
json!(self.application.with_extension("exe")),
);
ms_edge_options.insert("args".into(), self.args.into());
if let Some(webview_options) = self.webview_options {
ms_edge_options.insert("webviewOptions".into(), webview_options);
}
let mut map = Map::new();
map.insert("ms:edgeChromium".into(), json!(true));
map.insert("browserName".into(), json!("webview2"));
map.insert("ms:edgeOptions".into(), ms_edge_options.into());
map
}
}
async fn handle(
client: Client<HttpConnector, Full<Bytes>>,
req: Request<Incoming>,
args: Args,
) -> Result<Response<Incoming>, Error> {
// manipulate a new session to convert options to the native driver format
let new_req: Request<Full<Bytes>> =
if let (&Method::POST, "/session") = (req.method(), req.uri().path()) {
let (mut parts, body) = req.into_parts();
// get the body from the future stream and parse it as json
let body = body.collect().await?.to_bytes().to_vec();
let json: Value = serde_json::from_slice(&body)?;
// manipulate the json to convert from tauri option to native driver options
let json = map_capabilities(json);
// serialize json and update the content-length header to be accurate
let bytes = serde_json::to_vec(&json)?;
parts.headers.insert(CONTENT_LENGTH, bytes.len().into());
Request::from_parts(parts, Full::new(bytes.into()))
} else {
let (parts, body) = req.into_parts();
let body = body.collect().await?.to_bytes().to_vec();
Request::from_parts(parts, Full::new(body.into()))
};
client
.request(forward_to_native_driver(new_req, args)?)
.err_into()
.await
}
/// Transform the request to a request for the native webdriver server.
fn forward_to_native_driver(
mut req: Request<Full<Bytes>>,
args: Args,
) -> Result<Request<Full<Bytes>>, Error> {
let host: Authority = {
let headers = req.headers_mut();
headers.remove("host").expect("hyper request has host")
}
.to_str()?
.parse()?;
let path = req
.uri()
.path_and_query()
.expect("hyper request has uri")
.clone();
let uri = format!(
"http://{}:{}{}",
host.host(),
args.native_port,
path.as_str()
);
let (mut parts, body) = req.into_parts();
parts.uri = uri.parse()?;
Ok(Request::from_parts(parts, body))
}
/// only happy path for now, no errors
fn map_capabilities(mut json: Value) -> Value {
let mut native = None;
if let Some(capabilities) = json.get_mut("capabilities") {
if let Some(always_match) = capabilities.get_mut("alwaysMatch") {
if let Some(always_match) = always_match.as_object_mut() {
if let Some(tauri_options) = always_match.remove(TAURI_OPTIONS) {
if let Ok(options) = serde_json::from_value::<TauriOptions>(tauri_options) {
native = Some(options.into_native_object());
}
}
if let Some(native) = native.clone() {
always_match.extend(native);
}
}
}
}
if let Some(native) = native {
if let Some(desired) = json.get_mut("desiredCapabilities") {
if let Some(desired) = desired.as_object_mut() {
desired.remove(TAURI_OPTIONS);
desired.extend(native);
}
}
}
json
}
#[tokio::main(flavor = "current_thread")]
pub async fn run(args: Args, mut _driver: Child) -> Result<(), Error> {
#[cfg(unix)]
let (signals_handle, signals_task) = {
use futures_util::StreamExt;
use signal_hook::consts::signal::*;
let signals = signal_hook_tokio::Signals::new([SIGTERM, SIGINT, SIGQUIT])?;
let signals_handle = signals.handle();
let signals_task = tokio::spawn(async move {
let mut signals = signals.fuse();
#[allow(clippy::never_loop)]
while let Some(signal) = signals.next().await {
match signal {
SIGTERM | SIGINT | SIGQUIT => {
_driver
.kill()
.expect("unable to kill native webdriver server");
std::process::exit(0);
}
_ => unreachable!(),
}
}
});
(signals_handle, signals_task)
};
let address = std::net::SocketAddr::from(([127, 0, 0, 1], args.port));
// the client we use to proxy requests to the native webdriver
let client = Client::builder(TokioExecutor::new())
.http1_preserve_header_case(true)
.http1_title_case_headers(true)
.retry_canceled_requests(false)
.build_http();
// set up a http1 server that uses the service we just created
let srv = async move {
if let Ok(listener) = TcpListener::bind(address).await {
loop {
let client = client.clone();
let args = args.clone();
if let Ok((stream, _)) = listener.accept().await {
let io = TokioIo::new(stream);
tokio::task::spawn(async move {
if let Err(err) = auto::Builder::new(TokioExecutor::new())
.http1()
.title_case_headers(true)
.preserve_header_case(true)
.serve_connection(
io,
service_fn(|request| handle(client.clone(), request, args.clone())),
)
.await
{
println!("Error serving connection: {err:?}");
}
});
} else {
println!("accept new stream fail, ignore here");
}
}
} else {
println!("can not listen to address: {address:?}");
}
};
srv.await;
#[cfg(unix)]
{
signals_handle.close();
signals_task.await?;
}
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-driver/src/main.rs | crates/tauri-driver/src/main.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Cross-platform WebDriver server for Tauri applications.
//!
//! This is a [WebDriver Intermediary Node](https://www.w3.org/TR/webdriver/#dfn-intermediary-nodes) that wraps the native WebDriver server for platforms that [Tauri](https://github.com/tauri-apps/tauri) supports. Your WebDriver client will connect to the running `tauri-driver` server, and `tauri-driver` will handle starting the native WebDriver server for you behind the scenes. It requires two separate ports to be used since two distinct [WebDriver Remote Ends](https://www.w3.org/TR/webdriver/#dfn-remote-ends) run.
#![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"
)]
#[cfg(any(target_os = "linux", windows))]
mod cli;
#[cfg(any(target_os = "linux", windows))]
mod server;
#[cfg(any(target_os = "linux", windows))]
mod webdriver;
#[cfg(not(any(target_os = "linux", windows)))]
fn main() {
println!("tauri-driver is not supported on this platform");
std::process::exit(1);
}
#[cfg(any(target_os = "linux", windows))]
fn main() {
let args = pico_args::Arguments::from_env().into();
#[cfg(windows)]
let _job_handle = {
let job = win32job::Job::create().unwrap();
let mut info = job.query_extended_limit_info().unwrap();
info.limit_kill_on_job_close();
job.set_extended_limit_info(&info).unwrap();
job.assign_current_process().unwrap();
job
};
// start the native webdriver on the port specified in args
let mut driver = webdriver::native(&args);
let driver = driver
.spawn()
.expect("error while running native webdriver");
// start our webdriver intermediary node
if let Err(e) = server::run(args, driver) {
eprintln!("error while running server: {e}");
std::process::exit(1);
}
}
| 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-runtime-wry/build.rs | crates/tauri-runtime-wry/build.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
// 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 target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
let mobile = target_os == "ios" || target_os == "android";
alias("desktop", !mobile);
alias("mobile", mobile);
}
| 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-runtime-wry/src/lib.rs | crates/tauri-runtime-wry/src/lib.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! The [`wry`] Tauri [`Runtime`].
//!
//! None of the exposed API of this crate is stable, and it may break semver
//! compatibility in the future. The major version only signifies the intended Tauri version.
#![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 self::monitor::MonitorExt;
use http::Request;
#[cfg(target_os = "macos")]
use objc2::ClassType;
use raw_window_handle::{DisplayHandle, HasDisplayHandle, HasWindowHandle};
#[cfg(windows)]
use tauri_runtime::webview::ScrollBarStyle;
use tauri_runtime::{
dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize, Position, Size},
monitor::Monitor,
webview::{DetachedWebview, DownloadEvent, PendingWebview, WebviewIpcHandler},
window::{
CursorIcon, DetachedWindow, DetachedWindowWebview, DragDropEvent, PendingWindow, RawWindow,
WebviewEvent, WindowBuilder, WindowBuilderBase, WindowEvent, WindowId, WindowSizeConstraints,
},
Cookie, DeviceEventFilter, Error, EventLoopProxy, ExitRequestedEventAction, Icon,
ProgressBarState, ProgressBarStatus, Result, RunEvent, Runtime, RuntimeHandle, RuntimeInitArgs,
UserAttentionType, UserEvent, WebviewDispatch, WebviewEventId, WindowDispatch, WindowEventId,
};
#[cfg(target_vendor = "apple")]
use objc2::rc::Retained;
#[cfg(target_os = "macos")]
use tao::platform::macos::{EventLoopWindowTargetExtMacOS, WindowBuilderExtMacOS};
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
use tao::platform::unix::{WindowBuilderExtUnix, WindowExtUnix};
#[cfg(windows)]
use tao::platform::windows::{WindowBuilderExtWindows, WindowExtWindows};
#[cfg(windows)]
use webview2_com::{ContainsFullScreenElementChangedEventHandler, FocusChangedEventHandler};
#[cfg(windows)]
use windows::Win32::Foundation::HWND;
#[cfg(target_os = "ios")]
use wry::WebViewBuilderExtIos;
#[cfg(target_os = "macos")]
use wry::WebViewBuilderExtMacos;
#[cfg(windows)]
use wry::WebViewBuilderExtWindows;
#[cfg(target_vendor = "apple")]
use wry::{WebViewBuilderExtDarwin, WebViewExtDarwin};
use tao::{
dpi::{
LogicalPosition as TaoLogicalPosition, LogicalSize as TaoLogicalSize,
PhysicalPosition as TaoPhysicalPosition, PhysicalSize as TaoPhysicalSize,
Position as TaoPosition, Size as TaoSize,
},
event::{Event, StartCause, WindowEvent as TaoWindowEvent},
event_loop::{
ControlFlow, DeviceEventFilter as TaoDeviceEventFilter, EventLoop, EventLoopBuilder,
EventLoopProxy as TaoEventLoopProxy, EventLoopWindowTarget,
},
monitor::MonitorHandle,
window::{
CursorIcon as TaoCursorIcon, Fullscreen, Icon as TaoWindowIcon,
ProgressBarState as TaoProgressBarState, ProgressState as TaoProgressState, Theme as TaoTheme,
UserAttentionType as TaoUserAttentionType,
},
};
#[cfg(desktop)]
use tauri_utils::config::PreventOverflowConfig;
#[cfg(target_os = "macos")]
use tauri_utils::TitleBarStyle;
use tauri_utils::{
config::{Color, WindowConfig},
Theme,
};
use url::Url;
#[cfg(windows)]
use wry::ScrollBarStyle as WryScrollBarStyle;
use wry::{
DragDropEvent as WryDragDropEvent, ProxyConfig, ProxyEndpoint, WebContext as WryWebContext,
WebView, WebViewBuilder,
};
pub use tao;
pub use tao::window::{Window, WindowBuilder as TaoWindowBuilder, WindowId as TaoWindowId};
pub use wry;
pub use wry::webview_version;
#[cfg(windows)]
use wry::WebViewExtWindows;
#[cfg(target_os = "android")]
use wry::{
prelude::{dispatch, find_class},
WebViewBuilderExtAndroid, WebViewExtAndroid,
};
#[cfg(not(any(
target_os = "windows",
target_os = "macos",
target_os = "ios",
target_os = "android"
)))]
use wry::{WebViewBuilderExtUnix, WebViewExtUnix};
#[cfg(target_os = "ios")]
pub use tao::platform::ios::WindowExtIOS;
#[cfg(target_os = "macos")]
pub use tao::platform::macos::{
ActivationPolicy as TaoActivationPolicy, EventLoopExtMacOS, WindowExtMacOS,
};
#[cfg(target_os = "macos")]
use tauri_runtime::ActivationPolicy;
use std::{
cell::RefCell,
collections::{
hash_map::Entry::{Occupied, Vacant},
BTreeMap, HashMap, HashSet,
},
fmt,
ops::Deref,
path::PathBuf,
rc::Rc,
sync::{
atomic::{AtomicBool, AtomicU32, Ordering},
mpsc::{channel, Sender},
Arc, Mutex, Weak,
},
thread::{current as current_thread, ThreadId},
};
pub type WebviewId = u32;
type IpcHandler = dyn Fn(Request<String>) + 'static;
#[cfg(not(debug_assertions))]
mod dialog;
mod monitor;
#[cfg(any(
windows,
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
mod undecorated_resizing;
mod util;
mod webview;
mod window;
pub use webview::Webview;
use window::WindowExt as _;
#[derive(Debug)]
pub struct WebContext {
pub inner: WryWebContext,
pub referenced_by_webviews: HashSet<String>,
// on Linux the custom protocols are associated with the context
// and you cannot register a URI scheme more than once
pub registered_custom_protocols: HashSet<String>,
}
pub type WebContextStore = Arc<Mutex<HashMap<Option<PathBuf>, WebContext>>>;
// window
pub type WindowEventHandler = Box<dyn Fn(&WindowEvent) + Send>;
pub type WindowEventListeners = Arc<Mutex<HashMap<WindowEventId, WindowEventHandler>>>;
pub type WebviewEventHandler = Box<dyn Fn(&WebviewEvent) + Send>;
pub type WebviewEventListeners = Arc<Mutex<HashMap<WebviewEventId, WebviewEventHandler>>>;
#[derive(Debug, Clone, Default)]
pub struct WindowIdStore(Arc<Mutex<HashMap<TaoWindowId, WindowId>>>);
impl WindowIdStore {
pub fn insert(&self, w: TaoWindowId, id: WindowId) {
self.0.lock().unwrap().insert(w, id);
}
pub fn get(&self, w: &TaoWindowId) -> Option<WindowId> {
self.0.lock().unwrap().get(w).copied()
}
}
#[macro_export]
macro_rules! getter {
($self: ident, $rx: expr, $message: expr) => {{
$crate::send_user_message(&$self.context, $message)?;
$rx
.recv()
.map_err(|_| $crate::Error::FailedToReceiveMessage)
}};
}
macro_rules! window_getter {
($self: ident, $message: expr) => {{
let (tx, rx) = channel();
getter!($self, rx, Message::Window($self.window_id, $message(tx)))
}};
}
macro_rules! event_loop_window_getter {
($self: ident, $message: expr) => {{
let (tx, rx) = channel();
getter!($self, rx, Message::EventLoopWindowTarget($message(tx)))
}};
}
macro_rules! webview_getter {
($self: ident, $message: expr) => {{
let (tx, rx) = channel();
getter!(
$self,
rx,
Message::Webview(
*$self.window_id.lock().unwrap(),
$self.webview_id,
$message(tx)
)
)
}};
}
pub(crate) fn send_user_message<T: UserEvent>(
context: &Context<T>,
message: Message<T>,
) -> Result<()> {
if current_thread().id() == context.main_thread_id {
handle_user_message(
&context.main_thread.window_target,
message,
UserMessageContext {
window_id_map: context.window_id_map.clone(),
windows: context.main_thread.windows.clone(),
},
);
Ok(())
} else {
context
.proxy
.send_event(message)
.map_err(|_| Error::FailedToSendMessage)
}
}
#[derive(Clone)]
pub struct Context<T: UserEvent> {
pub window_id_map: WindowIdStore,
main_thread_id: ThreadId,
pub proxy: TaoEventLoopProxy<Message<T>>,
main_thread: DispatcherMainThreadContext<T>,
plugins: Arc<Mutex<Vec<Box<dyn Plugin<T> + Send>>>>,
next_window_id: Arc<AtomicU32>,
next_webview_id: Arc<AtomicU32>,
next_window_event_id: Arc<AtomicU32>,
next_webview_event_id: Arc<AtomicU32>,
webview_runtime_installed: bool,
}
impl<T: UserEvent> Context<T> {
pub fn run_threaded<R, F>(&self, f: F) -> R
where
F: FnOnce(Option<&DispatcherMainThreadContext<T>>) -> R,
{
f(if current_thread().id() == self.main_thread_id {
Some(&self.main_thread)
} else {
None
})
}
fn next_window_id(&self) -> WindowId {
self.next_window_id.fetch_add(1, Ordering::Relaxed).into()
}
fn next_webview_id(&self) -> WebviewId {
self.next_webview_id.fetch_add(1, Ordering::Relaxed)
}
fn next_window_event_id(&self) -> u32 {
self.next_window_event_id.fetch_add(1, Ordering::Relaxed)
}
fn next_webview_event_id(&self) -> u32 {
self.next_webview_event_id.fetch_add(1, Ordering::Relaxed)
}
}
impl<T: UserEvent> Context<T> {
fn create_window<F: Fn(RawWindow) + Send + 'static>(
&self,
pending: PendingWindow<T, Wry<T>>,
after_window_creation: Option<F>,
) -> Result<DetachedWindow<T, Wry<T>>> {
let label = pending.label.clone();
let context = self.clone();
let window_id = self.next_window_id();
let (webview_id, use_https_scheme) = pending
.webview
.as_ref()
.map(|w| {
(
Some(context.next_webview_id()),
w.webview_attributes.use_https_scheme,
)
})
.unwrap_or((None, false));
send_user_message(
self,
Message::CreateWindow(
window_id,
Box::new(move |event_loop| {
create_window(
window_id,
webview_id.unwrap_or_default(),
event_loop,
&context,
pending,
after_window_creation,
)
}),
),
)?;
let dispatcher = WryWindowDispatcher {
window_id,
context: self.clone(),
};
let detached_webview = webview_id.map(|id| {
let webview = DetachedWebview {
label: label.clone(),
dispatcher: WryWebviewDispatcher {
window_id: Arc::new(Mutex::new(window_id)),
webview_id: id,
context: self.clone(),
},
};
DetachedWindowWebview {
webview,
use_https_scheme,
}
});
Ok(DetachedWindow {
id: window_id,
label,
dispatcher,
webview: detached_webview,
})
}
fn create_webview(
&self,
window_id: WindowId,
pending: PendingWebview<T, Wry<T>>,
) -> Result<DetachedWebview<T, Wry<T>>> {
let label = pending.label.clone();
let context = self.clone();
let webview_id = self.next_webview_id();
let window_id_wrapper = Arc::new(Mutex::new(window_id));
let window_id_wrapper_ = window_id_wrapper.clone();
send_user_message(
self,
Message::CreateWebview(
window_id,
Box::new(move |window, options| {
create_webview(
WebviewKind::WindowChild,
window,
window_id_wrapper_,
webview_id,
&context,
pending,
options.focused_webview,
)
}),
),
)?;
let dispatcher = WryWebviewDispatcher {
window_id: window_id_wrapper,
webview_id,
context: self.clone(),
};
Ok(DetachedWebview { label, dispatcher })
}
}
#[cfg(feature = "tracing")]
#[derive(Debug, Clone, Default)]
pub struct ActiveTraceSpanStore(Rc<RefCell<Vec<ActiveTracingSpan>>>);
#[cfg(feature = "tracing")]
impl ActiveTraceSpanStore {
pub fn remove_window_draw(&self) {
self
.0
.borrow_mut()
.retain(|t| !matches!(t, ActiveTracingSpan::WindowDraw { id: _, span: _ }));
}
}
#[cfg(feature = "tracing")]
#[derive(Debug)]
pub enum ActiveTracingSpan {
WindowDraw {
id: TaoWindowId,
span: tracing::span::EnteredSpan,
},
}
#[derive(Debug)]
pub struct WindowsStore(pub RefCell<BTreeMap<WindowId, WindowWrapper>>);
// SAFETY: we ensure this type is only used on the main thread.
#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl Send for WindowsStore {}
// SAFETY: we ensure this type is only used on the main thread.
#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl Sync for WindowsStore {}
#[derive(Debug, Clone)]
pub struct DispatcherMainThreadContext<T: UserEvent> {
pub window_target: EventLoopWindowTarget<Message<T>>,
pub web_context: WebContextStore,
// changing this to an Rc will cause frequent app crashes.
pub windows: Arc<WindowsStore>,
#[cfg(feature = "tracing")]
pub active_tracing_spans: ActiveTraceSpanStore,
}
// SAFETY: we ensure this type is only used on the main thread.
#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl<T: UserEvent> Send for DispatcherMainThreadContext<T> {}
// SAFETY: we ensure this type is only used on the main thread.
#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl<T: UserEvent> Sync for DispatcherMainThreadContext<T> {}
impl<T: UserEvent> fmt::Debug for Context<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Context")
.field("main_thread_id", &self.main_thread_id)
.field("proxy", &self.proxy)
.field("main_thread", &self.main_thread)
.finish()
}
}
pub struct DeviceEventFilterWrapper(pub TaoDeviceEventFilter);
impl From<DeviceEventFilter> for DeviceEventFilterWrapper {
fn from(item: DeviceEventFilter) -> Self {
match item {
DeviceEventFilter::Always => Self(TaoDeviceEventFilter::Always),
DeviceEventFilter::Never => Self(TaoDeviceEventFilter::Never),
DeviceEventFilter::Unfocused => Self(TaoDeviceEventFilter::Unfocused),
}
}
}
pub struct RectWrapper(pub wry::Rect);
impl From<tauri_runtime::dpi::Rect> for RectWrapper {
fn from(value: tauri_runtime::dpi::Rect) -> Self {
RectWrapper(wry::Rect {
position: value.position,
size: value.size,
})
}
}
/// Wrapper around a [`tao::window::Icon`] that can be created from an [`Icon`].
pub struct TaoIcon(pub TaoWindowIcon);
impl TryFrom<Icon<'_>> for TaoIcon {
type Error = Error;
fn try_from(icon: Icon<'_>) -> std::result::Result<Self, Self::Error> {
TaoWindowIcon::from_rgba(icon.rgba.to_vec(), icon.width, icon.height)
.map(Self)
.map_err(|e| Error::InvalidIcon(Box::new(e)))
}
}
pub struct WindowEventWrapper(pub Option<WindowEvent>);
impl WindowEventWrapper {
fn map_from_tao(
event: &TaoWindowEvent<'_>,
#[allow(unused_variables)] window: &WindowWrapper,
) -> Self {
let event = match event {
TaoWindowEvent::Resized(size) => WindowEvent::Resized(PhysicalSizeWrapper(*size).into()),
TaoWindowEvent::Moved(position) => {
WindowEvent::Moved(PhysicalPositionWrapper(*position).into())
}
TaoWindowEvent::Destroyed => WindowEvent::Destroyed,
TaoWindowEvent::ScaleFactorChanged {
scale_factor,
new_inner_size,
} => WindowEvent::ScaleFactorChanged {
scale_factor: *scale_factor,
new_inner_size: PhysicalSizeWrapper(**new_inner_size).into(),
},
TaoWindowEvent::Focused(focused) => {
#[cfg(not(windows))]
return Self(Some(WindowEvent::Focused(*focused)));
// on multiwebview mode, if there's no focused webview, it means we're receiving a direct window focus change
// (without receiving a webview focus, such as when clicking the taskbar app icon or using Alt + Tab)
// in this case we must send the focus change event here
#[cfg(windows)]
if window.has_children.load(Ordering::Relaxed) {
const FOCUSED_WEBVIEW_MARKER: &str = "__tauriWindow?";
let mut focused_webview = window.focused_webview.lock().unwrap();
// when we focus a webview and the window was previously focused, we get a blur event here
// so on blur we should only send events if the current focus is owned by the window
if !*focused
&& focused_webview
.as_deref()
.is_some_and(|w| w != FOCUSED_WEBVIEW_MARKER)
{
return Self(None);
}
// reset focused_webview on blur, or set to a dummy value on focus
// (to prevent double focus event when we click a webview after focusing a window)
*focused_webview = (*focused).then(|| FOCUSED_WEBVIEW_MARKER.to_string());
return Self(Some(WindowEvent::Focused(*focused)));
} else {
// when not on multiwebview mode, we handle focus change events on the webview (add_GotFocus and add_LostFocus)
return Self(None);
}
}
TaoWindowEvent::ThemeChanged(theme) => WindowEvent::ThemeChanged(map_theme(theme)),
_ => return Self(None),
};
Self(Some(event))
}
fn parse(window: &WindowWrapper, event: &TaoWindowEvent<'_>) -> Self {
match event {
// resized event from tao doesn't include a reliable size on macOS
// because wry replaces the NSView
TaoWindowEvent::Resized(_) => {
if let Some(w) = &window.inner {
let size = inner_size(
w,
&window.webviews,
window.has_children.load(Ordering::Relaxed),
);
Self(Some(WindowEvent::Resized(PhysicalSizeWrapper(size).into())))
} else {
Self(None)
}
}
e => Self::map_from_tao(e, window),
}
}
}
pub fn map_theme(theme: &TaoTheme) -> Theme {
match theme {
TaoTheme::Light => Theme::Light,
TaoTheme::Dark => Theme::Dark,
_ => Theme::Light,
}
}
#[cfg(target_os = "macos")]
fn tao_activation_policy(activation_policy: ActivationPolicy) -> TaoActivationPolicy {
match activation_policy {
ActivationPolicy::Regular => TaoActivationPolicy::Regular,
ActivationPolicy::Accessory => TaoActivationPolicy::Accessory,
ActivationPolicy::Prohibited => TaoActivationPolicy::Prohibited,
_ => unimplemented!(),
}
}
pub struct MonitorHandleWrapper(pub MonitorHandle);
impl From<MonitorHandleWrapper> for Monitor {
fn from(monitor: MonitorHandleWrapper) -> Monitor {
Self {
name: monitor.0.name(),
position: PhysicalPositionWrapper(monitor.0.position()).into(),
size: PhysicalSizeWrapper(monitor.0.size()).into(),
work_area: monitor.0.work_area(),
scale_factor: monitor.0.scale_factor(),
}
}
}
pub struct PhysicalPositionWrapper<T>(pub TaoPhysicalPosition<T>);
impl<T> From<PhysicalPositionWrapper<T>> for PhysicalPosition<T> {
fn from(position: PhysicalPositionWrapper<T>) -> Self {
Self {
x: position.0.x,
y: position.0.y,
}
}
}
impl<T> From<PhysicalPosition<T>> for PhysicalPositionWrapper<T> {
fn from(position: PhysicalPosition<T>) -> Self {
Self(TaoPhysicalPosition {
x: position.x,
y: position.y,
})
}
}
struct LogicalPositionWrapper<T>(TaoLogicalPosition<T>);
impl<T> From<LogicalPosition<T>> for LogicalPositionWrapper<T> {
fn from(position: LogicalPosition<T>) -> Self {
Self(TaoLogicalPosition {
x: position.x,
y: position.y,
})
}
}
pub struct PhysicalSizeWrapper<T>(pub TaoPhysicalSize<T>);
impl<T> From<PhysicalSizeWrapper<T>> for PhysicalSize<T> {
fn from(size: PhysicalSizeWrapper<T>) -> Self {
Self {
width: size.0.width,
height: size.0.height,
}
}
}
impl<T> From<PhysicalSize<T>> for PhysicalSizeWrapper<T> {
fn from(size: PhysicalSize<T>) -> Self {
Self(TaoPhysicalSize {
width: size.width,
height: size.height,
})
}
}
struct LogicalSizeWrapper<T>(TaoLogicalSize<T>);
impl<T> From<LogicalSize<T>> for LogicalSizeWrapper<T> {
fn from(size: LogicalSize<T>) -> Self {
Self(TaoLogicalSize {
width: size.width,
height: size.height,
})
}
}
pub struct SizeWrapper(pub TaoSize);
impl From<Size> for SizeWrapper {
fn from(size: Size) -> Self {
match size {
Size::Logical(s) => Self(TaoSize::Logical(LogicalSizeWrapper::from(s).0)),
Size::Physical(s) => Self(TaoSize::Physical(PhysicalSizeWrapper::from(s).0)),
}
}
}
pub struct PositionWrapper(pub TaoPosition);
impl From<Position> for PositionWrapper {
fn from(position: Position) -> Self {
match position {
Position::Logical(s) => Self(TaoPosition::Logical(LogicalPositionWrapper::from(s).0)),
Position::Physical(s) => Self(TaoPosition::Physical(PhysicalPositionWrapper::from(s).0)),
}
}
}
#[derive(Debug, Clone)]
pub struct UserAttentionTypeWrapper(pub TaoUserAttentionType);
impl From<UserAttentionType> for UserAttentionTypeWrapper {
fn from(request_type: UserAttentionType) -> Self {
let o = match request_type {
UserAttentionType::Critical => TaoUserAttentionType::Critical,
UserAttentionType::Informational => TaoUserAttentionType::Informational,
};
Self(o)
}
}
#[derive(Debug)]
pub struct CursorIconWrapper(pub TaoCursorIcon);
impl From<CursorIcon> for CursorIconWrapper {
fn from(icon: CursorIcon) -> Self {
use CursorIcon::*;
let i = match icon {
Default => TaoCursorIcon::Default,
Crosshair => TaoCursorIcon::Crosshair,
Hand => TaoCursorIcon::Hand,
Arrow => TaoCursorIcon::Arrow,
Move => TaoCursorIcon::Move,
Text => TaoCursorIcon::Text,
Wait => TaoCursorIcon::Wait,
Help => TaoCursorIcon::Help,
Progress => TaoCursorIcon::Progress,
NotAllowed => TaoCursorIcon::NotAllowed,
ContextMenu => TaoCursorIcon::ContextMenu,
Cell => TaoCursorIcon::Cell,
VerticalText => TaoCursorIcon::VerticalText,
Alias => TaoCursorIcon::Alias,
Copy => TaoCursorIcon::Copy,
NoDrop => TaoCursorIcon::NoDrop,
Grab => TaoCursorIcon::Grab,
Grabbing => TaoCursorIcon::Grabbing,
AllScroll => TaoCursorIcon::AllScroll,
ZoomIn => TaoCursorIcon::ZoomIn,
ZoomOut => TaoCursorIcon::ZoomOut,
EResize => TaoCursorIcon::EResize,
NResize => TaoCursorIcon::NResize,
NeResize => TaoCursorIcon::NeResize,
NwResize => TaoCursorIcon::NwResize,
SResize => TaoCursorIcon::SResize,
SeResize => TaoCursorIcon::SeResize,
SwResize => TaoCursorIcon::SwResize,
WResize => TaoCursorIcon::WResize,
EwResize => TaoCursorIcon::EwResize,
NsResize => TaoCursorIcon::NsResize,
NeswResize => TaoCursorIcon::NeswResize,
NwseResize => TaoCursorIcon::NwseResize,
ColResize => TaoCursorIcon::ColResize,
RowResize => TaoCursorIcon::RowResize,
_ => TaoCursorIcon::Default,
};
Self(i)
}
}
pub struct ProgressStateWrapper(pub TaoProgressState);
impl From<ProgressBarStatus> for ProgressStateWrapper {
fn from(status: ProgressBarStatus) -> Self {
let state = match status {
ProgressBarStatus::None => TaoProgressState::None,
ProgressBarStatus::Normal => TaoProgressState::Normal,
ProgressBarStatus::Indeterminate => TaoProgressState::Indeterminate,
ProgressBarStatus::Paused => TaoProgressState::Paused,
ProgressBarStatus::Error => TaoProgressState::Error,
};
Self(state)
}
}
pub struct ProgressBarStateWrapper(pub TaoProgressBarState);
impl From<ProgressBarState> for ProgressBarStateWrapper {
fn from(progress_state: ProgressBarState) -> Self {
Self(TaoProgressBarState {
progress: progress_state.progress,
state: progress_state
.status
.map(|state| ProgressStateWrapper::from(state).0),
desktop_filename: progress_state.desktop_filename,
})
}
}
#[derive(Clone, Default)]
pub struct WindowBuilderWrapper {
inner: TaoWindowBuilder,
center: bool,
prevent_overflow: Option<Size>,
#[cfg(target_os = "macos")]
tabbing_identifier: Option<String>,
}
impl std::fmt::Debug for WindowBuilderWrapper {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut s = f.debug_struct("WindowBuilderWrapper");
s.field("inner", &self.inner)
.field("center", &self.center)
.field("prevent_overflow", &self.prevent_overflow);
#[cfg(target_os = "macos")]
{
s.field("tabbing_identifier", &self.tabbing_identifier);
}
s.finish()
}
}
// SAFETY: this type is `Send` since `menu_items` are read only here
#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl Send for WindowBuilderWrapper {}
impl WindowBuilderBase for WindowBuilderWrapper {}
impl WindowBuilder for WindowBuilderWrapper {
fn new() -> Self {
#[allow(unused_mut)]
let mut builder = Self::default().focused(true);
#[cfg(target_os = "macos")]
{
// TODO: find a proper way to prevent webview being pushed out of the window.
// Workround for issue: https://github.com/tauri-apps/tauri/issues/10225
// The window requires `NSFullSizeContentViewWindowMask` flag to prevent devtools
// pushing the content view out of the window.
// By setting the default style to `TitleBarStyle::Visible` should fix the issue for most of the users.
builder = builder.title_bar_style(TitleBarStyle::Visible);
}
builder = builder.title("Tauri App");
#[cfg(windows)]
{
builder = builder.window_classname("Tauri Window");
}
builder
}
fn with_config(config: &WindowConfig) -> Self {
let mut window = WindowBuilderWrapper::new();
#[cfg(target_os = "macos")]
{
window = window
.hidden_title(config.hidden_title)
.title_bar_style(config.title_bar_style);
if let Some(identifier) = &config.tabbing_identifier {
window = window.tabbing_identifier(identifier);
}
if let Some(position) = &config.traffic_light_position {
window = window.traffic_light_position(tauri_runtime::dpi::LogicalPosition::new(
position.x, position.y,
));
}
}
#[cfg(any(not(target_os = "macos"), feature = "macos-private-api"))]
{
window = window.transparent(config.transparent);
}
#[cfg(all(
target_os = "macos",
not(feature = "macos-private-api"),
debug_assertions
))]
if config.transparent {
eprintln!(
"The window is set to be transparent but the `macos-private-api` is not enabled.
This can be enabled via the `tauri.macOSPrivateApi` configuration property <https://v2.tauri.app/reference/config/#macosprivateapi>
");
}
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
{
// Mouse event is disabled on Linux since sudden event bursts could block event loop.
window.inner = window.inner.with_cursor_moved_event(false);
}
#[cfg(desktop)]
{
window = window
.title(config.title.to_string())
.inner_size(config.width, config.height)
.focused(config.focus)
.focusable(config.focusable)
.visible(config.visible)
.resizable(config.resizable)
.fullscreen(config.fullscreen)
.decorations(config.decorations)
.maximized(config.maximized)
.always_on_bottom(config.always_on_bottom)
.always_on_top(config.always_on_top)
.visible_on_all_workspaces(config.visible_on_all_workspaces)
.content_protected(config.content_protected)
.skip_taskbar(config.skip_taskbar)
.theme(config.theme)
.closable(config.closable)
.maximizable(config.maximizable)
.minimizable(config.minimizable)
.shadow(config.shadow);
let mut constraints = WindowSizeConstraints::default();
if let Some(min_width) = config.min_width {
constraints.min_width = Some(tao::dpi::LogicalUnit::new(min_width).into());
}
if let Some(min_height) = config.min_height {
constraints.min_height = Some(tao::dpi::LogicalUnit::new(min_height).into());
}
if let Some(max_width) = config.max_width {
constraints.max_width = Some(tao::dpi::LogicalUnit::new(max_width).into());
}
if let Some(max_height) = config.max_height {
constraints.max_height = Some(tao::dpi::LogicalUnit::new(max_height).into());
}
if let Some(color) = config.background_color {
window = window.background_color(color);
}
window = window.inner_size_constraints(constraints);
if let (Some(x), Some(y)) = (config.x, config.y) {
window = window.position(x, y);
}
if config.center {
window = window.center();
}
if let Some(window_classname) = &config.window_classname {
window = window.window_classname(window_classname);
}
if let Some(prevent_overflow) = &config.prevent_overflow {
window = match prevent_overflow {
PreventOverflowConfig::Enable(true) => window.prevent_overflow(),
PreventOverflowConfig::Margin(margin) => window
.prevent_overflow_with_margin(TaoPhysicalSize::new(margin.width, margin.height).into()),
_ => window,
};
}
}
window
}
fn center(mut self) -> Self {
self.center = true;
self
}
fn position(mut self, x: f64, y: f64) -> Self {
self.inner = self.inner.with_position(TaoLogicalPosition::new(x, y));
self
}
fn inner_size(mut self, width: f64, height: f64) -> Self {
self.inner = self
.inner
.with_inner_size(TaoLogicalSize::new(width, height));
self
}
fn min_inner_size(mut self, min_width: f64, min_height: f64) -> Self {
self.inner = self
.inner
.with_min_inner_size(TaoLogicalSize::new(min_width, min_height));
self
}
fn max_inner_size(mut self, max_width: f64, max_height: f64) -> Self {
self.inner = self
.inner
.with_max_inner_size(TaoLogicalSize::new(max_width, max_height));
self
}
fn inner_size_constraints(mut self, constraints: WindowSizeConstraints) -> Self {
self.inner.window.inner_size_constraints = tao::window::WindowSizeConstraints {
min_width: constraints.min_width,
min_height: constraints.min_height,
max_width: constraints.max_width,
max_height: constraints.max_height,
};
self
}
/// Prevent the window from overflowing the working area (e.g. monitor size - taskbar size) on creation
///
/// ## Platform-specific
///
/// - **iOS / Android:** Unsupported.
fn prevent_overflow(mut self) -> Self {
self
.prevent_overflow
.replace(PhysicalSize::new(0, 0).into());
self
}
/// Prevent the window from overflowing the working area (e.g. monitor size - taskbar size)
/// on creation with a margin
///
/// ## Platform-specific
///
/// - **iOS / Android:** Unsupported.
fn prevent_overflow_with_margin(mut self, margin: Size) -> Self {
self.prevent_overflow.replace(margin);
self
}
fn resizable(mut self, resizable: bool) -> Self {
self.inner = self.inner.with_resizable(resizable);
self
}
fn maximizable(mut self, maximizable: bool) -> Self {
self.inner = self.inner.with_maximizable(maximizable);
self
}
fn minimizable(mut self, minimizable: bool) -> Self {
self.inner = self.inner.with_minimizable(minimizable);
self
}
fn closable(mut self, closable: bool) -> Self {
self.inner = self.inner.with_closable(closable);
self
}
fn title<S: Into<String>>(mut self, title: S) -> Self {
self.inner = self.inner.with_title(title.into());
self
}
fn fullscreen(mut self, fullscreen: bool) -> Self {
self.inner = if fullscreen {
self
.inner
.with_fullscreen(Some(Fullscreen::Borderless(None)))
} else {
self.inner.with_fullscreen(None)
};
self
}
fn focused(mut self, focused: bool) -> Self {
self.inner = self.inner.with_focused(focused);
self
}
fn focusable(mut self, focusable: bool) -> Self {
self.inner = self.inner.with_focusable(focusable);
self
}
fn maximized(mut self, maximized: bool) -> Self {
self.inner = self.inner.with_maximized(maximized);
self
}
fn visible(mut self, visible: bool) -> Self {
self.inner = self.inner.with_visible(visible);
self
}
#[cfg(any(not(target_os = "macos"), feature = "macos-private-api"))]
fn transparent(mut self, transparent: bool) -> Self {
self.inner = self.inner.with_transparent(transparent);
self
}
fn decorations(mut self, decorations: bool) -> Self {
self.inner = self.inner.with_decorations(decorations);
self
}
fn always_on_bottom(mut self, always_on_bottom: bool) -> Self {
self.inner = self.inner.with_always_on_bottom(always_on_bottom);
self
}
fn always_on_top(mut self, always_on_top: bool) -> Self {
self.inner = self.inner.with_always_on_top(always_on_top);
self
}
fn visible_on_all_workspaces(mut self, visible_on_all_workspaces: bool) -> Self {
self.inner = self
.inner
.with_visible_on_all_workspaces(visible_on_all_workspaces);
self
}
fn content_protected(mut self, protected: bool) -> Self {
self.inner = self.inner.with_content_protection(protected);
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-runtime-wry/src/util.rs | crates/tauri-runtime-wry/src/util.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
#[cfg_attr(not(windows), allow(unused_imports))]
pub use imp::*;
#[cfg(not(windows))]
mod imp {}
#[cfg(windows)]
mod imp {
use std::{iter::once, os::windows::ffi::OsStrExt};
use once_cell::sync::Lazy;
use windows::{
core::{HRESULT, PCSTR, PCWSTR},
Win32::{
Foundation::*,
Graphics::Gdi::*,
System::LibraryLoader::{GetProcAddress, LoadLibraryW},
UI::{HiDpi::*, WindowsAndMessaging::*},
},
};
pub fn encode_wide(string: impl AsRef<std::ffi::OsStr>) -> Vec<u16> {
string.as_ref().encode_wide().chain(once(0)).collect()
}
// Helper function to dynamically load function pointer.
// `library` and `function` must be zero-terminated.
pub(super) fn get_function_impl(library: &str, function: &str) -> FARPROC {
let library = encode_wide(library);
assert_eq!(function.chars().last(), Some('\0'));
// Library names we will use are ASCII so we can use the A version to avoid string conversion.
let module = unsafe { LoadLibraryW(PCWSTR::from_raw(library.as_ptr())) }.unwrap_or_default();
if module.is_invalid() {
return None;
}
unsafe { GetProcAddress(module, PCSTR::from_raw(function.as_ptr())) }
}
macro_rules! get_function {
($lib:expr, $func:ident) => {
$crate::util::get_function_impl($lib, concat!(stringify!($func), '\0'))
.map(|f| unsafe { std::mem::transmute::<_, $func>(f) })
};
}
type GetDpiForWindow = unsafe extern "system" fn(hwnd: HWND) -> u32;
type GetDpiForMonitor = unsafe extern "system" fn(
hmonitor: HMONITOR,
dpi_type: MONITOR_DPI_TYPE,
dpi_x: *mut u32,
dpi_y: *mut u32,
) -> HRESULT;
type GetSystemMetricsForDpi =
unsafe extern "system" fn(nindex: SYSTEM_METRICS_INDEX, dpi: u32) -> i32;
static GET_DPI_FOR_WINDOW: Lazy<Option<GetDpiForWindow>> =
Lazy::new(|| get_function!("user32.dll", GetDpiForWindow));
static GET_DPI_FOR_MONITOR: Lazy<Option<GetDpiForMonitor>> =
Lazy::new(|| get_function!("shcore.dll", GetDpiForMonitor));
static GET_SYSTEM_METRICS_FOR_DPI: Lazy<Option<GetSystemMetricsForDpi>> =
Lazy::new(|| get_function!("user32.dll", GetSystemMetricsForDpi));
#[allow(non_snake_case)]
pub unsafe fn hwnd_dpi(hwnd: HWND) -> u32 {
let hdc = GetDC(Some(hwnd));
if hdc.is_invalid() {
return USER_DEFAULT_SCREEN_DPI;
}
if let Some(GetDpiForWindow) = *GET_DPI_FOR_WINDOW {
// We are on Windows 10 Anniversary Update (1607) or later.
match GetDpiForWindow(hwnd) {
0 => USER_DEFAULT_SCREEN_DPI, // 0 is returned if hwnd is invalid
dpi => dpi,
}
} else if let Some(GetDpiForMonitor) = *GET_DPI_FOR_MONITOR {
// We are on Windows 8.1 or later.
let monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
if monitor.is_invalid() {
return USER_DEFAULT_SCREEN_DPI;
}
let mut dpi_x = 0;
let mut dpi_y = 0;
if GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y).is_ok() {
dpi_x
} else {
USER_DEFAULT_SCREEN_DPI
}
} else {
// We are on Vista or later.
if IsProcessDPIAware().as_bool() {
// If the process is DPI aware, then scaling must be handled by the application using
// this DPI value.
GetDeviceCaps(Some(hdc), LOGPIXELSX) as u32
} else {
// If the process is DPI unaware, then scaling is performed by the OS; we thus return
// 96 (scale factor 1.0) to prevent the window from being re-scaled by both the
// application and the WM.
USER_DEFAULT_SCREEN_DPI
}
}
}
#[allow(non_snake_case)]
pub unsafe fn get_system_metrics_for_dpi(nindex: SYSTEM_METRICS_INDEX, dpi: u32) -> i32 {
if let Some(GetSystemMetricsForDpi) = *GET_SYSTEM_METRICS_FOR_DPI {
GetSystemMetricsForDpi(nindex, dpi)
} else {
GetSystemMetrics(nindex)
}
}
}
| 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-runtime-wry/src/undecorated_resizing.rs | crates/tauri-runtime-wry/src/undecorated_resizing.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
#![cfg(any(
windows,
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
const CLIENT: isize = 0b0000;
const LEFT: isize = 0b0001;
const RIGHT: isize = 0b0010;
const TOP: isize = 0b0100;
const BOTTOM: isize = 0b1000;
const TOPLEFT: isize = TOP | LEFT;
const TOPRIGHT: isize = TOP | RIGHT;
const BOTTOMLEFT: isize = BOTTOM | LEFT;
const BOTTOMRIGHT: isize = BOTTOM | RIGHT;
#[cfg(not(windows))]
pub use self::gtk::*;
#[cfg(windows)]
pub use self::windows::*;
#[cfg(windows)]
type WindowPositions = i32;
#[cfg(not(windows))]
type WindowPositions = f64;
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum HitTestResult {
Client,
Left,
Right,
Top,
Bottom,
TopLeft,
TopRight,
BottomLeft,
BottomRight,
NoWhere,
}
#[allow(clippy::too_many_arguments)]
fn hit_test(
left: WindowPositions,
top: WindowPositions,
right: WindowPositions,
bottom: WindowPositions,
cx: WindowPositions,
cy: WindowPositions,
border_x: WindowPositions,
border_y: WindowPositions,
) -> HitTestResult {
#[rustfmt::skip]
let result = (LEFT * (cx < left + border_x) as isize)
| (RIGHT * (cx >= right - border_x) as isize)
| (TOP * (cy < top + border_y) as isize)
| (BOTTOM * (cy >= bottom - border_y) as isize);
match result {
CLIENT => HitTestResult::Client,
LEFT => HitTestResult::Left,
RIGHT => HitTestResult::Right,
TOP => HitTestResult::Top,
BOTTOM => HitTestResult::Bottom,
TOPLEFT => HitTestResult::TopLeft,
TOPRIGHT => HitTestResult::TopRight,
BOTTOMLEFT => HitTestResult::BottomLeft,
BOTTOMRIGHT => HitTestResult::BottomRight,
_ => HitTestResult::NoWhere,
}
}
#[cfg(windows)]
mod windows {
use crate::util;
use super::{hit_test, HitTestResult};
use windows::core::*;
use windows::Win32::System::LibraryLoader::*;
use windows::Win32::UI::WindowsAndMessaging::*;
use windows::Win32::{Foundation::*, UI::Shell::SetWindowSubclass};
use windows::Win32::{Graphics::Gdi::*, UI::Shell::DefSubclassProc};
impl HitTestResult {
fn to_win32(self) -> i32 {
match self {
HitTestResult::Left => HTLEFT as _,
HitTestResult::Right => HTRIGHT as _,
HitTestResult::Top => HTTOP as _,
HitTestResult::Bottom => HTBOTTOM as _,
HitTestResult::TopLeft => HTTOPLEFT as _,
HitTestResult::TopRight => HTTOPRIGHT as _,
HitTestResult::BottomLeft => HTBOTTOMLEFT as _,
HitTestResult::BottomRight => HTBOTTOMRIGHT as _,
_ => HTTRANSPARENT,
}
}
}
const CLASS_NAME: PCWSTR = w!("TAURI_DRAG_RESIZE_BORDERS");
const WINDOW_NAME: PCWSTR = w!("TAURI_DRAG_RESIZE_WINDOW");
const WM_UPDATE_UNDECORATED_SHADOWS: u32 = WM_USER + 100;
struct UndecoratedResizingData {
child: HWND,
has_undecorated_shadows: bool,
}
pub fn attach_resize_handler(hwnd: isize, has_undecorated_shadows: bool) {
let parent = HWND(hwnd as _);
// return early if we already attached
if unsafe { FindWindowExW(Some(parent), None, CLASS_NAME, WINDOW_NAME) }.is_ok() {
return;
}
let class = WNDCLASSEXW {
cbSize: std::mem::size_of::<WNDCLASSEXW>() as u32,
style: WNDCLASS_STYLES::default(),
lpfnWndProc: Some(drag_resize_window_proc),
cbClsExtra: 0,
cbWndExtra: 0,
hInstance: unsafe { HINSTANCE(GetModuleHandleW(PCWSTR::null()).unwrap_or_default().0) },
hIcon: HICON::default(),
hCursor: HCURSOR::default(),
hbrBackground: HBRUSH::default(),
lpszMenuName: PCWSTR::null(),
lpszClassName: CLASS_NAME,
hIconSm: HICON::default(),
};
unsafe { RegisterClassExW(&class) };
let mut rect = RECT::default();
unsafe { GetClientRect(parent, &mut rect).unwrap() };
let width = rect.right - rect.left;
let height = rect.bottom - rect.top;
let data = UndecoratedResizingData {
child: HWND::default(),
has_undecorated_shadows,
};
let Ok(drag_window) = (unsafe {
CreateWindowExW(
WINDOW_EX_STYLE::default(),
CLASS_NAME,
WINDOW_NAME,
WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS,
0,
0,
width,
height,
Some(parent),
None,
GetModuleHandleW(None).ok().map(|h| HINSTANCE(h.0)),
Some(Box::into_raw(Box::new(data)) as _),
)
}) else {
return;
};
unsafe {
set_drag_hwnd_rgn(drag_window, width, height, has_undecorated_shadows);
let _ = SetWindowPos(
drag_window,
Some(HWND_TOP),
0,
0,
0,
0,
SWP_ASYNCWINDOWPOS | SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOSIZE,
);
let data = UndecoratedResizingData {
child: drag_window,
has_undecorated_shadows,
};
let _ = SetWindowSubclass(
parent,
Some(subclass_parent),
(WM_USER + 1) as _,
Box::into_raw(Box::new(data)) as _,
);
}
}
unsafe extern "system" fn subclass_parent(
parent: HWND,
msg: u32,
wparam: WPARAM,
lparam: LPARAM,
_: usize,
data: usize,
) -> LRESULT {
match msg {
WM_SIZE => {
let data = data as *mut UndecoratedResizingData;
let data = &*data;
let child = data.child;
let has_undecorated_shadows = data.has_undecorated_shadows;
// when parent is maximized, remove the undecorated window drag resize region
if is_maximized(parent).unwrap_or(false) {
let _ = SetWindowPos(
child,
Some(HWND_TOP),
0,
0,
0,
0,
SWP_ASYNCWINDOWPOS | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOMOVE,
);
} else {
// otherwise updat the cutout region
let mut rect = RECT::default();
if GetClientRect(parent, &mut rect).is_ok() {
let width = rect.right - rect.left;
let height = rect.bottom - rect.top;
let _ = SetWindowPos(
child,
Some(HWND_TOP),
0,
0,
width,
height,
SWP_ASYNCWINDOWPOS | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOMOVE,
);
set_drag_hwnd_rgn(child, width, height, has_undecorated_shadows);
}
}
}
WM_UPDATE_UNDECORATED_SHADOWS => {
let data = data as *mut UndecoratedResizingData;
let data = &mut *data;
data.has_undecorated_shadows = wparam.0 != 0;
}
WM_NCDESTROY => {
let data = data as *mut UndecoratedResizingData;
drop(Box::from_raw(data));
}
_ => {}
}
DefSubclassProc(parent, msg, wparam, lparam)
}
unsafe extern "system" fn drag_resize_window_proc(
child: HWND,
msg: u32,
wparam: WPARAM,
lparam: LPARAM,
) -> LRESULT {
match msg {
WM_CREATE => {
let data = lparam.0 as *mut CREATESTRUCTW;
let data = (*data).lpCreateParams as *mut UndecoratedResizingData;
(*data).child = child;
SetWindowLongPtrW(child, GWLP_USERDATA, data as _);
}
WM_NCHITTEST => {
let data = GetWindowLongPtrW(child, GWLP_USERDATA);
let data = &*(data as *mut UndecoratedResizingData);
let Ok(parent) = GetParent(child) else {
return DefWindowProcW(child, msg, wparam, lparam);
};
let style = GetWindowLongPtrW(parent, GWL_STYLE);
let style = WINDOW_STYLE(style as u32);
let is_resizable = (style & WS_SIZEBOX).0 != 0;
if !is_resizable {
return DefWindowProcW(child, msg, wparam, lparam);
}
// if the window has undecorated shadows,
// it should always be the top border,
// ensured by the cutout drag window
if data.has_undecorated_shadows {
return LRESULT(HTTOP as _);
}
let mut rect = RECT::default();
if GetWindowRect(child, &mut rect).is_err() {
return DefWindowProcW(child, msg, wparam, lparam);
}
let (cx, cy) = (GET_X_LPARAM(lparam) as i32, GET_Y_LPARAM(lparam) as i32);
let dpi = unsafe { util::hwnd_dpi(child) };
let border_x = util::get_system_metrics_for_dpi(SM_CXFRAME, dpi);
let border_y = util::get_system_metrics_for_dpi(SM_CYFRAME, dpi);
let res = hit_test(
rect.left,
rect.top,
rect.right,
rect.bottom,
cx,
cy,
border_x,
border_y,
);
return LRESULT(res.to_win32() as _);
}
WM_NCLBUTTONDOWN => {
let data = GetWindowLongPtrW(child, GWLP_USERDATA);
let data = &*(data as *mut UndecoratedResizingData);
let Ok(parent) = GetParent(child) else {
return DefWindowProcW(child, msg, wparam, lparam);
};
let style = GetWindowLongPtrW(parent, GWL_STYLE);
let style = WINDOW_STYLE(style as u32);
let is_resizable = (style & WS_SIZEBOX).0 != 0;
if !is_resizable {
return DefWindowProcW(child, msg, wparam, lparam);
}
let (cx, cy) = (GET_X_LPARAM(lparam) as i32, GET_Y_LPARAM(lparam) as i32);
// if the window has undecorated shadows,
// it should always be the top border,
// ensured by the cutout drag window
let res = if data.has_undecorated_shadows {
HitTestResult::Top
} else {
let mut rect = RECT::default();
if GetWindowRect(child, &mut rect).is_err() {
return DefWindowProcW(child, msg, wparam, lparam);
}
let dpi = unsafe { util::hwnd_dpi(child) };
let border_x = util::get_system_metrics_for_dpi(SM_CXFRAME, dpi);
let border_y = util::get_system_metrics_for_dpi(SM_CYFRAME, dpi);
hit_test(
rect.left,
rect.top,
rect.right,
rect.bottom,
cx,
cy,
border_x,
border_y,
)
};
if res != HitTestResult::NoWhere {
let points = POINTS {
x: cx as i16,
y: cy as i16,
};
let _ = PostMessageW(
Some(parent),
WM_NCLBUTTONDOWN,
WPARAM(res.to_win32() as _),
LPARAM(&points as *const _ as _),
);
}
return LRESULT(0);
}
WM_UPDATE_UNDECORATED_SHADOWS => {
let data = GetWindowLongPtrW(child, GWLP_USERDATA);
let data = &mut *(data as *mut UndecoratedResizingData);
data.has_undecorated_shadows = wparam.0 != 0;
}
WM_NCDESTROY => {
let data = GetWindowLongPtrW(child, GWLP_USERDATA);
let data = data as *mut UndecoratedResizingData;
drop(Box::from_raw(data));
}
_ => {}
}
DefWindowProcW(child, msg, wparam, lparam)
}
pub fn detach_resize_handler(hwnd: isize) {
let hwnd = HWND(hwnd as _);
let Ok(child) = (unsafe { FindWindowExW(Some(hwnd), None, CLASS_NAME, WINDOW_NAME) }) else {
return;
};
let _ = unsafe { DestroyWindow(child) };
}
unsafe fn set_drag_hwnd_rgn(hwnd: HWND, width: i32, height: i32, only_top: bool) {
// The window used for drag resizing an undecorated window
// is a child HWND that covers the whole window
// and so we need create a cut out in the middle for the parent and other child
// windows like the webview can receive mouse events.
let dpi = unsafe { util::hwnd_dpi(hwnd) };
let border_x = util::get_system_metrics_for_dpi(SM_CXFRAME, dpi);
let border_y = util::get_system_metrics_for_dpi(SM_CYFRAME, dpi);
// hrgn1 must be mutable to call .free() later
let mut hrgn1 = CreateRectRgn(0, 0, width, height);
let x1 = if only_top { 0 } else { border_x };
let y1 = border_y;
let x2 = if only_top { width } else { width - border_x };
let y2 = if only_top { height } else { height - border_y };
// Wrap hrgn2 in Owned so it is automatically freed when going out of scope
let hrgn2 = Owned::new(CreateRectRgn(x1, y1, x2, y2));
CombineRgn(Some(hrgn1), Some(hrgn1), Some(*hrgn2), RGN_DIFF);
// Try to set the window region
if SetWindowRgn(hwnd, Some(hrgn1), true) == 0 {
// If it fails, we must free hrgn1 manually
hrgn1.free();
}
}
pub fn update_drag_hwnd_rgn_for_undecorated(hwnd: isize, has_undecorated_shadows: bool) {
let hwnd = HWND(hwnd as _);
let mut rect = RECT::default();
let Ok(_) = (unsafe { GetClientRect(hwnd, &mut rect) }) else {
return;
};
let width = rect.right - rect.left;
let height = rect.bottom - rect.top;
let Ok(child) = (unsafe { FindWindowExW(Some(hwnd), None, CLASS_NAME, WINDOW_NAME) }) else {
return;
};
unsafe { set_drag_hwnd_rgn(child, width, height, has_undecorated_shadows) };
unsafe {
SendMessageW(
hwnd,
WM_UPDATE_UNDECORATED_SHADOWS,
None,
Some(LPARAM(has_undecorated_shadows as _)),
)
};
unsafe {
SendMessageW(
child,
WM_UPDATE_UNDECORATED_SHADOWS,
None,
Some(LPARAM(has_undecorated_shadows as _)),
)
};
}
fn is_maximized(window: HWND) -> windows::core::Result<bool> {
let mut placement = WINDOWPLACEMENT {
length: std::mem::size_of::<WINDOWPLACEMENT>() as u32,
..WINDOWPLACEMENT::default()
};
unsafe { GetWindowPlacement(window, &mut placement)? };
Ok(placement.showCmd == SW_MAXIMIZE.0 as u32)
}
/// Implementation of the `GET_X_LPARAM` macro.
#[allow(non_snake_case)]
#[inline]
fn GET_X_LPARAM(lparam: LPARAM) -> i16 {
((lparam.0 as usize) & 0xFFFF) as u16 as i16
}
/// Implementation of the `GET_Y_LPARAM` macro.
#[allow(non_snake_case)]
#[inline]
fn GET_Y_LPARAM(lparam: LPARAM) -> i16 {
(((lparam.0 as usize) & 0xFFFF_0000) >> 16) as u16 as i16
}
}
#[cfg(not(windows))]
mod gtk {
use super::{hit_test, HitTestResult};
const BORDERLESS_RESIZE_INSET: i32 = 5;
impl HitTestResult {
fn to_gtk_edge(self) -> gtk::gdk::WindowEdge {
match self {
HitTestResult::Client | HitTestResult::NoWhere => gtk::gdk::WindowEdge::__Unknown(0),
HitTestResult::Left => gtk::gdk::WindowEdge::West,
HitTestResult::Right => gtk::gdk::WindowEdge::East,
HitTestResult::Top => gtk::gdk::WindowEdge::North,
HitTestResult::Bottom => gtk::gdk::WindowEdge::South,
HitTestResult::TopLeft => gtk::gdk::WindowEdge::NorthWest,
HitTestResult::TopRight => gtk::gdk::WindowEdge::NorthEast,
HitTestResult::BottomLeft => gtk::gdk::WindowEdge::SouthWest,
HitTestResult::BottomRight => gtk::gdk::WindowEdge::SouthEast,
}
}
}
pub fn attach_resize_handler(webview: &wry::WebView) {
use gtk::{
gdk::{prelude::*, WindowEdge},
glib::Propagation,
prelude::*,
};
use wry::WebViewExtUnix;
let webview = webview.webview();
webview.add_events(
gtk::gdk::EventMask::BUTTON1_MOTION_MASK
| gtk::gdk::EventMask::BUTTON_PRESS_MASK
| gtk::gdk::EventMask::TOUCH_MASK,
);
webview.connect_button_press_event(
move |webview: &webkit2gtk::WebView, event: >k::gdk::EventButton| {
if event.button() == 1 {
// This one should be GtkBox
if let Some(window) = webview.parent().and_then(|w| w.parent()) {
// Safe to unwrap unless this is not from tao
let window: gtk::Window = window.downcast().unwrap();
if !window.is_decorated() && window.is_resizable() && !window.is_maximized() {
if let Some(window) = window.window() {
let (root_x, root_y) = event.root();
let (window_x, window_y) = window.position();
let (client_x, client_y) = (root_x - window_x as f64, root_y - window_y as f64);
let border = window.scale_factor() * BORDERLESS_RESIZE_INSET;
let edge = hit_test(
0.0,
0.0,
window.width() as f64,
window.height() as f64,
client_x,
client_y,
border as _,
border as _,
)
.to_gtk_edge();
// we ignore the `__Unknown` variant so the webview receives the click correctly if it is not on the edges.
match edge {
WindowEdge::__Unknown(_) => (),
_ => {
window.begin_resize_drag(edge, 1, root_x as i32, root_y as i32, event.time())
}
}
}
}
}
}
Propagation::Proceed
},
);
webview.connect_touch_event(
move |webview: &webkit2gtk::WebView, event: >k::gdk::Event| {
// This one should be GtkBox
if let Some(window) = webview.parent().and_then(|w| w.parent()) {
// Safe to unwrap unless this is not from tao
let window: gtk::Window = window.downcast().unwrap();
if !window.is_decorated() && window.is_resizable() && !window.is_maximized() {
if let Some(window) = window.window() {
if let Some((root_x, root_y)) = event.root_coords() {
if let Some(device) = event.device() {
let (window_x, window_y) = window.position();
let (client_x, client_y) = (root_x - window_x as f64, root_y - window_y as f64);
let border = window.scale_factor() * BORDERLESS_RESIZE_INSET;
let edge = hit_test(
0.0,
0.0,
window.width() as f64,
window.height() as f64,
client_x,
client_y,
border as _,
border as _,
)
.to_gtk_edge();
// we ignore the `__Unknown` variant so the window receives the click correctly if it is not on the edges.
match edge {
WindowEdge::__Unknown(_) => (),
_ => window.begin_resize_drag_for_device(
edge,
&device,
0,
root_x as i32,
root_y as i32,
event.time(),
),
}
}
}
}
}
}
Propagation::Proceed
},
);
}
}
| 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-runtime-wry/src/webview.rs | crates/tauri-runtime-wry/src/webview.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
mod imp {
pub type Webview = webkit2gtk::WebView;
}
#[cfg(target_vendor = "apple")]
mod imp {
use std::ffi::c_void;
pub struct Webview {
pub webview: *mut c_void,
pub manager: *mut c_void,
#[cfg(target_os = "macos")]
pub ns_window: *mut c_void,
#[cfg(target_os = "ios")]
pub view_controller: *mut c_void,
}
}
#[cfg(windows)]
mod imp {
use webview2_com::Microsoft::Web::WebView2::Win32::{
ICoreWebView2Controller, ICoreWebView2Environment,
};
pub struct Webview {
pub controller: ICoreWebView2Controller,
pub environment: ICoreWebView2Environment,
}
}
#[cfg(target_os = "android")]
mod imp {
use wry::JniHandle;
pub type Webview = JniHandle;
}
pub use imp::*;
| 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-runtime-wry/src/dialog/windows.rs | crates/tauri-runtime-wry/src/dialog/windows.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use windows::core::{w, HSTRING};
enum Level {
Error,
#[allow(unused)]
Warning,
#[allow(unused)]
Info,
}
pub fn error<S: AsRef<str>>(err: S) {
dialog_inner(err.as_ref(), Level::Error);
}
fn dialog_inner(err: &str, level: Level) {
let title = match level {
Level::Warning => w!("Warning"),
Level::Error => w!("Error"),
Level::Info => w!("Info"),
};
#[cfg(not(feature = "common-controls-v6"))]
{
use windows::Win32::UI::WindowsAndMessaging::*;
let err = remove_hyperlink(err);
let err = HSTRING::from(err);
unsafe {
MessageBoxW(
None,
&err,
title,
match level {
Level::Warning => MB_ICONWARNING,
Level::Error => MB_ICONERROR,
Level::Info => MB_ICONINFORMATION,
},
)
};
}
#[cfg(feature = "common-controls-v6")]
{
use windows::core::{HRESULT, PCWSTR};
use windows::Win32::Foundation::*;
use windows::Win32::UI::Controls::*;
use windows::Win32::UI::Shell::*;
use windows::Win32::UI::WindowsAndMessaging::*;
extern "system" fn task_dialog_callback(
_hwnd: HWND,
msg: TASKDIALOG_NOTIFICATIONS,
_wparam: WPARAM,
lparam: LPARAM,
_data: isize,
) -> HRESULT {
if msg == TDN_HYPERLINK_CLICKED {
let link = PCWSTR(lparam.0 as _);
let _ = unsafe { ShellExecuteW(None, None, link, None, None, SW_SHOWNORMAL) };
}
S_OK
}
let err = HSTRING::from(err);
let err = PCWSTR(err.as_ptr());
let task_dialog_config = TASKDIALOGCONFIG {
cbSize: std::mem::size_of::<TASKDIALOGCONFIG>() as u32,
dwFlags: TDF_ALLOW_DIALOG_CANCELLATION | TDF_ENABLE_HYPERLINKS,
pszWindowTitle: title,
pszContent: err,
Anonymous1: TASKDIALOGCONFIG_0 {
pszMainIcon: match level {
Level::Warning => TD_WARNING_ICON,
Level::Error => TD_ERROR_ICON,
Level::Info => TD_INFORMATION_ICON,
},
},
dwCommonButtons: TDCBF_OK_BUTTON,
pfCallback: Some(task_dialog_callback),
..Default::default()
};
let _ = unsafe { TaskDialogIndirect(&task_dialog_config, None, None, None) };
}
}
#[cfg(not(feature = "common-controls-v6"))]
fn remove_hyperlink(str: &str) -> String {
let mut result = String::new();
let mut in_hyperlink = false;
for c in str.chars() {
if c == '<' {
in_hyperlink = true;
} else if c == '>' {
in_hyperlink = false;
} else if !in_hyperlink {
result.push(c);
}
}
result
}
#[cfg(test)]
#[cfg(not(feature = "common-controls-v6"))]
mod tests {
use super::*;
#[test]
fn test_remove_hyperlink() {
let input = "This is a <A href=\"some link\">test</A> string.";
let expected = "This is a test string.";
let result = remove_hyperlink(input);
assert_eq!(result, expected);
}
}
| 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-runtime-wry/src/dialog/mod.rs | crates/tauri-runtime-wry/src/dialog/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
#[cfg(windows)]
mod windows;
pub fn error<S: AsRef<str>>(err: S) {
#[cfg(windows)]
windows::error(err);
#[cfg(not(windows))]
{
unimplemented!("Error dialog is not implemented for this platform");
}
}
| 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-runtime-wry/src/window/macos.rs | crates/tauri-runtime-wry/src/window/macos.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use objc2_app_kit::{NSBackingStoreType, NSWindow, NSWindowStyleMask};
use objc2_foundation::MainThreadMarker;
use tao::platform::macos::WindowExtMacOS;
impl super::WindowExt for tao::window::Window {
// based on electron implementation
// https://github.com/electron/electron/blob/15db63e26df3e3d59ce6281f030624f746518511/shell/browser/native_window_mac.mm#L474
fn set_enabled(&self, enabled: bool) {
let ns_window: &NSWindow = unsafe { &*self.ns_window().cast() };
if !enabled {
let frame = ns_window.frame();
let mtm = MainThreadMarker::new()
.expect("`Window::set_enabled` can only be called on the main thread");
let sheet = unsafe {
NSWindow::initWithContentRect_styleMask_backing_defer(
mtm.alloc(),
frame,
NSWindowStyleMask::Titled,
NSBackingStoreType::Buffered,
false,
)
};
unsafe { sheet.setAlphaValue(0.5) };
unsafe { ns_window.beginSheet_completionHandler(&sheet, None) };
} else if let Some(attached) = unsafe { ns_window.attachedSheet() } {
unsafe { ns_window.endSheet(&attached) };
}
}
fn is_enabled(&self) -> bool {
let ns_window: &NSWindow = unsafe { &*self.ns_window().cast() };
unsafe { ns_window.attachedSheet() }.is_none()
}
fn center(&self) {
let ns_window: &NSWindow = unsafe { &*self.ns_window().cast() };
ns_window.center();
}
}
| 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-runtime-wry/src/window/linux.rs | crates/tauri-runtime-wry/src/window/linux.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use gtk::prelude::*;
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
use tao::platform::unix::WindowExtUnix;
impl super::WindowExt for tao::window::Window {
fn set_enabled(&self, enabled: bool) {
self.gtk_window().set_sensitive(enabled);
}
fn is_enabled(&self) -> bool {
self.gtk_window().is_sensitive()
}
fn center(&self) {
if let Some(monitor) = self.current_monitor() {
let window_size = self.outer_size();
let new_pos = super::calculate_window_center_position(window_size, monitor);
self.set_outer_position(new_pos);
}
}
}
| 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-runtime-wry/src/window/windows.rs | crates/tauri-runtime-wry/src/window/windows.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use windows::Win32::{
Foundation::{HWND, RECT},
Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS},
UI::Input::KeyboardAndMouse::{EnableWindow, IsWindowEnabled},
};
use tao::platform::windows::WindowExtWindows;
impl super::WindowExt for tao::window::Window {
fn set_enabled(&self, enabled: bool) {
let _ = unsafe { EnableWindow(HWND(self.hwnd() as _), enabled) };
}
fn is_enabled(&self) -> bool {
unsafe { IsWindowEnabled(HWND(self.hwnd() as _)) }.as_bool()
}
fn center(&self) {
if let Some(monitor) = self.current_monitor() {
let mut window_size = self.outer_size();
if self.is_decorated() {
let mut rect = RECT::default();
let result = unsafe {
DwmGetWindowAttribute(
HWND(self.hwnd() as _),
DWMWA_EXTENDED_FRAME_BOUNDS,
&mut rect as *mut _ as *mut _,
std::mem::size_of::<RECT>() as u32,
)
};
if result.is_ok() {
window_size.height = (rect.bottom - rect.top) as u32;
}
}
let new_pos = super::calculate_window_center_position(window_size, monitor);
self.set_outer_position(new_pos);
}
}
fn draw_surface(
&self,
surface: &mut softbuffer::Surface<
std::sync::Arc<tao::window::Window>,
std::sync::Arc<tao::window::Window>,
>,
background_color: Option<tao::window::RGBA>,
) {
let size = self.inner_size();
if let (Some(width), Some(height)) = (
std::num::NonZeroU32::new(size.width),
std::num::NonZeroU32::new(size.height),
) {
surface.resize(width, height).unwrap();
let mut buffer = surface.buffer_mut().unwrap();
let color = background_color
.map(|(r, g, b, _)| (b as u32) | ((g as u32) << 8) | ((r as u32) << 16))
.unwrap_or(0);
buffer.fill(color);
let _ = buffer.present();
}
}
}
| 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-runtime-wry/src/window/mod.rs | crates/tauri-runtime-wry/src/window/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(windows)]
mod windows;
use crate::monitor::MonitorExt;
pub trait WindowExt {
/// Enable or disable the window
///
/// ## Platform-specific:
///
/// - **Android / iOS**: Unsupported.
fn set_enabled(&self, enabled: bool);
/// Whether the window is enabled or disabled.
///
/// ## Platform-specific:
///
/// - **Android / iOS**: Unsupported, always returns `true`.
fn is_enabled(&self) -> bool;
/// Center the window
///
/// ## Platform-specific:
///
/// - **Android / iOS**: Unsupported.
fn center(&self) {}
/// Clears the window surface. i.e make it it transparent.
#[cfg(windows)]
fn draw_surface(
&self,
surface: &mut softbuffer::Surface<
std::sync::Arc<tao::window::Window>,
std::sync::Arc<tao::window::Window>,
>,
background_color: Option<tao::window::RGBA>,
);
}
#[cfg(mobile)]
impl WindowExt for tao::window::Window {
fn set_enabled(&self, _: bool) {}
fn is_enabled(&self) -> bool {
true
}
}
pub fn calculate_window_center_position(
window_size: tao::dpi::PhysicalSize<u32>,
target_monitor: tao::monitor::MonitorHandle,
) -> tao::dpi::PhysicalPosition<i32> {
let work_area = target_monitor.work_area();
tao::dpi::PhysicalPosition::new(
(work_area.size.width as i32 - window_size.width as i32) / 2 + work_area.position.x,
(work_area.size.height as i32 - window_size.height as i32) / 2 + work_area.position.y,
)
}
| 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-runtime-wry/src/monitor/macos.rs | crates/tauri-runtime-wry/src/monitor/macos.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use tauri_runtime::dpi::{LogicalSize, PhysicalRect};
impl super::MonitorExt for tao::monitor::MonitorHandle {
fn work_area(&self) -> PhysicalRect<i32, u32> {
use objc2_app_kit::NSScreen;
use tao::platform::macos::MonitorHandleExtMacOS;
if let Some(ns_screen) = self.ns_screen() {
let ns_screen: &NSScreen = unsafe { &*ns_screen.cast() };
let screen_frame = ns_screen.frame();
let visible_frame = ns_screen.visibleFrame();
let scale_factor = self.scale_factor();
let mut position = self.position().to_logical::<f64>(scale_factor);
position.x += visible_frame.origin.x - screen_frame.origin.x;
PhysicalRect {
size: LogicalSize::new(visible_frame.size.width, visible_frame.size.height)
.to_physical(scale_factor),
position: position.to_physical(scale_factor),
}
} else {
PhysicalRect {
size: self.size(),
position: self.position(),
}
}
}
}
| 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-runtime-wry/src/monitor/linux.rs | crates/tauri-runtime-wry/src/monitor/linux.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use gtk::prelude::MonitorExt;
use tao::platform::unix::MonitorHandleExtUnix;
use tauri_runtime::dpi::{LogicalPosition, LogicalSize, PhysicalRect};
impl super::MonitorExt for tao::monitor::MonitorHandle {
fn work_area(&self) -> PhysicalRect<i32, u32> {
let rect = self.gdk_monitor().workarea();
let scale_factor = self.scale_factor();
PhysicalRect {
size: LogicalSize::new(rect.width() as u32, rect.height() as u32).to_physical(scale_factor),
position: LogicalPosition::new(rect.x(), rect.y()).to_physical(scale_factor),
}
}
}
| 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-runtime-wry/src/monitor/windows.rs | crates/tauri-runtime-wry/src/monitor/windows.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use tao::dpi::{PhysicalPosition, PhysicalSize};
use tauri_runtime::dpi::PhysicalRect;
impl super::MonitorExt for tao::monitor::MonitorHandle {
fn work_area(&self) -> PhysicalRect<i32, u32> {
use tao::platform::windows::MonitorHandleExtWindows;
use windows::Win32::Graphics::Gdi::{GetMonitorInfoW, HMONITOR, MONITORINFO};
let mut monitor_info = MONITORINFO {
cbSize: std::mem::size_of::<MONITORINFO>() as u32,
..Default::default()
};
let status = unsafe { GetMonitorInfoW(HMONITOR(self.hmonitor() as _), &mut monitor_info) };
if status.as_bool() {
PhysicalRect {
size: PhysicalSize::new(
(monitor_info.rcWork.right - monitor_info.rcWork.left) as u32,
(monitor_info.rcWork.bottom - monitor_info.rcWork.top) as u32,
),
position: PhysicalPosition::new(monitor_info.rcWork.left, monitor_info.rcWork.top),
}
} else {
PhysicalRect {
size: self.size(),
position: self.position(),
}
}
}
}
| 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-runtime-wry/src/monitor/mod.rs | crates/tauri-runtime-wry/src/monitor/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use tauri_runtime::dpi::PhysicalRect;
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(windows)]
mod windows;
pub trait MonitorExt {
/// Get the work area of this monitor
///
/// ## Platform-specific:
///
/// - **Android / iOS**: Unsupported.
fn work_area(&self) -> PhysicalRect<i32, u32>;
}
#[cfg(mobile)]
impl MonitorExt for tao::monitor::MonitorHandle {
fn work_area(&self) -> PhysicalRect<i32, u32> {
PhysicalRect {
size: self.size(),
position: self.position(),
}
}
}
| 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/src/mobile.rs | crates/tauri-build/src/mobile.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, Result};
use tauri_utils::write_if_changed;
pub fn generate_gradle_files(project_dir: PathBuf) -> Result<()> {
let gradle_settings_path = project_dir.join("tauri.settings.gradle");
let app_build_gradle_path = project_dir.join("app").join("tauri.build.gradle.kts");
let mut gradle_settings =
"// THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.\n".to_string();
let mut app_build_gradle = "// THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
val implementation by configurations
dependencies {"
.to_string();
for (env, value) in std::env::vars_os() {
let env = env.to_string_lossy();
if env.starts_with("DEP_") && env.ends_with("_ANDROID_LIBRARY_PATH") {
let name_len = env.len() - "DEP_".len() - "_ANDROID_LIBRARY_PATH".len();
let mut plugin_name = env
.chars()
.skip("DEP_".len())
.take(name_len)
.collect::<String>()
.to_lowercase()
.replace('_', "-");
if plugin_name == "tauri" {
plugin_name = "tauri-android".into();
}
let plugin_path = PathBuf::from(value);
gradle_settings.push_str(&format!("include ':{plugin_name}'"));
gradle_settings.push('\n');
gradle_settings.push_str(&format!(
"project(':{plugin_name}').projectDir = new File({:?})",
tauri_utils::display_path(plugin_path)
));
gradle_settings.push('\n');
app_build_gradle.push('\n');
app_build_gradle.push_str(&format!(r#" implementation(project(":{plugin_name}"))"#));
}
}
app_build_gradle.push_str("\n}");
// Overwrite only if changed to not trigger rebuilds
write_if_changed(&gradle_settings_path, gradle_settings)
.context("failed to write tauri.settings.gradle")?;
write_if_changed(&app_build_gradle_path, app_build_gradle)
.context("failed to write tauri.build.gradle.kts")?;
println!("cargo:rerun-if-changed={}", gradle_settings_path.display());
println!("cargo:rerun-if-changed={}", app_build_gradle_path.display());
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-build/src/lib.rs | crates/tauri-build/src/lib.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! This applies the macros at build-time in order to rig some special features needed by `cargo`.
#![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"
)]
#![cfg_attr(docsrs, feature(doc_cfg))]
use anyhow::Context;
pub use anyhow::Result;
use cargo_toml::Manifest;
use tauri_utils::{
config::{BundleResources, Config, WebviewInstallMode},
resources::{external_binaries, ResourcePaths},
};
use std::{
collections::HashMap,
env, fs,
path::{Path, PathBuf},
};
mod acl;
#[cfg(feature = "codegen")]
mod codegen;
mod manifest;
mod mobile;
mod static_vcruntime;
#[cfg(feature = "codegen")]
#[cfg_attr(docsrs, doc(cfg(feature = "codegen")))]
pub use codegen::context::CodegenContext;
pub use acl::{AppManifest, DefaultPermissionRule, InlinedPlugin};
fn copy_file(from: impl AsRef<Path>, to: impl AsRef<Path>) -> Result<()> {
let from = from.as_ref();
let to = to.as_ref();
if !from.exists() {
return Err(anyhow::anyhow!("{:?} does not exist", from));
}
if !from.is_file() {
return Err(anyhow::anyhow!("{:?} is not a file", from));
}
let dest_dir = to.parent().expect("No data in parent");
fs::create_dir_all(dest_dir)?;
fs::copy(from, to)?;
Ok(())
}
fn copy_binaries(
binaries: ResourcePaths,
target_triple: &str,
path: &Path,
package_name: Option<&String>,
) -> Result<()> {
for src in binaries {
let src = src?;
println!("cargo:rerun-if-changed={}", src.display());
let file_name = src
.file_name()
.expect("failed to extract external binary filename")
.to_string_lossy()
.replace(&format!("-{target_triple}"), "");
if package_name == Some(&file_name) {
return Err(anyhow::anyhow!(
"Cannot define a sidecar with the same name as the Cargo package name `{}`. Please change the sidecar name in the filesystem and the Tauri configuration.",
file_name
));
}
let dest = path.join(file_name);
if dest.exists() {
fs::remove_file(&dest).unwrap();
}
copy_file(&src, &dest)?;
}
Ok(())
}
/// Copies resources to a path.
fn copy_resources(resources: ResourcePaths<'_>, path: &Path) -> Result<()> {
let path = path.canonicalize()?;
for resource in resources.iter() {
let resource = resource?;
println!("cargo:rerun-if-changed={}", resource.path().display());
// avoid copying the resource if target is the same as source
let src = resource.path().canonicalize()?;
let target = path.join(resource.target());
if src != target {
copy_file(src, target)?;
}
}
Ok(())
}
#[cfg(unix)]
fn symlink_dir(src: &Path, dst: &Path) -> std::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) -> std::io::Result<()> {
std::os::windows::fs::symlink_dir(src, dst)
}
/// Makes a symbolic link to a file.
#[cfg(unix)]
fn symlink_file(src: &Path, dst: &Path) -> std::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) -> std::io::Result<()> {
std::os::windows::fs::symlink_file(src, dst)
}
fn copy_dir(from: &Path, to: &Path) -> Result<()> {
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(dest_path)?;
} else {
fs::copy(entry.path(), dest_path)?;
}
}
Ok(())
}
// Copies the framework under `{src_dir}/{framework}.framework` to `{dest_dir}/{framework}.framework`.
fn copy_framework_from(src_dir: &Path, framework: &str, dest_dir: &Path) -> Result<bool> {
let src_name = format!("{framework}.framework");
let src_path = src_dir.join(&src_name);
if src_path.exists() {
copy_dir(&src_path, &dest_dir.join(&src_name))?;
Ok(true)
} else {
Ok(false)
}
}
// Copies the macOS application bundle frameworks to the target folder
fn copy_frameworks(dest_dir: &Path, frameworks: &[String]) -> Result<()> {
fs::create_dir_all(dest_dir)
.with_context(|| format!("Failed to create frameworks output directory at {dest_dir:?}"))?;
for framework in frameworks.iter() {
if framework.ends_with(".framework") {
let src_path = Path::new(framework);
let src_name = src_path
.file_name()
.expect("Couldn't get framework filename");
let dest_path = dest_dir.join(src_name);
copy_dir(src_path, &dest_path)?;
continue;
} else if framework.ends_with(".dylib") {
let src_path = Path::new(framework);
if !src_path.exists() {
return Err(anyhow::anyhow!("Library not found: {}", framework));
}
let src_name = src_path.file_name().expect("Couldn't get library filename");
let dest_path = dest_dir.join(src_name);
copy_file(src_path, &dest_path)?;
continue;
} else if framework.contains('/') {
return Err(anyhow::anyhow!(
"Framework path should have .framework extension: {}",
framework
));
}
if let Some(home_dir) = dirs::home_dir() {
if copy_framework_from(&home_dir.join("Library/Frameworks/"), framework, dest_dir)? {
continue;
}
}
if copy_framework_from("/Library/Frameworks/".as_ref(), framework, dest_dir)?
|| copy_framework_from("/Network/Library/Frameworks/".as_ref(), framework, dest_dir)?
{
continue;
}
}
Ok(())
}
// creates a cfg alias if `has_feature` is true.
// `alias` must be a snake case string.
fn cfg_alias(alias: &str, has_feature: bool) {
println!("cargo:rustc-check-cfg=cfg({alias})");
if has_feature {
println!("cargo:rustc-cfg={alias}");
}
}
/// Attributes used on Windows.
#[allow(dead_code)]
#[derive(Debug)]
pub struct WindowsAttributes {
window_icon_path: Option<PathBuf>,
/// A string containing an [application manifest] to be included with the application on Windows.
///
/// Defaults to:
/// ```text
#[doc = include_str!("windows-app-manifest.xml")]
/// ```
///
/// ## Warning
///
/// if you are using tauri's dialog APIs, you need to specify a dependency on Common Control v6 by adding the following to your custom manifest:
/// ```text
/// <dependency>
/// <dependentAssembly>
/// <assemblyIdentity
/// type="win32"
/// name="Microsoft.Windows.Common-Controls"
/// version="6.0.0.0"
/// processorArchitecture="*"
/// publicKeyToken="6595b64144ccf1df"
/// language="*"
/// />
/// </dependentAssembly>
/// </dependency>
/// ```
///
/// [application manifest]: https://learn.microsoft.com/en-us/windows/win32/sbscs/application-manifests
app_manifest: Option<String>,
}
impl Default for WindowsAttributes {
fn default() -> Self {
Self::new()
}
}
impl WindowsAttributes {
/// Creates the default attribute set.
pub fn new() -> Self {
Self {
window_icon_path: Default::default(),
app_manifest: Some(include_str!("windows-app-manifest.xml").into()),
}
}
/// Creates the default attribute set without the default app manifest.
#[must_use]
pub fn new_without_app_manifest() -> Self {
Self {
app_manifest: None,
window_icon_path: Default::default(),
}
}
/// Sets the icon to use on the window. Currently only used on Windows.
/// It must be in `ico` format. Defaults to `icons/icon.ico`.
#[must_use]
pub fn window_icon_path<P: AsRef<Path>>(mut self, window_icon_path: P) -> Self {
self
.window_icon_path
.replace(window_icon_path.as_ref().into());
self
}
/// Sets the [application manifest] to be included with the application on Windows.
///
/// Defaults to:
/// ```text
#[doc = include_str!("windows-app-manifest.xml")]
/// ```
///
/// ## Warning
///
/// if you are using tauri's dialog APIs, you need to specify a dependency on Common Control v6 by adding the following to your custom manifest:
/// ```text
/// <dependency>
/// <dependentAssembly>
/// <assemblyIdentity
/// type="win32"
/// name="Microsoft.Windows.Common-Controls"
/// version="6.0.0.0"
/// processorArchitecture="*"
/// publicKeyToken="6595b64144ccf1df"
/// language="*"
/// />
/// </dependentAssembly>
/// </dependency>
/// ```
///
/// # Example
///
/// The following manifest will brand the exe as requesting administrator privileges.
/// Thus, every time it is executed, a Windows UAC dialog will appear.
///
/// ```rust,no_run
/// let mut windows = tauri_build::WindowsAttributes::new();
/// windows = windows.app_manifest(r#"
/// <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
/// <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
/// <security>
/// <requestedPrivileges>
/// <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
/// </requestedPrivileges>
/// </security>
/// </trustInfo>
/// </assembly>
/// "#);
/// let attrs = tauri_build::Attributes::new().windows_attributes(windows);
/// tauri_build::try_build(attrs).expect("failed to run build script");
/// ```
///
/// Note that you can move the manifest contents to a separate file and use `include_str!("manifest.xml")`
/// instead of the inline string.
///
/// [manifest]: https://learn.microsoft.com/en-us/windows/win32/sbscs/application-manifests
#[must_use]
pub fn app_manifest<S: AsRef<str>>(mut self, manifest: S) -> Self {
self.app_manifest = Some(manifest.as_ref().to_string());
self
}
}
/// The attributes used on the build.
#[derive(Debug, Default)]
pub struct Attributes {
#[allow(dead_code)]
windows_attributes: WindowsAttributes,
capabilities_path_pattern: Option<&'static str>,
#[cfg(feature = "codegen")]
codegen: Option<codegen::context::CodegenContext>,
inlined_plugins: HashMap<&'static str, InlinedPlugin>,
app_manifest: AppManifest,
}
impl Attributes {
/// Creates the default attribute set.
pub fn new() -> Self {
Self::default()
}
/// Sets the icon to use on the window. Currently only used on Windows.
#[must_use]
pub fn windows_attributes(mut self, windows_attributes: WindowsAttributes) -> Self {
self.windows_attributes = windows_attributes;
self
}
/// Set the glob pattern to be used to find the capabilities.
///
/// **WARNING:** The `removeUnusedCommands` option does not work with a custom capabilities path.
///
/// **Note:** You must emit [rerun-if-changed] instructions for your capabilities directory.
///
/// [rerun-if-changed]: https://doc.rust-lang.org/cargo/reference/build-scripts.html#rerun-if-changed
#[must_use]
pub fn capabilities_path_pattern(mut self, pattern: &'static str) -> Self {
self.capabilities_path_pattern.replace(pattern);
self
}
/// Adds the given plugin to the list of inlined plugins (a plugin that is part of your application).
///
/// See [`InlinedPlugin`] for more information.
pub fn plugin(mut self, name: &'static str, plugin: InlinedPlugin) -> Self {
self.inlined_plugins.insert(name, plugin);
self
}
/// Adds the given list of plugins to the list of inlined plugins (a plugin that is part of your application).
///
/// See [`InlinedPlugin`] for more information.
pub fn plugins<I>(mut self, plugins: I) -> Self
where
I: IntoIterator<Item = (&'static str, InlinedPlugin)>,
{
self.inlined_plugins.extend(plugins);
self
}
/// Sets the application manifest for the Access Control List.
///
/// See [`AppManifest`] for more information.
pub fn app_manifest(mut self, manifest: AppManifest) -> Self {
self.app_manifest = manifest;
self
}
#[cfg(feature = "codegen")]
#[cfg_attr(docsrs, doc(cfg(feature = "codegen")))]
#[must_use]
pub fn codegen(mut self, codegen: codegen::context::CodegenContext) -> Self {
self.codegen.replace(codegen);
self
}
}
pub fn is_dev() -> bool {
env::var("DEP_TAURI_DEV").expect("missing `cargo:dev` instruction, please update tauri to latest")
== "true"
}
/// Run all build time helpers for your Tauri Application.
///
/// To provide extra configuration, such as [`AppManifest::commands`]
/// for fine-grained control over command permissions, see [`try_build`].
/// See [`Attributes`] for the complete list of configuration options.
///
/// # Platforms
///
/// [`build()`] should be called inside of `build.rs` regardless of the platform, so **DO NOT** use a [conditional compilation]
/// check that prevents it from running on any of your targets.
///
/// Platform specific code is handled by the helpers automatically.
///
/// A build script is required in order to activate some cargo environmental variables that are
/// used when generating code and embedding assets.
///
/// # Panics
///
/// If any of the build time helpers fail, they will [`std::panic!`] with the related error message.
/// This is typically desirable when running inside a build script; see [`try_build`] for no panics.
///
/// [conditional compilation]: https://web.mit.edu/rust-lang_v1.25/arch/amd64_ubuntu1404/share/doc/rust/html/book/first-edition/conditional-compilation.html
pub fn build() {
if let Err(error) = try_build(Attributes::default()) {
let error = format!("{error:#}");
println!("{error}");
if error.starts_with("unknown field") {
print!("found an unknown configuration field. This usually means that you are using a CLI version that is newer than `tauri-build` and is incompatible. ");
println!(
"Please try updating the Rust crates by running `cargo update` in the Tauri app folder."
);
}
std::process::exit(1);
}
}
/// Same as [`build()`], but takes an extra configuration argument, and does not panic.
#[allow(unused_variables)]
pub fn try_build(attributes: Attributes) -> Result<()> {
use anyhow::anyhow;
println!("cargo:rerun-if-env-changed=TAURI_CONFIG");
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
let mobile = target_os == "ios" || target_os == "android";
cfg_alias("desktop", !mobile);
cfg_alias("mobile", mobile);
let target_triple = env::var("TARGET").unwrap();
let target = tauri_utils::platform::Target::from_triple(&target_triple);
let (mut config, config_paths) =
tauri_utils::config::parse::read_from(target, &env::current_dir().unwrap())?;
for config_file_path in config_paths {
println!("cargo:rerun-if-changed={}", config_file_path.display());
}
if let Ok(env) = env::var("TAURI_CONFIG") {
let merge_config: serde_json::Value = serde_json::from_str(&env)?;
json_patch::merge(&mut config, &merge_config);
}
let config: Config = serde_json::from_value(config)?;
let s = config.identifier.split('.');
let last = s.clone().count() - 1;
let mut android_package_prefix = String::new();
for (i, w) in s.enumerate() {
if i == last {
println!(
"cargo:rustc-env=TAURI_ANDROID_PACKAGE_NAME_APP_NAME={}",
w.replace('-', "_")
);
} else {
android_package_prefix.push_str(&w.replace(['_', '-'], "_1"));
android_package_prefix.push('_');
}
}
android_package_prefix.pop();
println!("cargo:rustc-env=TAURI_ANDROID_PACKAGE_NAME_PREFIX={android_package_prefix}");
if let Some(project_dir) = env::var_os("TAURI_ANDROID_PROJECT_PATH").map(PathBuf::from) {
mobile::generate_gradle_files(project_dir)?;
}
cfg_alias("dev", is_dev());
let cargo_toml_path = Path::new("Cargo.toml").canonicalize()?;
let mut manifest = Manifest::<cargo_toml::Value>::from_path_with_metadata(cargo_toml_path)?;
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
manifest::check(&config, &mut manifest)?;
acl::build(&out_dir, target, &attributes)?;
tauri_utils::plugin::save_global_api_scripts_paths(&out_dir, None);
println!("cargo:rustc-env=TAURI_ENV_TARGET_TRIPLE={target_triple}");
// when running codegen in this build script, we need to access the env var directly
env::set_var("TAURI_ENV_TARGET_TRIPLE", &target_triple);
// TODO: far from ideal, but there's no other way to get the target dir, see <https://github.com/rust-lang/cargo/issues/5457>
let target_dir = out_dir
.parent()
.unwrap()
.parent()
.unwrap()
.parent()
.unwrap();
if let Some(paths) = &config.bundle.external_bin {
copy_binaries(
ResourcePaths::new(&external_binaries(paths, &target_triple, &target), true),
&target_triple,
target_dir,
manifest.package.as_ref().map(|p| &p.name),
)?;
}
#[allow(unused_mut, clippy::redundant_clone)]
let mut resources = config
.bundle
.resources
.clone()
.unwrap_or_else(|| BundleResources::List(Vec::new()));
if target_triple.contains("windows") {
if let Some(fixed_webview2_runtime_path) = match &config.bundle.windows.webview_install_mode {
WebviewInstallMode::FixedRuntime { path } => Some(path),
_ => None,
} {
resources.push(fixed_webview2_runtime_path.display().to_string());
}
}
match resources {
BundleResources::List(res) => {
copy_resources(ResourcePaths::new(res.as_slice(), true), target_dir)?
}
BundleResources::Map(map) => copy_resources(ResourcePaths::from_map(&map, true), target_dir)?,
}
if target_triple.contains("darwin") {
if let Some(frameworks) = &config.bundle.macos.frameworks {
if !frameworks.is_empty() {
let frameworks_dir = target_dir.parent().unwrap().join("Frameworks");
let _ = fs::remove_dir_all(&frameworks_dir);
// copy frameworks to the root `target` folder (instead of `target/debug` for instance)
// because the rpath is set to `@executable_path/../Frameworks`.
copy_frameworks(&frameworks_dir, frameworks)?;
// If we have frameworks, we need to set the @rpath
// https://github.com/tauri-apps/tauri/issues/7710
println!("cargo:rustc-link-arg=-Wl,-rpath,@executable_path/../Frameworks");
}
}
if !is_dev() {
if let Some(version) = &config.bundle.macos.minimum_system_version {
println!("cargo:rustc-env=MACOSX_DEPLOYMENT_TARGET={version}");
}
}
}
if target_triple.contains("ios") {
println!(
"cargo:rustc-env=IPHONEOS_DEPLOYMENT_TARGET={}",
config.bundle.ios.minimum_system_version
);
}
if target_triple.contains("windows") {
use semver::Version;
use tauri_winres::{VersionInfo, WindowsResource};
fn find_icon<F: Fn(&&String) -> bool>(config: &Config, predicate: F, default: &str) -> PathBuf {
let icon_path = config
.bundle
.icon
.iter()
.find(|i| predicate(i))
.cloned()
.unwrap_or_else(|| default.to_string());
icon_path.into()
}
let window_icon_path = attributes
.windows_attributes
.window_icon_path
.unwrap_or_else(|| find_icon(&config, |i| i.ends_with(".ico"), "icons/icon.ico"));
let mut res = WindowsResource::new();
if let Some(manifest) = attributes.windows_attributes.app_manifest {
res.set_manifest(&manifest);
}
if let Some(version_str) = &config.version {
if let Ok(v) = Version::parse(version_str) {
let version = (v.major << 48) | (v.minor << 32) | (v.patch << 16);
res.set_version_info(VersionInfo::FILEVERSION, version);
res.set_version_info(VersionInfo::PRODUCTVERSION, version);
}
}
if let Some(product_name) = &config.product_name {
res.set("ProductName", product_name);
}
let company_name = config.bundle.publisher.unwrap_or_else(|| {
config
.identifier
.split('.')
.nth(1)
.unwrap_or(&config.identifier)
.to_string()
});
res.set("CompanyName", &company_name);
let file_description = config
.product_name
.or_else(|| manifest.package.as_ref().map(|p| p.name.clone()))
.or_else(|| std::env::var("CARGO_PKG_NAME").ok());
res.set("FileDescription", &file_description.unwrap());
if let Some(copyright) = &config.bundle.copyright {
res.set("LegalCopyright", copyright);
}
if window_icon_path.exists() {
res.set_icon_with_id(&window_icon_path.display().to_string(), "32512");
} else {
return Err(anyhow!(format!(
"`{}` not found; required for generating a Windows Resource file during tauri-build",
window_icon_path.display()
)));
}
res.compile().with_context(|| {
format!(
"failed to compile `{}` into a Windows Resource file during tauri-build",
window_icon_path.display()
)
})?;
let target_env = env::var("CARGO_CFG_TARGET_ENV").unwrap();
match target_env.as_str() {
"gnu" => {
let target_arch = match env::var("CARGO_CFG_TARGET_ARCH").unwrap().as_str() {
"x86_64" => Some("x64"),
"x86" => Some("x86"),
"aarch64" => Some("arm64"),
arch => None,
};
if let Some(target_arch) = target_arch {
for entry in fs::read_dir(target_dir.join("build"))? {
let path = entry?.path();
let webview2_loader_path = path
.join("out")
.join(target_arch)
.join("WebView2Loader.dll");
if path.to_string_lossy().contains("webview2-com-sys") && webview2_loader_path.exists()
{
fs::copy(webview2_loader_path, target_dir.join("WebView2Loader.dll"))?;
break;
}
}
}
}
"msvc" => {
if env::var("STATIC_VCRUNTIME").is_ok_and(|v| v == "true") {
static_vcruntime::build();
}
}
_ => (),
}
}
#[cfg(feature = "codegen")]
if let Some(codegen) = attributes.codegen {
codegen.try_build()?;
}
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-build/src/manifest.rs | crates/tauri-build/src/manifest.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use anyhow::{anyhow, Result};
use cargo_toml::{Dependency, Manifest};
use tauri_utils::config::{AppConfig, Config, PatternKind};
#[derive(Debug, Default, PartialEq, Eq)]
struct Diff {
remove: Vec<String>,
add: Vec<String>,
}
#[derive(Debug, Clone, Copy)]
enum DependencyKind {
Build,
Normal,
}
#[derive(Debug)]
struct AllowlistedDependency {
name: String,
alias: Option<String>,
kind: DependencyKind,
all_cli_managed_features: Option<Vec<&'static str>>,
expected_features: Vec<String>,
}
pub fn check(config: &Config, manifest: &mut Manifest) -> Result<()> {
let dependencies = vec![
AllowlistedDependency {
name: "tauri-build".into(),
alias: None,
kind: DependencyKind::Build,
all_cli_managed_features: Some(vec!["isolation"]),
expected_features: match config.app.security.pattern {
PatternKind::Isolation { .. } => vec!["isolation".to_string()],
_ => vec![],
},
},
AllowlistedDependency {
name: "tauri".into(),
alias: None,
kind: DependencyKind::Normal,
all_cli_managed_features: Some(
AppConfig::all_features()
.into_iter()
.filter(|f| f != &"tray-icon")
.collect(),
),
expected_features: config
.app
.features()
.into_iter()
.filter(|f| f != &"tray-icon")
.map(|f| f.to_string())
.collect::<Vec<String>>(),
},
];
for metadata in dependencies {
let mut name = metadata.name.clone();
let mut deps = find_dependency(manifest, &metadata.name, metadata.kind);
if deps.is_empty() {
if let Some(alias) = &metadata.alias {
deps = find_dependency(manifest, alias, metadata.kind);
name.clone_from(alias);
}
}
for dep in deps {
if let Err(error) = check_features(dep, &metadata) {
return Err(anyhow!("
The `{}` dependency features on the `Cargo.toml` file does not match the allowlist defined under `tauri.conf.json`.
Please run `tauri dev` or `tauri build` or {}.
", name, error));
}
}
}
Ok(())
}
fn find_dependency(manifest: &mut Manifest, name: &str, kind: DependencyKind) -> Vec<Dependency> {
let dep = match kind {
DependencyKind::Build => manifest.build_dependencies.remove(name),
DependencyKind::Normal => manifest.dependencies.remove(name),
};
if let Some(dep) = dep {
vec![dep]
} else {
let mut deps = Vec::new();
for target in manifest.target.values_mut() {
if let Some(dep) = match kind {
DependencyKind::Build => target.build_dependencies.remove(name),
DependencyKind::Normal => target.dependencies.remove(name),
} {
deps.push(dep);
}
}
deps
}
}
fn features_diff(current: &[String], expected: &[String]) -> Diff {
let mut remove = Vec::new();
let mut add = Vec::new();
for feature in current {
if !expected.contains(feature) {
remove.push(feature.clone());
}
}
for feature in expected {
if !current.contains(feature) {
add.push(feature.clone());
}
}
Diff { remove, add }
}
fn check_features(dependency: Dependency, metadata: &AllowlistedDependency) -> Result<(), String> {
let features = match dependency {
Dependency::Simple(_) => Vec::new(),
Dependency::Detailed(dep) => dep.features,
Dependency::Inherited(dep) => dep.features,
};
let diff = if let Some(all_cli_managed_features) = &metadata.all_cli_managed_features {
features_diff(
&features
.into_iter()
.filter(|f| all_cli_managed_features.contains(&f.as_str()))
.collect::<Vec<String>>(),
&metadata.expected_features,
)
} else {
features_diff(
&features
.into_iter()
.filter(|f| f.starts_with("allow-"))
.collect::<Vec<String>>(),
&metadata.expected_features,
)
};
let mut error_message = String::new();
if !diff.remove.is_empty() {
error_message.push_str("remove the `");
error_message.push_str(&diff.remove.join(", "));
error_message.push_str(if diff.remove.len() == 1 {
"` feature"
} else {
"` features"
});
if !diff.add.is_empty() {
error_message.push_str(" and ");
}
}
if !diff.add.is_empty() {
error_message.push_str("add the `");
error_message.push_str(&diff.add.join(", "));
error_message.push_str(if diff.add.len() == 1 {
"` feature"
} else {
"` features"
});
}
if error_message.is_empty() {
Ok(())
} else {
Err(error_message)
}
}
#[cfg(test)]
mod tests {
use super::Diff;
#[test]
fn array_diff() {
for (current, expected, result) in [
(vec![], vec![], Default::default()),
(
vec!["a".into()],
vec![],
Diff {
remove: vec!["a".into()],
add: vec![],
},
),
(vec!["a".into()], vec!["a".into()], Default::default()),
(
vec!["a".into(), "b".into()],
vec!["a".into()],
Diff {
remove: vec!["b".into()],
add: vec![],
},
),
(
vec!["a".into(), "b".into()],
vec!["a".into(), "c".into()],
Diff {
remove: vec!["b".into()],
add: vec!["c".into()],
},
),
] {
assert_eq!(crate::manifest::features_diff(¤t, &expected), 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-build/src/acl.rs | crates/tauri-build/src/acl.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{
collections::{BTreeMap, HashMap},
env, fs,
path::{Path, PathBuf},
};
use anyhow::{Context, Result};
use tauri_utils::{
acl::{
capability::Capability,
manifest::{Manifest, PermissionFile},
schema::CAPABILITIES_SCHEMA_FOLDER_PATH,
ACL_MANIFESTS_FILE_NAME, APP_ACL_KEY, CAPABILITIES_FILE_NAME,
},
platform::Target,
write_if_changed,
};
use crate::Attributes;
/// Definition of a plugin that is part of the Tauri application instead of having its own crate.
///
/// By default it generates a plugin manifest that parses permissions from the `permissions/$plugin-name` directory.
/// To change the glob pattern that is used to find permissions, use [`Self::permissions_path_pattern`].
///
/// To autogenerate permissions for each of the plugin commands, see [`Self::commands`].
#[derive(Debug, Default, Clone)]
pub struct InlinedPlugin {
commands: &'static [&'static str],
permissions_path_pattern: Option<&'static str>,
default: Option<DefaultPermissionRule>,
}
/// Variants of a generated default permission that can be used on an [`InlinedPlugin`].
#[derive(Debug, Clone)]
pub enum DefaultPermissionRule {
/// Allow all commands from [`InlinedPlugin::commands`].
AllowAllCommands,
/// Allow the given list of permissions.
///
/// Note that the list refers to permissions instead of command names,
/// so for example a command called `execute` would need to be allowed as `allow-execute`.
Allow(Vec<String>),
}
impl InlinedPlugin {
pub fn new() -> Self {
Self::default()
}
/// Define a list of commands that gets permissions autogenerated in the format of `allow-$command` and `deny-$command`
/// where $command is the command name in snake_case.
pub fn commands(mut self, commands: &'static [&'static str]) -> Self {
self.commands = commands;
self
}
/// Sets a glob pattern that is used to find the permissions of this inlined plugin.
///
/// **Note:** You must emit [rerun-if-changed] instructions for the plugin permissions directory.
///
/// By default it is `./permissions/$plugin-name/**/*`
pub fn permissions_path_pattern(mut self, pattern: &'static str) -> Self {
self.permissions_path_pattern.replace(pattern);
self
}
/// Creates a default permission for the plugin using the given rule.
///
/// Alternatively you can pull a permission in the filesystem in the permissions directory, see [`Self::permissions_path_pattern`].
pub fn default_permission(mut self, default: DefaultPermissionRule) -> Self {
self.default.replace(default);
self
}
}
/// Tauri application permission manifest.
///
/// By default it generates a manifest that parses permissions from the `permissions` directory.
/// To change the glob pattern that is used to find permissions, use [`Self::permissions_path_pattern`].
///
/// To autogenerate permissions for each of the app commands, see [`Self::commands`].
#[derive(Debug, Default, Clone, Copy)]
pub struct AppManifest {
commands: &'static [&'static str],
permissions_path_pattern: Option<&'static str>,
}
impl AppManifest {
pub fn new() -> Self {
Self::default()
}
/// Define a list of commands that gets permissions autogenerated in the format of `allow-$command` and `deny-$command`
/// where $command is the command name in snake_case.
pub fn commands(mut self, commands: &'static [&'static str]) -> Self {
self.commands = commands;
self
}
/// Sets a glob pattern that is used to find the permissions of the app.
///
/// **Note:** You must emit [rerun-if-changed] instructions for the permissions directory.
///
/// By default it is `./permissions/**/*` ignoring any [`InlinedPlugin`].
pub fn permissions_path_pattern(mut self, pattern: &'static str) -> Self {
self.permissions_path_pattern.replace(pattern);
self
}
}
/// Saves capabilities in a file inside the project, mainly to be read by tauri-cli.
fn save_capabilities(capabilities: &BTreeMap<String, Capability>) -> Result<PathBuf> {
let dir = Path::new(CAPABILITIES_SCHEMA_FOLDER_PATH);
fs::create_dir_all(dir)?;
let path = dir.join(CAPABILITIES_FILE_NAME);
let json = serde_json::to_string(&capabilities)?;
write_if_changed(&path, json)?;
Ok(path)
}
/// Saves ACL manifests in a file inside the project, mainly to be read by tauri-cli.
fn save_acl_manifests(acl_manifests: &BTreeMap<String, Manifest>) -> Result<PathBuf> {
let dir = Path::new(CAPABILITIES_SCHEMA_FOLDER_PATH);
fs::create_dir_all(dir)?;
let path = dir.join(ACL_MANIFESTS_FILE_NAME);
let json = serde_json::to_string(&acl_manifests)?;
write_if_changed(&path, json)?;
Ok(path)
}
/// Read plugin permissions and scope schema from env vars
fn read_plugins_manifests() -> Result<BTreeMap<String, Manifest>> {
use tauri_utils::acl;
let permission_map =
acl::build::read_permissions().context("failed to read plugin permissions")?;
let mut global_scope_map =
acl::build::read_global_scope_schemas().context("failed to read global scope schemas")?;
let mut manifests = BTreeMap::new();
for (plugin_name, permission_files) in permission_map {
let global_scope_schema = global_scope_map.remove(&plugin_name);
let manifest = Manifest::new(permission_files, global_scope_schema);
manifests.insert(plugin_name, manifest);
}
Ok(manifests)
}
struct InlinedPluginsAcl {
manifests: BTreeMap<String, Manifest>,
permission_files: BTreeMap<String, Vec<PermissionFile>>,
}
fn inline_plugins(
out_dir: &Path,
inlined_plugins: HashMap<&'static str, InlinedPlugin>,
) -> Result<InlinedPluginsAcl> {
let mut acl_manifests = BTreeMap::new();
let mut permission_files_map = BTreeMap::new();
for (name, plugin) in inlined_plugins {
let plugin_out_dir = out_dir.join("plugins").join(name);
fs::create_dir_all(&plugin_out_dir)?;
let mut permission_files = if plugin.commands.is_empty() {
Vec::new()
} else {
let autogenerated = tauri_utils::acl::build::autogenerate_command_permissions(
&plugin_out_dir,
plugin.commands,
"",
false,
);
let default_permissions = plugin.default.map(|default| match default {
DefaultPermissionRule::AllowAllCommands => autogenerated.allowed,
DefaultPermissionRule::Allow(permissions) => permissions,
});
if let Some(default_permissions) = default_permissions {
let default_permissions = default_permissions
.iter()
.map(|p| format!("\"{p}\""))
.collect::<Vec<String>>()
.join(",");
let default_permission = format!(
r###"# Automatically generated - DO NOT EDIT!
[default]
permissions = [{default_permissions}]
"###
);
let default_permission_path = plugin_out_dir.join("default.toml");
write_if_changed(&default_permission_path, default_permission)
.unwrap_or_else(|_| panic!("unable to autogenerate {default_permission_path:?}"));
}
tauri_utils::acl::build::define_permissions(
&PathBuf::from(glob::Pattern::escape(&plugin_out_dir.to_string_lossy()))
.join("*")
.to_string_lossy(),
name,
&plugin_out_dir,
|_| true,
)?
};
if let Some(pattern) = plugin.permissions_path_pattern {
permission_files.extend(tauri_utils::acl::build::define_permissions(
pattern,
name,
&plugin_out_dir,
|_| true,
)?);
} else {
let default_permissions_path = Path::new("permissions").join(name);
if default_permissions_path.exists() {
println!(
"cargo:rerun-if-changed={}",
default_permissions_path.display()
);
}
permission_files.extend(tauri_utils::acl::build::define_permissions(
&PathBuf::from(glob::Pattern::escape(
&default_permissions_path.to_string_lossy(),
))
.join("**")
.join("*")
.to_string_lossy(),
name,
&plugin_out_dir,
|_| true,
)?);
}
permission_files_map.insert(name.into(), permission_files.clone());
let manifest = tauri_utils::acl::manifest::Manifest::new(permission_files, None);
acl_manifests.insert(name.into(), manifest);
}
Ok(InlinedPluginsAcl {
manifests: acl_manifests,
permission_files: permission_files_map,
})
}
#[derive(Debug)]
struct AppManifestAcl {
manifest: Manifest,
permission_files: Vec<PermissionFile>,
}
fn app_manifest_permissions(
out_dir: &Path,
manifest: AppManifest,
inlined_plugins: &HashMap<&'static str, InlinedPlugin>,
) -> Result<AppManifestAcl> {
let app_out_dir = out_dir.join("app-manifest");
fs::create_dir_all(&app_out_dir)?;
let pkg_name = "__app__";
let mut permission_files = if manifest.commands.is_empty() {
Vec::new()
} else {
let autogenerated_path = Path::new("./permissions/autogenerated");
tauri_utils::acl::build::autogenerate_command_permissions(
autogenerated_path,
manifest.commands,
"",
false,
);
tauri_utils::acl::build::define_permissions(
&autogenerated_path.join("*").to_string_lossy(),
pkg_name,
&app_out_dir,
|_| true,
)?
};
if let Some(pattern) = manifest.permissions_path_pattern {
permission_files.extend(tauri_utils::acl::build::define_permissions(
pattern,
pkg_name,
&app_out_dir,
|_| true,
)?);
} else {
let default_permissions_path = Path::new("permissions");
if default_permissions_path.exists() {
println!(
"cargo:rerun-if-changed={}",
default_permissions_path.display()
);
}
let permissions_root = env::current_dir()?.join("permissions");
let inlined_plugins_permissions: Vec<_> = inlined_plugins
.keys()
.map(|name| permissions_root.join(name))
.flat_map(|p| p.canonicalize())
.collect();
permission_files.extend(tauri_utils::acl::build::define_permissions(
&default_permissions_path
.join("**")
.join("*")
.to_string_lossy(),
pkg_name,
&app_out_dir,
// filter out directories containing inlined plugins
|p| {
!inlined_plugins_permissions
.iter()
.any(|inlined_path| p.starts_with(inlined_path))
},
)?);
}
Ok(AppManifestAcl {
permission_files: permission_files.clone(),
manifest: tauri_utils::acl::manifest::Manifest::new(permission_files, None),
})
}
fn validate_capabilities(
acl_manifests: &BTreeMap<String, Manifest>,
capabilities: &BTreeMap<String, Capability>,
) -> Result<()> {
let target = tauri_utils::platform::Target::from_triple(&std::env::var("TARGET").unwrap());
for capability in capabilities.values() {
if !capability
.platforms
.as_ref()
.map(|platforms| platforms.contains(&target))
.unwrap_or(true)
{
continue;
}
for permission_entry in &capability.permissions {
let permission_id = permission_entry.identifier();
let key = permission_id.get_prefix().unwrap_or(APP_ACL_KEY);
let permission_name = permission_id.get_base();
let permission_exists = acl_manifests
.get(key)
.map(|manifest| {
// the default permission is always treated as valid, the CLI automatically adds it on the `tauri add` command
permission_name == "default"
|| manifest.permissions.contains_key(permission_name)
|| manifest.permission_sets.contains_key(permission_name)
})
.unwrap_or(false);
if !permission_exists {
let mut available_permissions = Vec::new();
for (key, manifest) in acl_manifests {
let prefix = if key == APP_ACL_KEY {
"".to_string()
} else {
format!("{key}:")
};
if manifest.default_permission.is_some() {
available_permissions.push(format!("{prefix}default"));
}
for p in manifest.permissions.keys() {
available_permissions.push(format!("{prefix}{p}"));
}
for p in manifest.permission_sets.keys() {
available_permissions.push(format!("{prefix}{p}"));
}
}
anyhow::bail!(
"Permission {} not found, expected one of {}",
permission_id.get(),
available_permissions.join(", ")
);
}
}
}
Ok(())
}
pub fn build(out_dir: &Path, target: Target, attributes: &Attributes) -> super::Result<()> {
let mut acl_manifests = read_plugins_manifests()?;
let app_acl = app_manifest_permissions(
out_dir,
attributes.app_manifest,
&attributes.inlined_plugins,
)?;
let has_app_manifest = app_acl.manifest.default_permission.is_some()
|| !app_acl.manifest.permission_sets.is_empty()
|| !app_acl.manifest.permissions.is_empty();
if has_app_manifest {
acl_manifests.insert(APP_ACL_KEY.into(), app_acl.manifest);
}
let inline_plugins_acl = inline_plugins(out_dir, attributes.inlined_plugins.clone())?;
acl_manifests.extend(inline_plugins_acl.manifests);
let acl_manifests_path = save_acl_manifests(&acl_manifests)?;
fs::copy(acl_manifests_path, out_dir.join(ACL_MANIFESTS_FILE_NAME))?;
tauri_utils::acl::schema::generate_capability_schema(&acl_manifests, target)?;
let capabilities = if let Some(pattern) = attributes.capabilities_path_pattern {
tauri_utils::acl::build::parse_capabilities(pattern)?
} else {
println!("cargo:rerun-if-changed=capabilities");
tauri_utils::acl::build::parse_capabilities("./capabilities/**/*")?
};
validate_capabilities(&acl_manifests, &capabilities)?;
let capabilities_path = save_capabilities(&capabilities)?;
fs::copy(capabilities_path, out_dir.join(CAPABILITIES_FILE_NAME))?;
let mut permissions_map = inline_plugins_acl.permission_files;
if has_app_manifest {
permissions_map.insert(APP_ACL_KEY.to_string(), app_acl.permission_files);
}
tauri_utils::acl::build::generate_allowed_commands(out_dir, Some(capabilities), permissions_map)?;
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-build/src/static_vcruntime.rs | crates/tauri-build/src/static_vcruntime.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
// taken from <https://github.com/ChrisDenton/static_vcruntime/>
// we're not using static_vcruntime directly because we want this for debug builds too
use std::{env, fs, io::Write, path::Path};
pub fn build() {
override_msvcrt_lib();
// Disable conflicting libraries that aren't hard coded by Rust
println!("cargo:rustc-link-arg=/NODEFAULTLIB:libvcruntimed.lib");
println!("cargo:rustc-link-arg=/NODEFAULTLIB:vcruntime.lib");
println!("cargo:rustc-link-arg=/NODEFAULTLIB:vcruntimed.lib");
println!("cargo:rustc-link-arg=/NODEFAULTLIB:libcmtd.lib");
println!("cargo:rustc-link-arg=/NODEFAULTLIB:msvcrt.lib");
println!("cargo:rustc-link-arg=/NODEFAULTLIB:msvcrtd.lib");
println!("cargo:rustc-link-arg=/NODEFAULTLIB:libucrt.lib");
println!("cargo:rustc-link-arg=/NODEFAULTLIB:libucrtd.lib");
// Set the libraries we want.
println!("cargo:rustc-link-arg=/DEFAULTLIB:libcmt.lib");
println!("cargo:rustc-link-arg=/DEFAULTLIB:libvcruntime.lib");
println!("cargo:rustc-link-arg=/DEFAULTLIB:ucrt.lib");
}
/// Override the hard-coded msvcrt.lib by replacing it with a (mostly) empty object file.
fn override_msvcrt_lib() {
// Get the right machine type for the empty library.
let arch = std::env::var("CARGO_CFG_TARGET_ARCH");
let machine: &[u8] = if arch.as_deref() == Ok("x86_64") {
&[0x64, 0x86]
} else if arch.as_deref() == Ok("x86") {
&[0x4C, 0x01]
} else {
return;
};
let bytes: &[u8] = &[
1, 0, 94, 3, 96, 98, 60, 0, 0, 0, 1, 0, 0, 0, 0, 0, 132, 1, 46, 100, 114, 101, 99, 116, 118,
101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 60, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
10, 16, 0, 46, 100, 114, 101, 99, 116, 118, 101, 0, 0, 0, 0, 1, 0, 0, 0, 3, 0, 4, 0, 0, 0,
];
// Write the empty "msvcrt.lib" to the output directory.
let out_dir = env::var("OUT_DIR").unwrap();
let path = Path::new(&out_dir).join("msvcrt.lib");
let f = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path);
if let Ok(mut f) = f {
f.write_all(machine).unwrap();
f.write_all(bytes).unwrap();
}
// Add the output directory to the native library path.
println!("cargo:rustc-link-search=native={out_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-build/src/codegen/mod.rs | crates/tauri-build/src/codegen/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
pub(crate) mod context;
| 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/src/codegen/context.rs | crates/tauri-build/src/codegen/context.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use anyhow::{Context, Result};
use std::{
env::var,
fs::{create_dir_all, File},
io::{BufWriter, Write},
path::{Path, PathBuf},
};
use tauri_codegen::{context_codegen, ContextData};
use tauri_utils::config::FrontendDist;
// TODO docs
/// A builder for generating a Tauri application context during compile time.
#[cfg_attr(docsrs, doc(cfg(feature = "codegen")))]
#[derive(Debug)]
pub struct CodegenContext {
config_path: PathBuf,
out_file: PathBuf,
capabilities: Option<Vec<PathBuf>>,
}
impl Default for CodegenContext {
fn default() -> Self {
Self {
config_path: PathBuf::from("tauri.conf.json"),
out_file: PathBuf::from("tauri-build-context.rs"),
capabilities: None,
}
}
}
impl CodegenContext {
/// Create a new [`CodegenContext`] builder that is already filled with the default options.
pub fn new() -> Self {
Self::default()
}
/// Set the path to the `tauri.conf.json` (relative to the package's directory).
///
/// This defaults to a file called `tauri.conf.json` inside of the current working directory of
/// the package compiling; does not need to be set manually if that config file is in the same
/// directory as your `Cargo.toml`.
#[must_use]
pub fn config_path(mut self, config_path: impl Into<PathBuf>) -> Self {
self.config_path = config_path.into();
self
}
/// Sets the output file's path.
///
/// **Note:** This path should be relative to the `OUT_DIR`.
///
/// Don't set this if you are using [`tauri::tauri_build_context!`] as that helper macro
/// expects the default value. This option can be useful if you are not using the helper and
/// instead using [`std::include!`] on the generated code yourself.
///
/// Defaults to `tauri-build-context.rs`.
///
/// [`tauri::tauri_build_context!`]: https://docs.rs/tauri/latest/tauri/macro.tauri_build_context.html
#[must_use]
pub fn out_file(mut self, filename: PathBuf) -> Self {
self.out_file = filename;
self
}
/// Adds a capability file to the generated context.
#[must_use]
pub fn capability<P: AsRef<Path>>(mut self, path: P) -> Self {
self
.capabilities
.get_or_insert_with(Default::default)
.push(path.as_ref().to_path_buf());
self
}
/// Generate the code and write it to the output file - returning the path it was saved to.
///
/// Unless you are doing something special with this builder, you don't need to do anything with
/// the returned output path.
pub(crate) fn try_build(self) -> Result<PathBuf> {
let (config, config_parent) = tauri_codegen::get_config(&self.config_path)?;
// rerun if changed
match &config.build.frontend_dist {
Some(FrontendDist::Directory(p)) => {
let dist_path = config_parent.join(p);
if dist_path.exists() {
println!("cargo:rerun-if-changed={}", dist_path.display());
}
}
Some(FrontendDist::Files(files)) => {
for path in files {
println!(
"cargo:rerun-if-changed={}",
config_parent.join(path).display()
);
}
}
_ => (),
}
for icon in &config.bundle.icon {
println!(
"cargo:rerun-if-changed={}",
config_parent.join(icon).display()
);
}
if let Some(tray_icon) = config.app.tray_icon.as_ref().map(|t| &t.icon_path) {
println!(
"cargo:rerun-if-changed={}",
config_parent.join(tray_icon).display()
);
}
#[cfg(target_os = "macos")]
{
let info_plist_path = config_parent.join("Info.plist");
if info_plist_path.exists() {
println!("cargo:rerun-if-changed={}", info_plist_path.display());
}
if let Some(plist_path) = &config.bundle.macos.info_plist {
let info_plist_path = config_parent.join(plist_path);
if info_plist_path.exists() {
println!("cargo:rerun-if-changed={}", info_plist_path.display());
}
}
}
let code = context_codegen(ContextData {
dev: crate::is_dev(),
config,
config_parent,
// it's very hard to have a build script for unit tests, so assume this is always called from
// outside the tauri crate, making the ::tauri root valid.
root: quote::quote!(::tauri),
capabilities: self.capabilities,
assets: None,
test: false,
})?;
// get the full output file path
let out = var("OUT_DIR")
.map(PathBuf::from)
.map(|path| path.join(&self.out_file))
.with_context(|| "unable to find OUT_DIR during tauri-build")?;
// make sure any nested directories in OUT_DIR are created
let parent = out.parent().with_context(|| {
"`Codegen` could not find the parent to `out_file` while creating the file"
})?;
create_dir_all(parent)?;
let mut file = File::create(&out).map(BufWriter::new).with_context(|| {
format!(
"Unable to create output file during tauri-build {}",
out.display()
)
})?;
writeln!(file, "{code}").with_context(|| {
format!(
"Unable to write tokenstream to out file during tauri-build {}",
out.display()
)
})?;
Ok(out)
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tests/restart/build.rs | crates/tests/restart/build.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
fn main() {}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tests/restart/src/main.rs | crates/tests/restart/src/main.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use tauri::Env;
fn main() {
let mut argv = std::env::args();
let argc = argv.len();
if argc == 0 || argc > 2 {
panic!("restart test binary expect either no arguments or `restart`.")
}
println!(
"{}",
tauri::process::current_binary(&Default::default())
.expect("tauri::process::current_binary could not resolve")
.display()
);
match argv.nth(1).as_deref() {
Some("restart") => {
let mut env = Env::default();
env.args_os.clear();
tauri::process::restart(&env)
}
Some(invalid) => panic!("only argument `restart` is allowed, {invalid} is invalid"),
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/tests/restart/tests/restart.rs | crates/tests/restart/tests/restart.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::io;
use std::path::{Path, PathBuf};
use std::process::Command;
/// Helper for generic catch-all errors.
type Result = std::result::Result<(), Box<dyn std::error::Error>>;
/// <https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes--1300-1699->
#[cfg(windows)]
const ERROR_PRIVILEGE_NOT_HELD: i32 = 1314;
/// Represents a successfully created symlink.
enum Symlink {
/// Path to the created symlink
Created(PathBuf),
/// A symlink that failed due to missing permissions (Windows).
#[allow(dead_code)]
Privilege,
}
/// Compile the test binary, run it, and compare it with expected output.
///
/// Failing to create a symlink due to permissions issues is also a success
/// for the purpose of this runner.
fn symlink_runner(create_symlinks: impl Fn(&Path) -> io::Result<Symlink>) -> Result {
let mut compiled_binary = PathBuf::from(env!("OUT_DIR")).join("../../../restart");
if cfg!(windows) {
compiled_binary.set_extension("exe");
}
println!("{compiled_binary:?}");
// set up all the temporary file paths
let temp = tempfile::TempDir::new()?;
let bin = temp.path().canonicalize()?.join("restart.exe");
// copy the built restart test binary to our temporary directory
std::fs::copy(compiled_binary, &bin)?;
if let Symlink::Created(link) = create_symlinks(&bin)? {
// run the command from the symlink, so that we can test if restart resolves it correctly
let mut cmd = Command::new(link);
// add the restart parameter so that the invocation will call tauri::process::restart
cmd.arg("restart");
let output = cmd.output()?;
// run `TempDir` destructors to prevent resource leaking if the assertion fails
drop(temp);
if output.status.success() {
// gather the output into a string
let stdout = String::from_utf8_lossy(&output.stdout);
// we expect the output to be the bin path, twice
assert_eq!(stdout, format!("{bin}\n{bin}\n", bin = bin.display()));
} else if cfg!(all(
target_os = "macos",
not(feature = "process-relaunch-dangerous-allow-symlink-macos")
)) {
// we expect this to fail on macOS without the dangerous symlink flag set
let stderr = String::from_utf8_lossy(&output.stderr);
// make sure it's the error that we expect
assert!(stderr.contains(
"StartingBinary found current_exe() that contains a symlink on a non-allowed platform"
));
} else {
// we didn't expect the program to fail in this configuration, just panic
panic!("restart integration test runner failed for unknown reason");
}
}
Ok(())
}
/// Cross-platform way to create a symlink
///
/// Symlinks that failed to create due to permissions issues (like on Windows)
/// are also seen as successful for the purpose of this testing suite.
fn create_symlink(original: &Path, link: PathBuf) -> io::Result<Symlink> {
#[cfg(unix)]
return std::os::unix::fs::symlink(original, &link).map(|()| Symlink::Created(link));
#[cfg(windows)]
return match std::os::windows::fs::symlink_file(original, &link) {
Ok(()) => Ok(Symlink::Created(link)),
Err(e) => match e.raw_os_error() {
Some(ERROR_PRIVILEGE_NOT_HELD) => Ok(Symlink::Privilege),
_ => Err(e),
},
};
}
/// Only use 1 test to prevent cargo from waiting on itself.
///
/// While not ideal, this is fine because they use the same solution for both cases.
#[test]
fn restart_symlinks() -> Result {
// single symlink
symlink_runner(|bin| {
let mut link = bin.to_owned();
link.set_file_name("symlink");
link.set_extension("exe");
create_symlink(bin, link)
})?;
// nested symlinks
symlink_runner(|bin| {
let mut link1 = bin.to_owned();
link1.set_file_name("symlink1");
link1.set_extension("exe");
create_symlink(bin, link1.clone())?;
let mut link2 = bin.to_owned();
link2.set_file_name("symlink2");
link2.set_extension("exe");
create_symlink(&link1, link2)
})
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tests/acl/src/lib.rs | crates/tests/acl/src/lib.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
#[cfg(test)]
mod tests {
use std::{
collections::BTreeMap,
env::temp_dir,
fs::{read_dir, read_to_string},
path::Path,
};
use tauri_utils::{
acl::{build::parse_capabilities, manifest::Manifest, resolved::Resolved},
platform::Target,
};
fn load_plugins(plugins: &[String]) -> BTreeMap<String, Manifest> {
let mut manifests = BTreeMap::new();
let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
let out_dir = temp_dir();
for plugin in plugins {
let plugin_path = manifest_dir.join("fixtures").join("plugins").join(plugin);
let permission_files = tauri_utils::acl::build::define_permissions(
&format!("{}/*.toml", plugin_path.display()),
plugin,
&out_dir,
|_| true,
)
.expect("failed to define permissions");
let manifest = Manifest::new(permission_files, None);
manifests.insert(plugin.to_string(), manifest);
}
manifests
}
#[test]
fn resolve_acl() {
let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
let fixtures_path = manifest_dir.join("fixtures").join("capabilities");
for fixture_path in read_dir(fixtures_path).expect("failed to read fixtures") {
let fixture_entry = fixture_path.expect("failed to read fixture entry");
let mut settings = insta::Settings::clone_current();
settings.set_snapshot_path(
if fixture_entry.path().file_name().unwrap() == "platform-specific-permissions" {
Path::new("../fixtures/snapshots").join(Target::current().to_string())
} else {
Path::new("../fixtures/snapshots").to_path_buf()
},
);
let _guard = settings.bind_to_scope();
let fixture_plugins_str = read_to_string(fixture_entry.path().join("required-plugins.json"))
.expect("failed to read fixture required-plugins.json file");
let fixture_plugins: Vec<String> = serde_json::from_str(&fixture_plugins_str)
.expect("required-plugins.json is not a valid JSON");
let manifests = load_plugins(&fixture_plugins);
let capabilities = parse_capabilities(&format!("{}/cap*", fixture_entry.path().display()))
.expect("failed to parse capabilities");
let resolved = Resolved::resolve(&manifests, capabilities, Target::current())
.expect("failed to resolve ACL");
insta::assert_debug_snapshot!(
fixture_entry
.path()
.file_name()
.unwrap()
.to_string_lossy()
.to_string(),
resolved
);
}
}
}
| 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-generator/build.rs | crates/tauri-schema-generator/build.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{error::Error, path::PathBuf};
use serde::Deserialize;
use tauri_utils::{
acl::{capability::Capability, Permission, Scopes},
config::Config,
write_if_changed,
};
macro_rules! schema {
($name:literal, $path:ty) => {
(concat!($name, ".schema.json"), schemars::schema_for!($path))
};
}
#[derive(Deserialize)]
pub struct VersionMetadata {
tauri: String,
}
pub fn main() -> Result<(), Box<dyn Error>> {
let schemas = [
schema!("capability", Capability),
schema!("permission", Permission),
schema!("scope", Scopes),
];
let out = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR")?);
let schemas_dir = out.join("schemas");
std::fs::create_dir_all(&schemas_dir)?;
for (filename, schema) in schemas {
let schema = serde_json::to_string_pretty(&schema)?;
write_if_changed(schemas_dir.join(filename), &schema)?;
}
// write config schema file
{
let metadata = include_str!("../tauri-cli/metadata-v2.json");
let tauri_ver = serde_json::from_str::<VersionMetadata>(metadata)?.tauri;
// set id for generated schema
let (filename, mut config_schema) = schema!("config", Config);
let schema_metadata = config_schema.schema.metadata.as_mut().unwrap();
schema_metadata.id = Some(format!("https://schema.tauri.app/config/{tauri_ver}"));
let config_schema = serde_json::to_string_pretty(&config_schema)?;
write_if_changed(schemas_dir.join(filename), &config_schema)?;
write_if_changed(out.join("../tauri-cli/config.schema.json"), config_schema)?;
}
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-schema-generator/src/main.rs | crates/tauri-schema-generator/src/main.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Hosts the schema for the Tauri configuration file.
#![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"
)]
fn main() {}
| 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-codegen/src/lib.rs | crates/tauri-codegen/src/lib.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! - Embed, hash, and compress assets, including icons for the app as well as the tray icon.
//! - Parse `tauri.conf.json` at compile time and generate the Config struct.
#![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"
)]
pub use self::context::{context_codegen, ContextData};
use crate::embedded_assets::{ensure_out_dir, EmbeddedAssetsError};
use proc_macro2::TokenStream;
use quote::{quote, ToTokens, TokenStreamExt};
use std::{
borrow::Cow,
fmt::{self, Write},
path::{Path, PathBuf},
};
pub use tauri_utils::config::{parse::ConfigError, Config};
use tauri_utils::platform::Target;
use tauri_utils::write_if_changed;
mod context;
pub mod embedded_assets;
pub mod image;
#[doc(hidden)]
pub mod vendor;
/// Represents all the errors that can happen while reading the config during codegen.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum CodegenConfigError {
#[error("unable to access current working directory: {0}")]
CurrentDir(std::io::Error),
// this error should be "impossible" because we use std::env::current_dir() - cover it anyways
#[error("Tauri config file has no parent, this shouldn't be possible. file an issue on https://github.com/tauri-apps/tauri - target {0}")]
Parent(PathBuf),
#[error("unable to parse inline JSON TAURI_CONFIG env var: {0}")]
FormatInline(serde_json::Error),
#[error(transparent)]
Json(#[from] serde_json::Error),
#[error("{0}")]
ConfigError(#[from] ConfigError),
}
/// Get the [`Config`] from the `TAURI_CONFIG` environmental variable, or read from the passed path.
///
/// If the passed path is relative, it should be relative to the current working directory of the
/// compiling crate.
pub fn get_config(path: &Path) -> Result<(Config, PathBuf), CodegenConfigError> {
let path = if path.is_relative() {
let cwd = std::env::current_dir().map_err(CodegenConfigError::CurrentDir)?;
Cow::Owned(cwd.join(path))
} else {
Cow::Borrowed(path)
};
// this should be impossible because of the use of `current_dir()` above, but handle it anyways
let parent = path
.parent()
.map(ToOwned::to_owned)
.ok_or_else(|| CodegenConfigError::Parent(path.into_owned()))?;
let target = std::env::var("TAURI_ENV_TARGET_TRIPLE")
.as_deref()
.map(Target::from_triple)
.unwrap_or_else(|_| Target::current());
// in the future we may want to find a way to not need the TAURI_CONFIG env var so that
// it is impossible for the content of two separate configs to get mixed up. The chances are
// already unlikely unless the developer goes out of their way to run the cli on a different
// project than the target crate.
let mut config =
serde_json::from_value(tauri_utils::config::parse::read_from(target, &parent)?.0)?;
if let Ok(env) = std::env::var("TAURI_CONFIG") {
let merge_config: serde_json::Value =
serde_json::from_str(&env).map_err(CodegenConfigError::FormatInline)?;
json_patch::merge(&mut config, &merge_config);
}
// Set working directory to where `tauri.config.json` is, so that relative paths in it are parsed correctly.
let old_cwd = std::env::current_dir().map_err(CodegenConfigError::CurrentDir)?;
std::env::set_current_dir(parent.clone()).map_err(CodegenConfigError::CurrentDir)?;
let config = serde_json::from_value(config)?;
// Reset working directory.
std::env::set_current_dir(old_cwd).map_err(CodegenConfigError::CurrentDir)?;
Ok((config, parent))
}
/// Create a blake3 checksum of the passed bytes.
fn checksum(bytes: &[u8]) -> Result<String, fmt::Error> {
let mut hasher = vendor::blake3_reference::Hasher::default();
hasher.update(bytes);
let mut bytes = [0u8; 32];
hasher.finalize(&mut bytes);
let mut hex = String::with_capacity(2 * bytes.len());
for b in bytes {
write!(hex, "{b:02x}")?;
}
Ok(hex)
}
/// Cache the data to `$OUT_DIR`, only if it does not already exist.
///
/// Due to using a checksum as the filename, an existing file should be the exact same content
/// as the data being checked.
struct Cached {
checksum: String,
}
impl TryFrom<String> for Cached {
type Error = EmbeddedAssetsError;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::try_from(Vec::from(value))
}
}
impl TryFrom<Vec<u8>> for Cached {
type Error = EmbeddedAssetsError;
fn try_from(content: Vec<u8>) -> Result<Self, Self::Error> {
let checksum = checksum(content.as_ref()).map_err(EmbeddedAssetsError::Hex)?;
let path = ensure_out_dir()?.join(&checksum);
write_if_changed(&path, &content)
.map(|_| Self { checksum })
.map_err(|error| EmbeddedAssetsError::AssetWrite { path, error })
}
}
impl ToTokens for Cached {
fn to_tokens(&self, tokens: &mut TokenStream) {
let path = &self.checksum;
tokens.append_all(quote!(::std::concat!(::std::env!("OUT_DIR"), "/", #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-codegen/src/image.rs | crates/tauri-codegen/src/image.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{
embedded_assets::{EmbeddedAssetsError, EmbeddedAssetsResult},
Cached,
};
use proc_macro2::TokenStream;
use quote::{quote, ToTokens, TokenStreamExt};
use std::{ffi::OsStr, io::Cursor, path::Path};
/// The format the Icon is consumed as.
pub(crate) enum IconFormat {
/// The image, completely unmodified.
Raw,
/// RGBA raw data, meant to be consumed by [`tauri::image::Image`].
Image { width: u32, height: u32 },
}
pub struct CachedIcon {
cache: Cached,
format: IconFormat,
root: TokenStream,
}
impl CachedIcon {
pub fn new(root: &TokenStream, icon: &Path) -> EmbeddedAssetsResult<Self> {
match icon.extension().map(OsStr::to_string_lossy).as_deref() {
Some("png") => Self::new_png(root, icon),
Some("ico") => Self::new_ico(root, icon),
unknown => Err(EmbeddedAssetsError::InvalidImageExtension {
extension: unknown.unwrap_or_default().into(),
path: icon.to_path_buf(),
}),
}
}
/// Cache the icon without any manipulation.
pub fn new_raw(root: &TokenStream, icon: &Path) -> EmbeddedAssetsResult<Self> {
let buf = Self::open(icon);
Cached::try_from(buf).map(|cache| Self {
cache,
root: root.clone(),
format: IconFormat::Raw,
})
}
/// Cache an ICO icon as RGBA data, see [`ImageFormat::Image`].
pub fn new_ico(root: &TokenStream, icon: &Path) -> EmbeddedAssetsResult<Self> {
let buf = Self::open(icon);
let icon_dir = ico::IconDir::read(Cursor::new(&buf))
.unwrap_or_else(|e| panic!("failed to parse icon {}: {}", icon.display(), e));
let entry = &icon_dir.entries()[0];
let rgba = entry
.decode()
.unwrap_or_else(|e| panic!("failed to decode icon {}: {}", icon.display(), e))
.rgba_data()
.to_vec();
Cached::try_from(rgba).map(|cache| Self {
cache,
root: root.clone(),
format: IconFormat::Image {
width: entry.width(),
height: entry.height(),
},
})
}
/// Cache a PNG icon as RGBA data, see [`ImageFormat::Image`].
pub fn new_png(root: &TokenStream, icon: &Path) -> EmbeddedAssetsResult<Self> {
let buf = Self::open(icon);
let decoder = png::Decoder::new(Cursor::new(&buf));
let mut reader = decoder
.read_info()
.unwrap_or_else(|e| panic!("failed to read icon {}: {}", icon.display(), e));
if reader.output_color_type().0 != png::ColorType::Rgba {
panic!("icon {} is not RGBA", icon.display());
}
let mut rgba = Vec::with_capacity(reader.output_buffer_size());
while let Ok(Some(row)) = reader.next_row() {
rgba.extend(row.data());
}
Cached::try_from(rgba).map(|cache| Self {
cache,
root: root.clone(),
format: IconFormat::Image {
width: reader.info().width,
height: reader.info().height,
},
})
}
fn open(path: &Path) -> Vec<u8> {
std::fs::read(path).unwrap_or_else(|e| panic!("failed to open icon {}: {}", path.display(), e))
}
}
impl ToTokens for CachedIcon {
fn to_tokens(&self, tokens: &mut TokenStream) {
let root = &self.root;
let cache = &self.cache;
let raw = quote!(::std::include_bytes!(#cache));
tokens.append_all(match self.format {
IconFormat::Raw => raw,
IconFormat::Image { width, height } => {
quote!(#root::image::Image::new(#raw, #width, #height))
}
})
}
}
| 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-codegen/src/embedded_assets.rs | crates/tauri-codegen/src/embedded_assets.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use base64::Engine;
use proc_macro2::TokenStream;
use quote::{quote, ToTokens, TokenStreamExt};
use sha2::{Digest, Sha256};
use std::{
collections::HashMap,
fs::File,
path::{Path, PathBuf},
};
use tauri_utils::config::PatternKind;
use tauri_utils::{assets::AssetKey, config::DisabledCspModificationKind};
use thiserror::Error;
use walkdir::{DirEntry, WalkDir};
#[cfg(feature = "compression")]
use brotli::enc::backward_references::BrotliEncoderParams;
/// The subdirectory inside the target directory we want to place assets.
const TARGET_PATH: &str = "tauri-codegen-assets";
/// (key, (original filepath, compressed bytes))
type Asset = (AssetKey, (PathBuf, PathBuf));
/// All possible errors while reading and compressing an [`EmbeddedAssets`] directory
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum EmbeddedAssetsError {
#[error("failed to read asset at {path} because {error}")]
AssetRead {
path: PathBuf,
error: std::io::Error,
},
#[error("failed to write asset from {path} to Vec<u8> because {error}")]
AssetWrite {
path: PathBuf,
error: std::io::Error,
},
#[error("failed to create hex from bytes because {0}")]
Hex(std::fmt::Error),
#[error("invalid prefix {prefix} used while including path {path}")]
PrefixInvalid { prefix: PathBuf, path: PathBuf },
#[error("invalid extension `{extension}` used for image {path}, must be `ico` or `png`")]
InvalidImageExtension { extension: PathBuf, path: PathBuf },
#[error("failed to walk directory {path} because {error}")]
Walkdir {
path: PathBuf,
error: walkdir::Error,
},
#[error("OUT_DIR env var is not set, do you have a build script?")]
OutDir,
#[error("version error: {0}")]
Version(#[from] semver::Error),
}
pub type EmbeddedAssetsResult<T> = Result<T, EmbeddedAssetsError>;
/// Represent a directory of assets that are compressed and embedded.
///
/// This is the compile time generation of [`tauri_utils::assets::Assets`] from a directory. Assets
/// from the directory are added as compiler dependencies by dummy including the original,
/// uncompressed assets.
///
/// The assets are compressed during this runtime, and can only be represented as a [`TokenStream`]
/// through [`ToTokens`]. The generated code is meant to be injected into an application to include
/// the compressed assets in that application's binary.
#[derive(Default)]
pub struct EmbeddedAssets {
assets: HashMap<AssetKey, (PathBuf, PathBuf)>,
csp_hashes: CspHashes,
}
pub struct EmbeddedAssetsInput(Vec<PathBuf>);
impl From<PathBuf> for EmbeddedAssetsInput {
fn from(path: PathBuf) -> Self {
Self(vec![path])
}
}
impl From<Vec<PathBuf>> for EmbeddedAssetsInput {
fn from(paths: Vec<PathBuf>) -> Self {
Self(paths)
}
}
/// Holds a list of (prefix, entry)
struct RawEmbeddedAssets {
paths: Vec<(PathBuf, DirEntry)>,
csp_hashes: CspHashes,
}
impl RawEmbeddedAssets {
/// Creates a new list of (prefix, entry) from a collection of inputs.
fn new(input: EmbeddedAssetsInput, options: &AssetOptions) -> Result<Self, EmbeddedAssetsError> {
let mut csp_hashes = CspHashes::default();
input
.0
.into_iter()
.flat_map(|path| {
let prefix = if path.is_dir() {
path.clone()
} else {
path
.parent()
.expect("embedded file asset has no parent")
.to_path_buf()
};
WalkDir::new(&path)
.follow_links(true)
.contents_first(true)
.into_iter()
.map(move |entry| (prefix.clone(), entry))
})
.filter_map(|(prefix, entry)| {
match entry {
// we only serve files, not directory listings
Ok(entry) if entry.file_type().is_dir() => None,
// compress all files encountered
Ok(entry) => {
if let Err(error) = csp_hashes
.add_if_applicable(&entry, &options.dangerous_disable_asset_csp_modification)
{
Some(Err(error))
} else {
Some(Ok((prefix, entry)))
}
}
// pass down error through filter to fail when encountering any error
Err(error) => Some(Err(EmbeddedAssetsError::Walkdir {
path: prefix,
error,
})),
}
})
.collect::<Result<Vec<(PathBuf, DirEntry)>, _>>()
.map(|paths| Self { paths, csp_hashes })
}
}
/// Holds all hashes that we will apply on the CSP tag/header.
#[derive(Debug, Default)]
pub struct CspHashes {
/// Scripts that are part of the asset collection (JS or MJS files).
pub(crate) scripts: Vec<String>,
/// Inline scripts (`<script>code</script>`). Maps a HTML path to a list of hashes.
pub(crate) inline_scripts: HashMap<String, Vec<String>>,
/// A list of hashes of the contents of all `style` elements.
pub(crate) styles: Vec<String>,
}
impl CspHashes {
/// Only add a CSP hash to the appropriate category if we think the file matches
///
/// Note: this only checks the file extension, much like how a browser will assume a .js file is
/// a JavaScript file unless HTTP headers tell it otherwise.
pub fn add_if_applicable(
&mut self,
entry: &DirEntry,
dangerous_disable_asset_csp_modification: &DisabledCspModificationKind,
) -> Result<(), EmbeddedAssetsError> {
let path = entry.path();
// we only hash JavaScript files for now, may expand to other CSP hashable types in the future
if let Some("js") | Some("mjs") = path.extension().and_then(|os| os.to_str()) {
if dangerous_disable_asset_csp_modification.can_modify("script-src") {
let mut hasher = Sha256::new();
hasher.update(
&std::fs::read(path)
.map(|b| tauri_utils::html::normalize_script_for_csp(&b))
.map_err(|error| EmbeddedAssetsError::AssetRead {
path: path.to_path_buf(),
error,
})?,
);
let hash = hasher.finalize();
self.scripts.push(format!(
"'sha256-{}'",
base64::engine::general_purpose::STANDARD.encode(hash)
));
}
}
Ok(())
}
}
/// Options used to embed assets.
#[derive(Default)]
pub struct AssetOptions {
pub(crate) csp: bool,
pub(crate) pattern: PatternKind,
pub(crate) freeze_prototype: bool,
pub(crate) dangerous_disable_asset_csp_modification: DisabledCspModificationKind,
#[cfg(feature = "isolation")]
pub(crate) isolation_schema: String,
}
impl AssetOptions {
/// Creates the default asset options.
pub fn new(pattern: PatternKind) -> Self {
Self {
csp: false,
pattern,
freeze_prototype: false,
dangerous_disable_asset_csp_modification: DisabledCspModificationKind::Flag(false),
#[cfg(feature = "isolation")]
isolation_schema: format!("isolation-{}", uuid::Uuid::new_v4()),
}
}
/// Instruct the asset handler to inject the CSP token to HTML files (Linux only) and add asset nonces and hashes to the policy.
#[must_use]
pub fn with_csp(mut self) -> Self {
self.csp = true;
self
}
/// Instruct the asset handler to include a script to freeze the `Object.prototype` on all HTML files.
#[must_use]
pub fn freeze_prototype(mut self, freeze: bool) -> Self {
self.freeze_prototype = freeze;
self
}
/// Instruct the asset handler to **NOT** modify the CSP. This is **NOT** recommended.
pub fn dangerous_disable_asset_csp_modification(
mut self,
dangerous_disable_asset_csp_modification: DisabledCspModificationKind,
) -> Self {
self.dangerous_disable_asset_csp_modification = dangerous_disable_asset_csp_modification;
self
}
}
impl EmbeddedAssets {
/// Compress a collection of files and directories, ready to be generated into [`Assets`].
///
/// [`Assets`]: tauri_utils::assets::Assets
pub fn new(
input: impl Into<EmbeddedAssetsInput>,
options: &AssetOptions,
mut map: impl FnMut(
&AssetKey,
&Path,
&mut Vec<u8>,
&mut CspHashes,
) -> Result<(), EmbeddedAssetsError>,
) -> Result<Self, EmbeddedAssetsError> {
// we need to pre-compute all files now, so that we can inject data from all files into a few
let RawEmbeddedAssets { paths, csp_hashes } = RawEmbeddedAssets::new(input.into(), options)?;
struct CompressState {
csp_hashes: CspHashes,
assets: HashMap<AssetKey, (PathBuf, PathBuf)>,
}
let CompressState { assets, csp_hashes } = paths.into_iter().try_fold(
CompressState {
csp_hashes,
assets: HashMap::new(),
},
move |mut state, (prefix, entry)| {
let (key, asset) =
Self::compress_file(&prefix, entry.path(), &mut map, &mut state.csp_hashes)?;
state.assets.insert(key, asset);
Result::<_, EmbeddedAssetsError>::Ok(state)
},
)?;
Ok(Self { assets, csp_hashes })
}
/// Use highest compression level for release, the fastest one for everything else
#[cfg(feature = "compression")]
fn compression_settings() -> BrotliEncoderParams {
let mut settings = BrotliEncoderParams::default();
// the following compression levels are hand-picked and are not min-maxed.
// they have a good balance of runtime vs size for the respective profile goals.
// see the "brotli" section of this comment https://github.com/tauri-apps/tauri/issues/3571#issuecomment-1054847558
if cfg!(debug_assertions) {
settings.quality = 2
} else {
settings.quality = 9
}
settings
}
/// Compress a file and spit out the information in a [`HashMap`] friendly form.
fn compress_file(
prefix: &Path,
path: &Path,
map: &mut impl FnMut(
&AssetKey,
&Path,
&mut Vec<u8>,
&mut CspHashes,
) -> Result<(), EmbeddedAssetsError>,
csp_hashes: &mut CspHashes,
) -> Result<Asset, EmbeddedAssetsError> {
let mut input = std::fs::read(path).map_err(|error| EmbeddedAssetsError::AssetRead {
path: path.to_owned(),
error,
})?;
// get a key to the asset path without the asset directory prefix
let key = path
.strip_prefix(prefix)
.map(AssetKey::from) // format the path for use in assets
.map_err(|_| EmbeddedAssetsError::PrefixInvalid {
prefix: prefix.to_owned(),
path: path.to_owned(),
})?;
// perform any caller-requested input manipulation
map(&key, path, &mut input, csp_hashes)?;
// we must canonicalize the base of our paths to allow long paths on windows
let out_dir = std::env::var("OUT_DIR")
.map_err(|_| EmbeddedAssetsError::OutDir)
.map(PathBuf::from)
.and_then(|p| p.canonicalize().map_err(|_| EmbeddedAssetsError::OutDir))
.map(|p| p.join(TARGET_PATH))?;
// make sure that our output directory is created
std::fs::create_dir_all(&out_dir).map_err(|_| EmbeddedAssetsError::OutDir)?;
// get a hash of the input - allows for caching existing files
let hash = crate::checksum(&input).map_err(EmbeddedAssetsError::Hex)?;
// use the content hash to determine filename, keep extensions that exist
let out_path = if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
out_dir.join(format!("{hash}.{ext}"))
} else {
out_dir.join(hash)
};
// only compress and write to the file if it doesn't already exist.
if !out_path.exists() {
#[allow(unused_mut)]
let mut out_file =
File::create(&out_path).map_err(|error| EmbeddedAssetsError::AssetWrite {
path: out_path.clone(),
error,
})?;
#[cfg(not(feature = "compression"))]
{
use std::io::Write;
out_file
.write_all(&input)
.map_err(|error| EmbeddedAssetsError::AssetWrite {
path: path.to_owned(),
error,
})?;
}
#[cfg(feature = "compression")]
{
let mut input = std::io::Cursor::new(input);
// entirely write input to the output file path with compression
brotli::BrotliCompress(&mut input, &mut out_file, &Self::compression_settings()).map_err(
|error| EmbeddedAssetsError::AssetWrite {
path: path.to_owned(),
error,
},
)?;
}
}
Ok((key, (path.into(), out_path)))
}
}
impl ToTokens for EmbeddedAssets {
fn to_tokens(&self, tokens: &mut TokenStream) {
let mut assets = TokenStream::new();
for (key, (input, output)) in &self.assets {
let key: &str = key.as_ref();
let input = input.display().to_string();
let output = output.display().to_string();
// add original asset as a compiler dependency, rely on dead code elimination to clean it up
assets.append_all(quote!(#key => {
const _: &[u8] = include_bytes!(#input);
include_bytes!(#output)
},));
}
let mut global_hashes = TokenStream::new();
for script_hash in &self.csp_hashes.scripts {
let hash = script_hash.as_str();
global_hashes.append_all(quote!(CspHash::Script(#hash),));
}
for style_hash in &self.csp_hashes.styles {
let hash = style_hash.as_str();
global_hashes.append_all(quote!(CspHash::Style(#hash),));
}
let mut html_hashes = TokenStream::new();
for (path, hashes) in &self.csp_hashes.inline_scripts {
let key = path.as_str();
let mut value = TokenStream::new();
for script_hash in hashes {
let hash = script_hash.as_str();
value.append_all(quote!(CspHash::Script(#hash),));
}
html_hashes.append_all(quote!(#key => &[#value],));
}
// we expect phf related items to be in path when generating the path code
tokens.append_all(quote! {{
#[allow(unused_imports)]
use ::tauri::utils::assets::{CspHash, EmbeddedAssets, phf, phf::phf_map};
EmbeddedAssets::new(phf_map! { #assets }, &[#global_hashes], phf_map! { #html_hashes })
}});
}
}
pub(crate) fn ensure_out_dir() -> EmbeddedAssetsResult<PathBuf> {
let out_dir = std::env::var("OUT_DIR")
.map_err(|_| EmbeddedAssetsError::OutDir)
.map(PathBuf::from)
.and_then(|p| p.canonicalize().map_err(|_| EmbeddedAssetsError::OutDir))?;
// make sure that our output directory is created
std::fs::create_dir_all(&out_dir).map_err(|_| EmbeddedAssetsError::OutDir)?;
Ok(out_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-codegen/src/context.rs | crates/tauri-codegen/src/context.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::convert::identity;
use std::path::{Path, PathBuf};
use std::{ffi::OsStr, str::FromStr};
use crate::{
embedded_assets::{
ensure_out_dir, AssetOptions, CspHashes, EmbeddedAssets, EmbeddedAssetsResult,
},
image::CachedIcon,
};
use base64::Engine;
use proc_macro2::TokenStream;
use quote::quote;
use sha2::{Digest, Sha256};
use syn::Expr;
use tauri_utils::{
acl::{
get_capabilities, manifest::Manifest, resolved::Resolved, ACL_MANIFESTS_FILE_NAME,
CAPABILITIES_FILE_NAME,
},
assets::AssetKey,
config::{Config, FrontendDist, PatternKind},
html::{inject_nonce_token, parse as parse_html, serialize_node as serialize_html_node, NodeRef},
platform::Target,
tokens::{map_lit, str_lit},
};
/// Necessary data needed by [`context_codegen`] to generate code for a Tauri application context.
pub struct ContextData {
pub dev: bool,
pub config: Config,
pub config_parent: PathBuf,
pub root: TokenStream,
/// Additional capabilities to include.
pub capabilities: Option<Vec<PathBuf>>,
/// The custom assets implementation
pub assets: Option<Expr>,
/// Skip runtime-only types generation for tests (e.g. embed-plist usage).
pub test: bool,
}
fn inject_script_hashes(document: &NodeRef, key: &AssetKey, csp_hashes: &mut CspHashes) {
if let Ok(inline_script_elements) = document.select("script:not(:empty)") {
let mut scripts = Vec::new();
for inline_script_el in inline_script_elements {
let script = inline_script_el.as_node().text_contents();
let mut hasher = Sha256::new();
hasher.update(tauri_utils::html::normalize_script_for_csp(
script.as_bytes(),
));
let hash = hasher.finalize();
scripts.push(format!(
"'sha256-{}'",
base64::engine::general_purpose::STANDARD.encode(hash)
));
}
csp_hashes
.inline_scripts
.entry(key.clone().into())
.or_default()
.append(&mut scripts);
}
}
fn map_core_assets(
options: &AssetOptions,
) -> impl Fn(&AssetKey, &Path, &mut Vec<u8>, &mut CspHashes) -> EmbeddedAssetsResult<()> {
let csp = options.csp;
let dangerous_disable_asset_csp_modification =
options.dangerous_disable_asset_csp_modification.clone();
move |key, path, input, csp_hashes| {
if path.extension() == Some(OsStr::new("html")) {
#[allow(clippy::collapsible_if)]
if csp {
let document = parse_html(String::from_utf8_lossy(input).into_owned());
inject_nonce_token(&document, &dangerous_disable_asset_csp_modification);
if dangerous_disable_asset_csp_modification.can_modify("script-src") {
inject_script_hashes(&document, key, csp_hashes);
}
*input = serialize_html_node(&document);
}
}
Ok(())
}
}
#[cfg(feature = "isolation")]
fn map_isolation(
_options: &AssetOptions,
dir: PathBuf,
) -> impl Fn(&AssetKey, &Path, &mut Vec<u8>, &mut CspHashes) -> EmbeddedAssetsResult<()> {
// create the csp for the isolation iframe styling now, to make the runtime less complex
let mut hasher = Sha256::new();
hasher.update(tauri_utils::pattern::isolation::IFRAME_STYLE);
let hash = hasher.finalize();
let iframe_style_csp_hash = format!(
"'sha256-{}'",
base64::engine::general_purpose::STANDARD.encode(hash)
);
move |key, path, input, csp_hashes| {
if path.extension() == Some(OsStr::new("html")) {
let isolation_html = parse_html(String::from_utf8_lossy(input).into_owned());
// this is appended, so no need to reverse order it
tauri_utils::html::inject_codegen_isolation_script(&isolation_html);
// temporary workaround for windows not loading assets
tauri_utils::html::inline_isolation(&isolation_html, &dir);
inject_nonce_token(
&isolation_html,
&tauri_utils::config::DisabledCspModificationKind::Flag(false),
);
inject_script_hashes(&isolation_html, key, csp_hashes);
csp_hashes.styles.push(iframe_style_csp_hash.clone());
*input = isolation_html.to_string().as_bytes().to_vec()
}
Ok(())
}
}
/// Build a `tauri::Context` for including in application code.
pub fn context_codegen(data: ContextData) -> EmbeddedAssetsResult<TokenStream> {
let ContextData {
dev,
config,
config_parent,
root,
capabilities: additional_capabilities,
assets,
test,
} = data;
#[allow(unused_variables)]
let running_tests = test;
let target = std::env::var("TAURI_ENV_TARGET_TRIPLE")
.as_deref()
.map(Target::from_triple)
.unwrap_or_else(|_| Target::current());
let mut options = AssetOptions::new(config.app.security.pattern.clone())
.freeze_prototype(config.app.security.freeze_prototype)
.dangerous_disable_asset_csp_modification(
config
.app
.security
.dangerous_disable_asset_csp_modification
.clone(),
);
let csp = if dev {
config
.app
.security
.dev_csp
.as_ref()
.or(config.app.security.csp.as_ref())
} else {
config.app.security.csp.as_ref()
};
if csp.is_some() {
options = options.with_csp();
}
let assets = if let Some(assets) = assets {
quote!(#assets)
} else if dev && config.build.dev_url.is_some() {
let assets = EmbeddedAssets::default();
quote!(#assets)
} else {
let assets = match &config.build.frontend_dist {
Some(url) => match url {
FrontendDist::Url(_url) => Default::default(),
FrontendDist::Directory(path) => {
let assets_path = config_parent.join(path);
if !assets_path.exists() {
panic!(
"The `frontendDist` configuration is set to `{path:?}` but this path doesn't exist"
)
}
EmbeddedAssets::new(assets_path, &options, map_core_assets(&options))?
}
FrontendDist::Files(files) => EmbeddedAssets::new(
files
.iter()
.map(|p| config_parent.join(p))
.collect::<Vec<_>>(),
&options,
map_core_assets(&options),
)?,
_ => unimplemented!(),
},
None => Default::default(),
};
quote!(#assets)
};
let out_dir = ensure_out_dir()?;
let default_window_icon = {
if target == Target::Windows {
// handle default window icons for Windows targets
let icon_path = find_icon(
&config,
&config_parent,
|i| i.ends_with(".ico"),
"icons/icon.ico",
);
if icon_path.exists() {
let icon = CachedIcon::new(&root, &icon_path)?;
quote!(::std::option::Option::Some(#icon))
} else {
let icon_path = find_icon(
&config,
&config_parent,
|i| i.ends_with(".png"),
"icons/icon.png",
);
let icon = CachedIcon::new(&root, &icon_path)?;
quote!(::std::option::Option::Some(#icon))
}
} else {
// handle default window icons for Unix targets
let icon_path = find_icon(
&config,
&config_parent,
|i| i.ends_with(".png"),
"icons/icon.png",
);
let icon = CachedIcon::new(&root, &icon_path)?;
quote!(::std::option::Option::Some(#icon))
}
};
let app_icon = if target == Target::MacOS && dev {
let mut icon_path = find_icon(
&config,
&config_parent,
|i| i.ends_with(".icns"),
"icons/icon.png",
);
if !icon_path.exists() {
icon_path = find_icon(
&config,
&config_parent,
|i| i.ends_with(".png"),
"icons/icon.png",
);
}
let icon = CachedIcon::new_raw(&root, &icon_path)?;
quote!(::std::option::Option::Some(#icon.to_vec()))
} else {
quote!(::std::option::Option::None)
};
let package_name = if let Some(product_name) = &config.product_name {
quote!(#product_name.to_string())
} else {
quote!(env!("CARGO_PKG_NAME").to_string())
};
let package_version = if let Some(version) = &config.version {
semver::Version::from_str(version)?;
quote!(#version.to_string())
} else {
quote!(env!("CARGO_PKG_VERSION").to_string())
};
let package_info = quote!(
#root::PackageInfo {
name: #package_name,
version: #package_version.parse().unwrap(),
authors: env!("CARGO_PKG_AUTHORS"),
description: env!("CARGO_PKG_DESCRIPTION"),
crate_name: env!("CARGO_PKG_NAME"),
}
);
let with_tray_icon_code = if target.is_desktop() {
if let Some(tray) = &config.app.tray_icon {
let tray_icon_icon_path = config_parent.join(&tray.icon_path);
let icon = CachedIcon::new(&root, &tray_icon_icon_path)?;
quote!(context.set_tray_icon(::std::option::Option::Some(#icon));)
} else {
quote!()
}
} else {
quote!()
};
#[cfg(target_os = "macos")]
let maybe_embed_plist_block = if target == Target::MacOS && dev && !running_tests {
let info_plist_path = config_parent.join("Info.plist");
let mut info_plist = if info_plist_path.exists() {
plist::Value::from_file(&info_plist_path)
.unwrap_or_else(|e| panic!("failed to read plist {}: {}", info_plist_path.display(), e))
} else {
plist::Value::Dictionary(Default::default())
};
if let Some(plist) = info_plist.as_dictionary_mut() {
if let Some(bundle_name) = config
.bundle
.macos
.bundle_name
.as_ref()
.or(config.product_name.as_ref())
{
plist.insert("CFBundleName".into(), bundle_name.as_str().into());
}
if let Some(version) = &config.version {
let bundle_version = &config.bundle.macos.bundle_version;
plist.insert("CFBundleShortVersionString".into(), version.clone().into());
plist.insert(
"CFBundleVersion".into(),
bundle_version
.clone()
.unwrap_or_else(|| version.clone())
.into(),
);
}
}
let mut plist_contents = std::io::BufWriter::new(Vec::new());
info_plist
.to_writer_xml(&mut plist_contents)
.expect("failed to serialize plist");
let plist_contents =
String::from_utf8_lossy(&plist_contents.into_inner().unwrap()).into_owned();
let plist = crate::Cached::try_from(plist_contents)?;
quote!({
tauri::embed_plist::embed_info_plist!(#plist);
})
} else {
quote!()
};
#[cfg(not(target_os = "macos"))]
let maybe_embed_plist_block = quote!();
let pattern = match &options.pattern {
PatternKind::Brownfield => quote!(#root::Pattern::Brownfield),
#[cfg(not(feature = "isolation"))]
PatternKind::Isolation { dir: _ } => {
quote!(#root::Pattern::Brownfield)
}
#[cfg(feature = "isolation")]
PatternKind::Isolation { dir } => {
let dir = config_parent.join(dir);
if !dir.exists() {
panic!("The isolation application path is set to `{dir:?}` but it does not exist")
}
let mut sets_isolation_hook = false;
let key = uuid::Uuid::new_v4().to_string();
let map_isolation = map_isolation(&options, dir.clone());
let assets = EmbeddedAssets::new(dir, &options, |key, path, input, csp_hashes| {
// we check if `__TAURI_ISOLATION_HOOK__` exists in the isolation code
// before modifying the files since we inject our own `__TAURI_ISOLATION_HOOK__` reference in HTML files
if String::from_utf8_lossy(input).contains("__TAURI_ISOLATION_HOOK__") {
sets_isolation_hook = true;
}
map_isolation(key, path, input, csp_hashes)
})?;
if !sets_isolation_hook {
panic!("The isolation application does not contain a file setting the `window.__TAURI_ISOLATION_HOOK__` value.");
}
let schema = options.isolation_schema;
quote!(#root::Pattern::Isolation {
assets: ::std::sync::Arc::new(#assets),
schema: #schema.into(),
key: #key.into(),
crypto_keys: std::boxed::Box::new(::tauri::utils::pattern::isolation::Keys::new().expect("unable to generate cryptographically secure keys for Tauri \"Isolation\" Pattern")),
})
}
};
let acl_file_path = out_dir.join(ACL_MANIFESTS_FILE_NAME);
let acl: BTreeMap<String, Manifest> = if acl_file_path.exists() {
let acl_file =
std::fs::read_to_string(acl_file_path).expect("failed to read plugin manifest map");
serde_json::from_str(&acl_file).expect("failed to parse plugin manifest map")
} else {
Default::default()
};
let capabilities_file_path = out_dir.join(CAPABILITIES_FILE_NAME);
let capabilities_from_files = if capabilities_file_path.exists() {
let capabilities_json =
std::fs::read_to_string(&capabilities_file_path).expect("failed to read capabilities");
serde_json::from_str(&capabilities_json).expect("failed to parse capabilities")
} else {
Default::default()
};
let capabilities = get_capabilities(
&config,
capabilities_from_files,
additional_capabilities.as_deref(),
)
.unwrap();
let resolved = Resolved::resolve(&acl, capabilities, target).expect("failed to resolve ACL");
let acl_tokens = map_lit(
quote! { ::std::collections::BTreeMap },
&acl,
str_lit,
identity,
);
let runtime_authority = quote!(#root::runtime_authority!(#acl_tokens, #resolved));
let plugin_global_api_scripts = if config.app.with_global_tauri {
if let Some(scripts) = tauri_utils::plugin::read_global_api_scripts(&out_dir) {
let scripts = scripts.into_iter().map(|s| quote!(#s));
quote!(::std::option::Option::Some(&[#(#scripts),*]))
} else {
quote!(::std::option::Option::None)
}
} else {
quote!(::std::option::Option::None)
};
let maybe_config_parent_setter = if dev {
let config_parent = config_parent.to_string_lossy();
quote!({
context.with_config_parent(#config_parent);
})
} else {
quote!()
};
let context = quote!({
#maybe_embed_plist_block
#[allow(unused_mut, clippy::let_and_return)]
let mut context = #root::Context::new(
#config,
::std::boxed::Box::new(#assets),
#default_window_icon,
#app_icon,
#package_info,
#pattern,
#runtime_authority,
#plugin_global_api_scripts
);
#with_tray_icon_code
#maybe_config_parent_setter
context
});
Ok(quote!({
// Wrapping in a function to make rust analyzer faster,
// see https://github.com/tauri-apps/tauri/pull/14457
fn inner<R: #root::Runtime>() -> #root::Context<R> {
let thread = ::std::thread::Builder::new()
.name(String::from("generated tauri context creation"))
.stack_size(8 * 1024 * 1024)
.spawn(|| #context)
.expect("unable to create thread with 8MiB stack");
match thread.join() {
Ok(context) => context,
Err(_) => {
eprintln!("the generated Tauri `Context` panicked during creation");
::std::process::exit(101);
}
}
}
inner()
}))
}
fn find_icon(
config: &Config,
config_parent: &Path,
predicate: impl Fn(&&String) -> bool,
default: &str,
) -> PathBuf {
let icon_path = config
.bundle
.icon
.iter()
.find(predicate)
.map(AsRef::as_ref)
.unwrap_or(default);
config_parent.join(icon_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-codegen/src/vendor/mod.rs | crates/tauri-codegen/src/vendor/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Manual vendored dependencies - NOT STABLE.
//!
//! This module and all submodules are not considered part of the public
//! api. They can and will change at any time for any reason in any
//! version.
pub mod blake3_reference;
| 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-codegen/src/vendor/blake3_reference.rs | crates/tauri-codegen/src/vendor/blake3_reference.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! This is a lightly modified version of the BLAKE3 reference implementation.
//!
//! The changes applied are to remove unused item warnings due to using it
//! vendored along with some minor clippy suggestions. No logic changes. I
//! suggest diffing against the original to find all the changes.
//!
//! ## Original Header
//! This is the reference implementation of BLAKE3. It is used for testing and
//! as a readable example of the algorithms involved. Section 5.1 of [the BLAKE3
//! spec](https://github.com/BLAKE3-team/BLAKE3-specs/blob/master/blake3.pdf)
//! discusses this implementation. You can render docs for this implementation
//! by running `cargo doc --open` in this directory.
//!
//! # Example
//!
//! ```
//! let mut hasher = tauri_codegen::vendor::blake3_reference::Hasher::new();
//! hasher.update(b"abc");
//! hasher.update(b"def");
//! let mut hash = [0; 32];
//! hasher.finalize(&mut hash);
//! let mut extended_hash = [0; 500];
//! hasher.finalize(&mut extended_hash);
//! assert_eq!(hash, extended_hash[..32]);
//! ```
//!
//! CC0-1.0 OR Apache-2.0
use core::cmp::min;
use core::convert::TryInto;
const OUT_LEN: usize = 32;
const BLOCK_LEN: usize = 64;
const CHUNK_LEN: usize = 1024;
const CHUNK_START: u32 = 1 << 0;
const CHUNK_END: u32 = 1 << 1;
const PARENT: u32 = 1 << 2;
const ROOT: u32 = 1 << 3;
const IV: [u32; 8] = [
0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19,
];
const MSG_PERMUTATION: [usize; 16] = [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8];
// The mixing function, G, which mixes either a column or a diagonal.
fn g(state: &mut [u32; 16], a: usize, b: usize, c: usize, d: usize, mx: u32, my: u32) {
state[a] = state[a].wrapping_add(state[b]).wrapping_add(mx);
state[d] = (state[d] ^ state[a]).rotate_right(16);
state[c] = state[c].wrapping_add(state[d]);
state[b] = (state[b] ^ state[c]).rotate_right(12);
state[a] = state[a].wrapping_add(state[b]).wrapping_add(my);
state[d] = (state[d] ^ state[a]).rotate_right(8);
state[c] = state[c].wrapping_add(state[d]);
state[b] = (state[b] ^ state[c]).rotate_right(7);
}
fn round(state: &mut [u32; 16], m: &[u32; 16]) {
// Mix the columns.
g(state, 0, 4, 8, 12, m[0], m[1]);
g(state, 1, 5, 9, 13, m[2], m[3]);
g(state, 2, 6, 10, 14, m[4], m[5]);
g(state, 3, 7, 11, 15, m[6], m[7]);
// Mix the diagonals.
g(state, 0, 5, 10, 15, m[8], m[9]);
g(state, 1, 6, 11, 12, m[10], m[11]);
g(state, 2, 7, 8, 13, m[12], m[13]);
g(state, 3, 4, 9, 14, m[14], m[15]);
}
fn permute(m: &mut [u32; 16]) {
let mut permuted = [0; 16];
for i in 0..16 {
permuted[i] = m[MSG_PERMUTATION[i]];
}
*m = permuted;
}
fn compress(
chaining_value: &[u32; 8],
block_words: &[u32; 16],
counter: u64,
block_len: u32,
flags: u32,
) -> [u32; 16] {
let mut state = [
chaining_value[0],
chaining_value[1],
chaining_value[2],
chaining_value[3],
chaining_value[4],
chaining_value[5],
chaining_value[6],
chaining_value[7],
IV[0],
IV[1],
IV[2],
IV[3],
counter as u32,
(counter >> 32) as u32,
block_len,
flags,
];
let mut block = *block_words;
round(&mut state, &block); // round 1
permute(&mut block);
round(&mut state, &block); // round 2
permute(&mut block);
round(&mut state, &block); // round 3
permute(&mut block);
round(&mut state, &block); // round 4
permute(&mut block);
round(&mut state, &block); // round 5
permute(&mut block);
round(&mut state, &block); // round 6
permute(&mut block);
round(&mut state, &block); // round 7
for i in 0..8 {
state[i] ^= state[i + 8];
state[i + 8] ^= chaining_value[i];
}
state
}
fn first_8_words(compression_output: [u32; 16]) -> [u32; 8] {
compression_output[0..8].try_into().unwrap()
}
fn words_from_little_endian_bytes(bytes: &[u8], words: &mut [u32]) {
debug_assert_eq!(bytes.len(), 4 * words.len());
for (four_bytes, word) in bytes.chunks_exact(4).zip(words) {
*word = u32::from_le_bytes(four_bytes.try_into().unwrap());
}
}
// Each chunk or parent node can produce either an 8-word chaining value or, by
// setting the ROOT flag, any number of final output bytes. The Output struct
// captures the state just prior to choosing between those two possibilities.
struct Output {
input_chaining_value: [u32; 8],
block_words: [u32; 16],
counter: u64,
block_len: u32,
flags: u32,
}
impl Output {
fn chaining_value(&self) -> [u32; 8] {
first_8_words(compress(
&self.input_chaining_value,
&self.block_words,
self.counter,
self.block_len,
self.flags,
))
}
fn root_output_bytes(&self, out_slice: &mut [u8]) {
for (output_block_counter, out_block) in (0u64..).zip(out_slice.chunks_mut(2 * OUT_LEN)) {
let words = compress(
&self.input_chaining_value,
&self.block_words,
output_block_counter,
self.block_len,
self.flags | ROOT,
);
// The output length might not be a multiple of 4.
for (word, out_word) in words.iter().zip(out_block.chunks_mut(4)) {
out_word.copy_from_slice(&word.to_le_bytes()[..out_word.len()]);
}
}
}
}
struct ChunkState {
chaining_value: [u32; 8],
chunk_counter: u64,
block: [u8; BLOCK_LEN],
block_len: u8,
blocks_compressed: u8,
flags: u32,
}
impl ChunkState {
fn new(key_words: [u32; 8], chunk_counter: u64, flags: u32) -> Self {
Self {
chaining_value: key_words,
chunk_counter,
block: [0; BLOCK_LEN],
block_len: 0,
blocks_compressed: 0,
flags,
}
}
fn len(&self) -> usize {
BLOCK_LEN * self.blocks_compressed as usize + self.block_len as usize
}
fn start_flag(&self) -> u32 {
if self.blocks_compressed == 0 {
CHUNK_START
} else {
0
}
}
fn update(&mut self, mut input: &[u8]) {
while !input.is_empty() {
// If the block buffer is full, compress it and clear it. More
// input is coming, so this compression is not CHUNK_END.
if self.block_len as usize == BLOCK_LEN {
let mut block_words = [0; 16];
words_from_little_endian_bytes(&self.block, &mut block_words);
self.chaining_value = first_8_words(compress(
&self.chaining_value,
&block_words,
self.chunk_counter,
BLOCK_LEN as u32,
self.flags | self.start_flag(),
));
self.blocks_compressed += 1;
self.block = [0; BLOCK_LEN];
self.block_len = 0;
}
// Copy input bytes into the block buffer.
let want = BLOCK_LEN - self.block_len as usize;
let take = min(want, input.len());
self.block[self.block_len as usize..][..take].copy_from_slice(&input[..take]);
self.block_len += take as u8;
input = &input[take..];
}
}
fn output(&self) -> Output {
let mut block_words = [0; 16];
words_from_little_endian_bytes(&self.block, &mut block_words);
Output {
input_chaining_value: self.chaining_value,
block_words,
counter: self.chunk_counter,
block_len: self.block_len as u32,
flags: self.flags | self.start_flag() | CHUNK_END,
}
}
}
fn parent_output(
left_child_cv: [u32; 8],
right_child_cv: [u32; 8],
key_words: [u32; 8],
flags: u32,
) -> Output {
let mut block_words = [0; 16];
block_words[..8].copy_from_slice(&left_child_cv);
block_words[8..].copy_from_slice(&right_child_cv);
Output {
input_chaining_value: key_words,
block_words,
counter: 0, // Always 0 for parent nodes.
block_len: BLOCK_LEN as u32, // Always BLOCK_LEN (64) for parent nodes.
flags: PARENT | flags,
}
}
fn parent_cv(
left_child_cv: [u32; 8],
right_child_cv: [u32; 8],
key_words: [u32; 8],
flags: u32,
) -> [u32; 8] {
parent_output(left_child_cv, right_child_cv, key_words, flags).chaining_value()
}
/// An incremental hasher that can accept any number of writes.
pub struct Hasher {
chunk_state: ChunkState,
key_words: [u32; 8],
cv_stack: [[u32; 8]; 54], // Space for 54 subtree chaining values:
cv_stack_len: u8, // 2^54 * CHUNK_LEN = 2^64
flags: u32,
}
impl Hasher {
fn new_internal(key_words: [u32; 8], flags: u32) -> Self {
Self {
chunk_state: ChunkState::new(key_words, 0, flags),
key_words,
cv_stack: [[0; 8]; 54],
cv_stack_len: 0,
flags,
}
}
/// Construct a new `Hasher` for the regular hash function.
pub fn new() -> Self {
Self::new_internal(IV, 0)
}
fn push_stack(&mut self, cv: [u32; 8]) {
self.cv_stack[self.cv_stack_len as usize] = cv;
self.cv_stack_len += 1;
}
fn pop_stack(&mut self) -> [u32; 8] {
self.cv_stack_len -= 1;
self.cv_stack[self.cv_stack_len as usize]
}
// Section 5.1.2 of the BLAKE3 spec explains this algorithm in more detail.
fn add_chunk_chaining_value(&mut self, mut new_cv: [u32; 8], mut total_chunks: u64) {
// This chunk might complete some subtrees. For each completed subtree,
// its left child will be the current top entry in the CV stack, and
// its right child will be the current value of `new_cv`. Pop each left
// child off the stack, merge it with `new_cv`, and overwrite `new_cv`
// with the result. After all these merges, push the final value of
// `new_cv` onto the stack. The number of completed subtrees is given
// by the number of trailing 0-bits in the new total number of chunks.
while total_chunks & 1 == 0 {
new_cv = parent_cv(self.pop_stack(), new_cv, self.key_words, self.flags);
total_chunks >>= 1;
}
self.push_stack(new_cv);
}
/// Add input to the hash state. This can be called any number of times.
pub fn update(&mut self, mut input: &[u8]) {
while !input.is_empty() {
// If the current chunk is complete, finalize it and reset the
// chunk state. More input is coming, so this chunk is not ROOT.
if self.chunk_state.len() == CHUNK_LEN {
let chunk_cv = self.chunk_state.output().chaining_value();
let total_chunks = self.chunk_state.chunk_counter + 1;
self.add_chunk_chaining_value(chunk_cv, total_chunks);
self.chunk_state = ChunkState::new(self.key_words, total_chunks, self.flags);
}
// Compress input bytes into the current chunk state.
let want = CHUNK_LEN - self.chunk_state.len();
let take = min(want, input.len());
self.chunk_state.update(&input[..take]);
input = &input[take..];
}
}
/// Finalize the hash and write any number of output bytes.
pub fn finalize(&self, out_slice: &mut [u8]) {
// Starting with the Output from the current chunk, compute all the
// parent chaining values along the right edge of the tree, until we
// have the root Output.
let mut output = self.chunk_state.output();
let mut parent_nodes_remaining = self.cv_stack_len as usize;
while parent_nodes_remaining > 0 {
parent_nodes_remaining -= 1;
output = parent_output(
self.cv_stack[parent_nodes_remaining],
output.chaining_value(),
self.key_words,
self.flags,
);
}
output.root_output_bytes(out_slice);
}
}
impl Default for Hasher {
fn default() -> Self {
Self::new()
}
}
| 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/config.rs | crates/tauri-utils/src/config.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! The Tauri configuration used at runtime.
//!
//! It is pulled from a `tauri.conf.json` file and the [`Config`] struct is generated at compile time.
//!
//! # Stability
//!
//! This is a core functionality that is not considered part of the stable API.
//! If you use it, note that it may include breaking changes in the future.
//!
//! These items are intended to be non-breaking from a de/serialization standpoint only.
//! Using and modifying existing config values will try to avoid breaking changes, but they are
//! free to add fields in the future - causing breaking changes for creating and full destructuring.
//!
//! To avoid this, [ignore unknown fields when destructuring] with the `{my, config, ..}` pattern.
//! If you need to create the Rust config directly without deserializing, then create the struct
//! the [Struct Update Syntax] with `..Default::default()`, which may need a
//! `#[allow(clippy::needless_update)]` attribute if you are declaring all fields.
//!
//! [ignore unknown fields when destructuring]: https://doc.rust-lang.org/book/ch18-03-pattern-syntax.html#ignoring-remaining-parts-of-a-value-with-
//! [Struct Update Syntax]: https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax
use http::response::Builder;
#[cfg(feature = "schema")]
use schemars::schema::Schema;
#[cfg(feature = "schema")]
use schemars::JsonSchema;
use semver::Version;
use serde::{
de::{Deserializer, Error as DeError, Visitor},
Deserialize, Serialize, Serializer,
};
use serde_json::Value as JsonValue;
use serde_untagged::UntaggedEnumVisitor;
use serde_with::skip_serializing_none;
use url::Url;
use std::{
collections::HashMap,
fmt::{self, Display},
fs::read_to_string,
path::PathBuf,
str::FromStr,
};
#[cfg(feature = "schema")]
fn add_description(schema: Schema, description: impl Into<String>) -> Schema {
let value = description.into();
if value.is_empty() {
schema
} else {
let mut schema_obj = schema.into_object();
schema_obj.metadata().description = value.into();
Schema::Object(schema_obj)
}
}
/// Items to help with parsing content into a [`Config`].
pub mod parse;
use crate::{acl::capability::Capability, TitleBarStyle, WindowEffect, WindowEffectState};
pub use self::parse::parse;
fn default_true() -> bool {
true
}
/// An URL to open on a Tauri webview window.
#[derive(PartialEq, Eq, Debug, Clone, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(untagged)]
#[non_exhaustive]
pub enum WebviewUrl {
/// An external URL. Must use either the `http` or `https` schemes.
External(Url),
/// The path portion of an app URL.
/// For instance, to load `tauri://localhost/users/john`,
/// you can simply provide `users/john` in this configuration.
App(PathBuf),
/// A custom protocol url, for example, `doom://index.html`
CustomProtocol(Url),
}
impl<'de> Deserialize<'de> for WebviewUrl {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(untagged)]
enum WebviewUrlDeserializer {
Url(Url),
Path(PathBuf),
}
match WebviewUrlDeserializer::deserialize(deserializer)? {
WebviewUrlDeserializer::Url(u) => {
if u.scheme() == "https" || u.scheme() == "http" {
Ok(Self::External(u))
} else {
Ok(Self::CustomProtocol(u))
}
}
WebviewUrlDeserializer::Path(p) => Ok(Self::App(p)),
}
}
}
impl fmt::Display for WebviewUrl {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::External(url) | Self::CustomProtocol(url) => write!(f, "{url}"),
Self::App(path) => write!(f, "{}", path.display()),
}
}
}
impl Default for WebviewUrl {
fn default() -> Self {
Self::App("index.html".into())
}
}
/// A bundle referenced by tauri-bundler.
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[cfg_attr(feature = "schema", schemars(rename_all = "lowercase"))]
pub enum BundleType {
/// The debian bundle (.deb).
Deb,
/// The RPM bundle (.rpm).
Rpm,
/// The AppImage bundle (.appimage).
AppImage,
/// The Microsoft Installer bundle (.msi).
Msi,
/// The NSIS bundle (.exe).
Nsis,
/// The macOS application bundle (.app).
App,
/// The Apple Disk Image bundle (.dmg).
Dmg,
}
impl BundleType {
/// All bundle types.
fn all() -> &'static [Self] {
&[
BundleType::Deb,
BundleType::Rpm,
BundleType::AppImage,
BundleType::Msi,
BundleType::Nsis,
BundleType::App,
BundleType::Dmg,
]
}
}
impl Display for BundleType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
Self::Deb => "deb",
Self::Rpm => "rpm",
Self::AppImage => "appimage",
Self::Msi => "msi",
Self::Nsis => "nsis",
Self::App => "app",
Self::Dmg => "dmg",
}
)
}
}
impl Serialize for BundleType {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.to_string().as_ref())
}
}
impl<'de> Deserialize<'de> for BundleType {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
match s.to_lowercase().as_str() {
"deb" => Ok(Self::Deb),
"rpm" => Ok(Self::Rpm),
"appimage" => Ok(Self::AppImage),
"msi" => Ok(Self::Msi),
"nsis" => Ok(Self::Nsis),
"app" => Ok(Self::App),
"dmg" => Ok(Self::Dmg),
_ => Err(DeError::custom(format!("unknown bundle target '{s}'"))),
}
}
}
/// Targets to bundle. Each value is case insensitive.
#[derive(Debug, PartialEq, Eq, Clone, Default)]
pub enum BundleTarget {
/// Bundle all targets.
#[default]
All,
/// A list of bundle targets.
List(Vec<BundleType>),
/// A single bundle target.
One(BundleType),
}
#[cfg(feature = "schema")]
impl schemars::JsonSchema for BundleTarget {
fn schema_name() -> std::string::String {
"BundleTarget".to_owned()
}
fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
let any_of = vec![
schemars::schema::SchemaObject {
const_value: Some("all".into()),
metadata: Some(Box::new(schemars::schema::Metadata {
description: Some("Bundle all targets.".to_owned()),
..Default::default()
})),
..Default::default()
}
.into(),
add_description(
gen.subschema_for::<Vec<BundleType>>(),
"A list of bundle targets.",
),
add_description(gen.subschema_for::<BundleType>(), "A single bundle target."),
];
schemars::schema::SchemaObject {
subschemas: Some(Box::new(schemars::schema::SubschemaValidation {
any_of: Some(any_of),
..Default::default()
})),
metadata: Some(Box::new(schemars::schema::Metadata {
description: Some("Targets to bundle. Each value is case insensitive.".to_owned()),
..Default::default()
})),
..Default::default()
}
.into()
}
}
impl Serialize for BundleTarget {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::All => serializer.serialize_str("all"),
Self::List(l) => l.serialize(serializer),
Self::One(t) => serializer.serialize_str(t.to_string().as_ref()),
}
}
}
impl<'de> Deserialize<'de> for BundleTarget {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize, Serialize)]
#[serde(untagged)]
pub enum BundleTargetInner {
List(Vec<BundleType>),
One(BundleType),
All(String),
}
match BundleTargetInner::deserialize(deserializer)? {
BundleTargetInner::All(s) if s.to_lowercase() == "all" => Ok(Self::All),
BundleTargetInner::All(t) => Err(DeError::custom(format!(
"invalid bundle type {t}, expected one of `all`, {}",
BundleType::all()
.iter()
.map(|b| format!("`{b}`"))
.collect::<Vec<_>>()
.join(", ")
))),
BundleTargetInner::List(l) => Ok(Self::List(l)),
BundleTargetInner::One(t) => Ok(Self::One(t)),
}
}
}
impl BundleTarget {
/// Gets the bundle targets as a [`Vec`]. The vector is empty when set to [`BundleTarget::All`].
#[allow(dead_code)]
pub fn to_vec(&self) -> Vec<BundleType> {
match self {
Self::All => BundleType::all().to_vec(),
Self::List(list) => list.clone(),
Self::One(i) => vec![i.clone()],
}
}
}
/// Configuration for AppImage bundles.
///
/// See more: <https://v2.tauri.app/reference/config/#appimageconfig>
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AppImageConfig {
/// Include additional gstreamer dependencies needed for audio and video playback.
/// This increases the bundle size by ~15-35MB depending on your build system.
#[serde(default, alias = "bundle-media-framework")]
pub bundle_media_framework: bool,
/// The files to include in the Appimage Binary.
#[serde(default)]
pub files: HashMap<PathBuf, PathBuf>,
}
/// Configuration for Debian (.deb) bundles.
///
/// See more: <https://v2.tauri.app/reference/config/#debconfig>
#[skip_serializing_none]
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DebConfig {
/// The list of deb dependencies your application relies on.
pub depends: Option<Vec<String>>,
/// The list of deb dependencies your application recommends.
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>>,
/// The files to include on the package.
#[serde(default)]
pub files: HashMap<PathBuf, 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 a custom desktop file Handlebars template.
///
/// Available variables: `categories`, `comment` (optional), `exec`, `icon` and `name`.
#[serde(alias = "desktop-template")]
pub desktop_template: 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>
#[serde(alias = "pre-install-script")]
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>
#[serde(alias = "post-install-script")]
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>
#[serde(alias = "pre-remove-script")]
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>
#[serde(alias = "post-remove-script")]
pub post_remove_script: Option<PathBuf>,
}
/// Configuration for Linux bundles.
///
/// See more: <https://v2.tauri.app/reference/config/#linuxconfig>
#[skip_serializing_none]
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct LinuxConfig {
/// Configuration for the AppImage bundle.
#[serde(default)]
pub appimage: AppImageConfig,
/// Configuration for the Debian bundle.
#[serde(default)]
pub deb: DebConfig,
/// Configuration for the RPM bundle.
#[serde(default)]
pub rpm: RpmConfig,
}
/// Compression algorithms used when bundling RPM packages.
#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields, tag = "type")]
#[non_exhaustive]
pub enum RpmCompression {
/// Gzip compression
Gzip {
/// Gzip compression level
level: u32,
},
/// Zstd compression
Zstd {
/// Zstd compression level
level: i32,
},
/// Xz compression
Xz {
/// Xz compression level
level: u32,
},
/// Bzip2 compression
Bzip2 {
/// Bzip2 compression level
level: u32,
},
/// Disable compression
None,
}
/// Configuration for RPM bundles.
#[skip_serializing_none]
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RpmConfig {
/// The list of RPM dependencies your application relies on.
pub depends: Option<Vec<String>>,
/// The list 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.
#[serde(default = "default_release")]
pub release: String,
/// The RPM epoch.
#[serde(default)]
pub epoch: u32,
/// The files to include on the package.
#[serde(default)]
pub files: HashMap<PathBuf, PathBuf>,
/// Path to a custom desktop file Handlebars template.
///
/// Available variables: `categories`, `comment` (optional), `exec`, `icon` and `name`.
#[serde(alias = "desktop-template")]
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>
#[serde(alias = "pre-install-script")]
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>
#[serde(alias = "post-install-script")]
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>
#[serde(alias = "pre-remove-script")]
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>
#[serde(alias = "post-remove-script")]
pub post_remove_script: Option<PathBuf>,
/// Compression algorithm and level. Defaults to `Gzip` with level 6.
pub compression: Option<RpmCompression>,
}
impl Default for RpmConfig {
fn default() -> Self {
Self {
depends: None,
recommends: None,
provides: None,
conflicts: None,
obsoletes: None,
release: default_release(),
epoch: 0,
files: Default::default(),
desktop_template: None,
pre_install_script: None,
post_install_script: None,
pre_remove_script: None,
post_remove_script: None,
compression: None,
}
}
}
fn default_release() -> String {
"1".into()
}
/// Position coordinates struct.
#[derive(Default, Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Position {
/// X coordinate.
pub x: u32,
/// Y coordinate.
pub y: u32,
}
/// Position coordinates struct.
#[derive(Default, Debug, PartialEq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct LogicalPosition {
/// X coordinate.
pub x: f64,
/// Y coordinate.
pub y: f64,
}
/// Size of the window.
#[derive(Default, Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Size {
/// Width of the window.
pub width: u32,
/// Height of the window.
pub height: u32,
}
/// Configuration for Apple Disk Image (.dmg) bundles.
///
/// See more: <https://v2.tauri.app/reference/config/#dmgconfig>
#[skip_serializing_none]
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DmgConfig {
/// 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.
#[serde(default = "dmg_window_size", alias = "window-size")]
pub window_size: Size,
/// Position of app file on window.
#[serde(default = "dmg_app_position", alias = "app-position")]
pub app_position: Position,
/// Position of application folder on window.
#[serde(
default = "dmg_application_folder_position",
alias = "application-folder-position"
)]
pub application_folder_position: Position,
}
impl Default for DmgConfig {
fn default() -> Self {
Self {
background: None,
window_position: None,
window_size: dmg_window_size(),
app_position: dmg_app_position(),
application_folder_position: dmg_application_folder_position(),
}
}
}
fn dmg_window_size() -> Size {
Size {
width: 660,
height: 400,
}
}
fn dmg_app_position() -> Position {
Position { x: 180, y: 170 }
}
fn dmg_application_folder_position() -> Position {
Position { x: 480, y: 170 }
}
fn de_macos_minimum_system_version<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
where
D: Deserializer<'de>,
{
let version = Option::<String>::deserialize(deserializer)?;
match version {
Some(v) if v.is_empty() => Ok(macos_minimum_system_version()),
e => Ok(e),
}
}
/// Configuration for the macOS bundles.
///
/// See more: <https://v2.tauri.app/reference/config/#macconfig>
#[skip_serializing_none]
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct MacConfig {
/// A list of strings indicating any macOS X frameworks that need to be bundled with the application.
///
/// If a name is used, ".framework" must be omitted and it will look for standard install locations. You may also use a path to a specific framework.
pub frameworks: Option<Vec<String>>,
/// The files to include in the application relative to the Contents directory.
#[serde(default)]
pub files: HashMap<PathBuf, PathBuf>,
/// The version of the build that identifies an iteration of the bundle.
///
/// Translates to the bundle's CFBundleVersion property.
#[serde(alias = "bundle-version")]
pub bundle_version: Option<String>,
/// The name of the builder that built the bundle.
///
/// Translates to the bundle's CFBundleName property.
///
/// If not set, defaults to the package's product name.
#[serde(alias = "bundle-name")]
pub bundle_name: Option<String>,
/// A version string indicating the minimum macOS X version that the bundled application supports. Defaults to `10.13`.
///
/// Setting it to `null` completely removes the `LSMinimumSystemVersion` field on the bundle's `Info.plist`
/// and the `MACOSX_DEPLOYMENT_TARGET` environment variable.
///
/// Ignored in `tauri dev`.
///
/// An empty string is considered an invalid value so the default value is used.
#[serde(
deserialize_with = "de_macos_minimum_system_version",
default = "macos_minimum_system_version",
alias = "minimum-system-version"
)]
pub minimum_system_version: Option<String>,
/// Allows your application to communicate with the outside world.
/// It should be a lowercase, without port and protocol domain name.
#[serde(alias = "exception-domain")]
pub exception_domain: Option<String>,
/// Identity to use for code signing.
#[serde(alias = "signing-identity")]
pub signing_identity: Option<String>,
/// Whether the codesign should enable [hardened runtime](https://developer.apple.com/documentation/security/hardened_runtime) (for executables) or not.
#[serde(alias = "hardened-runtime", default = "default_true")]
pub hardened_runtime: bool,
/// Provider short name for notarization.
#[serde(alias = "provider-short-name")]
pub provider_short_name: Option<String>,
/// Path to the entitlements file.
pub entitlements: Option<String>,
/// Path to a Info.plist file to merge with the default Info.plist.
///
/// Note that Tauri also looks for a `Info.plist` file in the same directory as the Tauri configuration file.
#[serde(alias = "info-plist")]
pub info_plist: Option<PathBuf>,
/// DMG-specific settings.
#[serde(default)]
pub dmg: DmgConfig,
}
impl Default for MacConfig {
fn default() -> Self {
Self {
frameworks: None,
files: HashMap::new(),
bundle_version: None,
bundle_name: None,
minimum_system_version: macos_minimum_system_version(),
exception_domain: None,
signing_identity: None,
hardened_runtime: true,
provider_short_name: None,
entitlements: None,
info_plist: None,
dmg: Default::default(),
}
}
}
fn macos_minimum_system_version() -> Option<String> {
Some("10.13".into())
}
fn ios_minimum_system_version() -> String {
"14.0".into()
}
/// Configuration for a target language for the WiX build.
///
/// See more: <https://v2.tauri.app/reference/config/#wixlanguageconfig>
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
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>.
#[serde(alias = "locale-path")]
pub locale_path: Option<String>,
}
/// The languages to build using WiX.
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(untagged)]
pub enum WixLanguage {
/// A single language to build, without configuration.
One(String),
/// A list of languages to build, without configuration.
List(Vec<String>),
/// A map of languages and its configuration.
Localized(HashMap<String, WixLanguageConfig>),
}
impl Default for WixLanguage {
fn default() -> Self {
Self::One("en-US".into())
}
}
/// Configuration for the MSI bundle using WiX.
///
/// See more: <https://v2.tauri.app/reference/config/#wixconfig>
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WixConfig {
/// 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 [`Config::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, run `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.
#[serde(alias = "upgrade-code")]
pub upgrade_code: Option<uuid::Uuid>,
/// The installer languages to build. See <https://docs.microsoft.com/en-us/windows/win32/msi/localizing-the-error-and-actiontext-tables>.
#[serde(default)]
pub language: WixLanguage,
/// A custom .wxs template to use.
pub template: Option<PathBuf>,
/// A list of paths to .wxs files with WiX fragments to use.
#[serde(default, alias = "fragment-paths")]
pub fragment_paths: Vec<PathBuf>,
/// The ComponentGroup element ids you want to reference from the fragments.
#[serde(default, alias = "component-group-refs")]
pub component_group_refs: Vec<String>,
/// The Component element ids you want to reference from the fragments.
#[serde(default, alias = "component-refs")]
pub component_refs: Vec<String>,
/// The FeatureGroup element ids you want to reference from the fragments.
#[serde(default, alias = "feature-group-refs")]
pub feature_group_refs: Vec<String>,
/// The Feature element ids you want to reference from the fragments.
#[serde(default, alias = "feature-refs")]
pub feature_refs: Vec<String>,
/// The Merge element ids you want to reference from the fragments.
#[serde(default, alias = "merge-refs")]
pub merge_refs: Vec<String>,
/// Create an elevated update task within Windows Task Scheduler.
#[serde(default, alias = "enable-elevated-update-task")]
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.
#[serde(alias = "banner-path")]
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.
#[serde(alias = "dialog-image-path")]
pub dialog_image_path: Option<PathBuf>,
/// Enables FIPS compliant algorithms.
/// Can also be enabled via the `TAURI_BUNDLER_WIX_FIPS_COMPLIANT` env var.
#[serde(default, alias = "fips-compliant")]
pub fips_compliant: bool,
}
/// Compression algorithms used in the NSIS installer.
///
/// See <https://nsis.sourceforge.io/Reference/SetCompressor>
#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub enum NsisCompression {
/// ZLIB uses the deflate algorithm, it is a quick and simple method. With the default compression level it uses about 300 KB of memory.
Zlib,
/// BZIP2 usually gives better compression ratios than ZLIB, but it is a bit slower and uses more memory. With the default compression level it uses about 4 MB of memory.
Bzip2,
/// LZMA (default) is a new compression method that gives very good compression ratios. The decompression speed is high (10-20 MB/s on a 2 GHz CPU), the compression speed is lower. The memory size that will be used for decompression is the dictionary size plus a few KBs, the default is 8 MB.
#[default]
Lzma,
/// Disable compression
None,
}
/// Install Modes for the NSIS installer.
#[derive(Default, Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub enum NSISInstallerMode {
/// Default mode for the installer.
///
/// Install the app by default in a directory that doesn't require Administrator access.
///
/// Installer metadata will be saved under the `HKCU` registry path.
#[default]
CurrentUser,
/// Install the app by default in the `Program Files` folder directory requires Administrator
/// access for the installation.
///
/// Installer metadata will be saved under the `HKLM` registry path.
PerMachine,
/// Combines both modes and allows the user to choose at install time
/// whether to install for the current user or per machine. Note that this mode
/// will require Administrator access even if the user wants to install it for the current user only.
///
/// Installer metadata will be saved under the `HKLM` or `HKCU` registry path based on the user's choice.
Both,
}
/// Configuration for the Installer bundle using NSIS.
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct NsisConfig {
/// 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.
#[serde(alias = "header-image")]
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.
#[serde(alias = "sidebar-image")]
pub sidebar_image: Option<PathBuf>,
/// The path to an icon file used as the installer icon.
#[serde(alias = "install-icon")]
pub installer_icon: Option<PathBuf>,
/// Whether the installation will be for all users or just the current user.
#[serde(default, alias = "install-mode")]
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>>,
/// A key-value pair where the key is the language and the
/// value is the path to a custom `.nsh` 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 `.nsh` 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.
#[serde(default, alias = "display-language-selector")]
pub display_language_selector: bool,
/// Set the compression algorithm used to compress files in the installer.
///
/// See <https://nsis.sourceforge.io/Reference/SetCompressor>
#[serde(default)]
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:
| 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-utils/src/html.rs | crates/tauri-utils/src/html.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! The module to process HTML in Tauri.
use std::path::{Path, PathBuf};
use html5ever::{
interface::QualName,
namespace_url, ns,
serialize::{HtmlSerializer, SerializeOpts, Serializer, TraversalScope},
tendril::TendrilSink,
LocalName,
};
pub use kuchiki::NodeRef;
use kuchiki::{Attribute, ExpandedName, NodeData};
use serde::Serialize;
#[cfg(feature = "isolation")]
use serialize_to_javascript::DefaultTemplate;
#[cfg(feature = "isolation")]
use crate::pattern::isolation::IsolationJavascriptCodegen;
use crate::{
assets::{SCRIPT_NONCE_TOKEN, STYLE_NONCE_TOKEN},
config::{DisabledCspModificationKind, PatternKind},
};
// taken from <https://github.com/kuchiki-rs/kuchiki/blob/57ee6920d835315a498e748ba4b07a851ae5e498/src/serializer.rs#L12>
fn serialize_node_ref_internal<S: Serializer>(
node: &NodeRef,
serializer: &mut S,
traversal_scope: TraversalScope,
) -> crate::Result<()> {
match (traversal_scope, node.data()) {
(ref scope, NodeData::Element(element)) => {
if *scope == TraversalScope::IncludeNode {
let attrs = element.attributes.borrow();
// Unfortunately we need to allocate something to hold these &'a QualName
let attrs = attrs
.map
.iter()
.map(|(name, attr)| {
(
QualName::new(attr.prefix.clone(), name.ns.clone(), name.local.clone()),
&attr.value,
)
})
.collect::<Vec<_>>();
serializer.start_elem(
element.name.clone(),
attrs.iter().map(|&(ref name, value)| (name, &**value)),
)?
}
let children = match element.template_contents.as_ref() {
Some(template_root) => template_root.children(),
None => node.children(),
};
for child in children {
serialize_node_ref_internal(&child, serializer, TraversalScope::IncludeNode)?
}
if *scope == TraversalScope::IncludeNode {
serializer.end_elem(element.name.clone())?
}
Ok(())
}
(_, &NodeData::DocumentFragment) | (_, &NodeData::Document(_)) => {
for child in node.children() {
serialize_node_ref_internal(&child, serializer, TraversalScope::IncludeNode)?
}
Ok(())
}
(TraversalScope::ChildrenOnly(_), _) => Ok(()),
(TraversalScope::IncludeNode, NodeData::Doctype(doctype)) => {
serializer.write_doctype(&doctype.name).map_err(Into::into)
}
(TraversalScope::IncludeNode, NodeData::Text(text)) => {
serializer.write_text(&text.borrow()).map_err(Into::into)
}
(TraversalScope::IncludeNode, NodeData::Comment(text)) => {
serializer.write_comment(&text.borrow()).map_err(Into::into)
}
(TraversalScope::IncludeNode, NodeData::ProcessingInstruction(contents)) => {
let contents = contents.borrow();
serializer
.write_processing_instruction(&contents.0, &contents.1)
.map_err(Into::into)
}
}
}
/// Serializes the node to HTML.
pub fn serialize_node(node: &NodeRef) -> Vec<u8> {
let mut u8_vec = Vec::new();
let mut ser = HtmlSerializer::new(
&mut u8_vec,
SerializeOpts {
traversal_scope: TraversalScope::IncludeNode,
..Default::default()
},
);
serialize_node_ref_internal(node, &mut ser, TraversalScope::IncludeNode).unwrap();
u8_vec
}
/// Parses the given HTML string.
pub fn parse(html: String) -> NodeRef {
kuchiki::parse_html().one(html).document_node
}
fn with_head<F: FnOnce(&NodeRef)>(document: &NodeRef, f: F) {
if let Ok(ref node) = document.select_first("head") {
f(node.as_node())
} else {
let node = NodeRef::new_element(
QualName::new(None, ns!(html), LocalName::from("head")),
None,
);
f(&node);
document.prepend(node)
}
}
fn inject_nonce(document: &NodeRef, selector: &str, token: &str) {
if let Ok(elements) = document.select(selector) {
for target in elements {
let node = target.as_node();
let element = node.as_element().unwrap();
let mut attrs = element.attributes.borrow_mut();
// if the node already has the `nonce` attribute, skip it
if attrs.get("nonce").is_some() {
continue;
}
attrs.insert("nonce", token.into());
}
}
}
/// Inject nonce tokens to all scripts and styles.
pub fn inject_nonce_token(
document: &NodeRef,
dangerous_disable_asset_csp_modification: &DisabledCspModificationKind,
) {
if dangerous_disable_asset_csp_modification.can_modify("script-src") {
inject_nonce(document, "script[src^='http']", SCRIPT_NONCE_TOKEN);
}
if dangerous_disable_asset_csp_modification.can_modify("style-src") {
inject_nonce(document, "style", STYLE_NONCE_TOKEN);
}
}
/// Injects a content security policy to the HTML.
pub fn inject_csp(document: &NodeRef, csp: &str) {
with_head(document, |head| {
head.append(create_csp_meta_tag(csp));
});
}
fn create_csp_meta_tag(csp: &str) -> NodeRef {
NodeRef::new_element(
QualName::new(None, ns!(html), LocalName::from("meta")),
vec![
(
ExpandedName::new(ns!(), LocalName::from("http-equiv")),
Attribute {
prefix: None,
value: "Content-Security-Policy".into(),
},
),
(
ExpandedName::new(ns!(), LocalName::from("content")),
Attribute {
prefix: None,
value: csp.into(),
},
),
],
)
}
/// The shape of the JavaScript Pattern config
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase", tag = "pattern")]
pub enum PatternObject {
/// Brownfield pattern.
Brownfield,
/// Isolation pattern. Recommended for security purposes.
Isolation {
/// Which `IsolationSide` this `PatternObject` is getting injected into
side: IsolationSide,
},
}
impl From<&PatternKind> for PatternObject {
fn from(pattern_kind: &PatternKind) -> Self {
match pattern_kind {
PatternKind::Brownfield => Self::Brownfield,
PatternKind::Isolation { .. } => Self::Isolation {
side: IsolationSide::default(),
},
}
}
}
/// Where the JavaScript is injected to
#[derive(Debug, Serialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum IsolationSide {
/// Original frame, the Brownfield application
#[default]
Original,
/// Secure frame, the isolation security application
Secure,
}
/// Injects the Isolation JavaScript to a codegen time document.
///
/// Note: This function is not considered part of the stable API.
#[cfg(feature = "isolation")]
pub fn inject_codegen_isolation_script(document: &NodeRef) {
with_head(document, |head| {
let script = NodeRef::new_element(
QualName::new(None, ns!(html), "script".into()),
vec![(
ExpandedName::new(ns!(), LocalName::from("nonce")),
Attribute {
prefix: None,
value: SCRIPT_NONCE_TOKEN.into(),
},
)],
);
script.append(NodeRef::new_text(
IsolationJavascriptCodegen {}
.render_default(&Default::default())
.expect("unable to render codegen isolation script template")
.into_string(),
));
head.prepend(script);
});
}
/// Temporary workaround for Windows not allowing requests
///
/// Note: this does not prevent path traversal due to the isolation application expectation that it
/// is secure.
pub fn inline_isolation(document: &NodeRef, dir: &Path) {
for script in document
.select("script[src]")
.expect("unable to parse document for scripts")
{
let src = {
let attributes = script.attributes.borrow();
attributes
.get(LocalName::from("src"))
.expect("script with src attribute has no src value")
.to_string()
};
let mut path = PathBuf::from(src);
if path.has_root() {
path = path
.strip_prefix("/")
.expect("Tauri \"Isolation\" Pattern only supports relative or absolute (`/`) paths.")
.into();
}
let file = std::fs::read_to_string(dir.join(path)).expect("unable to find isolation file");
script.as_node().append(NodeRef::new_text(file));
let mut attributes = script.attributes.borrow_mut();
attributes.remove(LocalName::from("src"));
}
}
/// Normalize line endings in script content to match what the browser uses for CSP hashing.
///
/// According to the HTML spec, browsers normalize:
/// - `\r\n` → `\n`
/// - `\r` → `\n`
pub fn normalize_script_for_csp(input: &[u8]) -> Vec<u8> {
let mut output = Vec::with_capacity(input.len());
let mut i = 0;
while i < input.len() {
match input[i] {
b'\r' => {
if i + 1 < input.len() && input[i + 1] == b'\n' {
// CRLF → LF
output.push(b'\n');
i += 2;
} else {
// Lone CR → LF
output.push(b'\n');
i += 1;
}
}
_ => {
output.push(input[i]);
i += 1;
}
}
}
output
}
#[cfg(test)]
mod tests {
#[test]
fn csp() {
let htmls = vec![
"<html><head></head></html>".to_string(),
"<html></html>".to_string(),
];
for html in htmls {
let document = super::parse(html);
let csp = "csp-string";
super::inject_csp(&document, csp);
assert_eq!(
document.to_string(),
format!(
r#"<html><head><meta http-equiv="Content-Security-Policy" content="{csp}"></head><body></body></html>"#,
)
);
}
}
#[test]
fn normalize_script_for_csp() {
let js = "// Copyright 2019-2024 Tauri Programme within The Commons Conservancy\r// SPDX-License-Identifier: Apache-2.0\n// SPDX-License-Identifier: MIT\r\n\r\nwindow.__TAURI_ISOLATION_HOOK__ = (payload, options) => {\r\n return payload\r\n}\r\n";
let expected = "// Copyright 2019-2024 Tauri Programme within The Commons Conservancy\n// SPDX-License-Identifier: Apache-2.0\n// SPDX-License-Identifier: MIT\n\nwindow.__TAURI_ISOLATION_HOOK__ = (payload, options) => {\n return payload\n}\n";
assert_eq!(
super::normalize_script_for_csp(js.as_bytes()),
expected.as_bytes()
)
}
}
| 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/lib.rs | crates/tauri-utils/src/lib.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! This crate contains common code that is reused in many places and offers useful utilities like parsing configuration files, detecting platform triples, injecting the CSP, and managing assets.
#![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)]
#![allow(clippy::deprecated_semver)]
use std::{
ffi::OsString,
fmt::Display,
path::{Path, PathBuf},
};
use semver::Version;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
pub mod acl;
pub mod assets;
pub mod config;
pub mod config_v1;
#[cfg(feature = "html-manipulation")]
pub mod html;
pub mod io;
pub mod mime_type;
pub mod platform;
pub mod plugin;
/// Prepare application resources and sidecars.
#[cfg(feature = "resources")]
pub mod resources;
#[cfg(feature = "build")]
pub mod tokens;
#[cfg(feature = "build")]
pub mod build;
/// Application pattern.
pub mod pattern;
/// `tauri::App` package information.
#[derive(Debug, Clone)]
pub struct PackageInfo {
/// App name
pub name: String,
/// App version
pub version: Version,
/// The crate authors.
pub authors: &'static str,
/// The crate description.
pub description: &'static str,
/// The crate name.
pub crate_name: &'static str,
}
#[allow(deprecated)]
mod window_effects {
use super::*;
#[derive(Debug, PartialEq, Eq, Clone, Copy, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
/// Platform-specific window effects
pub enum WindowEffect {
/// A default material appropriate for the view's effectiveAppearance. **macOS 10.14-**
#[deprecated(
since = "macOS 10.14",
note = "You should instead choose an appropriate semantic material."
)]
AppearanceBased,
/// **macOS 10.14-**
#[deprecated(since = "macOS 10.14", note = "Use a semantic material instead.")]
Light,
/// **macOS 10.14-**
#[deprecated(since = "macOS 10.14", note = "Use a semantic material instead.")]
Dark,
/// **macOS 10.14-**
#[deprecated(since = "macOS 10.14", note = "Use a semantic material instead.")]
MediumLight,
/// **macOS 10.14-**
#[deprecated(since = "macOS 10.14", note = "Use a semantic material instead.")]
UltraDark,
/// **macOS 10.10+**
Titlebar,
/// **macOS 10.10+**
Selection,
/// **macOS 10.11+**
Menu,
/// **macOS 10.11+**
Popover,
/// **macOS 10.11+**
Sidebar,
/// **macOS 10.14+**
HeaderView,
/// **macOS 10.14+**
Sheet,
/// **macOS 10.14+**
WindowBackground,
/// **macOS 10.14+**
HudWindow,
/// **macOS 10.14+**
FullScreenUI,
/// **macOS 10.14+**
Tooltip,
/// **macOS 10.14+**
ContentBackground,
/// **macOS 10.14+**
UnderWindowBackground,
/// **macOS 10.14+**
UnderPageBackground,
/// Mica effect that matches the system dark preference **Windows 11 Only**
Mica,
/// Mica effect with dark mode but only if dark mode is enabled on the system **Windows 11 Only**
MicaDark,
/// Mica effect with light mode **Windows 11 Only**
MicaLight,
/// Tabbed effect that matches the system dark preference **Windows 11 Only**
Tabbed,
/// Tabbed effect with dark mode but only if dark mode is enabled on the system **Windows 11 Only**
TabbedDark,
/// Tabbed effect with light mode **Windows 11 Only**
TabbedLight,
/// **Windows 7/10/11(22H1) Only**
///
/// ## Notes
///
/// This effect has bad performance when resizing/dragging the window on Windows 11 build 22621.
Blur,
/// **Windows 10/11 Only**
///
/// ## Notes
///
/// This effect has bad performance when resizing/dragging the window on Windows 10 v1903+ and Windows 11 build 22000.
Acrylic,
}
/// Window effect state **macOS only**
///
/// <https://developer.apple.com/documentation/appkit/nsvisualeffectview/state>
#[derive(Debug, PartialEq, Eq, Clone, Copy, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum WindowEffectState {
/// Make window effect state follow the window's active state
FollowsWindowActiveState,
/// Make window effect state always active
Active,
/// Make window effect state always inactive
Inactive,
}
}
pub use window_effects::{WindowEffect, WindowEffectState};
/// How the window title bar should be displayed on macOS.
#[derive(Debug, Clone, PartialEq, Eq, Copy, Default)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub enum TitleBarStyle {
/// A normal title bar.
#[default]
Visible,
/// Makes the title bar transparent, so the window background color is shown instead.
///
/// Useful if you don't need to have actual HTML under the title bar. This lets you avoid the caveats of using `TitleBarStyle::Overlay`. Will be more useful when Tauri lets you set a custom window background color.
Transparent,
/// Shows the title bar as a transparent overlay over the window's content.
///
/// Keep in mind:
/// - The height of the title bar is different on different OS versions, which can lead to window the controls and title not being where you don't expect.
/// - You need to define a custom drag region to make your window draggable, however due to a limitation you can't drag the window when it's not in focus <https://github.com/tauri-apps/tauri/issues/4316>.
/// - The color of the window title depends on the system theme.
Overlay,
}
impl Serialize for TitleBarStyle {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.to_string().as_ref())
}
}
impl<'de> Deserialize<'de> for TitleBarStyle {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
Ok(match s.to_lowercase().as_str() {
"transparent" => Self::Transparent,
"overlay" => Self::Overlay,
_ => Self::Visible,
})
}
}
impl Display for TitleBarStyle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
Self::Visible => "Visible",
Self::Transparent => "Transparent",
Self::Overlay => "Overlay",
}
)
}
}
/// System theme.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub enum Theme {
/// Light theme.
Light,
/// Dark theme.
Dark,
}
impl Serialize for Theme {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.to_string().as_ref())
}
}
impl<'de> Deserialize<'de> for Theme {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
Ok(match s.to_lowercase().as_str() {
"dark" => Self::Dark,
_ => Self::Light,
})
}
}
impl Display for Theme {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
Self::Light => "light",
Self::Dark => "dark",
}
)
}
}
/// Information about environment variables.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Env {
/// The APPIMAGE environment variable.
#[cfg(target_os = "linux")]
pub appimage: Option<std::ffi::OsString>,
/// The APPDIR environment variable.
#[cfg(target_os = "linux")]
pub appdir: Option<std::ffi::OsString>,
/// The command line arguments of the current process.
pub args_os: Vec<OsString>,
}
#[allow(clippy::derivable_impls)]
impl Default for Env {
fn default() -> Self {
let args_os = std::env::args_os().collect();
#[cfg(target_os = "linux")]
{
let env = Self {
#[cfg(target_os = "linux")]
appimage: std::env::var_os("APPIMAGE"),
#[cfg(target_os = "linux")]
appdir: std::env::var_os("APPDIR"),
args_os,
};
if env.appimage.is_some() || env.appdir.is_some() {
// validate that we're actually running on an AppImage
// an AppImage is mounted to `/$TEMPDIR/.mount_${appPrefix}${hash}`
// see <https://github.com/AppImage/AppImageKit/blob/1681fd84dbe09c7d9b22e13cdb16ea601aa0ec47/src/runtime.c#L501>
// note that it is safe to use `std::env::current_exe` here since we just loaded an AppImage.
let is_temp = std::env::current_exe()
.map(|p| {
p.display()
.to_string()
.starts_with(&format!("{}/.mount_", std::env::temp_dir().display()))
})
.unwrap_or(true);
if !is_temp {
log::warn!("`APPDIR` or `APPIMAGE` environment variable found but this application was not detected as an AppImage; this might be a security issue.");
}
}
env
}
#[cfg(not(target_os = "linux"))]
{
Self { args_os }
}
}
}
/// The result type of `tauri-utils`.
pub type Result<T> = std::result::Result<T, Error>;
/// The error type of `tauri-utils`.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
/// Target triple architecture error
#[error("Unable to determine target-architecture")]
Architecture,
/// Target triple OS error
#[error("Unable to determine target-os")]
Os,
/// Target triple environment error
#[error("Unable to determine target-environment")]
Environment,
/// Tried to get resource on an unsupported platform
#[error("Unsupported platform for reading resources")]
UnsupportedPlatform,
/// Get parent process error
#[error("Could not get parent process")]
ParentProcess,
/// Get parent process PID error
#[error("Could not get parent PID")]
ParentPid,
/// Get child process error
#[error("Could not get child process")]
ChildProcess,
/// IO error
#[error("{0}")]
Io(#[from] std::io::Error),
/// Invalid pattern.
#[error("invalid pattern `{0}`. Expected either `brownfield` or `isolation`.")]
InvalidPattern(String),
/// Invalid glob pattern.
#[cfg(feature = "resources")]
#[error("{0}")]
GlobPattern(#[from] glob::PatternError),
/// Failed to use glob pattern.
#[cfg(feature = "resources")]
#[error("`{0}`")]
Glob(#[from] glob::GlobError),
/// Glob pattern did not find any results.
#[cfg(feature = "resources")]
#[error("glob pattern {0} path not found or didn't match any files.")]
GlobPathNotFound(String),
/// Error walking directory.
#[cfg(feature = "resources")]
#[error("{0}")]
WalkdirError(#[from] walkdir::Error),
/// Not allowed to walk dir.
#[cfg(feature = "resources")]
#[error("could not walk directory `{0}`, try changing `allow_walk` to true on the `ResourcePaths` constructor.")]
NotAllowedToWalkDir(std::path::PathBuf),
/// Resource path doesn't exist
#[cfg(feature = "resources")]
#[error("resource path `{0}` doesn't exist")]
ResourcePathNotFound(std::path::PathBuf),
}
/// Reconstructs a path from its components using the platform separator then converts it to String and removes UNC prefixes on Windows if it exists.
pub fn display_path<P: AsRef<Path>>(p: P) -> String {
dunce::simplified(&p.as_ref().components().collect::<PathBuf>())
.display()
.to_string()
}
/// Write the file only if the content of the existing file (if any) is different.
///
/// This will always write unless the file exists with identical content.
pub fn write_if_changed<P, C>(path: P, content: C) -> std::io::Result<()>
where
P: AsRef<Path>,
C: AsRef<[u8]>,
{
if let Ok(existing) = std::fs::read(&path) {
if existing == content.as_ref() {
return Ok(());
}
}
std::fs::write(path, content)
}
| 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/io.rs | crates/tauri-utils/src/io.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! IO helpers.
use std::io::BufRead;
/// Read all bytes until a newline (the `0xA` byte) or a carriage return (`\r`) is reached, and append them to the provided buffer.
///
/// Adapted from <https://doc.rust-lang.org/std/io/trait.BufRead.html#method.read_line>.
pub fn read_line<R: BufRead + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> std::io::Result<usize> {
let mut read = 0;
loop {
let (done, used) = {
let available = match r.fill_buf() {
Ok(n) => n,
Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
Err(e) => return Err(e),
};
match memchr::memchr(b'\n', available) {
Some(i) => {
let end = i + 1;
buf.extend_from_slice(&available[..end]);
(true, end)
}
None => match memchr::memchr(b'\r', available) {
Some(i) => {
let end = i + 1;
buf.extend_from_slice(&available[..end]);
(true, end)
}
None => {
buf.extend_from_slice(available);
(false, available.len())
}
},
}
};
r.consume(used);
read += used;
if done || used == 0 {
return Ok(read);
}
}
}
| 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/tokens.rs | crates/tauri-utils/src/tokens.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Utilities to implement [`ToTokens`] for a type.
use std::path::Path;
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use serde_json::Value as JsonValue;
use url::Url;
/// Write a `TokenStream` of the `$struct`'s fields to the `$tokens`.
///
/// All fields must represent a binding of the same name that implements `ToTokens`.
#[macro_export]
macro_rules! literal_struct {
($tokens:ident, $struct:path, $($field:ident),+) => {
$tokens.append_all(quote! {
$struct {
$($field: #$field),+
}
})
};
}
/// Create a `String` constructor `TokenStream`.
///
/// e.g. `"Hello World"` -> `String::from("Hello World")`.
/// This takes a `&String` to reduce casting all the `&String` -> `&str` manually.
pub fn str_lit(s: impl AsRef<str>) -> TokenStream {
let s = s.as_ref();
quote! { #s.into() }
}
/// Create an `Option` constructor `TokenStream`.
pub fn opt_lit(item: Option<&impl ToTokens>) -> TokenStream {
match item {
None => quote! { ::core::option::Option::None },
Some(item) => quote! { ::core::option::Option::Some(#item) },
}
}
/// Create an `Option` constructor `TokenStream` over an owned [`ToTokens`] impl type.
pub fn opt_lit_owned(item: Option<impl ToTokens>) -> TokenStream {
match item {
None => quote! { ::core::option::Option::None },
Some(item) => quote! { ::core::option::Option::Some(#item) },
}
}
/// Helper function to combine an `opt_lit` with `str_lit`.
pub fn opt_str_lit(item: Option<impl AsRef<str>>) -> TokenStream {
opt_lit(item.map(str_lit).as_ref())
}
/// Helper function to combine an `opt_lit` with a list of `str_lit`
pub fn opt_vec_lit<Raw, Tokens>(
item: Option<impl IntoIterator<Item = Raw>>,
map: impl Fn(Raw) -> Tokens,
) -> TokenStream
where
Tokens: ToTokens,
{
opt_lit(item.map(|list| vec_lit(list, map)).as_ref())
}
/// Create a `Vec` constructor, mapping items with a function that spits out `TokenStream`s.
pub fn vec_lit<Raw, Tokens>(
list: impl IntoIterator<Item = Raw>,
map: impl Fn(Raw) -> Tokens,
) -> TokenStream
where
Tokens: ToTokens,
{
let items = list.into_iter().map(map);
quote! { vec![#(#items),*] }
}
/// Create a `PathBuf` constructor `TokenStream`.
///
/// e.g. `"Hello World" -> String::from("Hello World").
pub fn path_buf_lit(s: impl AsRef<Path>) -> TokenStream {
let s = s.as_ref().to_string_lossy().into_owned();
quote! { ::std::path::PathBuf::from(#s) }
}
/// Creates a `Url` constructor `TokenStream`.
pub fn url_lit(url: &Url) -> TokenStream {
let url = url.as_str();
quote! { #url.parse().unwrap() }
}
/// Create a map constructor, mapping keys and values with other `TokenStream`s.
///
/// This function is pretty generic because the types of keys AND values get transformed.
pub fn map_lit<Map, Key, Value, TokenStreamKey, TokenStreamValue, FuncKey, FuncValue>(
map_type: TokenStream,
map: Map,
map_key: FuncKey,
map_value: FuncValue,
) -> TokenStream
where
<Map as IntoIterator>::IntoIter: ExactSizeIterator,
Map: IntoIterator<Item = (Key, Value)>,
TokenStreamKey: ToTokens,
TokenStreamValue: ToTokens,
FuncKey: Fn(Key) -> TokenStreamKey,
FuncValue: Fn(Value) -> TokenStreamValue,
{
let ident = quote::format_ident!("map");
let map = map.into_iter();
if map.len() > 0 {
let items = map.map(|(key, value)| {
let key = map_key(key);
let value = map_value(value);
quote! { #ident.insert(#key, #value); }
});
quote! {{
let mut #ident = #map_type::new();
#(#items)*
#ident
}}
} else {
quote! { #map_type::new() }
}
}
/// Create a `serde_json::Value` variant `TokenStream` for a number
pub fn json_value_number_lit(num: &serde_json::Number) -> TokenStream {
// See <https://docs.rs/serde_json/1/serde_json/struct.Number.html> for guarantees
let prefix = quote! { ::serde_json::Value };
if num.is_u64() {
// guaranteed u64
let num = num.as_u64().unwrap();
quote! { #prefix::Number(#num.into()) }
} else if num.is_i64() {
// guaranteed i64
let num = num.as_i64().unwrap();
quote! { #prefix::Number(#num.into()) }
} else if num.is_f64() {
// guaranteed f64
let num = num.as_f64().unwrap();
quote! { #prefix::Number(::serde_json::Number::from_f64(#num).unwrap(/* safe to unwrap, guaranteed f64 */)) }
} else {
// invalid number
quote! { #prefix::Null }
}
}
/// Create a `serde_json::Value` constructor `TokenStream`
pub fn json_value_lit(jv: &JsonValue) -> TokenStream {
let prefix = quote! { ::serde_json::Value };
match jv {
JsonValue::Null => quote! { #prefix::Null },
JsonValue::Bool(bool) => quote! { #prefix::Bool(#bool) },
JsonValue::Number(number) => json_value_number_lit(number),
JsonValue::String(str) => {
let s = str_lit(str);
quote! { #prefix::String(#s) }
}
JsonValue::Array(vec) => {
let items = vec.iter().map(json_value_lit);
quote! { #prefix::Array(vec![#(#items),*]) }
}
JsonValue::Object(map) => {
let map = map_lit(quote! { ::serde_json::Map }, map, str_lit, json_value_lit);
quote! { #prefix::Object(#map) }
}
}
}
| 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.rs | crates/tauri-utils/src/platform.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Platform helper functions.
use std::{fmt::Display, path::PathBuf};
use serde::{Deserialize, Serialize};
use crate::{config::BundleType, Env, PackageInfo};
mod starting_binary;
/// URI prefix of a Tauri asset.
///
/// This is referenced in the Tauri Android library,
/// which resolves these assets to a file descriptor.
#[cfg(target_os = "android")]
pub const ANDROID_ASSET_PROTOCOL_URI_PREFIX: &str = "asset://localhost/";
/// Platform target.
#[derive(PartialEq, Eq, Copy, Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum Target {
/// MacOS.
#[serde(rename = "macOS")]
MacOS,
/// Windows.
Windows,
/// Linux.
Linux,
/// Android.
Android,
/// iOS.
#[serde(rename = "iOS")]
Ios,
}
impl Display for Target {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
Self::MacOS => "macOS",
Self::Windows => "windows",
Self::Linux => "linux",
Self::Android => "android",
Self::Ios => "iOS",
}
)
}
}
impl Target {
/// Parses the target from the given target triple.
pub fn from_triple(target: &str) -> Self {
if target.contains("darwin") {
Self::MacOS
} else if target.contains("windows") {
Self::Windows
} else if target.contains("android") {
Self::Android
} else if target.contains("ios") {
Self::Ios
} else {
Self::Linux
}
}
/// Gets the current build target.
pub fn current() -> Self {
if cfg!(target_os = "macos") {
Self::MacOS
} else if cfg!(target_os = "windows") {
Self::Windows
} else if cfg!(target_os = "ios") {
Self::Ios
} else if cfg!(target_os = "android") {
Self::Android
} else {
Self::Linux
}
}
/// Whether the target is mobile or not.
pub fn is_mobile(&self) -> bool {
matches!(self, Target::Android | Target::Ios)
}
/// Whether the target is desktop or not.
pub fn is_desktop(&self) -> bool {
!self.is_mobile()
}
}
/// Retrieves the currently running binary's path, taking into account security considerations.
///
/// The path is cached as soon as possible (before even `main` runs) and that value is returned
/// repeatedly instead of fetching the path every time. It is possible for the path to not be found,
/// or explicitly disabled (see following macOS specific behavior).
///
/// # Platform-specific behavior
///
/// 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
///
/// If the above platform-specific behavior does **not** take place, this function uses the
/// following resolution.
///
/// We canonicalize the path we received from [`std::env::current_exe`] to resolve any soft links.
/// This avoids the usual issue of needing the file to exist at the passed path because a valid
/// current executable result for our purpose should always exist. Notably,
/// [`std::env::current_exe`] also has a security section that goes over a theoretical attack using
/// hard links. Let's cover some specific topics that relate to different ways an attacker might
/// try to trick this function into returning the wrong binary path.
///
/// ## Symlinks ("Soft Links")
///
/// [`std::path::Path::canonicalize`] is used to resolve symbolic links to the original path,
/// including nested symbolic links (`link2 -> link1 -> bin`). On macOS, any results that include
/// a symlink are rejected by default due to lesser symlink protections. This can be disabled,
/// **although discouraged**, with the `process-relaunch-dangerous-allow-symlink-macos` feature.
///
/// ## Hard Links
///
/// A [Hard Link] is a named entry that points to a file in the file system.
/// On most systems, this is what you would think of as a "file". The term is
/// used on filesystems that allow multiple entries to point to the same file.
/// The linked [Hard Link] Wikipedia page provides a decent overview.
///
/// In short, unless the attacker was able to create the link with elevated
/// permissions, it should generally not be possible for them to hard link
/// to a file they do not have permissions to - with exception to possible
/// operating system exploits.
///
/// There are also some platform-specific information about this below.
///
/// ### Windows
///
/// Windows requires a permission to be set for the user to create a symlink
/// or a hard link, regardless of ownership status of the target. Elevated
/// permissions users have the ability to create them.
///
/// ### macOS
///
/// macOS allows for the creation of symlinks and hard links to any file.
/// Accessing through those links will fail if the user who owns the links
/// does not have the proper permissions on the original file.
///
/// ### Linux
///
/// Linux allows for the creation of symlinks to any file. Accessing the
/// symlink will fail if the user who owns the symlink does not have the
/// proper permissions on the original file.
///
/// Linux additionally provides a kernel hardening feature since version
/// 3.6 (30 September 2012). Most distributions since then have enabled
/// the protection (setting `fs.protected_hardlinks = 1`) by default, which
/// means that a vast majority of desktop Linux users should have it enabled.
/// **The feature prevents the creation of hardlinks that the user does not own
/// or have read/write access to.** [See the patch that enabled this].
///
/// [Hard Link]: https://en.wikipedia.org/wiki/Hard_link
/// [See the patch that enabled this]: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=800179c9b8a1e796e441674776d11cd4c05d61d7
pub fn current_exe() -> std::io::Result<PathBuf> {
self::starting_binary::STARTING_BINARY.cloned()
}
/// 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() -> crate::Result<String> {
let arch = if cfg!(target_arch = "x86") {
"i686"
} else if cfg!(target_arch = "x86_64") {
"x86_64"
} else if cfg!(target_arch = "arm") {
"armv7"
} else if cfg!(target_arch = "aarch64") {
"aarch64"
} else if cfg!(target_arch = "riscv64") {
"riscv64"
} else {
return Err(crate::Error::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::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::Environment);
};
format!("{os}-{env}")
};
Ok(format!("{arch}-{os}"))
}
#[cfg(all(not(test), not(target_os = "android")))]
fn is_cargo_output_directory(path: &std::path::Path) -> bool {
path.join(".cargo-lock").exists()
}
#[cfg(test)]
const CARGO_OUTPUT_DIRECTORIES: &[&str] = &["debug", "release", "custom-profile"];
#[cfg(test)]
fn is_cargo_output_directory(path: &std::path::Path) -> bool {
let Some(last_component) = path.components().next_back() else {
return false;
};
CARGO_OUTPUT_DIRECTORIES
.iter()
.any(|dirname| &last_component.as_os_str() == dirname)
}
/// Computes the resource directory of the current environment.
///
/// ## Platform-specific
///
/// - **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(package_info: &PackageInfo, env: &Env) -> crate::Result<PathBuf> {
#[cfg(target_os = "android")]
return resource_dir_android(package_info, env);
#[cfg(not(target_os = "android"))]
{
let exe = current_exe()?;
resource_dir_from(exe, package_info, env)
}
}
#[cfg(target_os = "android")]
fn resource_dir_android(_package_info: &PackageInfo, _env: &Env) -> crate::Result<PathBuf> {
Ok(PathBuf::from(ANDROID_ASSET_PROTOCOL_URI_PREFIX))
}
#[cfg(not(target_os = "android"))]
#[allow(unused_variables)]
fn resource_dir_from<P: AsRef<std::path::Path>>(
exe: P,
package_info: &PackageInfo,
env: &Env,
) -> crate::Result<PathBuf> {
let exe_dir = exe.as_ref().parent().expect("failed to get exe directory");
let curr_dir = exe_dir.display().to_string();
let parts: Vec<&str> = curr_dir.split(std::path::MAIN_SEPARATOR).collect();
let len = parts.len();
// Check if running from the Cargo output directory, which means it's an executable in a development machine
// We check if the binary is inside a `target` folder which can be either `target/$profile` or `target/$triple/$profile`
// and see if there's a .cargo-lock file along the executable
// This ensures the check is safer so it doesn't affect apps in production
// Windows also includes the resources in the executable folder so we check that too
if cfg!(target_os = "windows")
|| ((len >= 2 && parts[len - 2] == "target") || (len >= 3 && parts[len - 3] == "target"))
&& is_cargo_output_directory(exe_dir)
{
return Ok(exe_dir.to_path_buf());
}
#[allow(unused_mut, unused_assignments)]
let mut res = Err(crate::Error::UnsupportedPlatform);
#[cfg(target_os = "linux")]
{
// (canonicalize checks for existence, so there's no need for an extra check)
res = if let Ok(bundle_dir) = exe_dir
.join(format!("../lib/{}", package_info.name))
.canonicalize()
{
Ok(bundle_dir)
} else if let Some(appdir) = &env.appdir {
let appdir: &std::path::Path = appdir.as_ref();
Ok(PathBuf::from(format!(
"{}/usr/lib/{}",
appdir.display(),
package_info.name
)))
} else {
// running bundle
Ok(PathBuf::from(format!("/usr/lib/{}", package_info.name)))
};
}
#[cfg(target_os = "macos")]
{
res = exe_dir
.join("../Resources")
.canonicalize()
.map_err(Into::into);
}
#[cfg(target_os = "ios")]
{
res = exe_dir.join("assets").canonicalize().map_err(Into::into);
}
res
}
// Variable holding the type of bundle the executable is stored in. This is modified by binary
// patching during build
#[used]
#[no_mangle]
#[cfg_attr(not(target_vendor = "apple"), link_section = ".taubndl")]
#[cfg_attr(target_vendor = "apple", link_section = "__DATA,taubndl")]
// Marked as `mut` because it could get optimized away without it,
// see https://github.com/tauri-apps/tauri/pull/13812
static mut __TAURI_BUNDLE_TYPE: &str = "UNK";
/// Get the type of the bundle current binary is packaged in.
/// If the bundle type is unknown, it returns [`Option::None`].
pub fn bundle_type() -> Option<BundleType> {
unsafe {
match __TAURI_BUNDLE_TYPE {
"DEB" => Some(BundleType::Deb),
"RPM" => Some(BundleType::Rpm),
"APP" => Some(BundleType::AppImage),
"MSI" => Some(BundleType::Msi),
"NSS" => Some(BundleType::Nsis),
_ => {
if cfg!(target_os = "macos") {
Some(BundleType::App)
} else {
None
}
}
}
}
}
#[cfg(feature = "build")]
mod build {
use proc_macro2::TokenStream;
use quote::{quote, ToTokens, TokenStreamExt};
use super::*;
impl ToTokens for Target {
fn to_tokens(&self, tokens: &mut TokenStream) {
let prefix = quote! { ::tauri::utils::platform::Target };
tokens.append_all(match self {
Self::MacOS => quote! { #prefix::MacOS },
Self::Linux => quote! { #prefix::Linux },
Self::Windows => quote! { #prefix::Windows },
Self::Android => quote! { #prefix::Android },
Self::Ios => quote! { #prefix::Ios },
});
}
}
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use crate::{Env, PackageInfo};
#[test]
fn resolve_resource_dir() {
let package_info = PackageInfo {
name: "MyApp".into(),
version: "1.0.0".parse().unwrap(),
authors: "",
description: "",
crate_name: "my-app",
};
let env = Env::default();
let path = PathBuf::from("/path/to/target/aarch64-apple-darwin/debug/app");
let resource_dir = super::resource_dir_from(&path, &package_info, &env).unwrap();
assert_eq!(resource_dir, path.parent().unwrap());
let path = PathBuf::from("/path/to/target/custom-profile/app");
let resource_dir = super::resource_dir_from(&path, &package_info, &env).unwrap();
assert_eq!(resource_dir, path.parent().unwrap());
let path = PathBuf::from("/path/to/target/release/app");
let resource_dir = super::resource_dir_from(&path, &package_info, &env).unwrap();
assert_eq!(resource_dir, path.parent().unwrap());
let path = PathBuf::from("/path/to/target/unknown-profile/app");
#[allow(clippy::needless_borrows_for_generic_args)]
let resource_dir = super::resource_dir_from(&path, &package_info, &env);
#[cfg(target_os = "macos")]
assert!(resource_dir.is_err());
#[cfg(target_os = "linux")]
assert_eq!(resource_dir.unwrap(), PathBuf::from("/usr/lib/MyApp"));
#[cfg(windows)]
assert_eq!(resource_dir.unwrap(), path.parent().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-utils/src/mime_type.rs | crates/tauri-utils/src/mime_type.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Determine a mime type from a URI or file contents.
use std::fmt;
const MIMETYPE_PLAIN: &str = "text/plain";
/// [Web Compatible MimeTypes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#important_mime_types_for_web_developers)
#[allow(missing_docs)]
pub enum MimeType {
Css,
Csv,
Html,
Ico,
Js,
Json,
Jsonld,
Mp4,
OctetStream,
Rtf,
Svg,
Txt,
}
impl std::fmt::Display for MimeType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mime = match self {
MimeType::Css => "text/css",
MimeType::Csv => "text/csv",
MimeType::Html => "text/html",
MimeType::Ico => "image/vnd.microsoft.icon",
MimeType::Js => "text/javascript",
MimeType::Json => "application/json",
MimeType::Jsonld => "application/ld+json",
MimeType::Mp4 => "video/mp4",
MimeType::OctetStream => "application/octet-stream",
MimeType::Rtf => "application/rtf",
MimeType::Svg => "image/svg+xml",
MimeType::Txt => MIMETYPE_PLAIN,
};
write!(f, "{mime}")
}
}
impl MimeType {
/// parse a URI suffix to convert text/plain mimeType to their actual web compatible mimeType.
pub fn parse_from_uri(uri: &str) -> MimeType {
Self::parse_from_uri_with_fallback(uri, Self::Html)
}
/// parse a URI suffix to convert text/plain mimeType to their actual web compatible mimeType with specified fallback for unknown file extensions.
pub fn parse_from_uri_with_fallback(uri: &str, fallback: MimeType) -> MimeType {
let suffix = uri.split('.').next_back();
match suffix {
Some("bin") => Self::OctetStream,
Some("css" | "less" | "sass" | "styl") => Self::Css,
Some("csv") => Self::Csv,
Some("html") => Self::Html,
Some("ico") => Self::Ico,
Some("js") => Self::Js,
Some("json") => Self::Json,
Some("jsonld") => Self::Jsonld,
Some("mjs") => Self::Js,
Some("mp4") => Self::Mp4,
Some("rtf") => Self::Rtf,
Some("svg") => Self::Svg,
Some("txt") => Self::Txt,
// Assume HTML when a TLD is found for eg. `wry:://tauri.app` | `wry://hello.com`
Some(_) => fallback,
// using octet stream according to this:
// <https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types>
None => Self::OctetStream,
}
}
/// infer mimetype from content (or) URI if needed.
pub fn parse(content: &[u8], uri: &str) -> String {
Self::parse_with_fallback(content, uri, Self::Html)
}
/// infer mimetype from content (or) URI if needed with specified fallback for unknown file extensions.
pub fn parse_with_fallback(content: &[u8], uri: &str, fallback: MimeType) -> String {
let mime = if uri.ends_with(".svg") {
// when reading svg, we can't use `infer`
None
} else {
infer::get(content).map(|info| info.mime_type())
};
match mime {
Some(mime) if mime == MIMETYPE_PLAIN => {
Self::parse_from_uri_with_fallback(uri, fallback).to_string()
}
None => Self::parse_from_uri_with_fallback(uri, fallback).to_string(),
Some(mime) => mime.to_string(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn should_parse_mimetype_from_uri() {
let css = MimeType::parse_from_uri(
"https://unpkg.com/browse/bootstrap@4.1.0/dist/css/bootstrap-grid.css",
)
.to_string();
assert_eq!(css, "text/css".to_string());
let csv: String = MimeType::parse_from_uri("https://example.com/random.csv").to_string();
assert_eq!(csv, "text/csv".to_string());
let ico: String =
MimeType::parse_from_uri("https://icons.duckduckgo.com/ip3/microsoft.com.ico").to_string();
assert_eq!(ico, String::from("image/vnd.microsoft.icon"));
let html: String = MimeType::parse_from_uri("https://tauri.app/index.html").to_string();
assert_eq!(html, String::from("text/html"));
let js: String =
MimeType::parse_from_uri("https://unpkg.com/react@17.0.1/umd/react.production.min.js")
.to_string();
assert_eq!(js, "text/javascript".to_string());
let json: String =
MimeType::parse_from_uri("https://unpkg.com/browse/react@17.0.1/build-info.json").to_string();
assert_eq!(json, String::from("application/json"));
let jsonld: String = MimeType::parse_from_uri("https:/example.com/hello.jsonld").to_string();
assert_eq!(jsonld, String::from("application/ld+json"));
let mjs: String = MimeType::parse_from_uri("https://example.com/bundled.mjs").to_string();
assert_eq!(mjs, String::from("text/javascript"));
let mp4: String = MimeType::parse_from_uri("https://example.com/video.mp4").to_string();
assert_eq!(mp4, String::from("video/mp4"));
let rtf: String = MimeType::parse_from_uri("https://example.com/document.rtf").to_string();
assert_eq!(rtf, String::from("application/rtf"));
let svg: String = MimeType::parse_from_uri("https://example.com/picture.svg").to_string();
assert_eq!(svg, String::from("image/svg+xml"));
let txt: String = MimeType::parse_from_uri("https://example.com/file.txt").to_string();
assert_eq!(txt, String::from("text/plain"));
let custom_scheme = MimeType::parse_from_uri("wry://tauri.app").to_string();
assert_eq!(custom_scheme, String::from("text/html"));
}
}
| 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/resources.rs | crates/tauri-utils/src/resources.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{
collections::HashMap,
path::{Component, Path, PathBuf},
};
use walkdir::WalkDir;
use crate::platform::Target as TargetPlatform;
/// Given a path (absolute or relative) to a resource file, returns the
/// relative path from the bundle resources directory where that resource
/// should be stored.
pub fn resource_relpath(path: &Path) -> PathBuf {
let mut dest = PathBuf::new();
for component in path.components() {
match component {
Component::Prefix(_) => {}
Component::RootDir => dest.push("_root_"),
Component::CurDir => {}
Component::ParentDir => dest.push("_up_"),
Component::Normal(string) => dest.push(string),
}
}
dest
}
fn normalize(path: &Path) -> PathBuf {
let mut dest = PathBuf::new();
for component in path.components() {
match component {
Component::Prefix(_) => {}
Component::RootDir => dest.push("/"),
Component::CurDir => {}
Component::ParentDir => dest.push(".."),
Component::Normal(string) => dest.push(string),
}
}
dest
}
/// Parses the external binaries to bundle, adding the target triple suffix to each of them.
pub fn external_binaries(
external_binaries: &[String],
target_triple: &str,
target_platform: &TargetPlatform,
) -> Vec<String> {
let mut paths = Vec::new();
for curr_path in external_binaries {
let extension = if matches!(target_platform, TargetPlatform::Windows) {
".exe"
} else {
""
};
paths.push(format!("{curr_path}-{target_triple}{extension}"));
}
paths
}
/// Information for a resource.
#[derive(Debug)]
pub struct Resource {
path: PathBuf,
target: PathBuf,
}
impl Resource {
/// The path of the resource.
pub fn path(&self) -> &Path {
&self.path
}
/// The target location of the resource.
pub fn target(&self) -> &Path {
&self.target
}
}
#[derive(Debug)]
enum PatternIter<'a> {
Slice(std::slice::Iter<'a, String>),
Map(std::collections::hash_map::Iter<'a, String, String>),
}
/// A helper to iterate through resources.
pub struct ResourcePaths<'a> {
iter: ResourcePathsIter<'a>,
}
impl<'a> ResourcePaths<'a> {
/// Creates a new ResourcePaths from a slice of patterns to iterate
pub fn new(patterns: &'a [String], allow_walk: bool) -> ResourcePaths<'a> {
ResourcePaths {
iter: ResourcePathsIter {
pattern_iter: PatternIter::Slice(patterns.iter()),
allow_walk,
current_pattern: None,
walk_iter: None,
glob_iter: None,
},
}
}
/// Creates a new ResourcePaths from a slice of patterns to iterate
pub fn from_map(patterns: &'a HashMap<String, String>, allow_walk: bool) -> ResourcePaths<'a> {
ResourcePaths {
iter: ResourcePathsIter {
pattern_iter: PatternIter::Map(patterns.iter()),
allow_walk,
current_pattern: None,
walk_iter: None,
glob_iter: None,
},
}
}
/// Returns the resource iterator that yields the source and target paths.
/// Needed when using [`Self::from_map`].
pub fn iter(self) -> ResourcePathsIter<'a> {
self.iter
}
}
/// Iterator of a [`ResourcePaths`].
#[derive(Debug)]
pub struct ResourcePathsIter<'a> {
/// the patterns to iterate.
pattern_iter: PatternIter<'a>,
/// whether the resource paths allows directories or not.
allow_walk: bool,
/// The (key, value) of map when `pattern_iter` is a [`PatternIter::Map`],
/// used for determining [`Resource::target`]
current_pattern: Option<(String, PathBuf)>,
walk_iter: Option<walkdir::IntoIter>,
glob_iter: Option<glob::Paths>,
}
impl ResourcePathsIter<'_> {
fn next_glob_iter(&mut self) -> Option<crate::Result<Resource>> {
let entry = self.glob_iter.as_mut().unwrap().next()?;
let entry = match entry {
Ok(entry) => entry,
Err(err) => return Some(Err(err.into())),
};
self.next_current_path(normalize(&entry))
}
fn next_walk_iter(&mut self) -> Option<crate::Result<Resource>> {
let entry = self.walk_iter.as_mut().unwrap().next()?;
let entry = match entry {
Ok(entry) => entry,
Err(err) => return Some(Err(err.into())),
};
self.next_current_path(normalize(entry.path()))
}
fn resource_from_path(&mut self, path: &Path) -> crate::Result<Resource> {
if !path.exists() {
return Err(crate::Error::ResourcePathNotFound(path.to_path_buf()));
}
Ok(Resource {
path: path.to_path_buf(),
target: if let Some((pattern, dest)) = &self.current_pattern {
// if processing a directory, preserve directory structure under current_dest
if self.walk_iter.is_some() {
dest.join(path.strip_prefix(pattern).unwrap_or(path))
} else if dest.components().count() == 0 {
// if current_dest is empty while processing a file pattern or glob
// we preserve the file name as it is
PathBuf::from(path.file_name().unwrap())
} else if self.glob_iter.is_some() {
// if processing a glob and current_dest is not empty
// we put all globbed paths under current_dest
// preserving the file name as it is
dest.join(path.file_name().unwrap())
} else {
dest.clone()
}
} else {
// If `pattern_iter` is a [`PatternIter::Slice`]
resource_relpath(path)
},
})
}
fn next_current_path(&mut self, path: PathBuf) -> Option<crate::Result<Resource>> {
let is_dir = path.is_dir();
if is_dir {
if self.glob_iter.is_some() {
return self.next();
}
if !self.allow_walk {
return Some(Err(crate::Error::NotAllowedToWalkDir(path.to_path_buf())));
}
if self.walk_iter.is_none() {
self.walk_iter = Some(WalkDir::new(&path).into_iter());
}
match self.next_walk_iter() {
Some(resource) => Some(resource),
None => {
self.walk_iter = None;
self.next()
}
}
} else {
Some(self.resource_from_path(&path))
}
}
fn next_pattern(&mut self) -> Option<crate::Result<Resource>> {
self.current_pattern = None;
let pattern = match &mut self.pattern_iter {
PatternIter::Slice(iter) => iter.next()?,
PatternIter::Map(iter) => {
let (pattern, dest) = iter.next()?;
self.current_pattern = Some((pattern.clone(), resource_relpath(Path::new(dest))));
pattern
}
};
if pattern.contains('*') {
self.glob_iter = match glob::glob(pattern) {
Ok(glob) => Some(glob),
Err(error) => return Some(Err(error.into())),
};
match self.next_glob_iter() {
Some(r) => return Some(r),
None => {
self.glob_iter = None;
return Some(Err(crate::Error::GlobPathNotFound(pattern.clone())));
}
}
}
self.next_current_path(normalize(Path::new(pattern)))
}
}
impl Iterator for ResourcePaths<'_> {
type Item = crate::Result<PathBuf>;
fn next(&mut self) -> Option<crate::Result<PathBuf>> {
self.iter.next().map(|r| r.map(|res| res.path))
}
}
impl Iterator for ResourcePathsIter<'_> {
type Item = crate::Result<Resource>;
fn next(&mut self) -> Option<crate::Result<Resource>> {
if self.walk_iter.is_some() {
match self.next_walk_iter() {
Some(r) => return Some(r),
None => self.walk_iter = None,
}
}
if self.glob_iter.is_some() {
match self.next_glob_iter() {
Some(r) => return Some(r),
None => self.glob_iter = None,
}
}
self.next_pattern()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use std::path::Path;
impl PartialEq for Resource {
fn eq(&self, other: &Self) -> bool {
self.path == other.path && self.target == other.target
}
}
fn expected_resources(resources: &[(&str, &str)]) -> Vec<Resource> {
resources
.iter()
.map(|(path, target)| Resource {
path: Path::new(path).components().collect(),
target: Path::new(target).components().collect(),
})
.collect()
}
fn setup_test_dirs() {
let mut random = [0; 1];
getrandom::fill(&mut random).unwrap();
let temp = std::env::temp_dir();
let temp = temp.join(format!("tauri_resource_paths_iter_test_{}", random[0]));
let _ = fs::remove_dir_all(&temp);
fs::create_dir_all(&temp).unwrap();
std::env::set_current_dir(&temp).unwrap();
let paths = [
"src-tauri/tauri.conf.json",
"src-tauri/some-other-json.json",
"src-tauri/Cargo.toml",
"src-tauri/Tauri.toml",
"src-tauri/build.rs",
"src/assets/javascript.svg",
"src/assets/tauri.svg",
"src/assets/rust.svg",
"src/assets/lang/en.json",
"src/assets/lang/ar.json",
"src/sounds/lang/es.wav",
"src/sounds/lang/fr.wav",
"src/textures/ground/earth.tex",
"src/textures/ground/sand.tex",
"src/textures/water.tex",
"src/textures/fire.tex",
"src/tiles/sky/grey.tile",
"src/tiles/sky/yellow.tile",
"src/tiles/grass.tile",
"src/tiles/stones.tile",
"src/index.html",
"src/style.css",
"src/script.js",
"src/dir/another-dir/file1.txt",
"src/dir/another-dir2/file2.txt",
];
for path in paths {
let path = Path::new(path);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, "").unwrap();
}
}
fn resources_map(literal: &[(&str, &str)]) -> HashMap<String, String> {
literal
.iter()
.map(|(from, to)| (from.to_string(), to.to_string()))
.collect()
}
#[test]
#[serial_test::serial(resources)]
fn resource_paths_iter_slice_allow_walk() {
setup_test_dirs();
let dir = std::env::current_dir().unwrap().join("src-tauri");
let _ = std::env::set_current_dir(dir);
let resources = ResourcePaths::new(
&[
"../src/script.js".into(),
"../src/assets".into(),
"../src/index.html".into(),
"../src/sounds".into(),
// Should be the same as `../src/textures/` or `../src/textures`
"../src/textures/**/*".into(),
"*.toml".into(),
"*.conf.json".into(),
],
true,
)
.iter()
.flatten()
.collect::<Vec<_>>();
let expected = expected_resources(&[
// From `../src/script.js`
("../src/script.js", "_up_/src/script.js"),
// From `../src/assets`
(
"../src/assets/javascript.svg",
"_up_/src/assets/javascript.svg",
),
("../src/assets/tauri.svg", "_up_/src/assets/tauri.svg"),
("../src/assets/rust.svg", "_up_/src/assets/rust.svg"),
("../src/assets/lang/en.json", "_up_/src/assets/lang/en.json"),
("../src/assets/lang/ar.json", "_up_/src/assets/lang/ar.json"),
// From `../src/index.html`
("../src/index.html", "_up_/src/index.html"),
// From `../src/sounds`
("../src/sounds/lang/es.wav", "_up_/src/sounds/lang/es.wav"),
("../src/sounds/lang/fr.wav", "_up_/src/sounds/lang/fr.wav"),
// From `../src/textures/**/*`
(
"../src/textures/ground/earth.tex",
"_up_/src/textures/earth.tex",
),
(
"../src/textures/ground/sand.tex",
"_up_/src/textures/sand.tex",
),
("../src/textures/water.tex", "_up_/src/textures/water.tex"),
("../src/textures/fire.tex", "_up_/src/textures/fire.tex"),
// From `*.toml`
("Cargo.toml", "Cargo.toml"),
("Tauri.toml", "Tauri.toml"),
// From `*.conf.json`
("tauri.conf.json", "tauri.conf.json"),
]);
assert_eq!(resources.len(), expected.len());
for resource in expected {
if !resources.contains(&resource) {
panic!("{resource:?} was expected but not found in {resources:?}");
}
}
}
#[test]
#[serial_test::serial(resources)]
fn resource_paths_iter_slice_no_walk() {
setup_test_dirs();
let dir = std::env::current_dir().unwrap().join("src-tauri");
let _ = std::env::set_current_dir(dir);
let resources = ResourcePaths::new(
&[
"../src/script.js".into(),
"../src/assets".into(),
"../src/index.html".into(),
"../src/sounds".into(),
"*.toml".into(),
"*.conf.json".into(),
],
false,
)
.iter()
.flatten()
.collect::<Vec<_>>();
let expected = expected_resources(&[
("../src/script.js", "_up_/src/script.js"),
("../src/index.html", "_up_/src/index.html"),
("Cargo.toml", "Cargo.toml"),
("Tauri.toml", "Tauri.toml"),
("tauri.conf.json", "tauri.conf.json"),
]);
assert_eq!(resources.len(), expected.len());
for resource in expected {
if !resources.contains(&resource) {
panic!("{resource:?} was expected but not found in {resources:?}");
}
}
}
#[test]
#[serial_test::serial(resources)]
fn resource_paths_iter_map_allow_walk() {
setup_test_dirs();
let dir = std::env::current_dir().unwrap().join("src-tauri");
let _ = std::env::set_current_dir(dir);
let resources = ResourcePaths::from_map(
&resources_map(&[
("../src/script.js", "main.js"),
("../src/assets", ""),
("../src/index.html", "frontend/index.html"),
("../src/sounds", "voices"),
("../src/textures/*", "textures"),
("../src/tiles/**/*", "tiles"),
("*.toml", ""),
("*.conf.json", "json"),
("../non-existent-file", "asd"), // invalid case
("../non/*", "asd"), // invalid case
]),
true,
)
.iter()
.flatten()
.collect::<Vec<_>>();
let expected = expected_resources(&[
("../src/script.js", "main.js"),
("../src/assets/javascript.svg", "javascript.svg"),
("../src/assets/tauri.svg", "tauri.svg"),
("../src/assets/rust.svg", "rust.svg"),
("../src/assets/lang/en.json", "lang/en.json"),
("../src/assets/lang/ar.json", "lang/ar.json"),
("../src/index.html", "frontend/index.html"),
("../src/sounds/lang/es.wav", "voices/lang/es.wav"),
("../src/sounds/lang/fr.wav", "voices/lang/fr.wav"),
("../src/textures/water.tex", "textures/water.tex"),
("../src/textures/fire.tex", "textures/fire.tex"),
("../src/tiles/grass.tile", "tiles/grass.tile"),
("../src/tiles/stones.tile", "tiles/stones.tile"),
("../src/tiles/sky/grey.tile", "tiles/grey.tile"),
("../src/tiles/sky/yellow.tile", "tiles/yellow.tile"),
("Cargo.toml", "Cargo.toml"),
("Tauri.toml", "Tauri.toml"),
("tauri.conf.json", "json/tauri.conf.json"),
]);
assert_eq!(resources.len(), expected.len());
for resource in expected {
if !resources.contains(&resource) {
panic!("{resource:?} was expected but not found in {resources:?}");
}
}
}
#[test]
#[serial_test::serial(resources)]
fn resource_paths_iter_map_no_walk() {
setup_test_dirs();
let dir = std::env::current_dir().unwrap().join("src-tauri");
let _ = std::env::set_current_dir(dir);
let resources = ResourcePaths::from_map(
&resources_map(&[
("../src/script.js", "main.js"),
("../src/assets", ""),
("../src/index.html", "frontend/index.html"),
("../src/sounds", "voices"),
("*.toml", ""),
("*.conf.json", "json"),
]),
false,
)
.iter()
.flatten()
.collect::<Vec<_>>();
let expected = expected_resources(&[
("../src/script.js", "main.js"),
("../src/index.html", "frontend/index.html"),
("Cargo.toml", "Cargo.toml"),
("Tauri.toml", "Tauri.toml"),
("tauri.conf.json", "json/tauri.conf.json"),
]);
assert_eq!(resources.len(), expected.len());
for resource in expected {
if !resources.contains(&resource) {
panic!("{resource:?} was expected but not found in {resources:?}");
}
}
}
#[test]
#[serial_test::serial(resources)]
fn resource_paths_errors() {
setup_test_dirs();
let dir = std::env::current_dir().unwrap().join("src-tauri");
let _ = std::env::set_current_dir(dir);
let resources = ResourcePaths::from_map(
&resources_map(&[
("../non-existent-file", "file"),
("../non-existent-dir", "dir"),
// exists but not allowed to walk
("../src", "dir2"),
// doesn't exist but it is a glob and will return an error
("../non-existent-glob-dir/*", "glob"),
// exists but only contains directories and will not produce any values
("../src/dir/*", "dir3"),
]),
false,
)
.iter()
.collect::<Vec<_>>();
assert_eq!(resources.len(), 4);
assert!(resources.iter().all(|r| r.is_err()));
// hashmap order is not guaranteed so we check the error variant exists and how many
assert!(resources
.iter()
.any(|r| matches!(r, Err(crate::Error::ResourcePathNotFound(_)))));
assert_eq!(
resources
.iter()
.filter(|r| matches!(r, Err(crate::Error::ResourcePathNotFound(_))))
.count(),
2
);
assert!(resources
.iter()
.any(|r| matches!(r, Err(crate::Error::NotAllowedToWalkDir(_)))));
assert_eq!(
resources
.iter()
.filter(|r| matches!(r, Err(crate::Error::NotAllowedToWalkDir(_))))
.count(),
1
);
assert!(resources
.iter()
.any(|r| matches!(r, Err(crate::Error::GlobPathNotFound(_)))));
assert_eq!(
resources
.iter()
.filter(|r| matches!(r, Err(crate::Error::GlobPathNotFound(_))))
.count(),
1
);
}
}
| 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/build.rs | crates/tauri-utils/src/build.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Build script utilities.
/// Link a Swift library.
#[cfg(target_os = "macos")]
pub fn link_apple_library(name: &str, source: impl AsRef<std::path::Path>) {
if source.as_ref().join("Package.swift").exists() {
link_swift_library(name, source);
} else {
link_xcode_library(name, source);
}
}
/// Link a Swift library.
#[cfg(target_os = "macos")]
fn link_swift_library(name: &str, source: impl AsRef<std::path::Path>) {
let source = source.as_ref();
let sdk_root = std::env::var_os("SDKROOT");
std::env::remove_var("SDKROOT");
swift_rs::SwiftLinker::new(
&std::env::var("MACOSX_DEPLOYMENT_TARGET").unwrap_or_else(|_| "10.13".into()),
)
.with_ios(&std::env::var("IPHONEOS_DEPLOYMENT_TARGET").unwrap_or_else(|_| "13.0".into()))
.with_package(name, source)
.link();
if let Some(root) = sdk_root {
std::env::set_var("SDKROOT", root);
}
}
/// Link a Xcode library.
#[cfg(target_os = "macos")]
fn link_xcode_library(name: &str, source: impl AsRef<std::path::Path>) {
use std::{path::PathBuf, process::Command};
let source = source.as_ref();
let configuration = if std::env::var("DEBUG")
.map(|v| v == "true")
.unwrap_or_default()
{
"Debug"
} else {
"Release"
};
let (sdk, arch) = match std::env::var("TARGET").unwrap().as_str() {
"aarch64-apple-ios" => ("iphoneos", "arm64"),
"aarch64-apple-ios-sim" => ("iphonesimulator", "arm64"),
"x86_64-apple-ios" => ("iphonesimulator", "x86_64"),
_ => return,
};
let out_dir = std::env::var_os("OUT_DIR").map(PathBuf::from).unwrap();
let derived_data_path = out_dir.join(format!("derivedData-{name}"));
let status = Command::new("xcodebuild")
.arg("build")
.arg("-scheme")
.arg(name)
.arg("-configuration")
.arg(configuration)
.arg("-sdk")
.arg(sdk)
.arg("-arch")
.arg(arch)
.arg("-derivedDataPath")
.arg(&derived_data_path)
.arg("BUILD_LIBRARY_FOR_DISTRIBUTION=YES")
.arg("OTHER_SWIFT_FLAGS=-no-verify-emitted-module-interface")
.current_dir(source)
.env_clear()
.env("PATH", std::env::var_os("PATH").unwrap_or_default())
.status()
.unwrap();
assert!(status.success());
let lib_out_dir = derived_data_path
.join("Build")
.join("Products")
.join(format!("{configuration}-{sdk}"));
println!(
"cargo::rustc-link-search=framework={}",
lib_out_dir.display()
);
println!("cargo:rerun-if-changed={}", source.display());
println!("cargo:rustc-link-search=native={}", lib_out_dir.display());
println!("cargo:rustc-link-lib=static={name}");
}
| 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/assets.rs | crates/tauri-utils/src/assets.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! The Assets module allows you to read files that have been bundled by tauri
//! during both compile time and runtime.
#[doc(hidden)]
pub use phf;
use std::{
borrow::Cow,
path::{Component, Path},
};
/// The token used for script nonces.
pub const SCRIPT_NONCE_TOKEN: &str = "__TAURI_SCRIPT_NONCE__";
/// The token used for style nonces.
pub const STYLE_NONCE_TOKEN: &str = "__TAURI_STYLE_NONCE__";
/// Assets iterator.
pub type AssetsIter<'a> = dyn Iterator<Item = (Cow<'a, str>, Cow<'a, [u8]>)> + 'a;
/// Represent an asset file path in a normalized way.
///
/// The following rules are enforced and added if needed:
/// * Unix path component separators
/// * Has a root directory
/// * No trailing slash - directories are not included in assets
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct AssetKey(String);
impl From<AssetKey> for String {
fn from(key: AssetKey) -> Self {
key.0
}
}
impl AsRef<str> for AssetKey {
fn as_ref(&self) -> &str {
&self.0
}
}
impl<P: AsRef<Path>> From<P> for AssetKey {
fn from(path: P) -> Self {
// TODO: change this to utilize `Cow` to prevent allocating an intermediate `PathBuf` when not necessary
let path = path.as_ref().to_owned();
// add in root to mimic how it is used from a server url
let path = if path.has_root() {
path
} else {
Path::new(&Component::RootDir).join(path)
};
let buf = if cfg!(windows) {
let mut buf = String::new();
for component in path.components() {
match component {
Component::RootDir => buf.push('/'),
Component::CurDir => buf.push_str("./"),
Component::ParentDir => buf.push_str("../"),
Component::Prefix(prefix) => buf.push_str(&prefix.as_os_str().to_string_lossy()),
Component::Normal(s) => {
buf.push_str(&s.to_string_lossy());
buf.push('/')
}
}
}
// remove the last slash
if buf != "/" {
buf.pop();
}
buf
} else {
path.to_string_lossy().to_string()
};
AssetKey(buf)
}
}
/// A Content-Security-Policy hash value for a specific directive.
/// For more information see [the MDN page](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy#directives).
#[non_exhaustive]
#[derive(Debug, Clone, Copy)]
pub enum CspHash<'a> {
/// The `script-src` directive.
Script(&'a str),
/// The `style-src` directive.
Style(&'a str),
}
impl CspHash<'_> {
/// The Content-Security-Policy directive this hash applies to.
pub fn directive(&self) -> &'static str {
match self {
Self::Script(_) => "script-src",
Self::Style(_) => "style-src",
}
}
/// The value of the Content-Security-Policy hash.
pub fn hash(&self) -> &str {
match self {
Self::Script(hash) => hash,
Self::Style(hash) => hash,
}
}
}
/// [`Assets`] implementation that only contains compile-time compressed and embedded assets.
pub struct EmbeddedAssets {
assets: phf::Map<&'static str, &'static [u8]>,
// Hashes that must be injected to the CSP of every HTML file.
global_hashes: &'static [CspHash<'static>],
// Hashes that are associated to the CSP of the HTML file identified by the map key (the HTML asset key).
html_hashes: phf::Map<&'static str, &'static [CspHash<'static>]>,
}
/// Temporary struct that overrides the Debug formatting for the `assets` field.
///
/// It reduces the output size compared to the default, as that would format the binary
/// data as a slice of numbers like `[65, 66, 67]` for "ABC". This instead shows the length
/// of the slice.
///
/// For example: `{"/index.html": [u8; 1835], "/index.js": [u8; 212]}`
struct DebugAssetMap<'a>(&'a phf::Map<&'static str, &'static [u8]>);
impl std::fmt::Debug for DebugAssetMap<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut map = f.debug_map();
for (k, v) in self.0.entries() {
map.key(k);
map.value(&format_args!("[u8; {}]", v.len()));
}
map.finish()
}
}
impl std::fmt::Debug for EmbeddedAssets {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("EmbeddedAssets")
.field("assets", &DebugAssetMap(&self.assets))
.field("global_hashes", &self.global_hashes)
.field("html_hashes", &self.html_hashes)
.finish()
}
}
impl EmbeddedAssets {
/// Creates a new instance from the given asset map and script hash list.
pub const fn new(
map: phf::Map<&'static str, &'static [u8]>,
global_hashes: &'static [CspHash<'static>],
html_hashes: phf::Map<&'static str, &'static [CspHash<'static>]>,
) -> Self {
Self {
assets: map,
global_hashes,
html_hashes,
}
}
/// Get an asset by key.
#[cfg(feature = "compression")]
pub fn get(&self, key: &AssetKey) -> Option<Cow<'_, [u8]>> {
self
.assets
.get(key.as_ref())
.map(|&(mut asdf)| {
// with the exception of extremely small files, output should usually be
// at least as large as the compressed version.
let mut buf = Vec::with_capacity(asdf.len());
brotli::BrotliDecompress(&mut asdf, &mut buf).map(|()| buf)
})
.and_then(Result::ok)
.map(Cow::Owned)
}
/// Get an asset by key.
#[cfg(not(feature = "compression"))]
pub fn get(&self, key: &AssetKey) -> Option<Cow<'_, [u8]>> {
self
.assets
.get(key.as_ref())
.copied()
.map(|a| Cow::Owned(a.to_vec()))
}
/// Iterate on the assets.
pub fn iter(&self) -> Box<AssetsIter<'_>> {
Box::new(
self
.assets
.into_iter()
.map(|(k, b)| (Cow::Borrowed(*k), Cow::Borrowed(*b))),
)
}
/// CSP hashes for the given asset.
pub fn csp_hashes(&self, html_path: &AssetKey) -> Box<dyn Iterator<Item = CspHash<'_>> + '_> {
Box::new(
self
.global_hashes
.iter()
.chain(
self
.html_hashes
.get(html_path.as_ref())
.copied()
.into_iter()
.flatten(),
)
.copied(),
)
}
}
| 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/plugin.rs | crates/tauri-utils/src/plugin.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Compile-time and runtime types for Tauri plugins.
#[cfg(feature = "build")]
pub use build::*;
#[cfg(feature = "build")]
mod build {
use std::{
env::vars_os,
fs,
path::{Path, PathBuf},
};
const GLOBAL_API_SCRIPT_PATH_KEY: &str = "GLOBAL_API_SCRIPT_PATH";
/// Known file name of the file that contains an array with the path of all API scripts defined with [`define_global_api_script_path`].
pub const GLOBAL_API_SCRIPT_FILE_LIST_PATH: &str = "__global-api-script.js";
/// Defines the path to the global API script using Cargo instructions.
pub fn define_global_api_script_path(path: &Path) {
println!(
"cargo:{GLOBAL_API_SCRIPT_PATH_KEY}={}",
path
.canonicalize()
.expect("failed to canonicalize global API script path")
.display()
)
}
/// Collects the path of all the global API scripts defined with [`define_global_api_script_path`]
/// and saves them to the out dir with filename [`GLOBAL_API_SCRIPT_FILE_LIST_PATH`].
///
/// `tauri_global_scripts` is only used in Tauri's monorepo for the examples to work
/// since they don't have a build script to run `tauri-build` and pull in the deps env vars
pub fn save_global_api_scripts_paths(out_dir: &Path, mut tauri_global_scripts: Option<PathBuf>) {
let mut scripts = Vec::new();
for (key, value) in vars_os() {
let key = key.to_string_lossy();
if key == format!("DEP_TAURI_{GLOBAL_API_SCRIPT_PATH_KEY}") {
tauri_global_scripts = Some(PathBuf::from(value));
} else if key.starts_with("DEP_") && key.ends_with(GLOBAL_API_SCRIPT_PATH_KEY) {
let script_path = PathBuf::from(value);
scripts.push(script_path);
}
}
if let Some(tauri_global_scripts) = tauri_global_scripts {
scripts.insert(0, tauri_global_scripts);
}
fs::write(
out_dir.join(GLOBAL_API_SCRIPT_FILE_LIST_PATH),
serde_json::to_string(&scripts).expect("failed to serialize global API script paths"),
)
.expect("failed to write global API script");
}
/// Read global api scripts from [`GLOBAL_API_SCRIPT_FILE_LIST_PATH`]
pub fn read_global_api_scripts(out_dir: &Path) -> Option<Vec<String>> {
let global_scripts_path = out_dir.join(GLOBAL_API_SCRIPT_FILE_LIST_PATH);
if !global_scripts_path.exists() {
return None;
}
let global_scripts_str = fs::read_to_string(global_scripts_path)
.expect("failed to read plugin global API script paths");
let global_scripts = serde_json::from_str::<Vec<PathBuf>>(&global_scripts_str)
.expect("failed to parse plugin global API script paths");
Some(
global_scripts
.into_iter()
.map(|p| {
fs::read_to_string(&p).unwrap_or_else(|e| {
panic!(
"failed to read plugin global API script {}: {e}",
p.display()
)
})
})
.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-utils/src/config_v1/parse.rs | crates/tauri-utils/src/config_v1/parse.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
#![allow(clippy::result_large_err)]
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.
const EXTENSIONS_SUPPORTED: &[&str] = &["json", "json5", "toml"];
/// All configuration formats that are currently enabled.
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)]
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.
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) -> &'static str {
match self {
Self::Json => {
if cfg!(target_os = "macos") {
"tauri.macos.conf.json"
} else if cfg!(windows) {
"tauri.windows.conf.json"
} else {
"tauri.linux.conf.json"
}
}
Self::Json5 => {
if cfg!(target_os = "macos") {
"tauri.macos.conf.json5"
} else if cfg!(windows) {
"tauri.windows.conf.json5"
} else {
"tauri.linux.conf.json5"
}
}
Self::Toml => {
if cfg!(target_os = "macos") {
"Tauri.macos.toml"
} else if cfg!(windows) {
"Tauri.windows.toml"
} else {
"Tauri.linux.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: ::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,
},
}
/// See [`parse`] for specifics, returns a JSON [`Value`] instead of [`Config`].
pub fn parse_value(path: impl Into<PathBuf>) -> Result<(Value, PathBuf), ConfigError> {
do_parse(path.into())
}
fn do_parse<D: DeserializeOwned>(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());
let json5 = path.with_file_name(if lookup_platform_config {
ConfigFormat::Json5.into_platform_file_name()
} else {
ConfigFormat::Json5.into_file_name()
});
let toml = path.with_file_name(if lookup_platform_config {
ConfigFormat::Toml.into_platform_file_name()
} 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, &path).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, &path).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(),
})
}
}
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,
})
}
#[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,
})
}
/// 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/config_v1/mod.rs | crates/tauri-utils/src/config_v1/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! The Tauri configuration used at runtime.
//!
//! It is pulled from a `tauri.conf.json` file and the [`Config`] struct is generated at compile time.
//!
//! # Stability
//! This is a core functionality that is not considered part of the stable API.
//! If you use it, note that it may include breaking changes in the future.
use semver::Version;
use serde::{
de::{Deserializer, Error as DeError, Visitor},
Deserialize, Serialize, Serializer,
};
use serde_json::Value as JsonValue;
use serde_with::skip_serializing_none;
use url::Url;
use std::{
collections::HashMap,
fmt::{self, Display},
fs::read_to_string,
path::PathBuf,
str::FromStr,
};
/// Items to help with parsing content into a [`Config`].
pub mod parse;
fn default_true() -> bool {
true
}
/// An URL to open on a Tauri webview window.
#[derive(PartialEq, Eq, Debug, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(untagged)]
#[non_exhaustive]
pub enum WindowUrl {
/// An external URL.
External(Url),
/// The path portion of an app URL.
/// For instance, to load `tauri://localhost/users/john`,
/// you can simply provide `users/john` in this configuration.
App(PathBuf),
}
impl fmt::Display for WindowUrl {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::External(url) => write!(f, "{url}"),
Self::App(path) => write!(f, "{}", path.display()),
}
}
}
impl Default for WindowUrl {
fn default() -> Self {
Self::App("index.html".into())
}
}
/// A bundle referenced by tauri-bundler.
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "schema", schemars(rename_all = "lowercase"))]
pub enum BundleType {
/// The debian bundle (.deb).
Deb,
/// The AppImage bundle (.appimage).
AppImage,
/// The Microsoft Installer bundle (.msi).
Msi,
/// The NSIS bundle (.exe).
Nsis,
/// The macOS application bundle (.app).
App,
/// The Apple Disk Image bundle (.dmg).
Dmg,
/// The Tauri updater bundle.
Updater,
}
impl Display for BundleType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
Self::Deb => "deb",
Self::AppImage => "appimage",
Self::Msi => "msi",
Self::Nsis => "nsis",
Self::App => "app",
Self::Dmg => "dmg",
Self::Updater => "updater",
}
)
}
}
impl Serialize for BundleType {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.to_string().as_ref())
}
}
impl<'de> Deserialize<'de> for BundleType {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
match s.to_lowercase().as_str() {
"deb" => Ok(Self::Deb),
"appimage" => Ok(Self::AppImage),
"msi" => Ok(Self::Msi),
"nsis" => Ok(Self::Nsis),
"app" => Ok(Self::App),
"dmg" => Ok(Self::Dmg),
"updater" => Ok(Self::Updater),
_ => Err(DeError::custom(format!("unknown bundle target '{s}'"))),
}
}
}
/// Targets to bundle. Each value is case insensitive.
#[derive(Debug, PartialEq, Eq, Clone, Default)]
pub enum BundleTarget {
/// Bundle all targets.
#[default]
All,
/// A list of bundle targets.
List(Vec<BundleType>),
/// A single bundle target.
One(BundleType),
}
#[cfg(feature = "schemars")]
pub(crate) trait Merge: Sized {
fn merge(self, other: Self) -> Self;
}
#[cfg(feature = "schema")]
use schemars::schema::{Metadata, Schema};
#[cfg(feature = "schema")]
impl<T: Merge> Merge for Option<T> {
fn merge(self, other: Self) -> Self {
match (self, other) {
(Some(x), Some(y)) => Some(x.merge(y)),
(None, y) => y,
(x, None) => x,
}
}
}
#[cfg(feature = "schema")]
impl<T: Merge> Merge for Box<T> {
fn merge(mut self, other: Self) -> Self {
*self = (*self).merge(*other);
self
}
}
#[cfg(feature = "schema")]
impl<T> Merge for Vec<T> {
fn merge(mut self, other: Self) -> Self {
self.extend(other);
self
}
}
#[cfg(feature = "schema")]
impl Merge for Metadata {
fn merge(self, other: Self) -> Self {
Metadata {
id: self.id.or(other.id),
title: self.title.or(other.title),
description: self.description.or(other.description),
default: self.default.or(other.default),
deprecated: self.deprecated || other.deprecated,
read_only: self.read_only || other.read_only,
write_only: self.write_only || other.write_only,
examples: self.examples.merge(other.examples),
}
}
}
#[cfg(feature = "schema")]
fn apply_metadata(schema: Schema, metadata: Metadata) -> Schema {
if metadata == Metadata::default() {
schema
} else {
let mut schema_obj = schema.into_object();
schema_obj.metadata = Some(Box::new(metadata)).merge(schema_obj.metadata);
Schema::Object(schema_obj)
}
}
#[cfg(feature = "schema")]
impl schemars::JsonSchema for BundleTarget {
fn schema_name() -> std::string::String {
"BundleTarget".to_owned()
}
fn json_schema(generator: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
let any_of = vec![
schemars::schema::SchemaObject {
enum_values: Some(vec!["all".into()]),
metadata: Some(Box::new(schemars::schema::Metadata {
description: Some("Bundle all targets.".to_owned()),
..Default::default()
})),
..Default::default()
}
.into(),
apply_metadata(
generator.subschema_for::<Vec<BundleType>>(),
schemars::schema::Metadata {
description: Some("A list of bundle targets.".to_owned()),
..Default::default()
},
),
apply_metadata(
generator.subschema_for::<BundleType>(),
schemars::schema::Metadata {
description: Some("A single bundle target.".to_owned()),
..Default::default()
},
),
];
schemars::schema::SchemaObject {
subschemas: Some(Box::new(schemars::schema::SubschemaValidation {
any_of: Some(any_of),
..Default::default()
})),
metadata: Some(Box::new(schemars::schema::Metadata {
description: Some("Targets to bundle. Each value is case insensitive.".to_owned()),
..Default::default()
})),
..Default::default()
}
.into()
}
}
impl Serialize for BundleTarget {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::All => serializer.serialize_str("all"),
Self::List(l) => l.serialize(serializer),
Self::One(t) => serializer.serialize_str(t.to_string().as_ref()),
}
}
}
impl<'de> Deserialize<'de> for BundleTarget {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize, Serialize)]
#[serde(untagged)]
pub enum BundleTargetInner {
List(Vec<BundleType>),
One(BundleType),
All(String),
}
match BundleTargetInner::deserialize(deserializer)? {
BundleTargetInner::All(s) if s.to_lowercase() == "all" => Ok(Self::All),
BundleTargetInner::All(t) => Err(DeError::custom(format!("invalid bundle type {t}"))),
BundleTargetInner::List(l) => Ok(Self::List(l)),
BundleTargetInner::One(t) => Ok(Self::One(t)),
}
}
}
/// Configuration for AppImage bundles.
///
/// See more: https://tauri.app/v1/api/config#appimageconfig
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AppImageConfig {
/// Include additional gstreamer dependencies needed for audio and video playback.
/// This increases the bundle size by ~15-35MB depending on your build system.
#[serde(default, alias = "bundle-media-framework")]
pub bundle_media_framework: bool,
}
/// Configuration for Debian (.deb) bundles.
///
/// See more: https://tauri.app/v1/api/config#debconfig
#[skip_serializing_none]
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DebConfig {
/// The list of deb dependencies your application relies on.
pub depends: Option<Vec<String>>,
/// The files to include on the package.
#[serde(default)]
pub files: HashMap<PathBuf, PathBuf>,
/// Path to a custom desktop file Handlebars template.
///
/// Available variables: `categories`, `comment` (optional), `exec`, `icon` and `name`.
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>,
}
fn de_minimum_system_version<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
where
D: Deserializer<'de>,
{
let version = Option::<String>::deserialize(deserializer)?;
match version {
Some(v) if v.is_empty() => Ok(minimum_system_version()),
e => Ok(e),
}
}
/// Configuration for the macOS bundles.
///
/// See more: https://tauri.app/v1/api/config#macconfig
#[skip_serializing_none]
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct MacConfig {
/// A list of strings indicating any macOS X frameworks that need to be bundled with the application.
///
/// If a name is used, ".framework" must be omitted and it will look for standard install locations. You may also use a path to a specific framework.
pub frameworks: Option<Vec<String>>,
/// A version string indicating the minimum macOS X version that the bundled application supports. Defaults to `10.13`.
///
/// Setting it to `null` completely removes the `LSMinimumSystemVersion` field on the bundle's `Info.plist`
/// and the `MACOSX_DEPLOYMENT_TARGET` environment variable.
///
/// An empty string is considered an invalid value so the default value is used.
#[serde(
deserialize_with = "de_minimum_system_version",
default = "minimum_system_version",
alias = "minimum-system-version"
)]
pub minimum_system_version: Option<String>,
/// Allows your application to communicate with the outside world.
/// It should be a lowercase, without port and protocol domain name.
#[serde(alias = "exception-domain")]
pub exception_domain: Option<String>,
/// The path to the license file to add to the DMG bundle.
pub license: Option<String>,
/// Identity to use for code signing.
#[serde(alias = "signing-identity")]
pub signing_identity: Option<String>,
/// Provider short name for notarization.
#[serde(alias = "provider-short-name")]
pub provider_short_name: Option<String>,
/// Path to the entitlements file.
pub entitlements: Option<String>,
}
impl Default for MacConfig {
fn default() -> Self {
Self {
frameworks: None,
minimum_system_version: minimum_system_version(),
exception_domain: None,
license: None,
signing_identity: None,
provider_short_name: None,
entitlements: None,
}
}
}
fn minimum_system_version() -> Option<String> {
Some("10.13".into())
}
/// Configuration for a target language for the WiX build.
///
/// See more: https://tauri.app/v1/api/config#wixlanguageconfig
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
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>.
#[serde(alias = "locale-path")]
pub locale_path: Option<String>,
}
/// The languages to build using WiX.
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(untagged)]
pub enum WixLanguage {
/// A single language to build, without configuration.
One(String),
/// A list of languages to build, without configuration.
List(Vec<String>),
/// A map of languages and its configuration.
Localized(HashMap<String, WixLanguageConfig>),
}
impl Default for WixLanguage {
fn default() -> Self {
Self::One("en-US".into())
}
}
/// Configuration for the MSI bundle using WiX.
///
/// See more: https://tauri.app/v1/api/config#wixconfig
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WixConfig {
/// The installer languages to build. See <https://docs.microsoft.com/en-us/windows/win32/msi/localizing-the-error-and-actiontext-tables>.
#[serde(default)]
pub language: WixLanguage,
/// A custom .wxs template to use.
pub template: Option<PathBuf>,
/// A list of paths to .wxs files with WiX fragments to use.
#[serde(default, alias = "fragment-paths")]
pub fragment_paths: Vec<PathBuf>,
/// The ComponentGroup element ids you want to reference from the fragments.
#[serde(default, alias = "component-group-refs")]
pub component_group_refs: Vec<String>,
/// The Component element ids you want to reference from the fragments.
#[serde(default, alias = "component-refs")]
pub component_refs: Vec<String>,
/// The FeatureGroup element ids you want to reference from the fragments.
#[serde(default, alias = "feature-group-refs")]
pub feature_group_refs: Vec<String>,
/// The Feature element ids you want to reference from the fragments.
#[serde(default, alias = "feature-refs")]
pub feature_refs: Vec<String>,
/// The Merge element ids you want to reference from the fragments.
#[serde(default, alias = "merge-refs")]
pub merge_refs: Vec<String>,
/// Disables the Webview2 runtime installation after app install.
///
/// Will be removed in v2, prefer the [`WindowsConfig::webview_install_mode`] option.
#[serde(default, alias = "skip-webview-install")]
pub skip_webview_install: bool,
/// The path to the license file to render on the installer.
///
/// Must be an RTF file, so if a different extension is provided, we convert it to the RTF format.
pub license: Option<PathBuf>,
/// Create an elevated update task within Windows Task Scheduler.
#[serde(default, alias = "enable-elevated-update-task")]
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.
#[serde(alias = "banner-path")]
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.
#[serde(alias = "dialog-image-path")]
pub dialog_image_path: Option<PathBuf>,
}
/// Compression algorithms used in the NSIS installer.
///
/// See <https://nsis.sourceforge.io/Reference/SetCompressor>
#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub enum NsisCompression {
/// ZLIB uses the deflate algorithm, it is a quick and simple method. With the default compression level it uses about 300 KB of memory.
Zlib,
/// BZIP2 usually gives better compression ratios than ZLIB, but it is a bit slower and uses more memory. With the default compression level it uses about 4 MB of memory.
Bzip2,
/// LZMA (default) is a new compression method that gives very good compression ratios. The decompression speed is high (10-20 MB/s on a 2 GHz CPU), the compression speed is lower. The memory size that will be used for decompression is the dictionary size plus a few KBs, the default is 8 MB.
Lzma,
}
/// Configuration for the Installer bundle using NSIS.
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct NsisConfig {
/// A custom .nsi template to use.
pub template: Option<PathBuf>,
/// The path to the license file to render on the installer.
pub license: Option<PathBuf>,
/// The path to a bitmap file to display on the header of installers pages.
///
/// The recommended dimensions are 150px x 57px.
#[serde(alias = "header-image")]
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.
#[serde(alias = "sidebar-image")]
pub sidebar_image: Option<PathBuf>,
/// The path to an icon file used as the installer icon.
#[serde(alias = "install-icon")]
pub installer_icon: Option<PathBuf>,
/// Whether the installation will be for all users or just the current user.
#[serde(default, alias = "install-mode")]
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>>,
/// A key-value pair where the key is the language and the
/// value is the path to a custom `.nsh` file that holds the translated text for tauri's custom messages.
///
/// See <https://github.com/tauri-apps/tauri/blob/dev/tooling/bundler/src/bundle/windows/templates/nsis-languages/English.nsh> for an example `.nsh` 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.
#[serde(default, alias = "display-language-selector")]
pub display_language_selector: bool,
/// Set the compression algorithm used to compress files in the installer.
///
/// See <https://nsis.sourceforge.io/Reference/SetCompressor>
pub compression: Option<NsisCompression>,
}
/// Install Modes for the NSIS installer.
#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum NSISInstallerMode {
/// Default mode for the installer.
///
/// Install the app by default in a directory that doesn't require Administrator access.
///
/// Installer metadata will be saved under the `HKCU` registry path.
#[default]
CurrentUser,
/// Install the app by default in the `Program Files` folder directory requires Administrator
/// access for the installation.
///
/// Installer metadata will be saved under the `HKLM` registry path.
PerMachine,
/// Combines both modes and allows the user to choose at install time
/// whether to install for the current user or per machine. Note that this mode
/// will require Administrator access even if the user wants to install it for the current user only.
///
/// Installer metadata will be saved under the `HKLM` or `HKCU` registry path based on the user's choice.
Both,
}
/// Install modes for the Webview2 runtime.
/// Note that for the updater bundle [`Self::DownloadBootstrapper`] is used.
///
/// For more information see <https://tauri.app/v1/guides/building/windows>.
#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase", deny_unknown_fields)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum WebviewInstallMode {
/// Do not install the Webview2 as part of the Windows Installer.
Skip,
/// Download the bootstrapper and run it.
/// Requires an internet connection.
/// Results in a smaller installer size, but is not recommended on Windows 7.
DownloadBootstrapper {
/// Instructs the installer to run the bootstrapper in silent mode. Defaults to `true`.
#[serde(default = "default_true")]
silent: bool,
},
/// Embed the bootstrapper and run it.
/// Requires an internet connection.
/// Increases the installer size by around 1.8MB, but offers better support on Windows 7.
EmbedBootstrapper {
/// Instructs the installer to run the bootstrapper in silent mode. Defaults to `true`.
#[serde(default = "default_true")]
silent: bool,
},
/// Embed the offline installer and run it.
/// Does not require an internet connection.
/// Increases the installer size by around 127MB.
OfflineInstaller {
/// Instructs the installer to run the installer in silent mode. Defaults to `true`.
#[serde(default = "default_true")]
silent: bool,
},
/// Embed a fixed webview2 version and use it at runtime.
/// Increases the installer size by around 180MB.
FixedRuntime {
/// The path to the fixed runtime to use.
///
/// The fixed version can be downloaded [on the official website](https://developer.microsoft.com/en-us/microsoft-edge/webview2/#download-section).
/// The `.cab` file must be extracted to a folder and this folder path must be defined on this field.
path: PathBuf,
},
}
impl Default for WebviewInstallMode {
fn default() -> Self {
Self::DownloadBootstrapper { silent: true }
}
}
/// Windows bundler configuration.
///
/// See more: https://tauri.app/v1/api/config#windowsconfig
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WindowsConfig {
/// Specifies the file digest algorithm to use for creating file signatures.
/// Required for code signing. SHA-256 is recommended.
#[serde(alias = "digest-algorithm")]
pub digest_algorithm: Option<String>,
/// Specifies the SHA1 hash of the signing certificate.
#[serde(alias = "certificate-thumbprint")]
pub certificate_thumbprint: Option<String>,
/// Server to use during timestamping.
#[serde(alias = "timestamp-url")]
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.
#[serde(default)]
pub tsp: bool,
/// The installation mode for the Webview2 runtime.
#[serde(default, alias = "webview-install-mode")]
pub webview_install_mode: WebviewInstallMode,
/// Path to the webview fixed runtime to use. Overwrites [`Self::webview_install_mode`] if set.
///
/// Will be removed in v2, prefer the [`Self::webview_install_mode`] option.
///
/// The fixed version can be downloaded [on the official website](https://developer.microsoft.com/en-us/microsoft-edge/webview2/#download-section).
/// The `.cab` file must be extracted to a folder and this folder path must be defined on this field.
#[serde(alias = "webview-fixed-runtime-path")]
pub webview_fixed_runtime_path: Option<PathBuf>,
/// 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`.
#[serde(default = "default_true", alias = "allow-downgrades")]
pub allow_downgrades: bool,
/// Configuration for the MSI generated with WiX.
pub wix: Option<WixConfig>,
/// Configuration for the installer generated with NSIS.
pub nsis: Option<NsisConfig>,
}
impl Default for WindowsConfig {
fn default() -> Self {
Self {
digest_algorithm: None,
certificate_thumbprint: None,
timestamp_url: None,
tsp: false,
webview_install_mode: Default::default(),
webview_fixed_runtime_path: None,
allow_downgrades: true,
wix: None,
nsis: None,
}
}
}
/// Definition for bundle resources.
/// Can be either a list of paths to include or a map of source to target paths.
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields, untagged)]
pub enum BundleResources {
/// A list of paths to include.
List(Vec<String>),
/// A map of source to target paths.
Map(HashMap<String, String>),
}
/// Configuration for tauri-bundler.
///
/// See more: https://tauri.app/v1/api/config#bundleconfig
#[skip_serializing_none]
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct BundleConfig {
/// Whether Tauri should bundle your application or just output the executable.
#[serde(default)]
pub active: bool,
/// The bundle targets, currently supports ["deb", "appimage", "nsis", "msi", "app", "dmg", "updater"] or "all".
#[serde(default)]
pub targets: BundleTarget,
/// The application identifier in reverse domain name notation (e.g. `com.tauri.example`).
/// This string must be unique across applications since it is used in system configurations like
/// the bundle ID and path to the webview data directory.
/// This string must contain only alphanumeric characters (A-Z, a-z, and 0-9), hyphens (-),
/// and periods (.).
pub identifier: String,
/// The application's publisher. Defaults to the second element in the identifier string.
/// Currently maps to the Manufacturer property of the Windows Installer.
pub publisher: Option<String>,
/// The app's icons
#[serde(default)]
pub icon: Vec<String>,
/// App resources to bundle.
/// Each resource is a path to a file or directory.
/// Glob patterns are supported.
pub resources: Option<BundleResources>,
/// A copyright string associated with your application.
pub copyright: Option<String>,
/// The application kind.
///
/// Should be one of the following:
/// 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.
pub category: Option<String>,
/// A short description of your application.
#[serde(alias = "short-description")]
pub short_description: Option<String>,
/// A longer, multi-line description of the application.
#[serde(alias = "long-description")]
pub long_description: Option<String>,
/// Configuration for the AppImage bundle.
#[serde(default)]
pub appimage: AppImageConfig,
/// Configuration for the Debian bundle.
#[serde(default)]
pub deb: DebConfig,
/// Configuration for the macOS bundles.
#[serde(rename = "macOS", default)]
pub macos: MacConfig,
/// A list of—either absolute or relative—paths to binaries to embed with your application.
///
/// Note that Tauri will look for system-specific binaries following the pattern "binary-name{-target-triple}{.system-extension}".
///
/// E.g. for the external binary "my-binary", Tauri looks for:
///
/// - "my-binary-x86_64-pc-windows-msvc.exe" for Windows
/// - "my-binary-x86_64-apple-darwin" for macOS
/// - "my-binary-x86_64-unknown-linux-gnu" for Linux
///
/// so don't forget to provide binaries for all targeted platforms.
#[serde(alias = "external-bin")]
pub external_bin: Option<Vec<String>>,
/// Configuration for the Windows bundle.
#[serde(default)]
pub windows: WindowsConfig,
}
/// A CLI argument definition.
#[skip_serializing_none]
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct CliArg {
/// The short version of the argument, without the preceding -.
///
/// NOTE: Any leading `-` characters will be stripped, and only the first non-character will be used as the short version.
pub short: Option<char>,
/// The unique argument name
pub name: String,
/// The argument description which will be shown on the help information.
/// Typically, this is a short (one line) description of the arg.
pub description: Option<String>,
/// The argument long description which will be shown on the help information.
/// Typically this a more detailed (multi-line) message that describes the argument.
#[serde(alias = "long-description")]
pub long_description: Option<String>,
/// Specifies that the argument takes a value at run time.
///
/// NOTE: values for arguments may be specified in any of the following methods
/// - Using a space such as -o value or --option value
/// - Using an equals and no space such as -o=value or --option=value
/// - Use a short and no space such as -ovalue
#[serde(default, alias = "takes-value")]
pub takes_value: bool,
/// Specifies that the argument may have an unknown number of multiple values. Without any other settings, this argument may appear only once.
///
/// For example, --opt val1 val2 is allowed, but --opt val1 val2 --opt val3 is not.
///
/// NOTE: Setting this requires `takes_value` to be set to true.
#[serde(default)]
pub multiple: bool,
/// Specifies that the argument may appear more than once.
/// For flags, this results in the number of occurrences of the flag being recorded. For example -ddd or -d -d -d would count as three occurrences.
/// For options or arguments that take a value, this does not affect how many values they can accept. (i.e. only one at a time is allowed)
///
/// For example, --opt val1 --opt val2 is allowed, but --opt val1 val2 is not.
#[serde(default, alias = "multiple-occurrences")]
pub multiple_occurrences: bool,
/// Specifies how many values are required to satisfy this argument. For example, if you had a
/// `-f <file>` argument where you wanted exactly 3 'files' you would set
/// `number_of_values = 3`, and this argument wouldn't be satisfied unless the user provided
/// 3 and only 3 values.
///
/// **NOTE:** Does *not* require `multiple_occurrences = true` to be set. Setting
/// `multiple_occurrences = true` would allow `-f <file> <file> <file> -f <file> <file> <file>` where
/// as *not* setting it would only allow one occurrence of this argument.
///
/// **NOTE:** implicitly sets `takes_value = true` and `multiple_values = true`.
#[serde(alias = "number-of-values")]
pub number_of_values: Option<usize>,
/// Specifies a list of possible values for this argument.
/// At runtime, the CLI verifies that only one of the specified values was used, or fails with an error message.
#[serde(alias = "possible-values")]
pub possible_values: Option<Vec<String>>,
/// Specifies the minimum number of values for this argument.
/// For example, if you had a -f `<file>` argument where you wanted at least 2 'files',
/// you would set `minValues: 2`, and this argument would be satisfied if the user provided, 2 or more values.
| 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-utils/src/acl/manifest.rs | crates/tauri-utils/src/acl/manifest.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Plugin ACL types.
use std::{collections::BTreeMap, num::NonZeroU64};
use super::{Permission, PermissionSet};
#[cfg(feature = "schema")]
use schemars::schema::*;
use serde::{Deserialize, Serialize};
/// The default permission set of the plugin.
///
/// Works similarly to a permission with the "default" identifier.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct DefaultPermission {
/// The version of the permission.
pub version: Option<NonZeroU64>,
/// Human-readable description of what the permission does.
/// Tauri convention is to use `<h4>` headings in markdown content
/// for Tauri documentation generation purposes.
pub description: Option<String>,
/// All permissions this set contains.
pub permissions: Vec<String>,
}
/// Permission file that can define a default permission, a set of permissions or a list of inlined permissions.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct PermissionFile {
/// The default permission set for the plugin
pub default: Option<DefaultPermission>,
/// A list of permissions sets defined
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub set: Vec<PermissionSet>,
/// A list of inlined permissions
#[serde(default)]
pub permission: Vec<Permission>,
}
/// Plugin manifest.
#[derive(Debug, Serialize, Deserialize, Default)]
pub struct Manifest {
/// Default permission.
pub default_permission: Option<PermissionSet>,
/// Plugin permissions.
pub permissions: BTreeMap<String, Permission>,
/// Plugin permission sets.
pub permission_sets: BTreeMap<String, PermissionSet>,
/// The global scope schema.
pub global_scope_schema: Option<serde_json::Value>,
}
impl Manifest {
/// Creates a new manifest from the given plugin permission files and global scope schema.
pub fn new(
permission_files: Vec<PermissionFile>,
global_scope_schema: Option<serde_json::Value>,
) -> Self {
let mut manifest = Self {
default_permission: None,
permissions: BTreeMap::new(),
permission_sets: BTreeMap::new(),
global_scope_schema,
};
for permission_file in permission_files {
if let Some(default) = permission_file.default {
manifest.default_permission.replace(PermissionSet {
identifier: "default".into(),
description: default
.description
.unwrap_or_else(|| "Default plugin permissions.".to_string()),
permissions: default.permissions,
});
}
for permission in permission_file.permission {
let key = permission.identifier.clone();
manifest.permissions.insert(key, permission);
}
for set in permission_file.set {
let key = set.identifier.clone();
manifest.permission_sets.insert(key, set);
}
}
manifest
}
}
#[cfg(feature = "schema")]
type ScopeSchema = (Schema, schemars::Map<String, Schema>);
#[cfg(feature = "schema")]
impl Manifest {
/// Return scope schema and extra schema definitions for this plugin manifest.
pub fn global_scope_schema(&self) -> Result<Option<ScopeSchema>, super::Error> {
self
.global_scope_schema
.as_ref()
.map(|s| {
serde_json::from_value::<RootSchema>(s.clone()).map(|s| {
// convert RootSchema to Schema
let scope_schema = Schema::Object(SchemaObject {
array: Some(Box::new(ArrayValidation {
items: Some(Schema::Object(s.schema).into()),
..Default::default()
})),
..Default::default()
});
(scope_schema, s.definitions)
})
})
.transpose()
.map_err(Into::into)
}
}
#[cfg(feature = "build")]
mod build {
use proc_macro2::TokenStream;
use quote::{quote, ToTokens, TokenStreamExt};
use std::convert::identity;
use super::*;
use crate::{literal_struct, tokens::*};
impl ToTokens for DefaultPermission {
fn to_tokens(&self, tokens: &mut TokenStream) {
let version = opt_lit_owned(self.version.as_ref().map(|v| {
let v = v.get();
quote!(::core::num::NonZeroU64::new(#v).unwrap())
}));
// Only used in build script and macros, so don't include them in runtime
let description = quote! { ::core::option::Option::None };
let permissions = vec_lit(&self.permissions, str_lit);
literal_struct!(
tokens,
::tauri::utils::acl::plugin::DefaultPermission,
version,
description,
permissions
)
}
}
impl ToTokens for Manifest {
fn to_tokens(&self, tokens: &mut TokenStream) {
let default_permission = opt_lit(self.default_permission.as_ref());
let permissions = map_lit(
quote! { ::std::collections::BTreeMap },
&self.permissions,
str_lit,
identity,
);
let permission_sets = map_lit(
quote! { ::std::collections::BTreeMap },
&self.permission_sets,
str_lit,
identity,
);
// Only used in build script and macros, so don't include them in runtime
// let global_scope_schema =
// opt_lit_owned(self.global_scope_schema.as_ref().map(json_value_lit));
let global_scope_schema = quote! { ::core::option::Option::None };
literal_struct!(
tokens,
::tauri::utils::acl::manifest::Manifest,
default_permission,
permissions,
permission_sets,
global_scope_schema
)
}
}
}
| 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/acl/value.rs | crates/tauri-utils/src/acl/value.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! A [`Value`] that is used instead of [`toml::Value`] or [`serde_json::Value`]
//! to support both formats.
use std::collections::BTreeMap;
use std::fmt::Debug;
use serde::{Deserialize, Serialize};
/// A valid ACL number.
#[derive(Debug, PartialEq, Serialize, Deserialize, Copy, Clone, PartialOrd)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(untagged)]
pub enum Number {
/// Represents an [`i64`].
Int(i64),
/// Represents a [`f64`].
Float(f64),
}
impl From<i64> for Number {
#[inline(always)]
fn from(value: i64) -> Self {
Self::Int(value)
}
}
impl From<f64> for Number {
#[inline(always)]
fn from(value: f64) -> Self {
Self::Float(value)
}
}
/// All supported ACL values.
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone, PartialOrd)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(untagged)]
pub enum Value {
/// Represents a null JSON value.
Null,
/// Represents a [`bool`].
Bool(bool),
/// Represents a valid ACL [`Number`].
Number(Number),
/// Represents a [`String`].
String(String),
/// Represents a list of other [`Value`]s.
List(Vec<Value>),
/// Represents a map of [`String`] keys to [`Value`]s.
Map(BTreeMap<String, Value>),
}
impl From<Value> for serde_json::Value {
fn from(value: Value) -> Self {
match value {
Value::Null => serde_json::Value::Null,
Value::Bool(b) => serde_json::Value::Bool(b),
Value::Number(Number::Float(f)) => {
serde_json::Value::Number(serde_json::Number::from_f64(f).unwrap())
}
Value::Number(Number::Int(i)) => serde_json::Value::Number(i.into()),
Value::String(s) => serde_json::Value::String(s),
Value::List(list) => serde_json::Value::Array(list.into_iter().map(Into::into).collect()),
Value::Map(map) => serde_json::Value::Object(
map
.into_iter()
.map(|(key, value)| (key, value.into()))
.collect(),
),
}
}
}
impl From<serde_json::Value> for Value {
fn from(value: serde_json::Value) -> Self {
match value {
serde_json::Value::Null => Value::Null,
serde_json::Value::Bool(b) => Value::Bool(b),
serde_json::Value::Number(n) => Value::Number(if let Some(f) = n.as_f64() {
Number::Float(f)
} else if let Some(n) = n.as_u64() {
Number::Int(n as i64)
} else if let Some(n) = n.as_i64() {
Number::Int(n)
} else {
Number::Int(0)
}),
serde_json::Value::String(s) => Value::String(s),
serde_json::Value::Array(list) => Value::List(list.into_iter().map(Into::into).collect()),
serde_json::Value::Object(map) => Value::Map(
map
.into_iter()
.map(|(key, value)| (key, value.into()))
.collect(),
),
}
}
}
impl From<bool> for Value {
#[inline(always)]
fn from(value: bool) -> Self {
Self::Bool(value)
}
}
impl<T: Into<Number>> From<T> for Value {
#[inline(always)]
fn from(value: T) -> Self {
Self::Number(value.into())
}
}
impl From<String> for Value {
#[inline(always)]
fn from(value: String) -> Self {
Value::String(value)
}
}
impl From<toml::Value> for Value {
#[inline(always)]
fn from(value: toml::Value) -> Self {
use toml::Value as Toml;
match value {
Toml::String(s) => s.into(),
Toml::Integer(i) => i.into(),
Toml::Float(f) => f.into(),
Toml::Boolean(b) => b.into(),
Toml::Datetime(d) => d.to_string().into(),
Toml::Array(a) => Value::List(a.into_iter().map(Value::from).collect()),
Toml::Table(t) => Value::Map(t.into_iter().map(|(k, v)| (k, v.into())).collect()),
}
}
}
#[cfg(feature = "build")]
mod build {
use std::convert::identity;
use crate::tokens::*;
use super::*;
use proc_macro2::TokenStream;
use quote::{quote, ToTokens, TokenStreamExt};
impl ToTokens for Number {
fn to_tokens(&self, tokens: &mut TokenStream) {
let prefix = quote! { ::tauri::utils::acl::Number };
tokens.append_all(match self {
Self::Int(i) => {
quote! { #prefix::Int(#i) }
}
Self::Float(f) => {
quote! { #prefix::Float (#f) }
}
});
}
}
impl ToTokens for Value {
fn to_tokens(&self, tokens: &mut TokenStream) {
let prefix = quote! { ::tauri::utils::acl::Value };
tokens.append_all(match self {
Value::Null => quote! { #prefix::Null },
Value::Bool(bool) => quote! { #prefix::Bool(#bool) },
Value::Number(number) => quote! { #prefix::Number(#number) },
Value::String(str) => {
let s = str_lit(str);
quote! { #prefix::String(#s) }
}
Value::List(vec) => {
let items = vec_lit(vec, identity);
quote! { #prefix::List(#items) }
}
Value::Map(map) => {
let map = map_lit(
quote! { ::std::collections::BTreeMap },
map,
str_lit,
identity,
);
quote! { #prefix::Map(#map) }
}
});
}
}
}
| 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/acl/build.rs | crates/tauri-utils/src/acl/build.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! ACL items that are only useful inside of build script/codegen context.
use std::{
collections::{BTreeMap, HashMap},
env, fs,
path::{Path, PathBuf},
};
use crate::{
acl::{has_app_manifest, AllowedCommands, Error},
config::Config,
write_if_changed,
};
use super::{
capability::{Capability, CapabilityFile},
manifest::PermissionFile,
ALLOWED_COMMANDS_FILE_NAME, PERMISSION_SCHEMAS_FOLDER_NAME, PERMISSION_SCHEMA_FILE_NAME,
REMOVE_UNUSED_COMMANDS_ENV_VAR,
};
/// Known name of the folder containing autogenerated permissions.
pub const AUTOGENERATED_FOLDER_NAME: &str = "autogenerated";
/// Cargo cfg key for permissions file paths
pub const PERMISSION_FILES_PATH_KEY: &str = "PERMISSION_FILES_PATH";
/// Cargo cfg key for global scope schemas
pub const GLOBAL_SCOPE_SCHEMA_PATH_KEY: &str = "GLOBAL_SCOPE_SCHEMA_PATH";
/// Allowed permission file extensions
pub const PERMISSION_FILE_EXTENSIONS: &[&str] = &["json", "toml"];
/// Known filename of the permission documentation file
pub const PERMISSION_DOCS_FILE_NAME: &str = "reference.md";
/// Allowed capability file extensions
const CAPABILITY_FILE_EXTENSIONS: &[&str] = &[
"json",
#[cfg(feature = "config-json5")]
"json5",
"toml",
];
/// Known folder name of the capability schemas
const CAPABILITIES_SCHEMA_FOLDER_NAME: &str = "schemas";
const CORE_PLUGIN_PERMISSIONS_TOKEN: &str = "__CORE_PLUGIN__";
fn parse_permissions(paths: Vec<PathBuf>) -> Result<Vec<PermissionFile>, Error> {
let mut permissions = Vec::new();
for path in paths {
let ext = path.extension().unwrap().to_string_lossy().to_string();
let permission_file = fs::read_to_string(&path).map_err(|e| Error::ReadFile(e, path))?;
let permission: PermissionFile = match ext.as_str() {
"toml" => toml::from_str(&permission_file)?,
"json" => serde_json::from_str(&permission_file)?,
_ => return Err(Error::UnknownPermissionFormat(ext)),
};
permissions.push(permission);
}
Ok(permissions)
}
/// Write the permissions to a temporary directory and pass it to the immediate consuming crate.
pub fn define_permissions<F: Fn(&Path) -> bool>(
pattern: &str,
pkg_name: &str,
out_dir: &Path,
filter_fn: F,
) -> Result<Vec<PermissionFile>, Error> {
let permission_files = glob::glob(pattern)?
.flatten()
.flat_map(|p| p.canonicalize())
// filter extension
.filter(|p| {
p.extension()
.and_then(|e| e.to_str())
.map(|e| PERMISSION_FILE_EXTENSIONS.contains(&e))
.unwrap_or_default()
})
.filter(|p| filter_fn(p))
// filter schemas
.filter(|p| p.parent().unwrap().file_name().unwrap() != PERMISSION_SCHEMAS_FOLDER_NAME)
.collect::<Vec<PathBuf>>();
let pkg_name_valid_path = pkg_name.replace(':', "-");
let permission_files_path = out_dir.join(format!("{pkg_name_valid_path}-permission-files"));
let permission_files_json = serde_json::to_string(&permission_files)?;
write_if_changed(&permission_files_path, permission_files_json)
.map_err(|e| Error::WriteFile(e, permission_files_path.clone()))?;
if let Some(plugin_name) = pkg_name.strip_prefix("tauri:") {
println!(
"cargo:{plugin_name}{CORE_PLUGIN_PERMISSIONS_TOKEN}_{PERMISSION_FILES_PATH_KEY}={}",
permission_files_path.display()
);
} else {
println!(
"cargo:{PERMISSION_FILES_PATH_KEY}={}",
permission_files_path.display()
);
}
parse_permissions(permission_files)
}
/// Read all permissions listed from the defined cargo cfg key value.
pub fn read_permissions() -> Result<HashMap<String, Vec<PermissionFile>>, Error> {
let mut permissions_map = HashMap::new();
for (key, value) in env::vars_os() {
let key = key.to_string_lossy();
if let Some(plugin_crate_name_var) = key
.strip_prefix("DEP_")
.and_then(|v| v.strip_suffix(&format!("_{PERMISSION_FILES_PATH_KEY}")))
.map(|v| {
v.strip_suffix(CORE_PLUGIN_PERMISSIONS_TOKEN)
.and_then(|v| v.strip_prefix("TAURI_"))
.unwrap_or(v)
})
{
let permissions_path = PathBuf::from(value);
let permissions_str =
fs::read_to_string(&permissions_path).map_err(|e| Error::ReadFile(e, permissions_path))?;
let permissions: Vec<PathBuf> = serde_json::from_str(&permissions_str)?;
let permissions = parse_permissions(permissions)?;
let plugin_crate_name = plugin_crate_name_var.to_lowercase().replace('_', "-");
let plugin_crate_name = plugin_crate_name
.strip_prefix("tauri-plugin-")
.map(ToString::to_string)
.unwrap_or(plugin_crate_name);
permissions_map.insert(plugin_crate_name, permissions);
}
}
Ok(permissions_map)
}
/// Define the global scope schema JSON file path if it exists and pass it to the immediate consuming crate.
pub fn define_global_scope_schema(
schema: schemars::schema::RootSchema,
pkg_name: &str,
out_dir: &Path,
) -> Result<(), Error> {
let path = out_dir.join("global-scope.json");
write_if_changed(&path, serde_json::to_vec(&schema)?)
.map_err(|e| Error::WriteFile(e, path.clone()))?;
if let Some(plugin_name) = pkg_name.strip_prefix("tauri:") {
println!(
"cargo:{plugin_name}{CORE_PLUGIN_PERMISSIONS_TOKEN}_{GLOBAL_SCOPE_SCHEMA_PATH_KEY}={}",
path.display()
);
} else {
println!("cargo:{GLOBAL_SCOPE_SCHEMA_PATH_KEY}={}", path.display());
}
Ok(())
}
/// Read all global scope schemas listed from the defined cargo cfg key value.
pub fn read_global_scope_schemas() -> Result<HashMap<String, serde_json::Value>, Error> {
let mut schemas_map = HashMap::new();
for (key, value) in env::vars_os() {
let key = key.to_string_lossy();
if let Some(plugin_crate_name_var) = key
.strip_prefix("DEP_")
.and_then(|v| v.strip_suffix(&format!("_{GLOBAL_SCOPE_SCHEMA_PATH_KEY}")))
.map(|v| {
v.strip_suffix(CORE_PLUGIN_PERMISSIONS_TOKEN)
.and_then(|v| v.strip_prefix("TAURI_"))
.unwrap_or(v)
})
{
let path = PathBuf::from(value);
let json = fs::read_to_string(&path).map_err(|e| Error::ReadFile(e, path))?;
let schema: serde_json::Value = serde_json::from_str(&json)?;
let plugin_crate_name = plugin_crate_name_var.to_lowercase().replace('_', "-");
let plugin_crate_name = plugin_crate_name
.strip_prefix("tauri-plugin-")
.map(ToString::to_string)
.unwrap_or(plugin_crate_name);
schemas_map.insert(plugin_crate_name, schema);
}
}
Ok(schemas_map)
}
/// Parses all capability files with the given glob pattern.
pub fn parse_capabilities(pattern: &str) -> Result<BTreeMap<String, Capability>, Error> {
let mut capabilities_map = BTreeMap::new();
for path in glob::glob(pattern)?
.flatten() // filter extension
.filter(|p| {
p.extension()
.and_then(|e| e.to_str())
.map(|e| CAPABILITY_FILE_EXTENSIONS.contains(&e))
.unwrap_or_default()
})
// filter schema files
// TODO: remove this before stable
.filter(|p| p.parent().unwrap().file_name().unwrap() != CAPABILITIES_SCHEMA_FOLDER_NAME)
{
match CapabilityFile::load(&path)? {
CapabilityFile::Capability(capability) => {
if capabilities_map.contains_key(&capability.identifier) {
return Err(Error::CapabilityAlreadyExists {
identifier: capability.identifier,
});
}
capabilities_map.insert(capability.identifier.clone(), capability);
}
CapabilityFile::List(capabilities) | CapabilityFile::NamedList { capabilities } => {
for capability in capabilities {
if capabilities_map.contains_key(&capability.identifier) {
return Err(Error::CapabilityAlreadyExists {
identifier: capability.identifier,
});
}
capabilities_map.insert(capability.identifier.clone(), capability);
}
}
}
}
Ok(capabilities_map)
}
/// Permissions that are generated from commands using [`autogenerate_command_permissions`].
pub struct AutogeneratedPermissions {
/// The allow permissions generated from commands.
pub allowed: Vec<String>,
/// The deny permissions generated from commands.
pub denied: Vec<String>,
}
/// Autogenerate permission files for a list of commands.
pub fn autogenerate_command_permissions(
path: &Path,
commands: &[&str],
license_header: &str,
schema_ref: bool,
) -> AutogeneratedPermissions {
if !path.exists() {
fs::create_dir_all(path).expect("unable to create autogenerated commands dir");
}
let schema_entry = if schema_ref {
let cwd = env::current_dir().unwrap();
let components_len = path.strip_prefix(&cwd).unwrap_or(path).components().count();
let schema_path = (1..components_len)
.map(|_| "..")
.collect::<PathBuf>()
.join(PERMISSION_SCHEMAS_FOLDER_NAME)
.join(PERMISSION_SCHEMA_FILE_NAME);
format!(
"\n\"$schema\" = \"{}\"\n",
dunce::simplified(&schema_path)
.display()
.to_string()
.replace('\\', "/")
)
} else {
"".to_string()
};
let mut autogenerated = AutogeneratedPermissions {
allowed: Vec::new(),
denied: Vec::new(),
};
for command in commands {
let slugified_command = command.replace('_', "-");
let toml = format!(
r###"{license_header}# Automatically generated - DO NOT EDIT!
{schema_entry}
[[permission]]
identifier = "allow-{slugified_command}"
description = "Enables the {command} command without any pre-configured scope."
commands.allow = ["{command}"]
[[permission]]
identifier = "deny-{slugified_command}"
description = "Denies the {command} command without any pre-configured scope."
commands.deny = ["{command}"]
"###,
);
let out_path = path.join(format!("{command}.toml"));
write_if_changed(&out_path, toml)
.unwrap_or_else(|_| panic!("unable to autogenerate {out_path:?}"));
autogenerated
.allowed
.push(format!("allow-{slugified_command}"));
autogenerated
.denied
.push(format!("deny-{slugified_command}"));
}
autogenerated
}
const PERMISSION_TABLE_HEADER: &str =
"## Permission Table\n\n<table>\n<tr>\n<th>Identifier</th>\n<th>Description</th>\n</tr>\n";
/// Generate a markdown documentation page containing the list of permissions of the plugin.
pub fn generate_docs(
permissions: &[PermissionFile],
out_dir: &Path,
plugin_identifier: &str,
) -> Result<(), Error> {
let mut default_permission = "".to_owned();
let mut permission_table = "".to_string();
fn docs_from(id: &str, description: Option<&str>, plugin_identifier: &str) -> String {
let mut docs = format!("\n<tr>\n<td>\n\n`{plugin_identifier}:{id}`\n\n</td>\n");
if let Some(d) = description {
docs.push_str(&format!("<td>\n\n{d}\n\n</td>"));
}
docs.push_str("\n</tr>");
docs
}
for permission in permissions {
for set in &permission.set {
permission_table.push_str(&docs_from(
&set.identifier,
Some(&set.description),
plugin_identifier,
));
permission_table.push('\n');
}
if let Some(default) = &permission.default {
default_permission.push_str("## Default Permission\n\n");
default_permission.push_str(default.description.as_deref().unwrap_or_default().trim());
default_permission.push('\n');
default_permission.push('\n');
if !default.permissions.is_empty() {
default_permission.push_str("#### This default permission set includes the following:\n\n");
for permission in &default.permissions {
default_permission.push_str(&format!("- `{permission}`\n"));
}
default_permission.push('\n');
}
}
for permission in &permission.permission {
permission_table.push_str(&docs_from(
&permission.identifier,
permission.description.as_deref(),
plugin_identifier,
));
permission_table.push('\n');
}
}
let docs = format!("{default_permission}{PERMISSION_TABLE_HEADER}\n{permission_table}</table>\n");
let reference_path = out_dir.join(PERMISSION_DOCS_FILE_NAME);
write_if_changed(&reference_path, docs).map_err(|e| Error::WriteFile(e, reference_path))?;
Ok(())
}
// TODO: We have way too many duplicated code around getting the config files, e.g.
// - crates/tauri-codegen/src/lib.rs (`get_config`)
// - crates/tauri-build/src/lib.rs (`try_build`)
// - crates/tauri-cli/src/helpers/config.rs (`get_internal`)
/// Generate allowed commands file for the `generate_handler` macro to remove never allowed commands
pub fn generate_allowed_commands(
out_dir: &Path,
capabilities_from_files: Option<BTreeMap<String, Capability>>,
permissions_map: BTreeMap<String, Vec<PermissionFile>>,
) -> Result<(), anyhow::Error> {
println!("cargo:rerun-if-env-changed={REMOVE_UNUSED_COMMANDS_ENV_VAR}");
let allowed_commands_file_path = out_dir.join(ALLOWED_COMMANDS_FILE_NAME);
let remove_unused_commands_env_var = std::env::var(REMOVE_UNUSED_COMMANDS_ENV_VAR);
let should_generate_allowed_commands =
remove_unused_commands_env_var.is_ok() && !permissions_map.is_empty();
if !should_generate_allowed_commands {
let _ = std::fs::remove_file(allowed_commands_file_path);
return Ok(());
}
// It's safe to `unwrap` here since we have checked if the result is ok above
let config_directory = PathBuf::from(remove_unused_commands_env_var.unwrap());
let capabilities_path = config_directory.join("capabilities");
// Cargo re-builds if the variable points to an empty path,
// so we check for exists here
// see https://github.com/rust-lang/cargo/issues/4213
if capabilities_path.exists() {
println!("cargo:rerun-if-changed={}", capabilities_path.display());
}
let target_triple = env::var("TARGET")?;
let target = crate::platform::Target::from_triple(&target_triple);
let (mut config, config_paths) = crate::config::parse::read_from(target, &config_directory)?;
for config_file_path in config_paths {
println!("cargo:rerun-if-changed={}", config_file_path.display());
}
if let Ok(env) = std::env::var("TAURI_CONFIG") {
let merge_config: serde_json::Value = serde_json::from_str(&env)?;
json_patch::merge(&mut config, &merge_config);
}
println!("cargo:rerun-if-env-changed=TAURI_CONFIG");
// Set working directory to where `tauri.config.json` is, so that relative paths in it are parsed correctly.
let old_cwd = std::env::current_dir()?;
std::env::set_current_dir(config_directory)?;
let config: Config = serde_json::from_value(config)?;
// Reset working directory.
std::env::set_current_dir(old_cwd)?;
let acl: BTreeMap<String, crate::acl::manifest::Manifest> = permissions_map
.into_iter()
.map(|(key, permissions)| {
let key = key
.strip_prefix("tauri-plugin-")
.unwrap_or(&key)
.to_string();
let manifest = crate::acl::manifest::Manifest::new(permissions, None);
(key, manifest)
})
.collect();
let capabilities_from_files = if let Some(capabilities) = capabilities_from_files {
capabilities
} else {
crate::acl::build::parse_capabilities(&format!(
"{}/**/*",
glob::Pattern::escape(&capabilities_path.to_string_lossy())
))?
};
let capabilities = crate::acl::get_capabilities(&config, capabilities_from_files, None)?;
let permission_entries = capabilities
.into_iter()
.flat_map(|(_, capabilities)| capabilities.permissions);
let mut allowed_commands = AllowedCommands {
has_app_acl: has_app_manifest(&acl),
..Default::default()
};
for permission_entry in permission_entries {
let Ok(permissions) =
crate::acl::resolved::get_permissions(permission_entry.identifier(), &acl)
else {
continue;
};
for permission in permissions {
let plugin_name = permission.key;
let allowed_command_names = &permission.permission.commands.allow;
for allowed_command in allowed_command_names {
let command_name = if plugin_name == crate::acl::APP_ACL_KEY {
allowed_command.to_string()
} else if let Some(core_plugin_name) = plugin_name.strip_prefix("core:") {
format!("plugin:{core_plugin_name}|{allowed_command}")
} else {
format!("plugin:{plugin_name}|{allowed_command}")
};
allowed_commands.commands.insert(command_name);
}
}
}
write_if_changed(
allowed_commands_file_path,
serde_json::to_string(&allowed_commands)?,
)?;
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/acl/identifier.rs | crates/tauri-utils/src/acl/identifier.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Identifier for plugins.
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::num::NonZeroU8;
use thiserror::Error;
const IDENTIFIER_SEPARATOR: u8 = b':';
const PLUGIN_PREFIX: &str = "tauri-plugin-";
const CORE_PLUGIN_IDENTIFIER_PREFIX: &str = "core:";
// <https://doc.rust-lang.org/cargo/reference/manifest.html#the-name-field>
const MAX_LEN_PREFIX: usize = 64 - PLUGIN_PREFIX.len();
const MAX_LEN_BASE: usize = 64;
const MAX_LEN_IDENTIFIER: usize = MAX_LEN_PREFIX + 1 + MAX_LEN_BASE;
/// Plugin identifier.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Identifier {
inner: String,
separator: Option<NonZeroU8>,
}
#[cfg(feature = "schema")]
impl schemars::JsonSchema for Identifier {
fn schema_name() -> String {
"Identifier".to_string()
}
fn schema_id() -> std::borrow::Cow<'static, str> {
// Include the module, in case a type with the same name is in another module/crate
std::borrow::Cow::Borrowed(concat!(module_path!(), "::Identifier"))
}
fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
String::json_schema(gen)
}
}
impl AsRef<str> for Identifier {
#[inline(always)]
fn as_ref(&self) -> &str {
&self.inner
}
}
impl Identifier {
/// Get the identifier str.
#[inline(always)]
pub fn get(&self) -> &str {
self.as_ref()
}
/// Get the identifier without prefix.
pub fn get_base(&self) -> &str {
match self.separator_index() {
None => self.get(),
Some(i) => &self.inner[i + 1..],
}
}
/// Get the prefix of the identifier.
pub fn get_prefix(&self) -> Option<&str> {
self.separator_index().map(|i| &self.inner[0..i])
}
/// Set the identifier prefix.
pub fn set_prefix(&mut self) -> Result<(), ParseIdentifierError> {
todo!()
}
/// Get the identifier string and its separator.
pub fn into_inner(self) -> (String, Option<NonZeroU8>) {
(self.inner, self.separator)
}
fn separator_index(&self) -> Option<usize> {
self.separator.map(|i| i.get() as usize)
}
}
#[derive(Debug)]
enum ValidByte {
Separator,
Byte(u8),
}
impl ValidByte {
fn alpha_numeric(byte: u8) -> Option<Self> {
byte.is_ascii_alphanumeric().then_some(Self::Byte(byte))
}
fn alpha_numeric_hyphen(byte: u8) -> Option<Self> {
(byte.is_ascii_alphanumeric() || byte == b'-').then_some(Self::Byte(byte))
}
fn next(&self, next: u8) -> Option<ValidByte> {
match (self, next) {
(ValidByte::Byte(b'-'), IDENTIFIER_SEPARATOR) => None,
(ValidByte::Separator, b'-') => None,
(_, IDENTIFIER_SEPARATOR) => Some(ValidByte::Separator),
(ValidByte::Separator, next) => ValidByte::alpha_numeric(next),
(ValidByte::Byte(b'-'), next) => ValidByte::alpha_numeric_hyphen(next),
(ValidByte::Byte(b'_'), next) => ValidByte::alpha_numeric_hyphen(next),
(ValidByte::Byte(_), next) => ValidByte::alpha_numeric_hyphen(next),
}
}
}
/// Errors that can happen when parsing an identifier.
#[derive(Debug, Error)]
pub enum ParseIdentifierError {
/// Identifier start with the plugin prefix.
#[error("identifiers cannot start with {}", PLUGIN_PREFIX)]
StartsWithTauriPlugin,
/// Identifier empty.
#[error("identifiers cannot be empty")]
Empty,
/// Identifier is too long.
#[error("identifiers cannot be longer than {len}, found {0}", len = MAX_LEN_IDENTIFIER)]
Humongous(usize),
/// Identifier is not in a valid format.
#[error("identifiers can only include lowercase ASCII, hyphens which are not leading or trailing, and a single colon if using a prefix")]
InvalidFormat,
/// Identifier has multiple separators.
#[error(
"identifiers can only include a single separator '{}'",
IDENTIFIER_SEPARATOR
)]
MultipleSeparators,
/// Identifier has a trailing hyphen.
#[error("identifiers cannot have a trailing hyphen")]
TrailingHyphen,
/// Identifier has a prefix without a base.
#[error("identifiers cannot have a prefix without a base")]
PrefixWithoutBase,
}
impl TryFrom<String> for Identifier {
type Error = ParseIdentifierError;
fn try_from(value: String) -> Result<Self, Self::Error> {
if value.starts_with(PLUGIN_PREFIX) {
return Err(Self::Error::StartsWithTauriPlugin);
}
if value.is_empty() {
return Err(Self::Error::Empty);
}
if value.len() > MAX_LEN_IDENTIFIER {
return Err(Self::Error::Humongous(value.len()));
}
let is_core_identifier = value.starts_with(CORE_PLUGIN_IDENTIFIER_PREFIX);
let mut bytes = value.bytes();
// grab the first byte only before parsing the rest
let mut prev = bytes
.next()
.and_then(ValidByte::alpha_numeric)
.ok_or(Self::Error::InvalidFormat)?;
let mut idx = 0;
let mut separator = None;
for byte in bytes {
idx += 1; // we already consumed first item
match prev.next(byte) {
None => return Err(Self::Error::InvalidFormat),
Some(next @ ValidByte::Byte(_)) => prev = next,
Some(ValidByte::Separator) => {
if separator.is_none() || is_core_identifier {
// safe to unwrap because idx starts at 1 and cannot go over MAX_IDENTIFIER_LEN
separator = Some(idx.try_into().unwrap());
prev = ValidByte::Separator
} else {
return Err(Self::Error::MultipleSeparators);
}
}
}
}
match prev {
// empty base
ValidByte::Separator => return Err(Self::Error::PrefixWithoutBase),
// trailing hyphen
ValidByte::Byte(b'-') => return Err(Self::Error::TrailingHyphen),
_ => (),
}
Ok(Self {
inner: value,
separator,
})
}
}
impl<'de> Deserialize<'de> for Identifier {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Self::try_from(String::deserialize(deserializer)?).map_err(serde::de::Error::custom)
}
}
impl Serialize for Identifier {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.get())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn ident(s: impl Into<String>) -> Result<Identifier, ParseIdentifierError> {
Identifier::try_from(s.into())
}
#[test]
fn max_len_fits_in_u8() {
assert!(MAX_LEN_IDENTIFIER < u8::MAX as usize)
}
#[test]
fn format() {
assert!(ident("prefix:base").is_ok());
assert!(ident("prefix3:base").is_ok());
assert!(ident("preFix:base").is_ok());
// bad
assert!(ident("tauri-plugin-prefix:base").is_err());
assert!(ident("-prefix-:-base-").is_err());
assert!(ident("-prefix:base").is_err());
assert!(ident("prefix-:base").is_err());
assert!(ident("prefix:-base").is_err());
assert!(ident("prefix:base-").is_err());
assert!(ident("pre--fix:base--sep").is_ok());
assert!(ident("prefix:base--sep").is_ok());
assert!(ident("pre--fix:base").is_ok());
assert!(ident("prefix::base").is_err());
assert!(ident(":base").is_err());
assert!(ident("prefix:").is_err());
assert!(ident(":prefix:base:").is_err());
assert!(ident("base:").is_err());
assert!(ident("").is_err());
assert!(ident("💩").is_err());
assert!(ident("a".repeat(MAX_LEN_IDENTIFIER + 1)).is_err());
}
#[test]
fn base() {
assert_eq!(ident("prefix:base").unwrap().get_base(), "base");
assert_eq!(ident("base").unwrap().get_base(), "base");
}
#[test]
fn prefix() {
assert_eq!(ident("prefix:base").unwrap().get_prefix(), Some("prefix"));
assert_eq!(ident("base").unwrap().get_prefix(), None);
}
}
#[cfg(feature = "build")]
mod build {
use proc_macro2::TokenStream;
use quote::{quote, ToTokens, TokenStreamExt};
use super::*;
impl ToTokens for Identifier {
fn to_tokens(&self, tokens: &mut TokenStream) {
let s = self.get();
tokens
.append_all(quote! { ::tauri::utils::acl::Identifier::try_from(#s.to_string()).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-utils/src/acl/schema.rs | crates/tauri-utils/src/acl/schema.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Schema generation for ACL items.
use std::{
collections::{btree_map::Values, BTreeMap},
fs,
path::{Path, PathBuf},
slice::Iter,
};
use schemars::schema::*;
use super::{Error, PERMISSION_SCHEMAS_FOLDER_NAME};
use crate::{platform::Target, write_if_changed};
use super::{
capability::CapabilityFile,
manifest::{Manifest, PermissionFile},
Permission, PermissionSet, PERMISSION_SCHEMA_FILE_NAME,
};
/// Capability schema file name.
pub const CAPABILITIES_SCHEMA_FILE_NAME: &str = "schema.json";
/// Path of the folder where schemas are saved.
pub const CAPABILITIES_SCHEMA_FOLDER_PATH: &str = "gen/schemas";
// TODO: once MSRV is high enough, remove generic and use impl <trait>
// see https://github.com/tauri-apps/tauri/commit/b5561d74aee431f93c0c5b0fa6784fc0a956effe#diff-7c31d393f83cae149122e74ad44ac98e7d70ffb45c9e5b0a94ec52881b6f1cebR30-R42
/// Permission schema generator trait
pub trait PermissionSchemaGenerator<
'a,
Ps: Iterator<Item = &'a PermissionSet>,
P: Iterator<Item = &'a Permission>,
>
{
/// Whether has a default permission set or not.
fn has_default_permission_set(&self) -> bool;
/// Default permission set description if any.
fn default_set_description(&self) -> Option<&str>;
/// Default permission set's permissions if any.
fn default_set_permissions(&self) -> Option<&Vec<String>>;
/// Permissions sets to generate schema for.
fn permission_sets(&'a self) -> Ps;
/// Permissions to generate schema for.
fn permissions(&'a self) -> P;
/// A utility function to generate a schema for a permission identifier
fn perm_id_schema(name: Option<&str>, id: &str, description: Option<&str>) -> Schema {
let command_name = match name {
Some(name) if name == super::APP_ACL_KEY => id.to_string(),
Some(name) => format!("{name}:{id}"),
_ => id.to_string(),
};
let extensions = if let Some(description) = description {
[(
// This is non-standard, and only used by vscode right now,
// but it does work really well
"markdownDescription".to_string(),
serde_json::Value::String(description.to_string()),
)]
.into()
} else {
Default::default()
};
Schema::Object(SchemaObject {
metadata: Some(Box::new(Metadata {
description: description.map(ToString::to_string),
..Default::default()
})),
instance_type: Some(InstanceType::String.into()),
const_value: Some(serde_json::Value::String(command_name)),
extensions,
..Default::default()
})
}
/// Generate schemas for all possible permissions.
fn gen_possible_permission_schemas(&'a self, name: Option<&str>) -> Vec<Schema> {
let mut permission_schemas = Vec::new();
// schema for default set
if self.has_default_permission_set() {
let description = self.default_set_description().unwrap_or_default();
let description = if let Some(permissions) = self.default_set_permissions() {
add_permissions_to_description(description, permissions, true)
} else {
description.to_string()
};
if !description.is_empty() {
let default = Self::perm_id_schema(name, "default", Some(&description));
permission_schemas.push(default);
}
}
// schema for each permission set
for set in self.permission_sets() {
let description = add_permissions_to_description(&set.description, &set.permissions, false);
let schema = Self::perm_id_schema(name, &set.identifier, Some(&description));
permission_schemas.push(schema);
}
// schema for each permission
for perm in self.permissions() {
let schema = Self::perm_id_schema(name, &perm.identifier, perm.description.as_deref());
permission_schemas.push(schema);
}
permission_schemas
}
}
fn add_permissions_to_description(
description: &str,
permissions: &[String],
is_default: bool,
) -> String {
if permissions.is_empty() {
return description.to_string();
}
let permissions_list = permissions
.iter()
.map(|permission| format!("- `{permission}`"))
.collect::<Vec<_>>()
.join("\n");
let default_permission_set = if is_default {
"default permission set"
} else {
"permission set"
};
format!("{description}\n#### This {default_permission_set} includes:\n\n{permissions_list}")
}
impl<'a>
PermissionSchemaGenerator<
'a,
Values<'a, std::string::String, PermissionSet>,
Values<'a, std::string::String, Permission>,
> for Manifest
{
fn has_default_permission_set(&self) -> bool {
self.default_permission.is_some()
}
fn default_set_description(&self) -> Option<&str> {
self
.default_permission
.as_ref()
.map(|d| d.description.as_str())
}
fn default_set_permissions(&self) -> Option<&Vec<String>> {
self.default_permission.as_ref().map(|d| &d.permissions)
}
fn permission_sets(&'a self) -> Values<'a, std::string::String, PermissionSet> {
self.permission_sets.values()
}
fn permissions(&'a self) -> Values<'a, std::string::String, Permission> {
self.permissions.values()
}
}
impl<'a> PermissionSchemaGenerator<'a, Iter<'a, PermissionSet>, Iter<'a, Permission>>
for PermissionFile
{
fn has_default_permission_set(&self) -> bool {
self.default.is_some()
}
fn default_set_description(&self) -> Option<&str> {
self.default.as_ref().and_then(|d| d.description.as_deref())
}
fn default_set_permissions(&self) -> Option<&Vec<String>> {
self.default.as_ref().map(|d| &d.permissions)
}
fn permission_sets(&'a self) -> Iter<'a, PermissionSet> {
self.set.iter()
}
fn permissions(&'a self) -> Iter<'a, Permission> {
self.permission.iter()
}
}
/// Collect and include all possible identifiers in `Identifier` definition in the schema
fn extend_identifier_schema(schema: &mut RootSchema, acl: &BTreeMap<String, Manifest>) {
if let Some(Schema::Object(identifier_schema)) = schema.definitions.get_mut("Identifier") {
let permission_schemas = acl
.iter()
.flat_map(|(name, manifest)| manifest.gen_possible_permission_schemas(Some(name)))
.collect::<Vec<_>>();
let new_subschemas = Box::new(SubschemaValidation {
one_of: Some(permission_schemas),
..Default::default()
});
identifier_schema.subschemas = Some(new_subschemas);
identifier_schema.object = None;
identifier_schema.instance_type = None;
identifier_schema.metadata().description = Some("Permission identifier".to_string());
}
}
/// Collect permission schemas and its associated scope schema and schema definitions from plugins
/// and replace `PermissionEntry` extend object syntax with a new schema that does conditional
/// checks to serve the relevant scope schema for the right permissions schema, in a nutshell, it
/// will look something like this:
/// ```text
/// PermissionEntry {
/// anyOf {
/// String, // default string syntax
/// Object { // extended object syntax
/// allOf { // JSON allOf is used but actually means anyOf
/// {
/// "if": "identifier" property anyOf "fs" plugin permission,
/// "then": add "allow" and "deny" properties that match "fs" plugin scope schema
/// },
/// {
/// "if": "identifier" property anyOf "http" plugin permission,
/// "then": add "allow" and "deny" properties that match "http" plugin scope schema
/// },
/// ...etc,
/// {
/// No "if" or "then", just "allow" and "deny" properties with default "#/definitions/Value"
/// },
/// }
/// }
/// }
/// }
/// ```
fn extend_permission_entry_schema(root_schema: &mut RootSchema, acl: &BTreeMap<String, Manifest>) {
const IDENTIFIER: &str = "identifier";
const ALLOW: &str = "allow";
const DENY: &str = "deny";
let mut collected_defs = vec![];
if let Some(Schema::Object(obj)) = root_schema.definitions.get_mut("PermissionEntry") {
let any_of = obj.subschemas().any_of.as_mut().unwrap();
let Schema::Object(extend_permission_entry) = any_of.last_mut().unwrap() else {
unreachable!("PermissionsEntry should be an object not a boolean");
};
// remove default properties and save it to be added later as a fallback
let obj = extend_permission_entry.object.as_mut().unwrap();
let default_properties = std::mem::take(&mut obj.properties);
let default_identifier = default_properties.get(IDENTIFIER).cloned().unwrap();
let default_identifier = (IDENTIFIER.to_string(), default_identifier);
let mut all_of = vec![];
let schemas = acl.iter().filter_map(|(name, manifest)| {
manifest
.global_scope_schema()
.unwrap_or_else(|e| panic!("invalid JSON schema for plugin {name}: {e}"))
.map(|s| (s, manifest.gen_possible_permission_schemas(Some(name))))
});
for ((scope_schema, defs), acl_perm_schema) in schemas {
let mut perm_schema = SchemaObject::default();
perm_schema.subschemas().any_of = Some(acl_perm_schema);
let mut if_schema = SchemaObject::default();
if_schema.object().properties = [(IDENTIFIER.to_string(), perm_schema.into())].into();
let mut then_schema = SchemaObject::default();
then_schema.object().properties = [
(ALLOW.to_string(), scope_schema.clone()),
(DENY.to_string(), scope_schema.clone()),
]
.into();
let mut obj = SchemaObject::default();
obj.object().properties = [default_identifier.clone()].into();
obj.subschemas().if_schema = Some(Box::new(if_schema.into()));
obj.subschemas().then_schema = Some(Box::new(then_schema.into()));
all_of.push(Schema::Object(obj));
collected_defs.extend(defs);
}
// add back default properties as a fallback
let mut default_obj = SchemaObject::default();
default_obj.object().properties = default_properties;
all_of.push(Schema::Object(default_obj));
// replace extended PermissionEntry with the new schema
extend_permission_entry.subschemas().all_of = Some(all_of);
}
// extend root schema with definitions collected from plugins
root_schema.definitions.extend(collected_defs);
}
/// Generate schema for CapabilityFile with all possible plugins permissions
pub fn generate_capability_schema(
acl: &BTreeMap<String, Manifest>,
target: Target,
) -> crate::Result<()> {
let mut schema = schemars::schema_for!(CapabilityFile);
extend_identifier_schema(&mut schema, acl);
extend_permission_entry_schema(&mut schema, acl);
let schema_str = serde_json::to_string_pretty(&schema).unwrap();
// FIXME: in schemars@v1 this doesn't seem to be necessary anymore. If it is, find a better solution.
let schema_str = schema_str.replace("\\r\\n", "\\n");
let out_dir = PathBuf::from(CAPABILITIES_SCHEMA_FOLDER_PATH);
fs::create_dir_all(&out_dir)?;
let schema_path = out_dir.join(format!("{target}-{CAPABILITIES_SCHEMA_FILE_NAME}"));
if schema_str != fs::read_to_string(&schema_path).unwrap_or_default() {
fs::write(&schema_path, schema_str)?;
fs::copy(
schema_path,
out_dir.join(format!(
"{}-{CAPABILITIES_SCHEMA_FILE_NAME}",
if target.is_desktop() {
"desktop"
} else {
"mobile"
}
)),
)?;
}
Ok(())
}
/// Extend schema with collected permissions from the passed [`PermissionFile`]s.
fn extend_permission_file_schema(schema: &mut RootSchema, permissions: &[PermissionFile]) {
// collect possible permissions
let permission_schemas = permissions
.iter()
.flat_map(|p| p.gen_possible_permission_schemas(None))
.collect();
if let Some(Schema::Object(obj)) = schema.definitions.get_mut("PermissionSet") {
let permissions_obj = obj.object().properties.get_mut("permissions");
if let Some(Schema::Object(permissions_obj)) = permissions_obj {
// replace the permissions property schema object
// from a mere string to a reference to `PermissionKind`
permissions_obj.array().items.replace(
Schema::Object(SchemaObject {
reference: Some("#/definitions/PermissionKind".into()),
..Default::default()
})
.into(),
);
// add the new `PermissionKind` definition in the schema that
// is a list of all possible permissions collected
schema.definitions.insert(
"PermissionKind".into(),
Schema::Object(SchemaObject {
instance_type: Some(InstanceType::String.into()),
subschemas: Some(Box::new(SubschemaValidation {
one_of: Some(permission_schemas),
..Default::default()
})),
..Default::default()
}),
);
}
}
}
/// Generate and write a schema based on the format of a [`PermissionFile`].
pub fn generate_permissions_schema<P: AsRef<Path>>(
permissions: &[PermissionFile],
out_dir: P,
) -> Result<(), Error> {
let mut schema = schemars::schema_for!(PermissionFile);
extend_permission_file_schema(&mut schema, permissions);
let schema_str = serde_json::to_string_pretty(&schema)?;
// FIXME: in schemars@v1 this doesn't seem to be necessary anymore. If it is, find a better solution.
let schema_str = schema_str.replace("\\r\\n", "\\n");
let out_dir = out_dir.as_ref().join(PERMISSION_SCHEMAS_FOLDER_NAME);
fs::create_dir_all(&out_dir).map_err(|e| Error::CreateDir(e, out_dir.clone()))?;
let schema_path = out_dir.join(PERMISSION_SCHEMA_FILE_NAME);
write_if_changed(&schema_path, schema_str).map_err(|e| Error::WriteFile(e, schema_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-utils/src/acl/mod.rs | crates/tauri-utils/src/acl/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Access Control List types.
//!
//! # Stability
//!
//! This is a core functionality that is not considered part of the stable API.
//! If you use it, note that it may include breaking changes in the future.
//!
//! These items are intended to be non-breaking from a de/serialization standpoint only.
//! Using and modifying existing config values will try to avoid breaking changes, but they are
//! free to add fields in the future - causing breaking changes for creating and full destructuring.
//!
//! To avoid this, [ignore unknown fields when destructuring] with the `{my, config, ..}` pattern.
//! If you need to create the Rust config directly without deserializing, then create the struct
//! the [Struct Update Syntax] with `..Default::default()`, which may need a
//! `#[allow(clippy::needless_update)]` attribute if you are declaring all fields.
//!
//! [ignore unknown fields when destructuring]: https://doc.rust-lang.org/book/ch18-03-pattern-syntax.html#ignoring-remaining-parts-of-a-value-with-
//! [Struct Update Syntax]: https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax
use anyhow::Context;
use capability::{Capability, CapabilityFile};
use serde::{Deserialize, Serialize};
use std::{
collections::{BTreeMap, HashSet},
fs,
num::NonZeroU64,
path::PathBuf,
str::FromStr,
sync::Arc,
};
use thiserror::Error;
use url::Url;
use crate::{
config::{CapabilityEntry, Config},
platform::Target,
};
pub use self::{identifier::*, value::*};
/// Known foldername of the permission schema files
pub const PERMISSION_SCHEMAS_FOLDER_NAME: &str = "schemas";
/// Known filename of the permission schema JSON file
pub const PERMISSION_SCHEMA_FILE_NAME: &str = "schema.json";
/// Known ACL key for the app permissions.
pub const APP_ACL_KEY: &str = "__app-acl__";
/// Known acl manifests file
pub const ACL_MANIFESTS_FILE_NAME: &str = "acl-manifests.json";
/// Known capabilities file
pub const CAPABILITIES_FILE_NAME: &str = "capabilities.json";
/// Allowed commands file name
pub const ALLOWED_COMMANDS_FILE_NAME: &str = "allowed-commands.json";
/// Set by the CLI with when `build > removeUnusedCommands` is set for dead code elimination,
/// the value is set to the config's directory
pub const REMOVE_UNUSED_COMMANDS_ENV_VAR: &str = "REMOVE_UNUSED_COMMANDS";
#[cfg(feature = "build")]
pub mod build;
pub mod capability;
pub mod identifier;
pub mod manifest;
pub mod resolved;
#[cfg(feature = "schema")]
pub mod schema;
pub mod value;
/// Possible errors while processing ACL files.
#[derive(Debug, Error)]
pub enum Error {
/// Could not find an environmental variable that is set inside of build scripts.
///
/// Whatever generated this should be called inside of a build script.
#[error("expected build script env var {0}, but it was not found - ensure this is called in a build script")]
BuildVar(&'static str),
/// The links field in the manifest **MUST** be set and match the name of the crate.
#[error("package.links field in the Cargo manifest is not set, it should be set to the same as package.name")]
LinksMissing,
/// The links field in the manifest **MUST** match the name of the crate.
#[error(
"package.links field in the Cargo manifest MUST be set to the same value as package.name"
)]
LinksName,
/// IO error while reading a file
#[error("failed to read file '{}': {}", _1.display(), _0)]
ReadFile(std::io::Error, PathBuf),
/// IO error while writing a file
#[error("failed to write file '{}': {}", _1.display(), _0)]
WriteFile(std::io::Error, PathBuf),
/// IO error while creating a file
#[error("failed to create file '{}': {}", _1.display(), _0)]
CreateFile(std::io::Error, PathBuf),
/// IO error while creating a dir
#[error("failed to create dir '{}': {}", _1.display(), _0)]
CreateDir(std::io::Error, PathBuf),
/// [`cargo_metadata`] was not able to complete successfully
#[cfg(feature = "build")]
#[error("failed to execute: {0}")]
Metadata(#[from] ::cargo_metadata::Error),
/// Invalid glob
#[error("failed to run glob: {0}")]
Glob(#[from] glob::PatternError),
/// Invalid TOML encountered
#[error("failed to parse TOML: {0}")]
Toml(#[from] toml::de::Error),
/// Invalid JSON encountered
#[error("failed to parse JSON: {0}")]
Json(#[from] serde_json::Error),
/// Invalid JSON5 encountered
#[cfg(feature = "config-json5")]
#[error("failed to parse JSON5: {0}")]
Json5(#[from] json5::Error),
/// Invalid permissions file format
#[error("unknown permission format {0}")]
UnknownPermissionFormat(String),
/// Invalid capabilities file format
#[error("unknown capability format {0}")]
UnknownCapabilityFormat(String),
/// Permission referenced in set not found.
#[error("permission {permission} not found from set {set}")]
SetPermissionNotFound {
/// Permission identifier.
permission: String,
/// Set identifier.
set: String,
},
/// Unknown ACL manifest.
#[error("unknown ACL for {key}, expected one of {available}")]
UnknownManifest {
/// Manifest key.
key: String,
/// Available manifest keys.
available: String,
},
/// Unknown permission.
#[error("unknown permission {permission} for {key}")]
UnknownPermission {
/// Manifest key.
key: String,
/// Permission identifier.
permission: String,
},
/// Capability with the given identifier already exists.
#[error("capability with identifier `{identifier}` already exists")]
CapabilityAlreadyExists {
/// Capability identifier.
identifier: String,
},
}
/// Allowed and denied commands inside a permission.
///
/// If two commands clash inside of `allow` and `deny`, it should be denied by default.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct Commands {
/// Allowed command.
#[serde(default)]
pub allow: Vec<String>,
/// Denied command, which takes priority.
#[serde(default)]
pub deny: Vec<String>,
}
/// An argument for fine grained behavior control of Tauri commands.
///
/// It can be of any serde serializable type and is used to allow or prevent certain actions inside a Tauri command.
/// The configured scope is passed to the command and will be enforced by the command implementation.
///
/// ## Example
///
/// ```json
/// {
/// "allow": [{ "path": "$HOME/**" }],
/// "deny": [{ "path": "$HOME/secret.txt" }]
/// }
/// ```
#[derive(Debug, Default, PartialEq, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct Scopes {
/// Data that defines what is allowed by the scope.
#[serde(skip_serializing_if = "Option::is_none")]
pub allow: Option<Vec<Value>>,
/// Data that defines what is denied by the scope. This should be prioritized by validation logic.
#[serde(skip_serializing_if = "Option::is_none")]
pub deny: Option<Vec<Value>>,
}
impl Scopes {
fn is_empty(&self) -> bool {
self.allow.is_none() && self.deny.is_none()
}
}
/// Descriptions of explicit privileges of commands.
///
/// It can enable commands to be accessible in the frontend of the application.
///
/// If the scope is defined it can be used to fine grain control the access of individual or multiple commands.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct Permission {
/// The version of the permission.
#[serde(skip_serializing_if = "Option::is_none")]
pub version: Option<NonZeroU64>,
/// A unique identifier for the permission.
pub identifier: String,
/// Human-readable description of what the permission does.
/// Tauri internal convention is to use `<h4>` headings in markdown content
/// for Tauri documentation generation purposes.
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// Allowed or denied commands when using this permission.
#[serde(default)]
pub commands: Commands,
/// Allowed or denied scoped when using this permission.
#[serde(default, skip_serializing_if = "Scopes::is_empty")]
pub scope: Scopes,
/// Target platforms this permission applies. By default all platforms are affected by this permission.
#[serde(skip_serializing_if = "Option::is_none")]
pub platforms: Option<Vec<Target>>,
}
impl Permission {
/// Whether this permission should be active based on the platform target or not.
pub fn is_active(&self, target: &Target) -> bool {
self
.platforms
.as_ref()
.map(|platforms| platforms.contains(target))
.unwrap_or(true)
}
}
/// A set of direct permissions grouped together under a new name.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct PermissionSet {
/// A unique identifier for the permission.
pub identifier: String,
/// Human-readable description of what the permission does.
pub description: String,
/// All permissions this set contains.
pub permissions: Vec<String>,
}
/// UrlPattern for [`ExecutionContext::Remote`].
#[derive(Debug, Clone)]
pub struct RemoteUrlPattern(Arc<urlpattern::UrlPattern>, String);
impl FromStr for RemoteUrlPattern {
type Err = urlpattern::quirks::Error;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
let mut init = urlpattern::UrlPatternInit::parse_constructor_string::<regex::Regex>(s, None)?;
if init.search.as_ref().map(|p| p.is_empty()).unwrap_or(true) {
init.search.replace("*".to_string());
}
if init.hash.as_ref().map(|p| p.is_empty()).unwrap_or(true) {
init.hash.replace("*".to_string());
}
if init
.pathname
.as_ref()
.map(|p| p.is_empty() || p == "/")
.unwrap_or(true)
{
init.pathname.replace("*".to_string());
}
let pattern = urlpattern::UrlPattern::parse(init, Default::default())?;
Ok(Self(Arc::new(pattern), s.to_string()))
}
}
impl RemoteUrlPattern {
#[doc(hidden)]
pub fn as_str(&self) -> &str {
&self.1
}
/// Test if a given URL matches the pattern.
pub fn test(&self, url: &Url) -> bool {
self
.0
.test(urlpattern::UrlPatternMatchInput::Url(url.clone()))
.unwrap_or_default()
}
}
impl PartialEq for RemoteUrlPattern {
fn eq(&self, other: &Self) -> bool {
self.0.protocol() == other.0.protocol()
&& self.0.username() == other.0.username()
&& self.0.password() == other.0.password()
&& self.0.hostname() == other.0.hostname()
&& self.0.port() == other.0.port()
&& self.0.pathname() == other.0.pathname()
&& self.0.search() == other.0.search()
&& self.0.hash() == other.0.hash()
}
}
impl Eq for RemoteUrlPattern {}
/// Execution context of an IPC call.
#[derive(Debug, Default, Clone, Eq, PartialEq)]
pub enum ExecutionContext {
/// A local URL is used (the Tauri app URL).
#[default]
Local,
/// Remote URL is trying to use the IPC.
Remote {
/// The URL trying to access the IPC (URL pattern).
url: RemoteUrlPattern,
},
}
/// Test if the app has an application manifest from the ACL
pub fn has_app_manifest(acl: &BTreeMap<String, crate::acl::manifest::Manifest>) -> bool {
acl.contains_key(APP_ACL_KEY)
}
/// Get the capabilities from the config file
pub fn get_capabilities(
config: &Config,
mut capabilities_from_files: BTreeMap<String, Capability>,
additional_capability_files: Option<&[PathBuf]>,
) -> anyhow::Result<BTreeMap<String, Capability>> {
let mut capabilities = if config.app.security.capabilities.is_empty() {
capabilities_from_files
} else {
let mut capabilities = BTreeMap::new();
for capability_entry in &config.app.security.capabilities {
match capability_entry {
CapabilityEntry::Inlined(capability) => {
capabilities.insert(capability.identifier.clone(), capability.clone());
}
CapabilityEntry::Reference(id) => {
let capability = capabilities_from_files
.remove(id)
.with_context(|| format!("capability with identifier {id} not found"))?;
capabilities.insert(id.clone(), capability);
}
}
}
capabilities
};
if let Some(paths) = additional_capability_files {
for path in paths {
let capability = CapabilityFile::load(path)
.with_context(|| format!("failed to read capability {}", path.display()))?;
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)),
);
}
}
}
}
Ok(capabilities)
}
/// Allowed commands used to communicate between `generate_handle` and `generate_allowed_commands` through json files
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct AllowedCommands {
/// The commands allowed
pub commands: HashSet<String>,
/// Has application ACL or not
pub has_app_acl: bool,
}
/// Try to reads allowed commands from the out dir made by our build script
pub fn read_allowed_commands() -> Option<AllowedCommands> {
let out_file = std::env::var("OUT_DIR")
.map(PathBuf::from)
.ok()?
.join(ALLOWED_COMMANDS_FILE_NAME);
let file = fs::read_to_string(&out_file).ok()?;
let json = serde_json::from_str(&file).ok()?;
Some(json)
}
#[cfg(test)]
mod tests {
use crate::acl::RemoteUrlPattern;
#[test]
fn url_pattern_domain_wildcard() {
let pattern: RemoteUrlPattern = "http://*".parse().unwrap();
assert!(pattern.test(&"http://tauri.app/path".parse().unwrap()));
assert!(pattern.test(&"http://tauri.app/path?q=1".parse().unwrap()));
assert!(pattern.test(&"http://localhost/path".parse().unwrap()));
assert!(pattern.test(&"http://localhost/path?q=1".parse().unwrap()));
let pattern: RemoteUrlPattern = "http://*.tauri.app".parse().unwrap();
assert!(!pattern.test(&"http://tauri.app/path".parse().unwrap()));
assert!(!pattern.test(&"http://tauri.app/path?q=1".parse().unwrap()));
assert!(pattern.test(&"http://api.tauri.app/path".parse().unwrap()));
assert!(pattern.test(&"http://api.tauri.app/path?q=1".parse().unwrap()));
assert!(!pattern.test(&"http://localhost/path".parse().unwrap()));
assert!(!pattern.test(&"http://localhost/path?q=1".parse().unwrap()));
}
#[test]
fn url_pattern_path_wildcard() {
let pattern: RemoteUrlPattern = "http://localhost/*".parse().unwrap();
assert!(pattern.test(&"http://localhost/path".parse().unwrap()));
assert!(pattern.test(&"http://localhost/path?q=1".parse().unwrap()));
}
#[test]
fn url_pattern_scheme_wildcard() {
let pattern: RemoteUrlPattern = "*://localhost".parse().unwrap();
assert!(pattern.test(&"http://localhost/path".parse().unwrap()));
assert!(pattern.test(&"https://localhost/path?q=1".parse().unwrap()));
assert!(pattern.test(&"custom://localhost/path".parse().unwrap()));
}
}
#[cfg(feature = "build")]
mod build_ {
use std::convert::identity;
use crate::{literal_struct, tokens::*};
use super::*;
use proc_macro2::TokenStream;
use quote::{quote, ToTokens, TokenStreamExt};
impl ToTokens for ExecutionContext {
fn to_tokens(&self, tokens: &mut TokenStream) {
let prefix = quote! { ::tauri::utils::acl::ExecutionContext };
tokens.append_all(match self {
Self::Local => {
quote! { #prefix::Local }
}
Self::Remote { url } => {
let url = url.as_str();
quote! { #prefix::Remote { url: #url.parse().unwrap() } }
}
});
}
}
impl ToTokens for Commands {
fn to_tokens(&self, tokens: &mut TokenStream) {
let allow = vec_lit(&self.allow, str_lit);
let deny = vec_lit(&self.deny, str_lit);
literal_struct!(tokens, ::tauri::utils::acl::Commands, allow, deny)
}
}
impl ToTokens for Scopes {
fn to_tokens(&self, tokens: &mut TokenStream) {
let allow = opt_vec_lit(self.allow.as_ref(), identity);
let deny = opt_vec_lit(self.deny.as_ref(), identity);
literal_struct!(tokens, ::tauri::utils::acl::Scopes, allow, deny)
}
}
impl ToTokens for Permission {
fn to_tokens(&self, tokens: &mut TokenStream) {
let version = opt_lit_owned(self.version.as_ref().map(|v| {
let v = v.get();
quote!(::core::num::NonZeroU64::new(#v).unwrap())
}));
let identifier = str_lit(&self.identifier);
// Only used in build script and macros, so don't include them in runtime
let description = quote! { ::core::option::Option::None };
let commands = &self.commands;
let scope = &self.scope;
let platforms = opt_vec_lit(self.platforms.as_ref(), identity);
literal_struct!(
tokens,
::tauri::utils::acl::Permission,
version,
identifier,
description,
commands,
scope,
platforms
)
}
}
impl ToTokens for PermissionSet {
fn to_tokens(&self, tokens: &mut TokenStream) {
let identifier = str_lit(&self.identifier);
// Only used in build script and macros, so don't include them in runtime
let description = quote! { "".to_string() };
let permissions = vec_lit(&self.permissions, str_lit);
literal_struct!(
tokens,
::tauri::utils::acl::PermissionSet,
identifier,
description,
permissions
)
}
}
}
| 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/acl/capability.rs | crates/tauri-utils/src/acl/capability.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! End-user abstraction for selecting permissions a window has access to.
use std::{path::Path, str::FromStr};
use crate::{acl::Identifier, platform::Target};
use serde::{
de::{Error, IntoDeserializer},
Deserialize, Deserializer, Serialize,
};
use serde_untagged::UntaggedEnumVisitor;
use super::Scopes;
/// An entry for a permission value in a [`Capability`] can be either a raw permission [`Identifier`]
/// or an object that references a permission and extends its scope.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(untagged)]
pub enum PermissionEntry {
/// Reference a permission or permission set by identifier.
PermissionRef(Identifier),
/// Reference a permission or permission set by identifier and extends its scope.
ExtendedPermission {
/// Identifier of the permission or permission set.
identifier: Identifier,
/// Scope to append to the existing permission scope.
#[serde(default, flatten)]
scope: Scopes,
},
}
impl PermissionEntry {
/// The identifier of the permission referenced in this entry.
pub fn identifier(&self) -> &Identifier {
match self {
Self::PermissionRef(identifier) => identifier,
Self::ExtendedPermission {
identifier,
scope: _,
} => identifier,
}
}
}
impl<'de> Deserialize<'de> for PermissionEntry {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
struct ExtendedPermissionStruct {
identifier: Identifier,
#[serde(default, flatten)]
scope: Scopes,
}
UntaggedEnumVisitor::new()
.string(|string| {
let de = string.into_deserializer();
Identifier::deserialize(de).map(Self::PermissionRef)
})
.map(|map| {
let ext_perm = map.deserialize::<ExtendedPermissionStruct>()?;
Ok(Self::ExtendedPermission {
identifier: ext_perm.identifier,
scope: ext_perm.scope,
})
})
.deserialize(deserializer)
}
}
/// A grouping and boundary mechanism developers can use to isolate access to the IPC layer.
///
/// It controls application windows' and webviews' fine grained access
/// to the Tauri core, application, or plugin commands.
/// If a webview or its window is not matching any capability then it has no access to the IPC layer at all.
///
/// This can be done to create groups of windows, based on their required system access, which can reduce
/// impact of frontend vulnerabilities in less privileged windows.
/// Windows can be added to a capability by exact name (e.g. `main-window`) or glob patterns like `*` or `admin-*`.
/// A Window can have none, one, or multiple associated capabilities.
///
/// ## Example
///
/// ```json
/// {
/// "identifier": "main-user-files-write",
/// "description": "This capability allows the `main` window on macOS and Windows access to `filesystem` write related commands and `dialog` commands to enable programmatic access to files selected by the user.",
/// "windows": [
/// "main"
/// ],
/// "permissions": [
/// "core:default",
/// "dialog:open",
/// {
/// "identifier": "fs:allow-write-text-file",
/// "allow": [{ "path": "$HOME/test.txt" }]
/// },
/// ],
/// "platforms": ["macOS","windows"]
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct Capability {
/// Identifier of the capability.
///
/// ## Example
///
/// `main-user-files-write`
///
pub identifier: String,
/// Description of what the capability is intended to allow on associated windows.
///
/// It should contain a description of what the grouped permissions should allow.
///
/// ## Example
///
/// This capability allows the `main` window access to `filesystem` write related
/// commands and `dialog` commands to enable programmatic access to files selected by the user.
#[serde(default)]
pub description: String,
/// Configure remote URLs that can use the capability permissions.
///
/// This setting is optional and defaults to not being set, as our
/// default use case is that the content is served from our local application.
///
/// :::caution
/// Make sure you understand the security implications of providing remote
/// sources with local system access.
/// :::
///
/// ## Example
///
/// ```json
/// {
/// "urls": ["https://*.mydomain.dev"]
/// }
/// ```
#[serde(default, skip_serializing_if = "Option::is_none")]
pub remote: Option<CapabilityRemote>,
/// Whether this capability is enabled for local app URLs or not. Defaults to `true`.
#[serde(default = "default_capability_local")]
pub local: bool,
/// List of windows that are affected by this capability. Can be a glob pattern.
///
/// If a window label matches any of the patterns in this list,
/// the capability will be enabled on all the webviews of that window,
/// regardless of the value of [`Self::webviews`].
///
/// On multiwebview windows, prefer specifying [`Self::webviews`] and omitting [`Self::windows`]
/// for a fine grained access control.
///
/// ## Example
///
/// `["main"]`
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub windows: Vec<String>,
/// List of webviews that are affected by this capability. Can be a glob pattern.
///
/// The capability will be enabled on all the webviews
/// whose label matches any of the patterns in this list,
/// regardless of whether the webview's window label matches a pattern in [`Self::windows`].
///
/// ## Example
///
/// `["sub-webview-one", "sub-webview-two"]`
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub webviews: Vec<String>,
/// List of permissions attached to this capability.
///
/// Must include the plugin name as prefix in the form of `${plugin-name}:${permission-name}`.
/// For commands directly implemented in the application itself only `${permission-name}`
/// is required.
///
/// ## Example
///
/// ```json
/// [
/// "core:default",
/// "shell:allow-open",
/// "dialog:open",
/// {
/// "identifier": "fs:allow-write-text-file",
/// "allow": [{ "path": "$HOME/test.txt" }]
/// }
/// ]
/// ```
#[cfg_attr(feature = "schema", schemars(schema_with = "unique_permission"))]
pub permissions: Vec<PermissionEntry>,
/// Limit which target platforms this capability applies to.
///
/// By default all platforms are targeted.
///
/// ## Example
///
/// `["macOS","windows"]`
#[serde(skip_serializing_if = "Option::is_none")]
pub platforms: Option<Vec<Target>>,
}
impl Capability {
/// Whether this capability should be active based on the platform target or not.
pub fn is_active(&self, target: &Target) -> bool {
self
.platforms
.as_ref()
.map(|platforms| platforms.contains(target))
.unwrap_or(true)
}
}
#[cfg(feature = "schema")]
fn unique_permission(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
use schemars::schema;
schema::SchemaObject {
instance_type: Some(schema::InstanceType::Array.into()),
array: Some(Box::new(schema::ArrayValidation {
unique_items: Some(true),
items: Some(gen.subschema_for::<PermissionEntry>().into()),
..Default::default()
})),
..Default::default()
}
.into()
}
fn default_capability_local() -> bool {
true
}
/// Configuration for remote URLs that are associated with the capability.
#[derive(Debug, Default, Clone, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct CapabilityRemote {
/// Remote domains this capability refers to using the [URLPattern standard](https://urlpattern.spec.whatwg.org/).
///
/// ## Examples
///
/// - "https://*.mydomain.dev": allows subdomains of mydomain.dev
/// - "https://mydomain.dev/api/*": allows any subpath of mydomain.dev/api
pub urls: Vec<String>,
}
/// Capability formats accepted in a capability file.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "schema", schemars(untagged))]
#[cfg_attr(test, derive(Debug, PartialEq))]
pub enum CapabilityFile {
/// A single capability.
Capability(Capability),
/// A list of capabilities.
List(Vec<Capability>),
/// A list of capabilities.
NamedList {
/// The list of capabilities.
capabilities: Vec<Capability>,
},
}
impl CapabilityFile {
/// Load the given capability file.
pub fn load<P: AsRef<Path>>(path: P) -> Result<Self, super::Error> {
let path = path.as_ref();
let capability_file =
std::fs::read_to_string(path).map_err(|e| super::Error::ReadFile(e, path.into()))?;
let ext = path.extension().unwrap().to_string_lossy().to_string();
let file: Self = match ext.as_str() {
"toml" => toml::from_str(&capability_file)?,
"json" => serde_json::from_str(&capability_file)?,
#[cfg(feature = "config-json5")]
"json5" => json5::from_str(&capability_file)?,
_ => return Err(super::Error::UnknownCapabilityFormat(ext)),
};
Ok(file)
}
}
impl<'de> Deserialize<'de> for CapabilityFile {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
UntaggedEnumVisitor::new()
.seq(|seq| seq.deserialize::<Vec<Capability>>().map(Self::List))
.map(|map| {
#[derive(Deserialize)]
struct CapabilityNamedList {
capabilities: Vec<Capability>,
}
let value: serde_json::Map<String, serde_json::Value> = map.deserialize()?;
if value.contains_key("capabilities") {
serde_json::from_value::<CapabilityNamedList>(value.into())
.map(|named| Self::NamedList {
capabilities: named.capabilities,
})
.map_err(|e| serde_untagged::de::Error::custom(e.to_string()))
} else {
serde_json::from_value::<Capability>(value.into())
.map(Self::Capability)
.map_err(|e| serde_untagged::de::Error::custom(e.to_string()))
}
})
.deserialize(deserializer)
}
}
impl FromStr for CapabilityFile {
type Err = super::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
serde_json::from_str(s)
.or_else(|_| toml::from_str(s))
.map_err(Into::into)
}
}
#[cfg(feature = "build")]
mod build {
use std::convert::identity;
use proc_macro2::TokenStream;
use quote::{quote, ToTokens, TokenStreamExt};
use super::*;
use crate::{literal_struct, tokens::*};
impl ToTokens for CapabilityRemote {
fn to_tokens(&self, tokens: &mut TokenStream) {
let urls = vec_lit(&self.urls, str_lit);
literal_struct!(
tokens,
::tauri::utils::acl::capability::CapabilityRemote,
urls
);
}
}
impl ToTokens for PermissionEntry {
fn to_tokens(&self, tokens: &mut TokenStream) {
let prefix = quote! { ::tauri::utils::acl::capability::PermissionEntry };
tokens.append_all(match self {
Self::PermissionRef(id) => {
quote! { #prefix::PermissionRef(#id) }
}
Self::ExtendedPermission { identifier, scope } => {
quote! { #prefix::ExtendedPermission {
identifier: #identifier,
scope: #scope
} }
}
});
}
}
impl ToTokens for Capability {
fn to_tokens(&self, tokens: &mut TokenStream) {
let identifier = str_lit(&self.identifier);
let description = str_lit(&self.description);
let remote = opt_lit(self.remote.as_ref());
let local = self.local;
let windows = vec_lit(&self.windows, str_lit);
let webviews = vec_lit(&self.webviews, str_lit);
let permissions = vec_lit(&self.permissions, identity);
let platforms = opt_vec_lit(self.platforms.as_ref(), identity);
literal_struct!(
tokens,
::tauri::utils::acl::capability::Capability,
identifier,
description,
remote,
local,
windows,
webviews,
permissions,
platforms
);
}
}
}
#[cfg(test)]
mod tests {
use crate::acl::{Identifier, Scopes};
use super::{Capability, CapabilityFile, PermissionEntry};
#[test]
fn permission_entry_de() {
let identifier = Identifier::try_from("plugin:perm".to_string()).unwrap();
let identifier_json = serde_json::to_string(&identifier).unwrap();
assert_eq!(
serde_json::from_str::<PermissionEntry>(&identifier_json).unwrap(),
PermissionEntry::PermissionRef(identifier.clone())
);
assert_eq!(
serde_json::from_value::<PermissionEntry>(serde_json::json!({
"identifier": identifier,
"allow": [],
"deny": null
}))
.unwrap(),
PermissionEntry::ExtendedPermission {
identifier,
scope: Scopes {
allow: Some(vec![]),
deny: None
}
}
);
}
#[test]
fn capability_file_de() {
let capability = Capability {
identifier: "test".into(),
description: "".into(),
remote: None,
local: true,
windows: vec![],
webviews: vec![],
permissions: vec![],
platforms: None,
};
let capability_json = serde_json::to_string(&capability).unwrap();
assert_eq!(
serde_json::from_str::<CapabilityFile>(&capability_json).unwrap(),
CapabilityFile::Capability(capability.clone())
);
assert_eq!(
serde_json::from_str::<CapabilityFile>(&format!("[{capability_json}]")).unwrap(),
CapabilityFile::List(vec![capability.clone()])
);
assert_eq!(
serde_json::from_str::<CapabilityFile>(&format!(
"{{ \"capabilities\": [{capability_json}] }}"
))
.unwrap(),
CapabilityFile::NamedList {
capabilities: vec![capability]
}
);
}
}
| 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/acl/resolved.rs | crates/tauri-utils/src/acl/resolved.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Resolved ACL for runtime usage.
use std::{collections::BTreeMap, fmt};
use crate::platform::Target;
use super::{
capability::{Capability, PermissionEntry},
has_app_manifest,
manifest::Manifest,
Commands, Error, ExecutionContext, Identifier, Permission, PermissionSet, Scopes, Value,
APP_ACL_KEY,
};
/// A key for a scope, used to link a [`ResolvedCommand#structfield.scope`] to the store [`Resolved#structfield.scopes`].
pub type ScopeKey = u64;
/// Metadata for what referenced a [`ResolvedCommand`].
#[cfg(debug_assertions)]
#[derive(Default, Clone, PartialEq, Eq)]
pub struct ResolvedCommandReference {
/// Identifier of the capability.
pub capability: String,
/// Identifier of the permission.
pub permission: String,
}
/// A resolved command permission.
#[derive(Default, Clone, PartialEq, Eq)]
pub struct ResolvedCommand {
/// The execution context of this command.
pub context: ExecutionContext,
/// The capability/permission that referenced this command.
#[cfg(debug_assertions)]
pub referenced_by: ResolvedCommandReference,
/// The list of window label patterns that was resolved for this command.
pub windows: Vec<glob::Pattern>,
/// The list of webview label patterns that was resolved for this command.
pub webviews: Vec<glob::Pattern>,
/// The reference of the scope that is associated with this command. See [`Resolved#structfield.command_scopes`].
pub scope_id: Option<ScopeKey>,
}
impl fmt::Debug for ResolvedCommand {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ResolvedCommand")
.field("context", &self.context)
.field("windows", &self.windows)
.field("webviews", &self.webviews)
.field("scope_id", &self.scope_id)
.finish()
}
}
/// A resolved scope. Merges all scopes defined for a single command.
#[derive(Debug, Default, Clone)]
pub struct ResolvedScope {
/// Allows something on the command.
pub allow: Vec<Value>,
/// Denies something on the command.
pub deny: Vec<Value>,
}
/// Resolved access control list.
#[derive(Debug, Default)]
pub struct Resolved {
/// If we should check the ACL for the app commands
pub has_app_acl: bool,
/// The commands that are allowed. Map each command with its context to a [`ResolvedCommand`].
pub allowed_commands: BTreeMap<String, Vec<ResolvedCommand>>,
/// The commands that are denied. Map each command with its context to a [`ResolvedCommand`].
pub denied_commands: BTreeMap<String, Vec<ResolvedCommand>>,
/// The store of scopes referenced by a [`ResolvedCommand`].
pub command_scope: BTreeMap<ScopeKey, ResolvedScope>,
/// The global scope.
pub global_scope: BTreeMap<String, ResolvedScope>,
}
impl Resolved {
/// Resolves the ACL for the given plugin permissions and app capabilities.
pub fn resolve(
acl: &BTreeMap<String, Manifest>,
mut capabilities: BTreeMap<String, Capability>,
target: Target,
) -> Result<Self, Error> {
let mut allowed_commands = BTreeMap::new();
let mut denied_commands = BTreeMap::new();
let mut current_scope_id = 0;
let mut command_scope = BTreeMap::new();
let mut global_scope: BTreeMap<String, Vec<Scopes>> = BTreeMap::new();
// resolve commands
for capability in capabilities.values_mut().filter(|c| c.is_active(&target)) {
with_resolved_permissions(
capability,
acl,
target,
|ResolvedPermission {
key,
commands,
scope,
#[cfg_attr(not(debug_assertions), allow(unused))]
permission_name,
}| {
if commands.allow.is_empty() && commands.deny.is_empty() {
// global scope
global_scope.entry(key.to_string()).or_default().push(scope);
} else {
let scope_id = if scope.allow.is_some() || scope.deny.is_some() {
current_scope_id += 1;
command_scope.insert(
current_scope_id,
ResolvedScope {
allow: scope.allow.unwrap_or_default(),
deny: scope.deny.unwrap_or_default(),
},
);
Some(current_scope_id)
} else {
None
};
for allowed_command in &commands.allow {
resolve_command(
&mut allowed_commands,
if key == APP_ACL_KEY {
allowed_command.to_string()
} else if let Some(core_plugin_name) = key.strip_prefix("core:") {
format!("plugin:{core_plugin_name}|{allowed_command}")
} else {
format!("plugin:{key}|{allowed_command}")
},
capability,
scope_id,
#[cfg(debug_assertions)]
permission_name.to_string(),
)?;
}
for denied_command in &commands.deny {
resolve_command(
&mut denied_commands,
if key == APP_ACL_KEY {
denied_command.to_string()
} else if let Some(core_plugin_name) = key.strip_prefix("core:") {
format!("plugin:{core_plugin_name}|{denied_command}")
} else {
format!("plugin:{key}|{denied_command}")
},
capability,
scope_id,
#[cfg(debug_assertions)]
permission_name.to_string(),
)?;
}
}
Ok(())
},
)?;
}
let global_scope = global_scope
.into_iter()
.map(|(key, scopes)| {
let mut resolved_scope = ResolvedScope {
allow: Vec::new(),
deny: Vec::new(),
};
for scope in scopes {
if let Some(allow) = scope.allow {
resolved_scope.allow.extend(allow);
}
if let Some(deny) = scope.deny {
resolved_scope.deny.extend(deny);
}
}
(key, resolved_scope)
})
.collect();
let resolved = Self {
has_app_acl: has_app_manifest(acl),
allowed_commands,
denied_commands,
command_scope,
global_scope,
};
Ok(resolved)
}
}
fn parse_glob_patterns(mut raw: Vec<String>) -> Result<Vec<glob::Pattern>, Error> {
raw.sort();
let mut patterns = Vec::new();
for pattern in raw {
patterns.push(glob::Pattern::new(&pattern)?);
}
Ok(patterns)
}
fn resolve_command(
commands: &mut BTreeMap<String, Vec<ResolvedCommand>>,
command: String,
capability: &Capability,
scope_id: Option<ScopeKey>,
#[cfg(debug_assertions)] referenced_by_permission_identifier: String,
) -> Result<(), Error> {
let mut contexts = Vec::new();
if capability.local {
contexts.push(ExecutionContext::Local);
}
if let Some(remote) = &capability.remote {
contexts.extend(remote.urls.iter().map(|url| {
ExecutionContext::Remote {
url: url
.parse()
.unwrap_or_else(|e| panic!("invalid URL pattern for remote URL {url}: {e}")),
}
}));
}
for context in contexts {
let resolved_list = commands.entry(command.clone()).or_default();
resolved_list.push(ResolvedCommand {
context,
#[cfg(debug_assertions)]
referenced_by: ResolvedCommandReference {
capability: capability.identifier.clone(),
permission: referenced_by_permission_identifier.clone(),
},
windows: parse_glob_patterns(capability.windows.clone())?,
webviews: parse_glob_patterns(capability.webviews.clone())?,
scope_id,
});
}
Ok(())
}
struct ResolvedPermission<'a> {
key: &'a str,
permission_name: &'a str,
commands: Commands,
scope: Scopes,
}
/// Iterate over permissions in a capability, resolving permission sets if necessary
/// to produce a [`ResolvedPermission`] and calling the provided callback with it.
fn with_resolved_permissions<F: FnMut(ResolvedPermission<'_>) -> Result<(), Error>>(
capability: &Capability,
acl: &BTreeMap<String, Manifest>,
target: Target,
mut f: F,
) -> Result<(), Error> {
for permission_entry in &capability.permissions {
let permission_id = permission_entry.identifier();
let permissions = get_permissions(permission_id, acl)?
.into_iter()
.filter(|p| p.permission.is_active(&target));
for TraversedPermission {
key,
permission_name,
permission,
} in permissions
{
let mut resolved_scope = Scopes::default();
let mut commands = Commands::default();
if let PermissionEntry::ExtendedPermission {
identifier: _,
scope,
} = permission_entry
{
if let Some(allow) = scope.allow.clone() {
resolved_scope
.allow
.get_or_insert_with(Default::default)
.extend(allow);
}
if let Some(deny) = scope.deny.clone() {
resolved_scope
.deny
.get_or_insert_with(Default::default)
.extend(deny);
}
}
if let Some(allow) = permission.scope.allow.clone() {
resolved_scope
.allow
.get_or_insert_with(Default::default)
.extend(allow);
}
if let Some(deny) = permission.scope.deny.clone() {
resolved_scope
.deny
.get_or_insert_with(Default::default)
.extend(deny);
}
commands.allow.extend(permission.commands.allow.clone());
commands.deny.extend(permission.commands.deny.clone());
f(ResolvedPermission {
key: &key,
permission_name: &permission_name,
commands,
scope: resolved_scope,
})?;
}
}
Ok(())
}
/// Traversed permission
#[derive(Debug)]
pub struct TraversedPermission<'a> {
/// Plugin name without the tauri-plugin- prefix
pub key: String,
/// Permission's name
pub permission_name: String,
/// Permission details
pub permission: &'a Permission,
}
/// Expand a permissions id based on the ACL to get the associated permissions (e.g. expand some-plugin:default)
pub fn get_permissions<'a>(
permission_id: &Identifier,
acl: &'a BTreeMap<String, Manifest>,
) -> Result<Vec<TraversedPermission<'a>>, Error> {
let key = permission_id.get_prefix().unwrap_or(APP_ACL_KEY);
let permission_name = permission_id.get_base();
let manifest = acl.get(key).ok_or_else(|| Error::UnknownManifest {
key: display_perm_key(key).to_string(),
available: acl.keys().cloned().collect::<Vec<_>>().join(", "),
})?;
if permission_name == "default" {
manifest
.default_permission
.as_ref()
.map(|default| get_permission_set_permissions(permission_id, acl, manifest, default))
.unwrap_or_else(|| Ok(Default::default()))
} else if let Some(set) = manifest.permission_sets.get(permission_name) {
get_permission_set_permissions(permission_id, acl, manifest, set)
} else if let Some(permission) = manifest.permissions.get(permission_name) {
Ok(vec![TraversedPermission {
key: key.to_string(),
permission_name: permission_name.to_string(),
permission,
}])
} else {
Err(Error::UnknownPermission {
key: display_perm_key(key).to_string(),
permission: permission_name.to_string(),
})
}
}
// get the permissions from a permission set
fn get_permission_set_permissions<'a>(
permission_id: &Identifier,
acl: &'a BTreeMap<String, Manifest>,
manifest: &'a Manifest,
set: &'a PermissionSet,
) -> Result<Vec<TraversedPermission<'a>>, Error> {
let key = permission_id.get_prefix().unwrap_or(APP_ACL_KEY);
let mut permissions = Vec::new();
for perm in &set.permissions {
// a set could include permissions from other plugins
// for example `dialog:default`, could include `fs:default`
// in this case `perm = "fs:default"` which is not a permission
// in the dialog manifest so we check if `perm` still have a prefix (i.e `fs:`)
// and if so, we resolve this prefix from `acl` first before proceeding
let id = Identifier::try_from(perm.clone()).expect("invalid identifier in permission set?");
let (manifest, permission_id, key, permission_name) =
if let Some((new_key, manifest)) = id.get_prefix().and_then(|k| acl.get(k).map(|m| (k, m))) {
(manifest, &id, new_key, id.get_base())
} else {
(manifest, permission_id, key, perm.as_str())
};
if permission_name == "default" {
permissions.extend(
manifest
.default_permission
.as_ref()
.map(|default| get_permission_set_permissions(permission_id, acl, manifest, default))
.transpose()?
.unwrap_or_default(),
);
} else if let Some(permission) = manifest.permissions.get(permission_name) {
permissions.push(TraversedPermission {
key: key.to_string(),
permission_name: permission_name.to_string(),
permission,
});
} else if let Some(permission_set) = manifest.permission_sets.get(permission_name) {
permissions.extend(get_permission_set_permissions(
permission_id,
acl,
manifest,
permission_set,
)?);
} else {
return Err(Error::SetPermissionNotFound {
permission: permission_name.to_string(),
set: set.identifier.clone(),
});
}
}
Ok(permissions)
}
#[inline]
fn display_perm_key(prefix: &str) -> &str {
if prefix == APP_ACL_KEY {
"app manifest"
} else {
prefix
}
}
#[cfg(feature = "build")]
mod build {
use proc_macro2::TokenStream;
use quote::{quote, ToTokens, TokenStreamExt};
use std::convert::identity;
use super::*;
use crate::{literal_struct, tokens::*};
#[cfg(debug_assertions)]
impl ToTokens for ResolvedCommandReference {
fn to_tokens(&self, tokens: &mut TokenStream) {
let capability = str_lit(&self.capability);
let permission = str_lit(&self.permission);
literal_struct!(
tokens,
::tauri::utils::acl::resolved::ResolvedCommandReference,
capability,
permission
)
}
}
impl ToTokens for ResolvedCommand {
fn to_tokens(&self, tokens: &mut TokenStream) {
#[cfg(debug_assertions)]
let referenced_by = &self.referenced_by;
let context = &self.context;
let windows = vec_lit(&self.windows, |window| {
let w = window.as_str();
quote!(#w.parse().unwrap())
});
let webviews = vec_lit(&self.webviews, |window| {
let w = window.as_str();
quote!(#w.parse().unwrap())
});
let scope_id = opt_lit(self.scope_id.as_ref());
#[cfg(debug_assertions)]
{
literal_struct!(
tokens,
::tauri::utils::acl::resolved::ResolvedCommand,
context,
referenced_by,
windows,
webviews,
scope_id
)
}
#[cfg(not(debug_assertions))]
literal_struct!(
tokens,
::tauri::utils::acl::resolved::ResolvedCommand,
context,
windows,
webviews,
scope_id
)
}
}
impl ToTokens for ResolvedScope {
fn to_tokens(&self, tokens: &mut TokenStream) {
let allow = vec_lit(&self.allow, identity);
let deny = vec_lit(&self.deny, identity);
literal_struct!(
tokens,
::tauri::utils::acl::resolved::ResolvedScope,
allow,
deny
)
}
}
impl ToTokens for Resolved {
fn to_tokens(&self, tokens: &mut TokenStream) {
let has_app_acl = self.has_app_acl;
let allowed_commands = map_lit(
quote! { ::std::collections::BTreeMap },
&self.allowed_commands,
str_lit,
|v| vec_lit(v, identity),
);
let denied_commands = map_lit(
quote! { ::std::collections::BTreeMap },
&self.denied_commands,
str_lit,
|v| vec_lit(v, identity),
);
let command_scope = map_lit(
quote! { ::std::collections::BTreeMap },
&self.command_scope,
identity,
identity,
);
let global_scope = map_lit(
quote! { ::std::collections::BTreeMap },
&self.global_scope,
str_lit,
identity,
);
literal_struct!(
tokens,
::tauri::utils::acl::resolved::Resolved,
has_app_acl,
allowed_commands,
denied_commands,
command_scope,
global_scope
)
}
}
}
#[cfg(test)]
mod tests {
use super::{get_permissions, Identifier, Manifest, Permission, PermissionSet};
fn manifest<const P: usize, const S: usize>(
name: &str,
permissions: [&str; P],
default_set: Option<&[&str]>,
sets: [(&str, &[&str]); S],
) -> (String, Manifest) {
(
name.to_string(),
Manifest {
default_permission: default_set.map(|perms| PermissionSet {
identifier: "default".to_string(),
description: "default set".to_string(),
permissions: perms.iter().map(|s| s.to_string()).collect(),
}),
permissions: permissions
.iter()
.map(|p| {
(
p.to_string(),
Permission {
identifier: p.to_string(),
..Default::default()
},
)
})
.collect(),
permission_sets: sets
.iter()
.map(|(s, perms)| {
(
s.to_string(),
PermissionSet {
identifier: s.to_string(),
description: format!("{s} set"),
permissions: perms.iter().map(|s| s.to_string()).collect(),
},
)
})
.collect(),
..Default::default()
},
)
}
fn id(id: &str) -> Identifier {
Identifier::try_from(id.to_string()).unwrap()
}
#[test]
fn resolves_permissions_from_other_plugins() {
let acl = [
manifest(
"fs",
["read", "write", "rm", "exist"],
Some(&["read", "exist"]),
[],
),
manifest(
"http",
["fetch", "fetch-cancel"],
None,
[("fetch-with-cancel", &["fetch", "fetch-cancel"])],
),
manifest(
"dialog",
["open", "save"],
None,
[(
"extra",
&[
"save",
"fs:default",
"fs:write",
"http:default",
"http:fetch-with-cancel",
],
)],
),
]
.into();
let permissions = get_permissions(&id("fs:default"), &acl).unwrap();
assert_eq!(permissions.len(), 2);
assert_eq!(permissions[0].key, "fs");
assert_eq!(permissions[0].permission_name, "read");
assert_eq!(permissions[1].key, "fs");
assert_eq!(permissions[1].permission_name, "exist");
let permissions = get_permissions(&id("fs:rm"), &acl).unwrap();
assert_eq!(permissions.len(), 1);
assert_eq!(permissions[0].key, "fs");
assert_eq!(permissions[0].permission_name, "rm");
let permissions = get_permissions(&id("http:fetch-with-cancel"), &acl).unwrap();
assert_eq!(permissions.len(), 2);
assert_eq!(permissions[0].key, "http");
assert_eq!(permissions[0].permission_name, "fetch");
assert_eq!(permissions[1].key, "http");
assert_eq!(permissions[1].permission_name, "fetch-cancel");
let permissions = get_permissions(&id("dialog:extra"), &acl).unwrap();
assert_eq!(permissions.len(), 6);
assert_eq!(permissions[0].key, "dialog");
assert_eq!(permissions[0].permission_name, "save");
assert_eq!(permissions[1].key, "fs");
assert_eq!(permissions[1].permission_name, "read");
assert_eq!(permissions[2].key, "fs");
assert_eq!(permissions[2].permission_name, "exist");
assert_eq!(permissions[3].key, "fs");
assert_eq!(permissions[3].permission_name, "write");
assert_eq!(permissions[4].key, "http");
assert_eq!(permissions[4].permission_name, "fetch");
assert_eq!(permissions[5].key, "http");
assert_eq!(permissions[5].permission_name, "fetch-cancel");
}
}
| 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.