Skip to main content

tauri_utils/
config.rs

1// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
2// SPDX-License-Identifier: Apache-2.0
3// SPDX-License-Identifier: MIT
4
5//! The Tauri configuration used at runtime.
6//!
7//! It is pulled from a `tauri.conf.json` file and the [`Config`] struct is generated at compile time.
8//!
9//! # Stability
10//!
11//! This is a core functionality that is not considered part of the stable API.
12//! If you use it, note that it may include breaking changes in the future.
13//!
14//! These items are intended to be non-breaking from a de/serialization standpoint only.
15//! Using and modifying existing config values will try to avoid breaking changes, but they are
16//! free to add fields in the future - causing breaking changes for creating and full destructuring.
17//!
18//! To avoid this, [ignore unknown fields when destructuring] with the `{my, config, ..}` pattern.
19//! If you need to create the Rust config directly without deserializing, then create the struct
20//! the [Struct Update Syntax] with `..Default::default()`, which may need a
21//! `#[allow(clippy::needless_update)]` attribute if you are declaring all fields.
22//!
23//! [ignore unknown fields when destructuring]: https://doc.rust-lang.org/book/ch18-03-pattern-syntax.html#ignoring-remaining-parts-of-a-value-with-
24//! [Struct Update Syntax]: https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax
25
26use http::response::Builder;
27#[cfg(feature = "schema")]
28use schemars::JsonSchema;
29#[cfg(feature = "schema")]
30use schemars::schema::Schema;
31use semver::Version;
32use serde::{
33  Deserialize, Serialize, Serializer,
34  de::{Deserializer, Error as DeError, Visitor},
35};
36use serde_json::Value as JsonValue;
37use serde_untagged::UntaggedEnumVisitor;
38use serde_with::skip_serializing_none;
39use url::Url;
40
41use std::{
42  collections::{BTreeMap, HashMap, HashSet},
43  fmt::{self, Display},
44  fs::read_to_string,
45  path::{Component, Path, PathBuf},
46  str::FromStr,
47};
48
49#[cfg(feature = "schema")]
50fn add_description(schema: Schema, description: impl Into<String>) -> Schema {
51  let value = description.into();
52  if value.is_empty() {
53    schema
54  } else {
55    let mut schema_obj = schema.into_object();
56    schema_obj.metadata().description = value.into();
57    Schema::Object(schema_obj)
58  }
59}
60
61/// Items to help with parsing content into a [`Config`].
62pub mod parse;
63
64use crate::{TitleBarStyle, WindowEffect, WindowEffectState, acl::capability::Capability};
65
66pub use self::parse::parse;
67
68fn default_true() -> bool {
69  true
70}
71
72/// An URL to open on a Tauri webview window.
73#[derive(PartialEq, Eq, Debug, Clone, Serialize)]
74#[cfg_attr(feature = "schema", derive(JsonSchema))]
75#[serde(untagged)]
76#[non_exhaustive]
77pub enum WebviewUrl {
78  /// An external URL. Must use either the `http` or `https` schemes.
79  External(Url),
80  /// The path portion of an app URL.
81  /// For instance, to load `tauri://localhost/users/john`,
82  /// you can simply provide `users/john` in this configuration.
83  App(PathBuf),
84  /// A custom protocol url, for example, `doom://index.html`
85  CustomProtocol(Url),
86}
87
88impl<'de> Deserialize<'de> for WebviewUrl {
89  fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
90  where
91    D: Deserializer<'de>,
92  {
93    #[derive(Deserialize)]
94    #[serde(untagged)]
95    enum WebviewUrlDeserializer {
96      Url(Url),
97      Path(PathBuf),
98    }
99
100    match WebviewUrlDeserializer::deserialize(deserializer)? {
101      WebviewUrlDeserializer::Url(u) => {
102        if u.scheme() == "https" || u.scheme() == "http" {
103          Ok(Self::External(u))
104        } else {
105          Ok(Self::CustomProtocol(u))
106        }
107      }
108      WebviewUrlDeserializer::Path(p) => Ok(Self::App(p)),
109    }
110  }
111}
112
113impl fmt::Display for WebviewUrl {
114  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115    match self {
116      Self::External(url) | Self::CustomProtocol(url) => write!(f, "{url}"),
117      Self::App(path) => write!(f, "{}", path.display()),
118    }
119  }
120}
121
122impl Default for WebviewUrl {
123  fn default() -> Self {
124    Self::App("index.html".into())
125  }
126}
127
128/// A bundle referenced by tauri-bundler.
129#[derive(Debug, PartialEq, Eq, Clone)]
130#[cfg_attr(feature = "schema", derive(JsonSchema))]
131#[cfg_attr(feature = "schema", schemars(rename_all = "lowercase"))]
132pub enum BundleType {
133  /// The debian bundle (.deb).
134  Deb,
135  /// The RPM bundle (.rpm).
136  Rpm,
137  /// The AppImage bundle (.appimage).
138  AppImage,
139  /// The Microsoft Installer bundle (.msi).
140  Msi,
141  /// The NSIS bundle (.exe).
142  Nsis,
143  /// The macOS application bundle (.app).
144  App,
145  /// The Apple Disk Image bundle (.dmg).
146  Dmg,
147}
148
149impl BundleType {
150  /// All bundle types.
151  fn all() -> &'static [Self] {
152    &[
153      BundleType::Deb,
154      BundleType::Rpm,
155      BundleType::AppImage,
156      BundleType::Msi,
157      BundleType::Nsis,
158      BundleType::App,
159      BundleType::Dmg,
160    ]
161  }
162}
163
164impl Display for BundleType {
165  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
166    write!(
167      f,
168      "{}",
169      match self {
170        Self::Deb => "deb",
171        Self::Rpm => "rpm",
172        Self::AppImage => "appimage",
173        Self::Msi => "msi",
174        Self::Nsis => "nsis",
175        Self::App => "app",
176        Self::Dmg => "dmg",
177      }
178    )
179  }
180}
181
182impl Serialize for BundleType {
183  fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
184  where
185    S: Serializer,
186  {
187    serializer.serialize_str(self.to_string().as_ref())
188  }
189}
190
191impl<'de> Deserialize<'de> for BundleType {
192  fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
193  where
194    D: Deserializer<'de>,
195  {
196    let s = String::deserialize(deserializer)?;
197    match s.to_lowercase().as_str() {
198      "deb" => Ok(Self::Deb),
199      "rpm" => Ok(Self::Rpm),
200      "appimage" => Ok(Self::AppImage),
201      "msi" => Ok(Self::Msi),
202      "nsis" => Ok(Self::Nsis),
203      "app" => Ok(Self::App),
204      "dmg" => Ok(Self::Dmg),
205      _ => Err(DeError::custom(format!("unknown bundle target '{s}'"))),
206    }
207  }
208}
209
210/// Targets to bundle. Each value is case insensitive.
211#[derive(Debug, PartialEq, Eq, Clone, Default)]
212pub enum BundleTarget {
213  /// Bundle all targets.
214  #[default]
215  All,
216  /// A list of bundle targets.
217  List(Vec<BundleType>),
218  /// A single bundle target.
219  One(BundleType),
220}
221
222#[cfg(feature = "schema")]
223impl schemars::JsonSchema for BundleTarget {
224  fn schema_name() -> std::string::String {
225    "BundleTarget".to_owned()
226  }
227
228  fn json_schema(generator: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema {
229    let any_of = vec![
230      schemars::schema::SchemaObject {
231        const_value: Some("all".into()),
232        metadata: Some(Box::new(schemars::schema::Metadata {
233          description: Some("Bundle all targets.".to_owned()),
234          ..Default::default()
235        })),
236        ..Default::default()
237      }
238      .into(),
239      add_description(
240        generator.subschema_for::<Vec<BundleType>>(),
241        "A list of bundle targets.",
242      ),
243      add_description(
244        generator.subschema_for::<BundleType>(),
245        "A single bundle target.",
246      ),
247    ];
248
249    schemars::schema::SchemaObject {
250      subschemas: Some(Box::new(schemars::schema::SubschemaValidation {
251        any_of: Some(any_of),
252        ..Default::default()
253      })),
254      metadata: Some(Box::new(schemars::schema::Metadata {
255        description: Some("Targets to bundle. Each value is case insensitive.".to_owned()),
256        ..Default::default()
257      })),
258      ..Default::default()
259    }
260    .into()
261  }
262}
263
264impl Serialize for BundleTarget {
265  fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
266  where
267    S: Serializer,
268  {
269    match self {
270      Self::All => serializer.serialize_str("all"),
271      Self::List(l) => l.serialize(serializer),
272      Self::One(t) => serializer.serialize_str(t.to_string().as_ref()),
273    }
274  }
275}
276
277impl<'de> Deserialize<'de> for BundleTarget {
278  fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
279  where
280    D: Deserializer<'de>,
281  {
282    #[derive(Deserialize, Serialize)]
283    #[serde(untagged)]
284    pub enum BundleTargetInner {
285      List(Vec<BundleType>),
286      One(BundleType),
287      All(String),
288    }
289
290    match BundleTargetInner::deserialize(deserializer)? {
291      BundleTargetInner::All(s) if s.to_lowercase() == "all" => Ok(Self::All),
292      BundleTargetInner::All(t) => Err(DeError::custom(format!(
293        "invalid bundle type {t}, expected one of `all`, {}",
294        BundleType::all()
295          .iter()
296          .map(|b| format!("`{b}`"))
297          .collect::<Vec<_>>()
298          .join(", ")
299      ))),
300      BundleTargetInner::List(l) => Ok(Self::List(l)),
301      BundleTargetInner::One(t) => Ok(Self::One(t)),
302    }
303  }
304}
305
306impl BundleTarget {
307  /// Gets the bundle targets as a [`Vec`]. The vector is empty when set to [`BundleTarget::All`].
308  #[allow(dead_code)]
309  pub fn to_vec(&self) -> Vec<BundleType> {
310    match self {
311      Self::All => BundleType::all().to_vec(),
312      Self::List(list) => list.clone(),
313      Self::One(i) => vec![i.clone()],
314    }
315  }
316}
317
318/// Configuration for AppImage bundles.
319///
320/// See more: <https://v2.tauri.app/reference/config/#appimageconfig>
321#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
322#[cfg_attr(feature = "schema", derive(JsonSchema))]
323#[serde(rename_all = "camelCase", deny_unknown_fields)]
324pub struct AppImageConfig {
325  /// Include additional gstreamer dependencies needed for audio and video playback.
326  /// This increases the bundle size by ~15-35MB depending on your build system.
327  #[serde(default, alias = "bundle-media-framework")]
328  pub bundle_media_framework: bool,
329  /// The files to include in the Appimage Binary.
330  #[serde(default)]
331  pub files: HashMap<PathBuf, PathBuf>,
332}
333
334/// Configuration for Debian (.deb) bundles.
335///
336/// See more: <https://v2.tauri.app/reference/config/#debconfig>
337#[skip_serializing_none]
338#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
339#[cfg_attr(feature = "schema", derive(JsonSchema))]
340#[serde(rename_all = "camelCase", deny_unknown_fields)]
341pub struct DebConfig {
342  /// The list of deb dependencies your application relies on.
343  pub depends: Option<Vec<String>>,
344  /// The list of deb dependencies your application recommends.
345  pub recommends: Option<Vec<String>>,
346  /// The list of dependencies the package provides.
347  pub provides: Option<Vec<String>>,
348  /// The list of package conflicts.
349  pub conflicts: Option<Vec<String>>,
350  /// The list of package replaces.
351  pub replaces: Option<Vec<String>>,
352  /// The files to include on the package.
353  #[serde(default)]
354  pub files: HashMap<PathBuf, PathBuf>,
355  /// Define the section in Debian Control file. See : https://www.debian.org/doc/debian-policy/ch-archive.html#s-subsections
356  pub section: Option<String>,
357  /// Change the priority of the Debian Package. By default, it is set to `optional`.
358  /// Recognized Priorities as of now are :  `required`, `important`, `standard`, `optional`, `extra`
359  pub priority: Option<String>,
360  /// Path of the uncompressed Changelog file, to be stored at /usr/share/doc/package-name/changelog.gz. See
361  /// <https://www.debian.org/doc/debian-policy/ch-docs.html#changelog-files-and-release-notes>
362  pub changelog: Option<PathBuf>,
363  /// Path to a custom desktop file Handlebars template.
364  ///
365  /// Available variables: `categories`, `comment` (optional), `exec`, `icon` and `name`.
366  #[serde(alias = "desktop-template")]
367  pub desktop_template: Option<PathBuf>,
368  /// Path to script that will be executed before the package is unpacked. See
369  /// <https://www.debian.org/doc/debian-policy/ch-maintainerscripts.html>
370  #[serde(alias = "pre-install-script")]
371  pub pre_install_script: Option<PathBuf>,
372  /// Path to script that will be executed after the package is unpacked. See
373  /// <https://www.debian.org/doc/debian-policy/ch-maintainerscripts.html>
374  #[serde(alias = "post-install-script")]
375  pub post_install_script: Option<PathBuf>,
376  /// Path to script that will be executed before the package is removed. See
377  /// <https://www.debian.org/doc/debian-policy/ch-maintainerscripts.html>
378  #[serde(alias = "pre-remove-script")]
379  pub pre_remove_script: Option<PathBuf>,
380  /// Path to script that will be executed after the package is removed. See
381  /// <https://www.debian.org/doc/debian-policy/ch-maintainerscripts.html>
382  #[serde(alias = "post-remove-script")]
383  pub post_remove_script: Option<PathBuf>,
384}
385
386/// Configuration for Linux bundles.
387///
388/// See more: <https://v2.tauri.app/reference/config/#linuxconfig>
389#[skip_serializing_none]
390#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
391#[cfg_attr(feature = "schema", derive(JsonSchema))]
392#[serde(rename_all = "camelCase", deny_unknown_fields)]
393pub struct LinuxConfig {
394  /// Configuration for the AppImage bundle.
395  #[serde(default)]
396  pub appimage: AppImageConfig,
397  /// Configuration for the Debian bundle.
398  #[serde(default)]
399  pub deb: DebConfig,
400  /// Configuration for the RPM bundle.
401  #[serde(default)]
402  pub rpm: RpmConfig,
403}
404
405/// Compression algorithms used when bundling RPM packages.
406#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
407#[cfg_attr(feature = "schema", derive(JsonSchema))]
408#[serde(rename_all = "camelCase", deny_unknown_fields, tag = "type")]
409#[non_exhaustive]
410pub enum RpmCompression {
411  /// Gzip compression
412  Gzip {
413    /// Gzip compression level
414    level: u32,
415  },
416  /// Zstd compression
417  Zstd {
418    /// Zstd compression level
419    level: i32,
420  },
421  /// Xz compression
422  Xz {
423    /// Xz compression level
424    level: u32,
425  },
426  /// Bzip2 compression
427  Bzip2 {
428    /// Bzip2 compression level
429    level: u32,
430  },
431  /// Disable compression
432  None,
433}
434
435/// Configuration for RPM bundles.
436#[skip_serializing_none]
437#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
438#[cfg_attr(feature = "schema", derive(JsonSchema))]
439#[serde(rename_all = "camelCase", deny_unknown_fields)]
440pub struct RpmConfig {
441  /// The list of RPM dependencies your application relies on.
442  pub depends: Option<Vec<String>>,
443  /// The list of RPM dependencies your application recommends.
444  pub recommends: Option<Vec<String>>,
445  /// The list of RPM dependencies your application provides.
446  pub provides: Option<Vec<String>>,
447  /// The list of RPM dependencies your application conflicts with. They must not be present
448  /// in order for the package to be installed.
449  pub conflicts: Option<Vec<String>>,
450  /// The list of RPM dependencies your application supersedes - if this package is installed,
451  /// packages listed as "obsoletes" will be automatically removed (if they are present).
452  pub obsoletes: Option<Vec<String>>,
453  /// The RPM release tag.
454  #[serde(default = "default_release")]
455  pub release: String,
456  /// The RPM epoch.
457  #[serde(default)]
458  pub epoch: u32,
459  /// The files to include on the package.
460  #[serde(default)]
461  pub files: HashMap<PathBuf, PathBuf>,
462  /// Path to a custom desktop file Handlebars template.
463  ///
464  /// Available variables: `categories`, `comment` (optional), `exec`, `icon` and `name`.
465  #[serde(alias = "desktop-template")]
466  pub desktop_template: Option<PathBuf>,
467  /// Path to script that will be executed before the package is unpacked. See
468  /// <http://ftp.rpm.org/max-rpm/s1-rpm-inside-scripts.html>
469  #[serde(alias = "pre-install-script")]
470  pub pre_install_script: Option<PathBuf>,
471  /// Path to script that will be executed after the package is unpacked. See
472  /// <http://ftp.rpm.org/max-rpm/s1-rpm-inside-scripts.html>
473  #[serde(alias = "post-install-script")]
474  pub post_install_script: Option<PathBuf>,
475  /// Path to script that will be executed before the package is removed. See
476  /// <http://ftp.rpm.org/max-rpm/s1-rpm-inside-scripts.html>
477  #[serde(alias = "pre-remove-script")]
478  pub pre_remove_script: Option<PathBuf>,
479  /// Path to script that will be executed after the package is removed. See
480  /// <http://ftp.rpm.org/max-rpm/s1-rpm-inside-scripts.html>
481  #[serde(alias = "post-remove-script")]
482  pub post_remove_script: Option<PathBuf>,
483  /// Compression algorithm and level. Defaults to `Gzip` with level 6.
484  pub compression: Option<RpmCompression>,
485}
486
487impl Default for RpmConfig {
488  fn default() -> Self {
489    Self {
490      depends: None,
491      recommends: None,
492      provides: None,
493      conflicts: None,
494      obsoletes: None,
495      release: default_release(),
496      epoch: 0,
497      files: Default::default(),
498      desktop_template: None,
499      pre_install_script: None,
500      post_install_script: None,
501      pre_remove_script: None,
502      post_remove_script: None,
503      compression: None,
504    }
505  }
506}
507
508fn default_release() -> String {
509  "1".into()
510}
511
512/// Position coordinates struct.
513#[derive(Default, Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
514#[cfg_attr(feature = "schema", derive(JsonSchema))]
515#[serde(rename_all = "camelCase", deny_unknown_fields)]
516pub struct Position {
517  /// X coordinate.
518  pub x: u32,
519  /// Y coordinate.
520  pub y: u32,
521}
522
523/// Position coordinates struct.
524#[derive(Default, Debug, PartialEq, Clone, Deserialize, Serialize)]
525#[cfg_attr(feature = "schema", derive(JsonSchema))]
526#[serde(rename_all = "camelCase", deny_unknown_fields)]
527pub struct LogicalPosition {
528  /// X coordinate.
529  pub x: f64,
530  /// Y coordinate.
531  pub y: f64,
532}
533
534/// Size of the window.
535#[derive(Default, Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
536#[cfg_attr(feature = "schema", derive(JsonSchema))]
537#[serde(rename_all = "camelCase", deny_unknown_fields)]
538pub struct Size {
539  /// Width of the window.
540  pub width: u32,
541  /// Height of the window.
542  pub height: u32,
543}
544
545/// Configuration for Apple Disk Image (.dmg) bundles.
546///
547/// See more: <https://v2.tauri.app/reference/config/#dmgconfig>
548#[skip_serializing_none]
549#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
550#[cfg_attr(feature = "schema", derive(JsonSchema))]
551#[serde(rename_all = "camelCase", deny_unknown_fields)]
552pub struct DmgConfig {
553  /// Image to use as the background in dmg file. Accepted formats: `png`/`jpg`/`gif`.
554  pub background: Option<PathBuf>,
555  /// Position of volume window on screen.
556  pub window_position: Option<Position>,
557  /// Size of volume window.
558  #[serde(default = "dmg_window_size", alias = "window-size")]
559  pub window_size: Size,
560  /// Position of app file on window.
561  #[serde(default = "dmg_app_position", alias = "app-position")]
562  pub app_position: Position,
563  /// Position of application folder on window.
564  #[serde(
565    default = "dmg_application_folder_position",
566    alias = "application-folder-position"
567  )]
568  pub application_folder_position: Position,
569}
570
571impl Default for DmgConfig {
572  fn default() -> Self {
573    Self {
574      background: None,
575      window_position: None,
576      window_size: dmg_window_size(),
577      app_position: dmg_app_position(),
578      application_folder_position: dmg_application_folder_position(),
579    }
580  }
581}
582
583fn dmg_window_size() -> Size {
584  Size {
585    width: 660,
586    height: 400,
587  }
588}
589
590fn dmg_app_position() -> Position {
591  Position { x: 180, y: 170 }
592}
593
594fn dmg_application_folder_position() -> Position {
595  Position { x: 480, y: 170 }
596}
597
598fn de_macos_minimum_system_version<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
599where
600  D: Deserializer<'de>,
601{
602  let version = Option::<String>::deserialize(deserializer)?;
603  match version {
604    Some(v) if v.is_empty() => Ok(macos_minimum_system_version()),
605    e => Ok(e),
606  }
607}
608
609/// Configuration for the macOS bundles.
610///
611/// See more: <https://v2.tauri.app/reference/config/#macconfig>
612#[skip_serializing_none]
613#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
614#[cfg_attr(feature = "schema", derive(JsonSchema))]
615#[serde(rename_all = "camelCase", deny_unknown_fields)]
616pub struct MacConfig {
617  /// A list of strings indicating any macOS X frameworks that need to be bundled with the application.
618  ///
619  /// 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.
620  pub frameworks: Option<Vec<String>>,
621  /// The files to include in the application relative to the Contents directory.
622  #[serde(default)]
623  pub files: HashMap<PathBuf, PathBuf>,
624  /// The version of the build that identifies an iteration of the bundle.
625  ///
626  /// Translates to the bundle's CFBundleVersion property.
627  #[serde(alias = "bundle-version")]
628  pub bundle_version: Option<String>,
629  /// The name of the builder that built the bundle.
630  ///
631  /// Translates to the bundle's CFBundleName property.
632  ///
633  /// If not set, defaults to the package's product name.
634  #[serde(alias = "bundle-name")]
635  pub bundle_name: Option<String>,
636  /// A version string indicating the minimum macOS X version that the bundled application supports. Defaults to `10.13`.
637  ///
638  /// Setting it to `null` completely removes the `LSMinimumSystemVersion` field on the bundle's `Info.plist`
639  /// and the `MACOSX_DEPLOYMENT_TARGET` environment variable.
640  ///
641  /// Ignored in `tauri dev`.
642  ///
643  /// An empty string is considered an invalid value so the default value is used.
644  #[serde(
645    deserialize_with = "de_macos_minimum_system_version",
646    default = "macos_minimum_system_version",
647    alias = "minimum-system-version"
648  )]
649  pub minimum_system_version: Option<String>,
650  /// Allows your application to communicate with the outside world.
651  /// It should be a lowercase, without port and protocol domain name.
652  #[serde(alias = "exception-domain")]
653  pub exception_domain: Option<String>,
654  /// Identity to use for code signing.
655  #[serde(alias = "signing-identity")]
656  pub signing_identity: Option<String>,
657  /// Whether the codesign should enable [hardened runtime](https://developer.apple.com/documentation/security/hardened_runtime) (for executables) or not.
658  #[serde(alias = "hardened-runtime", default = "default_true")]
659  pub hardened_runtime: bool,
660  /// Provider short name for notarization.
661  #[serde(alias = "provider-short-name")]
662  pub provider_short_name: Option<String>,
663  /// Path to the entitlements file.
664  pub entitlements: Option<String>,
665  /// Path to a Info.plist file to merge with the default Info.plist.
666  ///
667  /// Note that Tauri also looks for a `Info.plist` file in the same directory as the Tauri configuration file.
668  #[serde(alias = "info-plist")]
669  pub info_plist: Option<PathBuf>,
670  /// DMG-specific settings.
671  #[serde(default)]
672  pub dmg: DmgConfig,
673}
674
675impl Default for MacConfig {
676  fn default() -> Self {
677    Self {
678      frameworks: None,
679      files: HashMap::new(),
680      bundle_version: None,
681      bundle_name: None,
682      minimum_system_version: macos_minimum_system_version(),
683      exception_domain: None,
684      signing_identity: None,
685      hardened_runtime: true,
686      provider_short_name: None,
687      entitlements: None,
688      info_plist: None,
689      dmg: Default::default(),
690    }
691  }
692}
693
694fn macos_minimum_system_version() -> Option<String> {
695  Some("10.13".into())
696}
697
698fn ios_minimum_system_version() -> String {
699  "15.0".into()
700}
701
702/// Configuration for a target language for the WiX build.
703///
704/// See more: <https://v2.tauri.app/reference/config/#wixlanguageconfig>
705#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
706#[cfg_attr(feature = "schema", derive(JsonSchema))]
707#[serde(rename_all = "camelCase", deny_unknown_fields)]
708pub struct WixLanguageConfig {
709  /// The path to a locale (`.wxl`) file. See <https://wixtoolset.org/documentation/manual/v3/howtos/ui_and_localization/build_a_localized_version.html>.
710  #[serde(alias = "locale-path")]
711  pub locale_path: Option<String>,
712}
713
714/// The languages to build using WiX.
715#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
716#[cfg_attr(feature = "schema", derive(JsonSchema))]
717#[serde(untagged)]
718pub enum WixLanguage {
719  /// A single language to build, without configuration.
720  One(String),
721  /// A list of languages to build, without configuration.
722  List(Vec<String>),
723  /// A map of languages and its configuration.
724  Localized(HashMap<String, WixLanguageConfig>),
725}
726
727impl Default for WixLanguage {
728  fn default() -> Self {
729    Self::One("en-US".into())
730  }
731}
732
733/// Configuration for the MSI bundle using WiX.
734///
735/// See more: <https://v2.tauri.app/reference/config/#wixconfig>
736#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
737#[cfg_attr(feature = "schema", derive(JsonSchema))]
738#[serde(rename_all = "camelCase", deny_unknown_fields)]
739pub struct WixConfig {
740  /// MSI installer version in the format `major.minor.patch.build` (build is optional).
741  ///
742  /// Because a valid version is required for MSI installer, it will be derived from [`Config::version`] if this field is not set.
743  ///
744  /// 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.
745  /// The third and fourth fields have a maximum value of 65,535.
746  ///
747  /// See <https://learn.microsoft.com/en-us/windows/win32/msi/productversion> for more info.
748  pub version: Option<String>,
749  /// A GUID upgrade code for MSI installer. This code **_must stay the same across all of your updates_**,
750  /// otherwise, Windows will treat your update as a different app and your users will have duplicate versions of your app.
751  ///
752  /// By default, tauri generates this code by generating a Uuid v5 using the string `<productName>.exe.app.x64` in the DNS namespace.
753  /// You can use Tauri's CLI to generate and print this code for you, run `tauri inspect wix-upgrade-code`.
754  ///
755  /// It is recommended that you set this value in your tauri config file to avoid accidental changes in your upgrade code
756  /// whenever you want to change your product name.
757  #[serde(alias = "upgrade-code")]
758  pub upgrade_code: Option<uuid::Uuid>,
759  /// The installer languages to build. See <https://docs.microsoft.com/en-us/windows/win32/msi/localizing-the-error-and-actiontext-tables>.
760  #[serde(default)]
761  pub language: WixLanguage,
762  /// A custom .wxs template to use.
763  pub template: Option<PathBuf>,
764  /// A list of paths to .wxs files with WiX fragments to use.
765  #[serde(default, alias = "fragment-paths")]
766  pub fragment_paths: Vec<PathBuf>,
767  /// The ComponentGroup element ids you want to reference from the fragments.
768  #[serde(default, alias = "component-group-refs")]
769  pub component_group_refs: Vec<String>,
770  /// The Component element ids you want to reference from the fragments.
771  #[serde(default, alias = "component-refs")]
772  pub component_refs: Vec<String>,
773  /// The FeatureGroup element ids you want to reference from the fragments.
774  #[serde(default, alias = "feature-group-refs")]
775  pub feature_group_refs: Vec<String>,
776  /// The Feature element ids you want to reference from the fragments.
777  #[serde(default, alias = "feature-refs")]
778  pub feature_refs: Vec<String>,
779  /// The Merge element ids you want to reference from the fragments.
780  #[serde(default, alias = "merge-refs")]
781  pub merge_refs: Vec<String>,
782  /// Create an elevated update task within Windows Task Scheduler.
783  #[serde(default, alias = "enable-elevated-update-task")]
784  pub enable_elevated_update_task: bool,
785  /// Path to a bitmap file to use as the installation user interface banner.
786  /// This bitmap will appear at the top of all but the first page of the installer.
787  ///
788  /// The required dimensions are 493px × 58px.
789  #[serde(alias = "banner-path")]
790  pub banner_path: Option<PathBuf>,
791  /// Path to a bitmap file to use on the installation user interface dialogs.
792  /// It is used on the welcome and completion dialogs.
793  ///
794  /// The required dimensions are 493px × 312px.
795  #[serde(alias = "dialog-image-path")]
796  pub dialog_image_path: Option<PathBuf>,
797  /// Enables FIPS compliant algorithms.
798  /// Can also be enabled via the `TAURI_BUNDLER_WIX_FIPS_COMPLIANT` env var.
799  #[serde(default, alias = "fips-compliant")]
800  pub fips_compliant: bool,
801}
802
803/// Compression algorithms used in the NSIS installer.
804///
805/// See <https://nsis.sourceforge.io/Reference/SetCompressor>
806#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize, Default)]
807#[cfg_attr(feature = "schema", derive(JsonSchema))]
808#[serde(rename_all = "camelCase", deny_unknown_fields)]
809pub enum NsisCompression {
810  /// ZLIB uses the deflate algorithm, it is a quick and simple method. With the default compression level it uses about 300 KB of memory.
811  Zlib,
812  /// 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.
813  Bzip2,
814  /// 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.
815  #[default]
816  Lzma,
817  /// Disable compression
818  None,
819}
820
821/// Install Modes for the NSIS installer.
822#[derive(Default, Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
823#[serde(rename_all = "camelCase", deny_unknown_fields)]
824#[cfg_attr(feature = "schema", derive(JsonSchema))]
825pub enum NSISInstallerMode {
826  /// Default mode for the installer.
827  ///
828  /// Install the app by default in a directory that doesn't require Administrator access.
829  ///
830  /// Installer metadata will be saved under the `HKCU` registry path.
831  #[default]
832  CurrentUser,
833  /// Install the app by default in the `Program Files` folder directory requires Administrator
834  /// access for the installation.
835  ///
836  /// Installer metadata will be saved under the `HKLM` registry path.
837  PerMachine,
838  /// Combines both modes and allows the user to choose at install time
839  /// whether to install for the current user or per machine. Note that this mode
840  /// will require Administrator access even if the user wants to install it for the current user only.
841  ///
842  /// Installer metadata will be saved under the `HKLM` or `HKCU` registry path based on the user's choice.
843  Both,
844}
845
846/// Configuration for the Installer bundle using NSIS.
847#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
848#[cfg_attr(feature = "schema", derive(JsonSchema))]
849#[serde(rename_all = "camelCase", deny_unknown_fields)]
850pub struct NsisConfig {
851  /// A custom .nsi template to use.
852  pub template: Option<PathBuf>,
853  /// The path to a bitmap file to display on the header of installers pages.
854  ///
855  /// The recommended dimensions are 150px x 57px.
856  #[serde(alias = "header-image")]
857  pub header_image: Option<PathBuf>,
858  /// The path to a bitmap file for the Welcome page and the Finish page.
859  ///
860  /// The recommended dimensions are 164px x 314px.
861  #[serde(alias = "sidebar-image")]
862  pub sidebar_image: Option<PathBuf>,
863  // TODO: Change the alias to installer-icon in v3
864  /// The path to an icon file used as the installer icon.
865  #[serde(alias = "install-icon")]
866  pub installer_icon: Option<PathBuf>,
867  /// The path to an icon file used as the uninstaller icon.
868  #[serde(alias = "uninstaller-icon")]
869  pub uninstaller_icon: Option<PathBuf>,
870  /// The path to a bitmap file to display on the header of uninstallers pages.
871  /// Defaults to [`Self::header_image`]. If this is set but [`Self::header_image`] is not, a default image from NSIS will be applied to `header_image`
872  ///
873  /// The recommended dimensions are 150px x 57px.
874  #[serde(alias = "uninstaller-header-image")]
875  pub uninstaller_header_image: Option<PathBuf>,
876  /// Whether the installation will be for all users or just the current user.
877  #[serde(default, alias = "install-mode")]
878  pub install_mode: NSISInstallerMode,
879  /// A list of installer languages. Default to `["English"]` if not set.
880  ///
881  /// By default the OS language is used. If the OS language is not in the list of languages, the first language will be used.
882  /// To allow the user to select the language, set `display_language_selector` to `true`.
883  ///
884  /// See <https://github.com/kichik/nsis/tree/9465c08046f00ccb6eda985abbdbf52c275c6c4d/Contrib/Language%20files> for the complete list of languages.
885  pub languages: Option<Vec<String>>,
886  /// A key-value pair where the key is the language and the
887  /// value is the path to a custom `.nsh` file that holds the translated text for tauri's custom messages.
888  ///
889  /// See <https://github.com/tauri-apps/tauri/blob/dev/crates/tauri-bundler/src/bundle/windows/nsis/languages/English.nsh> for an example `.nsh` file.
890  ///
891  /// **Note**: the key must be a valid NSIS language and it must be added to the [`Self::languages`] array,
892  pub custom_language_files: Option<HashMap<String, PathBuf>>,
893  /// Whether to display a language selector dialog before the installer and uninstaller windows are rendered or not.
894  /// By default the OS language is selected, with a fallback to the first language in the `languages` array.
895  #[serde(default, alias = "display-language-selector")]
896  pub display_language_selector: bool,
897  /// Set the compression algorithm used to compress files in the installer.
898  ///
899  /// See <https://nsis.sourceforge.io/Reference/SetCompressor>
900  #[serde(default)]
901  pub compression: NsisCompression,
902  /// Set the folder name for the start menu shortcut.
903  ///
904  /// Use this option if you have multiple apps and wish to group their shortcuts under one folder
905  /// or if you generally prefer to set your shortcut inside a folder.
906  ///
907  /// Examples:
908  /// - `AwesomePublisher`, shortcut will be placed in `%AppData%\Microsoft\Windows\Start Menu\Programs\AwesomePublisher\<your-app>.lnk`
909  /// - If unset, shortcut will be placed in `%AppData%\Microsoft\Windows\Start Menu\Programs\<your-app>.lnk`
910  #[serde(alias = "start-menu-folder")]
911  pub start_menu_folder: Option<String>,
912  /// A path to a `.nsh` file that contains special NSIS macros to be hooked into the
913  /// main installer.nsi script.
914  ///
915  /// Supported hooks are:
916  ///
917  /// - `NSIS_HOOK_PREINSTALL`: This hook runs before copying files, setting registry key values and creating shortcuts.
918  /// - `NSIS_HOOK_POSTINSTALL`: This hook runs after the installer has finished copying all files, setting the registry keys and created shortcuts.
919  /// - `NSIS_HOOK_PREUNINSTALL`: This hook runs before removing any files, registry keys and shortcuts.
920  /// - `NSIS_HOOK_POSTUNINSTALL`: This hook runs after files, registry keys and shortcuts have been removed.
921  ///
922  /// ### Example
923  ///
924  /// ```nsh
925  /// !macro NSIS_HOOK_PREINSTALL
926  ///   MessageBox MB_OK "PreInstall"
927  /// !macroend
928  ///
929  /// !macro NSIS_HOOK_POSTINSTALL
930  ///   MessageBox MB_OK "PostInstall"
931  /// !macroend
932  ///
933  /// !macro NSIS_HOOK_PREUNINSTALL
934  ///   MessageBox MB_OK "PreUnInstall"
935  /// !macroend
936  ///
937  /// !macro NSIS_HOOK_POSTUNINSTALL
938  ///   MessageBox MB_OK "PostUninstall"
939  /// !macroend
940  /// ```
941  #[serde(alias = "installer-hooks")]
942  pub installer_hooks: Option<PathBuf>,
943  /// Deprecated: use [`WindowsConfig::minimum_webview2_version`] (`bundle >  windows > minimumWebview2Version`) instead.
944  ///
945  /// Try to ensure that the WebView2 version is equal to or newer than this version,
946  /// if the user's WebView2 is older than this version,
947  /// the installer will try to trigger a WebView2 update.
948  #[deprecated(
949    since = "2.10.0",
950    note = "Use `WindowsConfig::minimum_webview2_version` instead."
951  )]
952  #[serde(alias = "minimum-webview2-version")]
953  pub minimum_webview2_version: Option<String>,
954}
955
956/// Install modes for the Webview2 runtime.
957/// Note that for the updater bundle [`Self::DownloadBootstrapper`] is used.
958///
959/// For more information see <https://v2.tauri.app/distribute/windows-installer/#webview2-installation-options>.
960#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
961#[serde(tag = "type", rename_all = "camelCase", deny_unknown_fields)]
962#[cfg_attr(feature = "schema", derive(JsonSchema))]
963pub enum WebviewInstallMode {
964  /// Do not install the Webview2 as part of the Windows Installer.
965  Skip,
966  /// Download the bootstrapper and run it.
967  /// Requires an internet connection.
968  /// Results in a smaller installer size, but is not recommended on Windows 7.
969  DownloadBootstrapper {
970    /// Instructs the installer to run the bootstrapper in silent mode. Defaults to `true`.
971    #[serde(default = "default_true")]
972    silent: bool,
973  },
974  /// Embed the bootstrapper and run it.
975  /// Requires an internet connection.
976  /// Increases the installer size by around 1.8MB, but offers better support on Windows 7.
977  EmbedBootstrapper {
978    /// Instructs the installer to run the bootstrapper in silent mode. Defaults to `true`.
979    #[serde(default = "default_true")]
980    silent: bool,
981  },
982  /// Embed the offline installer and run it.
983  /// Does not require an internet connection.
984  /// Increases the installer size by around 127MB.
985  OfflineInstaller {
986    /// Instructs the installer to run the installer in silent mode. Defaults to `true`.
987    #[serde(default = "default_true")]
988    silent: bool,
989  },
990  /// Embed a fixed webview2 version and use it at runtime.
991  /// Increases the installer size by around 180MB.
992  FixedRuntime {
993    /// The path to the fixed runtime to use.
994    ///
995    /// The fixed version can be downloaded [on the official website](https://developer.microsoft.com/en-us/microsoft-edge/webview2/#download-section).
996    /// The `.cab` file must be extracted to a folder and this folder path must be defined on this field.
997    path: PathBuf,
998  },
999}
1000
1001impl Default for WebviewInstallMode {
1002  fn default() -> Self {
1003    Self::DownloadBootstrapper { silent: true }
1004  }
1005}
1006
1007/// Custom Signing Command configuration.
1008#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1009#[cfg_attr(feature = "schema", derive(JsonSchema))]
1010#[serde(rename_all = "camelCase", deny_unknown_fields, untagged)]
1011pub enum CustomSignCommandConfig {
1012  /// A string notation of the script to execute.
1013  ///
1014  /// "%1" will be replaced with the path to the binary to be signed.
1015  ///
1016  /// This is a simpler notation for the command.
1017  /// Tauri will split the string with `' '` and use the first element as the command name and the rest as arguments.
1018  ///
1019  /// If you need to use whitespace in the command or arguments, use the object notation [`Self::CommandWithOptions`].
1020  Command(String),
1021  /// An object notation of the command.
1022  ///
1023  /// This is more complex notation for the command but
1024  /// this allows you to use whitespace in the command and arguments.
1025  CommandWithOptions {
1026    /// The command to run to sign the binary.
1027    cmd: String,
1028    /// The arguments to pass to the command.
1029    ///
1030    /// "%1" will be replaced with the path to the binary to be signed.
1031    args: Vec<String>,
1032  },
1033}
1034
1035/// Windows bundler configuration.
1036///
1037/// See more: <https://v2.tauri.app/reference/config/#windowsconfig>
1038#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1039#[cfg_attr(feature = "schema", derive(JsonSchema))]
1040#[serde(rename_all = "camelCase", deny_unknown_fields)]
1041pub struct WindowsConfig {
1042  /// Specifies the file digest algorithm to use for creating file signatures.
1043  /// Required for code signing. SHA-256 is recommended.
1044  #[serde(alias = "digest-algorithm")]
1045  pub digest_algorithm: Option<String>,
1046  /// Specifies the SHA1 hash of the signing certificate.
1047  #[serde(alias = "certificate-thumbprint")]
1048  pub certificate_thumbprint: Option<String>,
1049  /// Server to use during timestamping.
1050  #[serde(alias = "timestamp-url")]
1051  pub timestamp_url: Option<String>,
1052  /// Whether to use Time-Stamp Protocol (TSP, a.k.a. RFC 3161) for the timestamp server. Your code signing provider may
1053  /// use a TSP timestamp server, like e.g. SSL.com does. If so, enable TSP by setting to true.
1054  #[serde(default)]
1055  pub tsp: bool,
1056  /// The installation mode for the Webview2 runtime.
1057  #[serde(default, alias = "webview-install-mode")]
1058  pub webview_install_mode: WebviewInstallMode,
1059  /// Validates a second app installation, blocking the user from installing an older version if set to `false`.
1060  ///
1061  /// 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`.
1062  ///
1063  /// The default value of this flag is `true`.
1064  #[serde(default = "default_true", alias = "allow-downgrades")]
1065  pub allow_downgrades: bool,
1066  /// Try to ensure that the WebView2 version is equal to or newer than this version,
1067  /// if the user's WebView2 is older than this version,
1068  /// the installer will try to trigger a WebView2 update.
1069  #[serde(alias = "minimum-webview2-version")]
1070  pub minimum_webview2_version: Option<String>,
1071  /// Configuration for the MSI generated with WiX.
1072  pub wix: Option<WixConfig>,
1073  /// Configuration for the installer generated with NSIS.
1074  pub nsis: Option<NsisConfig>,
1075  /// Specify a custom command to sign the binaries.
1076  /// This command needs to have a `%1` in args which is just a placeholder for the binary path,
1077  /// which we will detect and replace before calling the command.
1078  ///
1079  /// By Default we use `signtool.exe` which can be found only on Windows so
1080  /// if you are on another platform and want to cross-compile and sign you will
1081  /// need to use another tool like `osslsigncode`.
1082  #[serde(alias = "sign-command")]
1083  pub sign_command: Option<CustomSignCommandConfig>,
1084  /// Whether to bundle the Visual C++ runtime DLLs alongside the application.
1085  ///
1086  /// This can be particularly useful when your application includes sidecars or DLLs that do
1087  /// not statically link the Visual C++ runtime and require the runtime DLLs at runtime, and
1088  /// you do not want to require users to install the Visual C++ Redistributable. This can also
1089  /// be useful when `build > windows > staticVCRuntime` is set to `false`.
1090  #[serde(
1091    default,
1092    rename = "bundleVCRuntime",
1093    alias = "bundle-vc-runtime",
1094    alias = "bundleVcRuntime"
1095  )]
1096  pub bundle_vc_runtime: bool,
1097}
1098
1099impl Default for WindowsConfig {
1100  fn default() -> Self {
1101    Self {
1102      digest_algorithm: None,
1103      certificate_thumbprint: None,
1104      timestamp_url: None,
1105      tsp: false,
1106      webview_install_mode: Default::default(),
1107      allow_downgrades: true,
1108      minimum_webview2_version: None,
1109      wix: None,
1110      nsis: None,
1111      sign_command: None,
1112      bundle_vc_runtime: false,
1113    }
1114  }
1115}
1116
1117/// macOS-only. Corresponds to CFBundleTypeRole
1118#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
1119#[cfg_attr(feature = "schema", derive(JsonSchema))]
1120pub enum BundleTypeRole {
1121  /// CFBundleTypeRole.Editor. Files can be read and edited.
1122  #[default]
1123  Editor,
1124  /// CFBundleTypeRole.Viewer. Files can be read.
1125  Viewer,
1126  /// CFBundleTypeRole.Shell
1127  Shell,
1128  /// CFBundleTypeRole.QLGenerator
1129  QLGenerator,
1130  /// CFBundleTypeRole.None
1131  None,
1132}
1133
1134impl Display for BundleTypeRole {
1135  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1136    match self {
1137      Self::Editor => write!(f, "Editor"),
1138      Self::Viewer => write!(f, "Viewer"),
1139      Self::Shell => write!(f, "Shell"),
1140      Self::QLGenerator => write!(f, "QLGenerator"),
1141      Self::None => write!(f, "None"),
1142    }
1143  }
1144}
1145
1146// Issue #13159 - Missing the LSHandlerRank and Apple warns after uploading to App Store Connect.
1147// https://github.com/tauri-apps/tauri/issues/13159
1148/// Corresponds to LSHandlerRank
1149#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
1150#[cfg_attr(feature = "schema", derive(JsonSchema))]
1151pub enum HandlerRank {
1152  /// LSHandlerRank.Default. This app is an opener of files of this type; this value is also used if no rank is specified.
1153  #[default]
1154  Default,
1155  /// LSHandlerRank.Owner. This app is the primary creator of files of this type.
1156  Owner,
1157  /// LSHandlerRank.Alternate. This app is a secondary viewer of files of this type.
1158  Alternate,
1159  /// LSHandlerRank.None. This app is never selected to open files of this type, but it accepts drops of files of this type.
1160  None,
1161}
1162
1163impl Display for HandlerRank {
1164  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1165    match self {
1166      Self::Default => write!(f, "Default"),
1167      Self::Owner => write!(f, "Owner"),
1168      Self::Alternate => write!(f, "Alternate"),
1169      Self::None => write!(f, "None"),
1170    }
1171  }
1172}
1173
1174/// An extension for a [`FileAssociation`].
1175///
1176/// A leading `.` is automatically stripped.
1177#[derive(Debug, PartialEq, Eq, Clone, Serialize)]
1178#[cfg_attr(feature = "schema", derive(JsonSchema))]
1179pub struct AssociationExt(pub String);
1180
1181impl fmt::Display for AssociationExt {
1182  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1183    write!(f, "{}", self.0)
1184  }
1185}
1186
1187impl<'d> serde::Deserialize<'d> for AssociationExt {
1188  fn deserialize<D: Deserializer<'d>>(deserializer: D) -> Result<Self, D::Error> {
1189    let ext = String::deserialize(deserializer)?;
1190    if let Some(ext) = ext.strip_prefix('.') {
1191      Ok(AssociationExt(ext.into()))
1192    } else {
1193      Ok(AssociationExt(ext))
1194    }
1195  }
1196}
1197
1198/// File association
1199#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1200#[cfg_attr(feature = "schema", derive(JsonSchema))]
1201#[serde(rename_all = "camelCase", deny_unknown_fields)]
1202pub struct FileAssociation {
1203  /// File extensions to associate with this app. e.g. 'png'
1204  pub ext: Vec<AssociationExt>,
1205  /// Declare support to a file with the given content type. Maps to `LSItemContentTypes` on macOS.
1206  ///
1207  /// This allows supporting any file format declared by another application that conforms to this type.
1208  /// Declaration of new types can be done with [`Self::exported_type`] and linking to certain content types are done via [`ExportedFileAssociation::conforms_to`].
1209  #[serde(alias = "content-types")]
1210  pub content_types: Option<Vec<String>>,
1211  /// The name. Maps to `CFBundleTypeName` on macOS. Default to `ext[0]`
1212  pub name: Option<String>,
1213  /// The association description. Windows-only. It is displayed on the `Type` column on Windows Explorer.
1214  pub description: Option<String>,
1215  /// The app's role with respect to the type. Maps to `CFBundleTypeRole` on macOS.
1216  #[serde(default)]
1217  pub role: BundleTypeRole,
1218  /// The mime-type of the association, e.g. `'image/png'` or `'text/plain'`.
1219  ///
1220  /// - **Linux**: written as `MimeType=` in the `.desktop` file.
1221  /// - **macOS / iOS**: added as `public.mime-type` in the `UTTypeTagSpecification` dictionary of
1222  ///   the `UTExportedTypeDeclarations` entry in `Info.plist`.
1223  /// - **Android**: used as `android:mimeType` in the `<data>` element of an `<intent-filter>`
1224  ///   in `AndroidManifest.xml`.
1225  #[serde(alias = "mime-type")]
1226  pub mime_type: Option<String>,
1227  /// The ranking of this app among apps that declare themselves as editors or viewers of the given file type.  Maps to `LSHandlerRank` on macOS.
1228  #[serde(default)]
1229  pub rank: HandlerRank,
1230  /// The exported type definition. Maps to a `UTExportedTypeDeclarations` entry on macOS.
1231  ///
1232  /// You should define this if the associated file is a custom file type defined by your application.
1233  pub exported_type: Option<ExportedFileAssociation>,
1234  /// Intent action filters for this file association.
1235  ///
1236  /// By default all filters are used.
1237  #[serde(alias = "android-intent-action-filters")]
1238  pub android_intent_action_filters: Option<Vec<AndroidIntentAction>>,
1239}
1240
1241/// Android intent action.
1242#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize, Hash)]
1243#[cfg_attr(feature = "schema", derive(JsonSchema))]
1244#[serde(rename_all = "camelCase")]
1245#[non_exhaustive]
1246pub enum AndroidIntentAction {
1247  /// ACTION_SEND.
1248  ///
1249  /// <https://developer.android.com/reference/android/content/Intent#ACTION_SEND>
1250  Send,
1251  /// ACTION_SEND_MULTIPLE.
1252  ///
1253  /// <https://developer.android.com/reference/android/content/Intent#ACTION_SEND_MULTIPLE>
1254  SendMultiple,
1255  /// ACTION_VIEW.
1256  ///
1257  /// <https://developer.android.com/reference/android/content/Intent#ACTION_SEND>
1258  View,
1259}
1260
1261/// The exported type definition. Maps to a `UTExportedTypeDeclarations` entry on macOS.
1262#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1263#[cfg_attr(feature = "schema", derive(JsonSchema))]
1264#[serde(rename_all = "camelCase", deny_unknown_fields)]
1265pub struct ExportedFileAssociation {
1266  /// The unique identifier for the exported type. Maps to `UTTypeIdentifier`.
1267  pub identifier: String,
1268  /// The types that this type conforms to. Maps to `UTTypeConformsTo`.
1269  ///
1270  /// Examples are `public.data`, `public.image`, `public.json` and `public.database`.
1271  #[serde(alias = "conforms-to")]
1272  pub conforms_to: Option<Vec<String>>,
1273}
1274
1275impl FileAssociation {
1276  /// Infers UTIs (Uniform Type Identifiers) from file extensions and mime types.
1277  /// This is useful for macOS and iOS to automatically populate `LSItemContentTypes`
1278  /// in the Info.plist for share sheet and file association support.
1279  ///
1280  /// Returns a vector of UTIs that should be included in `LSItemContentTypes`.
1281  /// Explicitly provided content types are included first, followed by inferred types.
1282  pub fn infer_content_types(&self) -> HashSet<String> {
1283    let mut content_types = HashSet::new();
1284
1285    // when we have an exported type, we only reference it
1286    if let Some(exported_type) = &self.exported_type {
1287      content_types.insert(exported_type.identifier.clone());
1288      return content_types;
1289    }
1290
1291    // Start with explicitly provided content types
1292    if let Some(explicit_types) = &self.content_types {
1293      content_types.extend(explicit_types.iter().cloned());
1294    }
1295
1296    // Infer from extensions and add to content_types (avoiding duplicates)
1297    for ext in &self.ext {
1298      if let Some(uti) = extension_to_uti(&ext.0) {
1299        content_types.insert(uti.to_string());
1300      }
1301    }
1302
1303    // Also infer from mime type if available (avoiding duplicates)
1304    if let Some(mime_type) = &self.mime_type {
1305      if let Some(uti) = mime_type_to_uti(mime_type) {
1306        content_types.insert(uti.to_string());
1307      }
1308    }
1309
1310    content_types
1311  }
1312}
1313
1314/// Generates plist dictionary entries for file associations.
1315/// This is used by both macOS and iOS bundlers to populate Info.plist.
1316///
1317/// Returns a plist dictionary containing `UTExportedTypeDeclarations` and `CFBundleDocumentTypes`
1318/// if there are any file associations configured.
1319pub fn file_associations_plist(associations: &[FileAssociation]) -> Option<plist::Value> {
1320  use plist::{Dictionary, Value};
1321
1322  if associations.is_empty() {
1323    return None;
1324  }
1325
1326  let exported_associations = associations
1327    .iter()
1328    .filter_map(|association| {
1329      association.exported_type.as_ref().map(|exported_type| {
1330        let mut dict = Dictionary::new();
1331
1332        dict.insert(
1333          "UTTypeIdentifier".into(),
1334          exported_type.identifier.clone().into(),
1335        );
1336        if let Some(description) = &association.description {
1337          dict.insert("UTTypeDescription".into(), description.clone().into());
1338        }
1339        if let Some(conforms_to) = &exported_type.conforms_to {
1340          dict.insert(
1341            "UTTypeConformsTo".into(),
1342            Value::Array(conforms_to.iter().map(|s| s.clone().into()).collect()),
1343          );
1344        }
1345
1346        let mut specification = Dictionary::new();
1347        specification.insert(
1348          "public.filename-extension".into(),
1349          Value::Array(
1350            association
1351              .ext
1352              .iter()
1353              .map(|s| s.to_string().into())
1354              .collect(),
1355          ),
1356        );
1357        if let Some(mime_type) = &association.mime_type {
1358          specification.insert("public.mime-type".into(), mime_type.clone().into());
1359        }
1360
1361        dict.insert("UTTypeTagSpecification".into(), specification.into());
1362
1363        Value::Dictionary(dict)
1364      })
1365    })
1366    .collect::<Vec<_>>();
1367
1368  let document_types = associations
1369    .iter()
1370    .map(|association| {
1371      let mut dict = Dictionary::new();
1372
1373      if !association.ext.is_empty() {
1374        dict.insert(
1375          "CFBundleTypeExtensions".into(),
1376          Value::Array(
1377            association
1378              .ext
1379              .iter()
1380              .map(|ext| ext.to_string().into())
1381              .collect(),
1382          ),
1383        );
1384      }
1385
1386      // For macOS/iOS share sheet, we need LSItemContentTypes with standard UTIs
1387      let content_types = association.infer_content_types();
1388
1389      // Add LSItemContentTypes if we have any content types
1390      if !content_types.is_empty() {
1391        dict.insert(
1392          "LSItemContentTypes".into(),
1393          Value::Array(content_types.iter().map(|s| s.clone().into()).collect()),
1394        );
1395      }
1396
1397      let type_name = association
1398        .name
1399        .clone()
1400        .or_else(|| association.ext.first().map(|ext| ext.0.clone()))
1401        .unwrap_or_default();
1402      dict.insert("CFBundleTypeName".into(), type_name.into());
1403      dict.insert(
1404        "CFBundleTypeRole".into(),
1405        association.role.to_string().into(),
1406      );
1407      dict.insert("LSHandlerRank".into(), association.rank.to_string().into());
1408
1409      Value::Dictionary(dict)
1410    })
1411    .collect::<Vec<_>>();
1412
1413  if exported_associations.is_empty() && document_types.is_empty() {
1414    return None;
1415  }
1416
1417  let mut plist = Dictionary::new();
1418  if !exported_associations.is_empty() {
1419    plist.insert(
1420      "UTExportedTypeDeclarations".into(),
1421      Value::Array(exported_associations),
1422    );
1423  }
1424  if !document_types.is_empty() {
1425    plist.insert("CFBundleDocumentTypes".into(), Value::Array(document_types));
1426  }
1427
1428  Some(Value::Dictionary(plist))
1429}
1430
1431/// Maps file extensions to their standard UTIs for macOS/iOS share sheet support
1432fn extension_to_uti(ext: &str) -> Option<&'static str> {
1433  match ext.to_lowercase().as_str() {
1434    // Images
1435    "png" => Some("public.png"),
1436    "jpg" | "jpeg" => Some("public.jpeg"),
1437    "gif" => Some("com.compuserve.gif"),
1438    "bmp" => Some("com.microsoft.bmp"),
1439    "tiff" | "tif" => Some("public.tiff"),
1440    "ico" => Some("com.microsoft.ico"),
1441    "heic" | "heif" => Some("public.heif-standard-image"),
1442    "webp" => Some("org.webmproject.webp"),
1443    "svg" => Some("public.svg-image"),
1444    // Videos
1445    "mp4" => Some("public.mpeg-4"),
1446    "mov" => Some("com.apple.quicktime-movie"),
1447    "avi" => Some("public.avi"),
1448    "mkv" => Some("public.mpeg-4"),
1449    // Audio
1450    "mp3" => Some("public.mp3"),
1451    "wav" => Some("com.microsoft.waveform-audio"),
1452    "aac" => Some("public.aac-audio"),
1453    "m4a" => Some("public.mpeg-4-audio"),
1454    // Documents
1455    "pdf" => Some("com.adobe.pdf"),
1456    "txt" => Some("public.plain-text"),
1457    "rtf" => Some("public.rtf"),
1458    "html" | "htm" => Some("public.html"),
1459    "json" => Some("public.json"),
1460    "xml" => Some("public.xml"),
1461    _ => None,
1462  }
1463}
1464
1465/// Infers UTIs from mime type
1466fn mime_type_to_uti(mime_type: &str) -> Option<&'static str> {
1467  match mime_type {
1468    "image/png" => Some("public.png"),
1469    "image/jpeg" | "image/jpg" => Some("public.jpeg"),
1470    "image/gif" => Some("com.compuserve.gif"),
1471    "image/bmp" => Some("com.microsoft.bmp"),
1472    "image/tiff" => Some("public.tiff"),
1473    "image/heic" | "image/heif" => Some("public.heif-standard-image"),
1474    "image/webp" => Some("org.webmproject.webp"),
1475    "image/svg+xml" => Some("public.svg-image"),
1476    mime if mime.starts_with("image/") => Some("public.image"),
1477    "video/mp4" => Some("public.mpeg-4"),
1478    "video/quicktime" => Some("com.apple.quicktime-movie"),
1479    "video/x-msvideo" => Some("public.avi"),
1480    mime if mime.starts_with("video/") => Some("public.movie"),
1481    "audio/mpeg" | "audio/mp3" => Some("public.mp3"),
1482    "audio/wav" | "audio/wave" => Some("com.microsoft.waveform-audio"),
1483    "audio/aac" => Some("public.aac-audio"),
1484    "audio/mp4" => Some("public.mpeg-4-audio"),
1485    mime if mime.starts_with("audio/") => Some("public.audio"),
1486    "application/pdf" => Some("com.adobe.pdf"),
1487    "text/plain" => Some("public.plain-text"),
1488    "text/rtf" => Some("public.rtf"),
1489    "text/html" => Some("public.html"),
1490    "application/json" => Some("public.json"),
1491    "application/xml" | "text/xml" => Some("public.xml"),
1492    _ => None,
1493  }
1494}
1495
1496/// Deep link protocol configuration.
1497#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1498#[cfg_attr(feature = "schema", derive(JsonSchema))]
1499#[serde(rename_all = "camelCase", deny_unknown_fields)]
1500pub struct DeepLinkProtocol {
1501  /// URL schemes to associate with this app without `://`. For example `my-app`
1502  #[serde(default)]
1503  pub schemes: Vec<String>,
1504  /// Domains to associate with this app. For example `example.com`.
1505  /// Currently only supported on macOS, translating to an [universal app link].
1506  ///
1507  /// Note that universal app links require signed apps with a provisioning profile to work.
1508  /// You can accomplish that by including the `embedded.provisionprofile` file in the `macOS > files` option.
1509  ///
1510  /// [universal app link]: https://developer.apple.com/documentation/xcode/supporting-universal-links-in-your-app
1511  #[serde(default)]
1512  pub domains: Vec<String>,
1513  /// The protocol name. **macOS-only** and maps to `CFBundleTypeName`. Defaults to `<bundle-id>.<schemes[0]>`
1514  pub name: Option<String>,
1515  /// The app's role for these schemes. **macOS-only** and maps to `CFBundleTypeRole`.
1516  #[serde(default)]
1517  pub role: BundleTypeRole,
1518}
1519
1520/// Definition for bundle resources.
1521/// Can be either a list of paths to include or a map of source to target paths.
1522#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1523#[cfg_attr(feature = "schema", derive(JsonSchema))]
1524#[serde(rename_all = "camelCase", deny_unknown_fields, untagged)]
1525pub enum BundleResources {
1526  /// A list of paths to include.
1527  List(Vec<String>),
1528  /// A map of source to target paths.
1529  Map(HashMap<String, String>),
1530}
1531
1532impl BundleResources {
1533  /// Adds a path to the resource collection.
1534  pub fn push(&mut self, path: impl Into<String>) {
1535    match self {
1536      Self::List(l) => l.push(path.into()),
1537      Self::Map(l) => {
1538        let path = path.into();
1539        l.insert(path.clone(), path);
1540      }
1541    }
1542  }
1543}
1544
1545/// Updater type
1546#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1547#[cfg_attr(feature = "schema", derive(JsonSchema))]
1548#[serde(rename_all = "camelCase", deny_unknown_fields, untagged)]
1549pub enum Updater {
1550  /// Generates legacy zipped v1 compatible updaters
1551  String(V1Compatible),
1552  /// Produce updaters and their signatures or not
1553  // Can't use untagged on enum field here: https://github.com/GREsau/schemars/issues/222
1554  Bool(bool),
1555}
1556
1557impl Default for Updater {
1558  fn default() -> Self {
1559    Self::Bool(false)
1560  }
1561}
1562
1563/// Generates legacy zipped v1 compatible updaters
1564#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1565#[cfg_attr(feature = "schema", derive(JsonSchema))]
1566#[serde(rename_all = "camelCase", deny_unknown_fields)]
1567pub enum V1Compatible {
1568  /// Generates legacy zipped v1 compatible updaters
1569  V1Compatible,
1570}
1571
1572/// Configuration for tauri-bundler.
1573///
1574/// See more: <https://v2.tauri.app/reference/config/#bundleconfig>
1575#[skip_serializing_none]
1576#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
1577#[cfg_attr(feature = "schema", derive(JsonSchema))]
1578#[serde(rename_all = "camelCase", deny_unknown_fields)]
1579pub struct BundleConfig {
1580  /// Whether Tauri should bundle your application or just output the executable.
1581  #[serde(default)]
1582  pub active: bool,
1583  /// The bundle targets, currently supports ["deb", "rpm", "appimage", "nsis", "msi", "app", "dmg"] or "all".
1584  #[serde(default)]
1585  pub targets: BundleTarget,
1586  #[serde(default)]
1587  /// Produce updaters and their signatures or not
1588  pub create_updater_artifacts: Updater,
1589  /// The application's publisher. Defaults to the second element in the identifier string.
1590  ///
1591  /// Currently maps to the Manufacturer property of the Windows Installer
1592  /// and the Maintainer field of debian packages if the Cargo.toml does not have the authors field.
1593  pub publisher: Option<String>,
1594  /// A url to the home page of your application. If unset, will
1595  /// fallback to `homepage` defined in `Cargo.toml`.
1596  ///
1597  /// Supported bundle targets: `deb`, `rpm`, `nsis` and `msi`.
1598  pub homepage: Option<String>,
1599  /// The app's icons
1600  #[serde(default)]
1601  pub icon: Vec<String>,
1602  /// App resources to bundle.
1603  /// Each resource is a path to a file or directory.
1604  /// Glob patterns are supported.
1605  ///
1606  /// ## Examples
1607  ///
1608  /// To include a list of files:
1609  ///
1610  /// ```json
1611  /// {
1612  ///   "bundle": {
1613  ///     "resources": [
1614  ///       "./path/to/some-file.txt",
1615  ///       "/absolute/path/to/textfile.txt",
1616  ///       "../relative/path/to/jsonfile.json",
1617  ///       "some-folder/",
1618  ///       "resources/**/*.md"
1619  ///     ]
1620  ///   }
1621  /// }
1622  /// ```
1623  ///
1624  /// The bundled files will be in `$RESOURCES/` with the original directory structure preserved,
1625  /// for example: `./path/to/some-file.txt` -> `$RESOURCE/path/to/some-file.txt`
1626  ///
1627  /// To fine control where the files will get copied to, use a map instead
1628  ///
1629  /// ```json
1630  /// {
1631  ///   "bundle": {
1632  ///     "resources": {
1633  ///       "/absolute/path/to/textfile.txt": "resources/textfile.txt",
1634  ///       "relative/path/to/jsonfile.json": "resources/jsonfile.json",
1635  ///       "resources/": "",
1636  ///       "docs/**/*md": "website-docs/"
1637  ///     }
1638  ///   }
1639  /// }
1640  /// ```
1641  ///
1642  /// Note that when using glob pattern in this case, the original directory structure is not preserved,
1643  /// everything gets copied to the target directory directly
1644  ///
1645  /// See more: <https://v2.tauri.app/develop/resources/>
1646  pub resources: Option<BundleResources>,
1647  /// A copyright string associated with your application.
1648  pub copyright: Option<String>,
1649  /// The package's license identifier to be included in the appropriate bundles.
1650  /// If not set, defaults to the license from the Cargo.toml file.
1651  pub license: Option<String>,
1652  /// The path to the license file to be included in the appropriate bundles.
1653  #[serde(alias = "license-file")]
1654  pub license_file: Option<PathBuf>,
1655  /// The application kind.
1656  ///
1657  /// Should be one of the following:
1658  /// 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.
1659  pub category: Option<String>,
1660  /// File types to associate with the application.
1661  pub file_associations: Option<Vec<FileAssociation>>,
1662  /// A short description of your application.
1663  #[serde(alias = "short-description")]
1664  pub short_description: Option<String>,
1665  /// A longer, multi-line description of the application.
1666  #[serde(alias = "long-description")]
1667  pub long_description: Option<String>,
1668  /// Whether to use the project's `target` directory, for caching build tools (e.g., Wix and NSIS) when building this application. Defaults to `false`.
1669  ///
1670  /// If true, tools will be cached in `target/.tauri/`.
1671  /// If false, tools will be cached in the current user's platform-specific cache directory.
1672  ///
1673  /// An example where it can be appropriate to set this to `true` is when building this application as a Windows System user (e.g., AWS EC2 workloads),
1674  /// because the Window system's app data directory is restricted.
1675  #[serde(default, alias = "use-local-tools-dir")]
1676  pub use_local_tools_dir: bool,
1677  /// A list of—either absolute or relative—paths to binaries to embed with your application.
1678  ///
1679  /// Note that Tauri will look for system-specific binaries following the pattern "binary-name{-target-triple}{.system-extension}".
1680  ///
1681  /// E.g. for the external binary "my-binary", Tauri looks for:
1682  ///
1683  /// - "my-binary-x86_64-pc-windows-msvc.exe" for Windows
1684  /// - "my-binary-x86_64-apple-darwin" for macOS
1685  /// - "my-binary-x86_64-unknown-linux-gnu" for Linux
1686  ///
1687  /// so don't forget to provide binaries for all targeted platforms.
1688  #[serde(alias = "external-bin")]
1689  pub external_bin: Option<Vec<String>>,
1690  /// Configuration for the Windows bundles.
1691  #[serde(default)]
1692  pub windows: WindowsConfig,
1693  /// Configuration for the Linux bundles.
1694  #[serde(default)]
1695  pub linux: LinuxConfig,
1696  /// Configuration for the macOS bundles.
1697  #[serde(rename = "macOS", alias = "macos", default)]
1698  pub macos: MacConfig,
1699  /// iOS configuration.
1700  #[serde(rename = "iOS", alias = "ios", default)]
1701  pub ios: IosConfig,
1702  /// Android configuration.
1703  #[serde(default)]
1704  pub android: AndroidConfig,
1705}
1706
1707/// A tuple struct of RGBA colors. Each value has minimum of 0 and maximum of 255.
1708#[derive(Debug, PartialEq, Eq, Serialize, Default, Clone, Copy)]
1709#[serde(rename_all = "camelCase", deny_unknown_fields)]
1710pub struct Color(pub u8, pub u8, pub u8, pub u8);
1711
1712impl From<Color> for (u8, u8, u8, u8) {
1713  fn from(value: Color) -> Self {
1714    (value.0, value.1, value.2, value.3)
1715  }
1716}
1717
1718impl From<Color> for (u8, u8, u8) {
1719  fn from(value: Color) -> Self {
1720    (value.0, value.1, value.2)
1721  }
1722}
1723
1724impl From<(u8, u8, u8, u8)> for Color {
1725  fn from(value: (u8, u8, u8, u8)) -> Self {
1726    Color(value.0, value.1, value.2, value.3)
1727  }
1728}
1729
1730impl From<(u8, u8, u8)> for Color {
1731  fn from(value: (u8, u8, u8)) -> Self {
1732    Color(value.0, value.1, value.2, 255)
1733  }
1734}
1735
1736impl From<Color> for [u8; 4] {
1737  fn from(value: Color) -> Self {
1738    [value.0, value.1, value.2, value.3]
1739  }
1740}
1741
1742impl From<Color> for [u8; 3] {
1743  fn from(value: Color) -> Self {
1744    [value.0, value.1, value.2]
1745  }
1746}
1747
1748impl From<[u8; 4]> for Color {
1749  fn from(value: [u8; 4]) -> Self {
1750    Color(value[0], value[1], value[2], value[3])
1751  }
1752}
1753
1754impl From<[u8; 3]> for Color {
1755  fn from(value: [u8; 3]) -> Self {
1756    Color(value[0], value[1], value[2], 255)
1757  }
1758}
1759
1760impl FromStr for Color {
1761  type Err = String;
1762  fn from_str(mut color: &str) -> Result<Self, Self::Err> {
1763    color = color.trim().strip_prefix('#').unwrap_or(color);
1764    let color = match color.len() {
1765      3 => color.chars()
1766            .flat_map(|c| std::iter::repeat_n(c, 2))
1767            .chain(std::iter::repeat_n('f', 2))
1768            .collect(),
1769      6 => format!("{color}FF"),
1770      8 => color.to_string(),
1771      _ => return Err("Invalid hex color length, must be either 3, 6 or 8, for example: #fff, #ffffff, or #ffffffff".into()),
1772    };
1773
1774    let r = u8::from_str_radix(&color[0..2], 16).map_err(|e| e.to_string())?;
1775    let g = u8::from_str_radix(&color[2..4], 16).map_err(|e| e.to_string())?;
1776    let b = u8::from_str_radix(&color[4..6], 16).map_err(|e| e.to_string())?;
1777    let a = u8::from_str_radix(&color[6..8], 16).map_err(|e| e.to_string())?;
1778
1779    Ok(Color(r, g, b, a))
1780  }
1781}
1782
1783fn default_alpha() -> u8 {
1784  255
1785}
1786
1787#[derive(Deserialize)]
1788#[cfg_attr(feature = "schema", derive(JsonSchema))]
1789#[serde(untagged)]
1790enum InnerColor {
1791  /// Color hex string, for example: #fff, #ffffff, or #ffffffff.
1792  String(String),
1793  /// Array of RGB colors. Each value has minimum of 0 and maximum of 255.
1794  Rgb((u8, u8, u8)),
1795  /// Array of RGBA colors. Each value has minimum of 0 and maximum of 255.
1796  Rgba((u8, u8, u8, u8)),
1797  /// Object of red, green, blue, alpha color values. Each value has minimum of 0 and maximum of 255.
1798  RgbaObject {
1799    red: u8,
1800    green: u8,
1801    blue: u8,
1802    #[serde(default = "default_alpha")]
1803    alpha: u8,
1804  },
1805}
1806
1807impl<'de> Deserialize<'de> for Color {
1808  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1809  where
1810    D: Deserializer<'de>,
1811  {
1812    let color = InnerColor::deserialize(deserializer)?;
1813    let color = match color {
1814      InnerColor::String(string) => string.parse().map_err(serde::de::Error::custom)?,
1815      InnerColor::Rgb(rgb) => Color(rgb.0, rgb.1, rgb.2, 255),
1816      InnerColor::Rgba(rgb) => rgb.into(),
1817      InnerColor::RgbaObject {
1818        red,
1819        green,
1820        blue,
1821        alpha,
1822      } => Color(red, green, blue, alpha),
1823    };
1824
1825    Ok(color)
1826  }
1827}
1828
1829#[cfg(feature = "schema")]
1830impl schemars::JsonSchema for Color {
1831  fn schema_name() -> String {
1832    "Color".to_string()
1833  }
1834
1835  fn json_schema(_generator: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema {
1836    let mut schema = schemars::schema_for!(InnerColor).schema;
1837    schema.metadata = None; // Remove `title: InnerColor` from schema
1838
1839    // add hex color pattern validation
1840    let any_of = schema.subschemas().any_of.as_mut().unwrap();
1841    let schemars::schema::Schema::Object(str_schema) = any_of.first_mut().unwrap() else {
1842      unreachable!()
1843    };
1844    str_schema.string().pattern = Some("^#?([A-Fa-f0-9]{3}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{8})$".into());
1845
1846    schema.into()
1847  }
1848}
1849
1850/// Background throttling policy.
1851#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1852#[cfg_attr(feature = "schema", derive(JsonSchema))]
1853#[serde(rename_all = "camelCase", deny_unknown_fields)]
1854pub enum BackgroundThrottlingPolicy {
1855  /// A policy where background throttling is disabled
1856  Disabled,
1857  /// A policy where a web view that's not in a window fully suspends tasks. This is usually the default behavior in case no policy is set.
1858  Suspend,
1859  /// A policy where a web view that's not in a window limits processing, but does not fully suspend tasks.
1860  Throttle,
1861}
1862
1863/// The window effects configuration object
1864#[skip_serializing_none]
1865#[derive(Debug, PartialEq, Clone, Deserialize, Serialize, Default)]
1866#[cfg_attr(feature = "schema", derive(JsonSchema))]
1867#[serde(rename_all = "camelCase", deny_unknown_fields)]
1868pub struct WindowEffectsConfig {
1869  /// List of Window effects to apply to the Window.
1870  ///
1871  /// Generally, conflicting effects will apply the first one and ignore the rest but
1872  /// on macOS you can specify one Liquid Glass style and one Visual Effect material at the same time
1873  /// to make Tauri fallback to the latter on macOS 15 and below.
1874  pub effects: Vec<WindowEffect>,
1875  /// Window effect state **macOS Only**. Ignored for Liquid Glass Effects.
1876  pub state: Option<WindowEffectState>,
1877  /// Window effect corner radius **macOS Only**
1878  pub radius: Option<f64>,
1879  /// Window effect color.
1880  ///
1881  /// ## Platform-specific
1882  ///
1883  /// - **Windows**: Affects [`WindowEffect::Blur`] and [`WindowEffect::Acrylic`] only
1884  /// on Windows 10 v1903+. Doesn't have any effect on Windows 7 or Windows 11.
1885  /// - **macOS**: Only affects Liquid Glass effects.
1886  pub color: Option<Color>,
1887  /// Enables interactive glass behavior, which adds a visual response to user interactions.
1888  ///
1889  /// **macOS 27.0+**. Only affects Liquid Glass effects.
1890  #[serde(default)]
1891  pub interactive: bool,
1892}
1893
1894/// Enable prevent overflow with a margin
1895/// so that the window's size + this margin won't overflow the workarea
1896#[derive(Debug, PartialEq, Clone, Deserialize, Serialize, Default)]
1897#[cfg_attr(feature = "schema", derive(JsonSchema))]
1898#[serde(rename_all = "camelCase", deny_unknown_fields)]
1899pub struct PreventOverflowMargin {
1900  /// Horizontal margin in physical pixels
1901  pub width: u32,
1902  /// Vertical margin in physical pixels
1903  pub height: u32,
1904}
1905
1906/// Prevent overflow with a margin
1907#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
1908#[cfg_attr(feature = "schema", derive(JsonSchema))]
1909#[serde(untagged)]
1910pub enum PreventOverflowConfig {
1911  /// Enable prevent overflow or not
1912  Enable(bool),
1913  /// Enable prevent overflow with a margin
1914  /// so that the window's size + this margin won't overflow the workarea
1915  Margin(PreventOverflowMargin),
1916}
1917
1918/// The scrollbar style to use in the webview.
1919///
1920/// ## Platform-specific
1921///
1922/// - **Windows**: This option must be given the same value for all webviews that target the same data directory.
1923#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Default)]
1924#[cfg_attr(feature = "schema", derive(JsonSchema))]
1925#[serde(rename_all = "camelCase", deny_unknown_fields)]
1926#[non_exhaustive]
1927pub enum ScrollBarStyle {
1928  #[default]
1929  /// The platform's native scrollbar, as rendered by the webview by default.
1930  ///
1931  /// This is the only supported value outside of Windows.
1932  Default,
1933
1934  /// Fluent UI style overlay scrollbars. **Windows Only**
1935  ///
1936  /// Requires WebView2 Runtime version 125.0.2535.41 or higher, does nothing on older versions,
1937  /// see <https://learn.microsoft.com/en-us/microsoft-edge/webview2/release-notes/?tabs=dotnetcsharp#10253541>
1938  FluentOverlay,
1939}
1940
1941/// The window configuration object.
1942///
1943/// See more: <https://v2.tauri.app/reference/config/#windowconfig>
1944#[skip_serializing_none]
1945#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
1946#[cfg_attr(feature = "schema", derive(JsonSchema))]
1947#[serde(rename_all = "camelCase", deny_unknown_fields)]
1948pub struct WindowConfig {
1949  /// The window identifier. It must be alphanumeric.
1950  #[serde(default = "default_window_label")]
1951  pub label: String,
1952  /// Whether Tauri should create this window at app startup or not.
1953  ///
1954  /// When this is set to `false` you must manually grab the config object via `app.config().app.windows`
1955  /// and create it with [`WebviewWindowBuilder::from_config`](https://docs.rs/tauri/2/tauri/webview/struct.WebviewWindowBuilder.html#method.from_config).
1956  ///
1957  /// ## Example:
1958  ///
1959  /// ```rust
1960  /// tauri::Builder::default()
1961  ///   .setup(|app| {
1962  ///     tauri::WebviewWindowBuilder::from_config(app.handle(), &app.config().app.windows[0])?.build()?;
1963  ///     Ok(())
1964  ///   });
1965  /// ```
1966  #[serde(default = "default_true")]
1967  pub create: bool,
1968  /// The window webview URL.
1969  #[serde(default)]
1970  pub url: WebviewUrl,
1971  /// The user agent for the webview
1972  #[serde(alias = "user-agent")]
1973  pub user_agent: Option<String>,
1974  /// Whether the drag and drop handlers used internally to generate [`DragDropEvent`]s are enabled on the webview. By default it is enabled.
1975  ///
1976  /// Disabling it is required to use HTML5 drag and drop on the frontend on Windows since we replace the drag drop handler of WebView2.
1977  ///
1978  /// Note: this setting maps to [`WebviewBuilder::disable_drag_drop_handler`], not [`WindowBuilder::drag_and_drop`].
1979  ///
1980  /// [`DragDropEvent`]: https://docs.rs/tauri/latest/tauri/enum.DragDropEvent.html
1981  /// [`WebviewBuilder::disable_drag_drop_handler`]: https://docs.rs/tauri/latest/tauri/webview/struct.WebviewBuilder.html#method.disable_drag_drop_handler
1982  /// [`WindowBuilder::drag_and_drop`]: https://docs.rs/tauri/latest/x86_64-pc-windows-msvc/tauri/window/struct.WindowBuilder.html#method.drag_and_drop
1983  #[serde(default = "default_true", alias = "drag-drop-enabled")]
1984  pub drag_drop_enabled: bool,
1985  /// Whether or not the window starts centered or not.
1986  #[serde(default)]
1987  pub center: bool,
1988  /// The horizontal position of the window's top left corner in logical pixels
1989  pub x: Option<f64>,
1990  /// The vertical position of the window's top left corner in logical pixels
1991  pub y: Option<f64>,
1992  /// The window width in logical pixels.
1993  #[serde(default = "default_width")]
1994  pub width: f64,
1995  /// The window height in logical pixels.
1996  #[serde(default = "default_height")]
1997  pub height: f64,
1998  /// The min window width in logical pixels.
1999  #[serde(alias = "min-width")]
2000  pub min_width: Option<f64>,
2001  /// The min window height in logical pixels.
2002  #[serde(alias = "min-height")]
2003  pub min_height: Option<f64>,
2004  /// The max window width in logical pixels.
2005  #[serde(alias = "max-width")]
2006  pub max_width: Option<f64>,
2007  /// The max window height in logical pixels.
2008  #[serde(alias = "max-height")]
2009  pub max_height: Option<f64>,
2010  /// Whether or not to prevent the window from overflowing the workarea
2011  ///
2012  /// ## Platform-specific
2013  ///
2014  /// - **iOS / Android:** Unsupported.
2015  #[serde(alias = "prevent-overflow")]
2016  pub prevent_overflow: Option<PreventOverflowConfig>,
2017  /// Whether the window is resizable or not. When resizable is set to false, native window's maximize button is automatically disabled.
2018  #[serde(default = "default_true")]
2019  pub resizable: bool,
2020  /// Whether the window's native maximize button is enabled or not.
2021  /// If resizable is set to false, this setting is ignored.
2022  ///
2023  /// ## Platform-specific
2024  ///
2025  /// - **macOS:** Disables the "zoom" button in the window titlebar, which is also used to enter fullscreen mode.
2026  /// - **Linux / iOS / Android:** Unsupported.
2027  #[serde(default = "default_true")]
2028  pub maximizable: bool,
2029  /// Whether the window's native minimize button is enabled or not.
2030  ///
2031  /// ## Platform-specific
2032  ///
2033  /// - **Linux / iOS / Android:** Unsupported.
2034  #[serde(default = "default_true")]
2035  pub minimizable: bool,
2036  /// Whether the window's native close button is enabled or not.
2037  ///
2038  /// ## Platform-specific
2039  ///
2040  /// - **Linux:** "GTK+ will do its best to convince the window manager not to show a close button.
2041  ///   Depending on the system, this function may not have any effect when called on a window that is already visible"
2042  /// - **iOS / Android:** Unsupported.
2043  #[serde(default = "default_true")]
2044  pub closable: bool,
2045  /// The window title.
2046  #[serde(default = "default_title")]
2047  pub title: String,
2048  /// Whether the window starts as fullscreen or not.
2049  #[serde(default)]
2050  pub fullscreen: bool,
2051  /// Whether the window will be initially focused or not.
2052  #[serde(default = "default_true")]
2053  pub focus: bool,
2054  /// Whether the window will be focusable or not.
2055  #[serde(default = "default_true")]
2056  pub focusable: bool,
2057  /// Whether the window is transparent or not.
2058  ///
2059  /// ## Platform-specific
2060  ///
2061  /// - **macOS**: Requires the `macos-private-api` Cargo feature, which is enabled by setting
2062  ///   `app > macOSPrivateApi` to `true` in the configuration file.
2063  ///   **WARNING:** Using private APIs on macOS prevents your application from being accepted to the App Store.
2064  ///   If you only need a translucent background, use `windowEffects` instead, which relies on public APIs.
2065  /// - **Windows**: Using `noRedirectionBitmap` can help avoid a white flash when creating a transparent window.
2066  #[serde(default)]
2067  pub transparent: bool,
2068  /// Whether the window is maximized or not.
2069  #[serde(default)]
2070  pub maximized: bool,
2071  /// Whether the window is visible or not.
2072  #[serde(default = "default_true")]
2073  pub visible: bool,
2074  /// Whether the window should have borders and bars.
2075  #[serde(default = "default_true")]
2076  pub decorations: bool,
2077  /// Whether the window should always be below other windows.
2078  #[serde(default, alias = "always-on-bottom")]
2079  pub always_on_bottom: bool,
2080  /// Whether the window should always be on top of other windows.
2081  #[serde(default, alias = "always-on-top")]
2082  pub always_on_top: bool,
2083  /// Whether the window should be visible on all workspaces or virtual desktops.
2084  ///
2085  /// ## Platform-specific
2086  ///
2087  /// - **Windows / iOS / Android:** Unsupported.
2088  #[serde(default, alias = "visible-on-all-workspaces")]
2089  pub visible_on_all_workspaces: bool,
2090  /// Prevents the window contents from being captured by other apps.
2091  #[serde(default, alias = "content-protected")]
2092  pub content_protected: bool,
2093  /// If `true`, hides the window icon from the taskbar on Windows and Linux.
2094  #[serde(default, alias = "skip-taskbar")]
2095  pub skip_taskbar: bool,
2096  /// The name of the window class created on Windows to create the window. **Windows only**.
2097  pub window_classname: Option<String>,
2098  /// This sets `WS_EX_NOREDIRECTIONBITMAP`.
2099  ///
2100  /// This can avoid the white flash that may appear before the webview content is rendered
2101  /// when using a transparent window. **Windows only**.
2102  #[serde(default, alias = "no-redirection-bitmap")]
2103  pub no_redirection_bitmap: bool,
2104  /// The initial window theme. Defaults to the system theme. Only implemented on Windows and macOS 10.14+.
2105  pub theme: Option<crate::Theme>,
2106  /// The style of the macOS title bar.
2107  #[serde(default, alias = "title-bar-style")]
2108  pub title_bar_style: TitleBarStyle,
2109  /// The position of the window controls on macOS.
2110  ///
2111  /// Requires titleBarStyle: Overlay and decorations: true.
2112  #[serde(default, alias = "traffic-light-position")]
2113  pub traffic_light_position: Option<LogicalPosition>,
2114  /// If `true`, sets the window title to be hidden on macOS.
2115  #[serde(default, alias = "hidden-title")]
2116  pub hidden_title: bool,
2117  /// Whether clicking an inactive window also clicks through to the webview on macOS.
2118  #[serde(default, alias = "accept-first-mouse")]
2119  pub accept_first_mouse: bool,
2120  /// Defines the window [tabbing identifier] for macOS.
2121  ///
2122  /// Windows with matching tabbing identifiers will be grouped together.
2123  /// If the tabbing identifier is not set, automatic tabbing will be disabled.
2124  ///
2125  /// [tabbing identifier]: <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier>
2126  #[serde(default, alias = "tabbing-identifier")]
2127  pub tabbing_identifier: Option<String>,
2128  /// Defines additional browser arguments on Windows.
2129  ///
2130  /// ## Warning
2131  ///
2132  /// Webview instances with different browser arguments must also have different [data directories](Self::data_directory).
2133  ///
2134  /// By default wry passes `--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection`
2135  /// so if you set this, you also need to disable these components by yourself if you want.
2136  #[serde(default, alias = "additional-browser-args")]
2137  pub additional_browser_args: Option<String>,
2138  /// Whether or not the window has shadow.
2139  ///
2140  /// ## Platform-specific
2141  ///
2142  /// - **Windows:**
2143  ///   - `false` has no effect on decorated window, shadow are always ON.
2144  ///   - `true` will make undecorated window have a 1px white border,
2145  /// and on Windows 11, it will have a rounded corners.
2146  /// - **Linux:** Unsupported.
2147  #[serde(default = "default_true")]
2148  pub shadow: bool,
2149  /// Window effects.
2150  ///
2151  /// Requires the window to be transparent.
2152  ///
2153  /// ## Platform-specific:
2154  ///
2155  /// - **Windows**: If using decorations or shadows, you may want to try this workaround <https://github.com/tauri-apps/tao/issues/72#issuecomment-975607891>
2156  /// - **Linux**: Unsupported
2157  #[serde(default, alias = "window-effects")]
2158  pub window_effects: Option<WindowEffectsConfig>,
2159  /// Whether or not the webview should be launched in incognito  mode.
2160  ///
2161  /// ## Platform-specific:
2162  ///
2163  /// - **Android**: Unsupported.
2164  #[serde(default)]
2165  pub incognito: bool,
2166  /// Sets the window associated with this label to be the parent of the window to be created.
2167  ///
2168  /// ## Platform-specific
2169  ///
2170  /// - **Windows**: This sets the passed parent as an owner window to the window to be created.
2171  ///   From [MSDN owned windows docs](https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows):
2172  ///     - An owned window is always above its owner in the z-order.
2173  ///     - The system automatically destroys an owned window when its owner is destroyed.
2174  ///     - An owned window is hidden when its owner is minimized.
2175  /// - **Linux**: This makes the new window transient for parent, see <https://docs.gtk.org/gtk3/method.Window.set_transient_for.html>
2176  /// - **macOS**: This adds the window as a child of parent, see <https://developer.apple.com/documentation/appkit/nswindow/1419152-addchildwindow?language=objc>
2177  pub parent: Option<String>,
2178  /// The proxy URL for the WebView for all network requests.
2179  ///
2180  /// Must be either a `http://` or a `socks5://` URL.
2181  ///
2182  /// ## Platform-specific
2183  ///
2184  /// - **macOS**: Requires the `macos-proxy` feature flag and only compiles for macOS 14+.
2185  #[serde(alias = "proxy-url")]
2186  pub proxy_url: Option<Url>,
2187  /// Whether page zooming by hotkeys is enabled
2188  ///
2189  /// ## Platform-specific:
2190  ///
2191  /// - **Windows**: Controls WebView2's [`IsZoomControlEnabled`](https://learn.microsoft.com/en-us/microsoft-edge/webview2/reference/winrt/microsoft_web_webview2_core/corewebview2settings?view=webview2-winrt-1.0.2420.47#iszoomcontrolenabled) setting.
2192  /// - **MacOS / Linux**: Injects a polyfill that zooms in and out with `ctrl/command` + `-/=`,
2193  /// 20% in each step, ranging from 20% to 1000%. Requires `webview:allow-set-webview-zoom` permission
2194  ///
2195  /// - **Android / iOS**: Unsupported.
2196  #[serde(default, alias = "zoom-hotkeys-enabled")]
2197  pub zoom_hotkeys_enabled: bool,
2198  /// Whether browser extensions can be installed for the webview process
2199  ///
2200  /// ## Platform-specific:
2201  ///
2202  /// - **Windows**: Enables the WebView2 environment's [`AreBrowserExtensionsEnabled`](https://learn.microsoft.com/en-us/microsoft-edge/webview2/reference/winrt/microsoft_web_webview2_core/corewebview2environmentoptions?view=webview2-winrt-1.0.2739.15#arebrowserextensionsenabled)
2203  /// - **MacOS / Linux / iOS / Android** - Unsupported.
2204  #[serde(default, alias = "browser-extensions-enabled")]
2205  pub browser_extensions_enabled: bool,
2206
2207  /// Sets whether the custom protocols should use `https://<scheme>.localhost` instead of the default `http://<scheme>.localhost` on Windows and Android. Defaults to `false`.
2208  ///
2209  /// ## Note
2210  ///
2211  /// Using a `https` scheme will NOT allow mixed content when trying to fetch `http` endpoints and therefore will not match the behavior of the `<scheme>://localhost` protocols used on macOS and Linux.
2212  ///
2213  /// ## Warning
2214  ///
2215  /// Changing this value between releases will change the IndexedDB, cookies and localstorage location and your app will not be able to access the old data.
2216  #[serde(default, alias = "use-https-scheme")]
2217  pub use_https_scheme: bool,
2218  /// Enable web inspector which is usually called browser devtools. Enabled by default.
2219  ///
2220  /// This API works in **debug** builds, but requires `devtools` feature flag to enable it in **release** builds.
2221  ///
2222  /// ## Platform-specific
2223  ///
2224  /// - macOS: This will call private functions on **macOS**.
2225  /// - Android: Open `chrome://inspect/#devices` in Chrome to get the devtools window. Wry's `WebView` devtools API isn't supported on Android.
2226  /// - iOS: Open Safari > Develop > [Your Device Name] > [Your WebView] to get the devtools window.
2227  pub devtools: Option<bool>,
2228
2229  /// Set the window and webview background color.
2230  ///
2231  /// ## Platform-specific:
2232  ///
2233  /// - **Windows**: alpha channel is ignored for the window layer.
2234  /// - **Windows**: On Windows 7, alpha channel is ignored for the webview layer.
2235  /// - **Windows**: On Windows 8 and newer, if alpha channel is not `0`, it will be ignored for the webview layer.
2236  #[serde(alias = "background-color")]
2237  pub background_color: Option<Color>,
2238
2239  /// Change the default background throttling behaviour.
2240  ///
2241  /// By default, browsers use a suspend policy that will throttle timers and even unload
2242  /// the whole tab (view) to free resources after roughly 5 minutes when a view became
2243  /// minimized or hidden. This will pause all tasks until the documents visibility state
2244  /// changes back from hidden to visible by bringing the view back to the foreground.
2245  ///
2246  /// ## Platform-specific
2247  ///
2248  /// - **Linux / Windows / Android**: Unsupported. Workarounds like a pending WebLock transaction might suffice.
2249  /// - **iOS**: Supported since version 17.0+.
2250  /// - **macOS**: Supported since version 14.0+.
2251  ///
2252  /// see <https://github.com/tauri-apps/tauri/issues/5250#issuecomment-2569380578>
2253  #[serde(default, alias = "background-throttling")]
2254  pub background_throttling: Option<BackgroundThrottlingPolicy>,
2255  /// Whether we should disable JavaScript code execution on the webview or not.
2256  #[serde(default, alias = "javascript-disabled")]
2257  pub javascript_disabled: bool,
2258  /// on macOS and iOS there is a link preview on long pressing links, this is enabled by default.
2259  /// see https://docs.rs/objc2-web-kit/latest/objc2_web_kit/struct.WKWebView.html#method.allowsLinkPreview
2260  #[serde(default = "default_true", alias = "allow-link-preview")]
2261  pub allow_link_preview: bool,
2262  /// Allows disabling the input accessory view on iOS.
2263  ///
2264  /// The accessory view is the view that appears above the keyboard when a text input element is focused.
2265  /// It usually displays a view with "Done", "Next" buttons.
2266  #[serde(
2267    default,
2268    alias = "disable-input-accessory-view",
2269    alias = "disable_input_accessory_view"
2270  )]
2271  pub disable_input_accessory_view: bool,
2272  /// Set a custom path for the webview's data directory (localStorage, cache, etc.),
2273  /// **relative to the local data directory (`localDataDir()`), followed by the window label**.
2274  ///
2275  /// To set absolute paths, use [`WebviewWindowBuilder::data_directory`](https://docs.rs/tauri/2/tauri/webview/struct.WebviewWindowBuilder.html#method.data_directory)
2276  ///
2277  /// This path is not affected by the `app > appDirectoriesOverride` config.
2278  /// To keep the webview data in an overridden directory, leave this unset (the webview then uses the app local data directory)
2279  /// or resolve a path from `app.path().app_local_data_dir()` and set it with `WebviewWindowBuilder::data_directory`.
2280  ///
2281  /// #### Platform-specific:
2282  ///
2283  /// - **Windows**: WebViews with different values for settings like `additionalBrowserArgs`, `browserExtensionsEnabled` or `scrollBarStyle` must have different data directories.
2284  /// - **macOS / iOS**: Unsupported, use `dataStoreIdentifier` instead.
2285  /// - **Android**: Unsupported.
2286  #[serde(default, alias = "data-directory")]
2287  pub data_directory: Option<PathBuf>,
2288  /// Initialize the WebView with a custom data store identifier. This can be seen as a replacement for `dataDirectory` which is unavailable in WKWebView.
2289  ///
2290  /// See <https://developer.apple.com/documentation/webkit/wkwebsitedatastore/init(foridentifier:)?language=objc>
2291  ///
2292  /// The array must contain 16 u8 numbers.
2293  ///
2294  /// #### Platform-specific:
2295  ///
2296  /// - **iOS**: Supported since version 17.0+.
2297  /// - **macOS**: Supported since version 14.0+.
2298  /// - **Windows / Linux / Android**: Unsupported.
2299  #[serde(default, alias = "data-store-identifier")]
2300  pub data_store_identifier: Option<[u8; 16]>,
2301
2302  /// Specifies the native scrollbar style to use with the webview.
2303  /// CSS styles that modify the scrollbar are applied on top of the native appearance configured here.
2304  ///
2305  /// Defaults to `default`, which is the browser default.
2306  ///
2307  /// ## Platform-specific
2308  ///
2309  /// - **Windows**:
2310  ///   - `fluentOverlay` requires WebView2 Runtime version 125.0.2535.41 or higher,
2311  ///     and does nothing on older versions.
2312  ///   - This option must be given the same value for all webviews that target the same data directory.
2313  /// - **Linux / Android / iOS / macOS**: Unsupported. Only supports `Default` and performs no operation.
2314  #[serde(default, alias = "scroll-bar-style")]
2315  pub scroll_bar_style: ScrollBarStyle,
2316
2317  /// Whether to limit navigations to App-Bound Domains.
2318  ///
2319  /// This is required to enable Service Workers in WKWebView, which are otherwise
2320  /// unavailable. Defaults to `false`.
2321  ///
2322  /// When this is set to `true`, the webview can only navigate to the domains listed in the
2323  /// `WKAppBoundDomains` array of `src-tauri/Info.ios.plist`. Add `localhost` and every
2324  /// [registrable domain](https://developer.mozilla.org/en-US/docs/Glossary/Registrable_domain)
2325  /// this webview loads to that array:
2326  ///
2327  /// ```xml
2328  /// <plist>
2329  /// <dict>
2330  ///     <key>WKAppBoundDomains</key>
2331  ///     <array>
2332  ///         <string>localhost</string>
2333  ///         <string>aregistrabledomain.example</string>
2334  ///     </array>
2335  /// </dict>
2336  /// </plist>
2337  /// ```
2338  ///
2339  /// `localhost` must be listed if any webview with this option enabled opens a local webpage,
2340  /// makes any localhost call, or uses the isolation pattern, because Tauri serves the
2341  /// application webpage, the IPC protocol and the isolation pattern iframe from the
2342  /// `localhost` domain.
2343  ///
2344  /// Requests served through custom URI schemes are allowed as long as they use a registrable
2345  /// domain listed in the `WKAppBoundDomains` array, including requests to the `localhost`
2346  /// domain.
2347  ///
2348  /// An entire URI scheme can be listed by adding the protocol name followed by a colon, for
2349  /// example `stream:` for a custom `stream` scheme (see the
2350  /// [streaming example](https://github.com/tauri-apps/tauri/blob/dev/examples/streaming/main.rs)).
2351  /// This is not covered by Apple's
2352  /// [App-Bound Domains announcement](https://webkit.org/blog/10882/app-bound-domains/),
2353  /// so it may not be accepted during App Store review.
2354  ///
2355  /// See <https://webkit.org/blog/10882/app-bound-domains/> and
2356  /// <https://developer.apple.com/documentation/webkit/wkwebviewconfiguration/limitsnavigationstoappbounddomains>
2357  /// for the official documentation on App-Bound Domains.
2358  ///
2359  /// ## Platform-specific
2360  ///
2361  /// - **iOS**: Supported since version 14.0+.
2362  /// - **Linux / Windows / Android / macOS:** Unsupported.
2363  #[serde(default, alias = "limit-navigations-to-app-bound-domains")]
2364  pub limit_navigations_to_app_bound_domains: bool,
2365  /// The name of the Android activity to create for this window.
2366  #[serde(default, alias = "activity-name")]
2367  pub activity_name: Option<String>,
2368  /// The name of the Android activity that is creating this webview window.
2369  ///
2370  /// This is important to determine which stack the activity will belong to.
2371  #[serde(default, alias = "created-by-activity-name")]
2372  pub created_by_activity_name: Option<String>,
2373
2374  /// Sets the identifier of the scene that is requesting the new scene,
2375  /// establishing a relationship between the two scenes.
2376  ///
2377  /// By default the system uses the foreground scene.
2378  #[serde(default, alias = "requested-by-scene-identifier")]
2379  pub requested_by_scene_identifier: Option<String>,
2380  /// Controls the WebView's browser-level general autofill behavior.
2381  ///
2382  /// **This option does not disable password or credit card autofill.**
2383  ///
2384  /// When set to `false`, the WebView will not automatically populate
2385  /// general form fields using previously stored data such as addresses
2386  /// or contact information.
2387  ///
2388  /// If not specified, this is `true` by default.
2389  ///
2390  /// ## Platform-specific
2391  ///
2392  /// - **Windows**: Supported. WebView2's autofill feature (called
2393  ///   "Suggestions") may not honor `autocomplete="off"` on input
2394  ///   elements in some cases.
2395  /// - **Linux / Android / iOS / macOS**: Unsupported and performs no
2396  ///   operation.
2397  #[serde(default = "default_true", alias = "general-autofill-enabled")]
2398  pub general_autofill_enabled: bool,
2399}
2400
2401impl Default for WindowConfig {
2402  fn default() -> Self {
2403    Self {
2404      label: default_window_label(),
2405      url: WebviewUrl::default(),
2406      create: true,
2407      user_agent: None,
2408      drag_drop_enabled: true,
2409      center: false,
2410      x: None,
2411      y: None,
2412      width: default_width(),
2413      height: default_height(),
2414      min_width: None,
2415      min_height: None,
2416      max_width: None,
2417      max_height: None,
2418      prevent_overflow: None,
2419      resizable: true,
2420      maximizable: true,
2421      minimizable: true,
2422      closable: true,
2423      title: default_title(),
2424      fullscreen: false,
2425      focus: true,
2426      focusable: true,
2427      transparent: false,
2428      maximized: false,
2429      visible: true,
2430      decorations: true,
2431      always_on_bottom: false,
2432      always_on_top: false,
2433      visible_on_all_workspaces: false,
2434      content_protected: false,
2435      skip_taskbar: false,
2436      window_classname: None,
2437      no_redirection_bitmap: false,
2438      theme: None,
2439      title_bar_style: Default::default(),
2440      traffic_light_position: None,
2441      hidden_title: false,
2442      accept_first_mouse: false,
2443      tabbing_identifier: None,
2444      additional_browser_args: None,
2445      shadow: true,
2446      window_effects: None,
2447      incognito: false,
2448      parent: None,
2449      proxy_url: None,
2450      zoom_hotkeys_enabled: false,
2451      browser_extensions_enabled: false,
2452      use_https_scheme: false,
2453      devtools: None,
2454      background_color: None,
2455      background_throttling: None,
2456      javascript_disabled: false,
2457      allow_link_preview: true,
2458      disable_input_accessory_view: false,
2459      data_directory: None,
2460      data_store_identifier: None,
2461      scroll_bar_style: ScrollBarStyle::Default,
2462      limit_navigations_to_app_bound_domains: false,
2463      activity_name: None,
2464      created_by_activity_name: None,
2465      requested_by_scene_identifier: None,
2466      general_autofill_enabled: true,
2467    }
2468  }
2469}
2470
2471fn default_window_label() -> String {
2472  "main".to_string()
2473}
2474
2475fn default_width() -> f64 {
2476  800.
2477}
2478
2479fn default_height() -> f64 {
2480  600.
2481}
2482
2483fn default_title() -> String {
2484  "Tauri App".to_string()
2485}
2486
2487/// A Content-Security-Policy directive source list.
2488/// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/Sources#sources>.
2489#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
2490#[cfg_attr(feature = "schema", derive(JsonSchema))]
2491#[serde(rename_all = "camelCase", untagged)]
2492pub enum CspDirectiveSources {
2493  /// An inline list of CSP sources. Same as [`Self::List`], but concatenated with a space separator.
2494  Inline(String),
2495  /// A list of CSP sources. The collection will be concatenated with a space separator for the CSP string.
2496  List(Vec<String>),
2497}
2498
2499impl Default for CspDirectiveSources {
2500  fn default() -> Self {
2501    Self::List(Vec::new())
2502  }
2503}
2504
2505impl From<CspDirectiveSources> for Vec<String> {
2506  fn from(sources: CspDirectiveSources) -> Self {
2507    match sources {
2508      CspDirectiveSources::Inline(source) => source.split(' ').map(|s| s.to_string()).collect(),
2509      CspDirectiveSources::List(l) => l,
2510    }
2511  }
2512}
2513
2514impl CspDirectiveSources {
2515  /// Whether the given source is configured on this directive or not.
2516  pub fn contains(&self, source: &str) -> bool {
2517    match self {
2518      Self::Inline(s) => s.contains(&format!("{source} ")) || s.contains(&format!(" {source}")),
2519      Self::List(l) => l.contains(&source.into()),
2520    }
2521  }
2522
2523  /// Appends the given source to this directive.
2524  pub fn push<S: AsRef<str>>(&mut self, source: S) {
2525    match self {
2526      Self::Inline(s) => {
2527        s.push(' ');
2528        s.push_str(source.as_ref());
2529      }
2530      Self::List(l) => {
2531        l.push(source.as_ref().to_string());
2532      }
2533    }
2534  }
2535
2536  /// Extends this CSP directive source list with the given array of sources.
2537  pub fn extend(&mut self, sources: Vec<String>) {
2538    for s in sources {
2539      self.push(s);
2540    }
2541  }
2542}
2543
2544/// A Content-Security-Policy definition.
2545/// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP>.
2546#[derive(Debug, PartialEq, Eq, Clone, Deserialize)]
2547#[cfg_attr(feature = "schema", derive(JsonSchema))]
2548#[serde(rename_all = "camelCase", untagged)]
2549pub enum Csp {
2550  /// The entire CSP policy in a single text string.
2551  Policy(String),
2552  /// An object mapping a directive with its sources values as a list of strings.
2553  DirectiveMap(HashMap<String, CspDirectiveSources>),
2554}
2555
2556impl Serialize for Csp {
2557  fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2558  where
2559    S: Serializer,
2560  {
2561    match self {
2562      Self::Policy(policy) => serializer.serialize_str(policy),
2563      Self::DirectiveMap(map) => {
2564        // Serialize through `BTreeMap` so the output is deterministic
2565        // see: https://github.com/tauri-apps/tauri/issues/14978
2566        // TODO: Remove this in v3, use a BTreeMap instead of a HashMap
2567        let btree_map: BTreeMap<_, _> = map.iter().collect();
2568        btree_map.serialize(serializer)
2569      }
2570    }
2571  }
2572}
2573
2574impl From<HashMap<String, CspDirectiveSources>> for Csp {
2575  fn from(map: HashMap<String, CspDirectiveSources>) -> Self {
2576    Self::DirectiveMap(map)
2577  }
2578}
2579
2580impl From<Csp> for HashMap<String, CspDirectiveSources> {
2581  fn from(csp: Csp) -> Self {
2582    match csp {
2583      Csp::Policy(policy) => {
2584        let mut map = HashMap::new();
2585        for directive in policy.split(';') {
2586          let mut tokens = directive.trim().split(' ');
2587          if let Some(directive) = tokens.next() {
2588            let sources = tokens.map(|s| s.to_string()).collect::<Vec<String>>();
2589            map.insert(directive.to_string(), CspDirectiveSources::List(sources));
2590          }
2591        }
2592        map
2593      }
2594      Csp::DirectiveMap(m) => m,
2595    }
2596  }
2597}
2598
2599impl Display for Csp {
2600  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2601    match self {
2602      Self::Policy(s) => write!(f, "{s}"),
2603      Self::DirectiveMap(m) => {
2604        let len = m.len();
2605        let mut i = 0;
2606        for (directive, sources) in m {
2607          let sources: Vec<String> = sources.clone().into();
2608          write!(f, "{} {}", directive, sources.join(" "))?;
2609          i += 1;
2610          if i != len {
2611            write!(f, "; ")?;
2612          }
2613        }
2614        Ok(())
2615      }
2616    }
2617  }
2618}
2619
2620/// The possible values for the `dangerous_disable_asset_csp_modification` config option.
2621#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
2622#[serde(untagged)]
2623#[cfg_attr(feature = "schema", derive(JsonSchema))]
2624pub enum DisabledCspModificationKind {
2625  /// If `true`, disables all CSP modification.
2626  /// `false` is the default value and it configures Tauri to control the CSP.
2627  Flag(bool),
2628  /// Disables the given list of CSP directives modifications.
2629  List(Vec<String>),
2630}
2631
2632impl DisabledCspModificationKind {
2633  /// Determines whether the given CSP directive can be modified or not.
2634  pub fn can_modify(&self, directive: &str) -> bool {
2635    match self {
2636      Self::Flag(f) => !f,
2637      Self::List(l) => !l.contains(&directive.into()),
2638    }
2639  }
2640}
2641
2642impl Default for DisabledCspModificationKind {
2643  fn default() -> Self {
2644    Self::Flag(false)
2645  }
2646}
2647
2648/// Protocol scope definition.
2649/// It is a list of glob patterns that restrict the API access from the webview.
2650///
2651/// Each pattern can start with a variable that resolves to a system base directory.
2652/// The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`,
2653/// `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`,
2654/// `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$TEMP`,
2655/// `$APPCONFIG`, `$APPDATA`, `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.
2656#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
2657#[serde(untagged)]
2658#[cfg_attr(feature = "schema", derive(JsonSchema))]
2659pub enum FsScope {
2660  /// A list of paths that are allowed by this scope.
2661  AllowedPaths(Vec<PathBuf>),
2662  /// A complete scope configuration.
2663  #[serde(rename_all = "camelCase")]
2664  Scope {
2665    /// A list of paths that are allowed by this scope.
2666    #[serde(default)]
2667    allow: Vec<PathBuf>,
2668    /// A list of paths that are not allowed by this scope.
2669    /// This gets precedence over the [`Self::Scope::allow`] list.
2670    #[serde(default)]
2671    deny: Vec<PathBuf>,
2672    /// Whether or not paths that contain components that start with a `.`
2673    /// will require that `.` appears literally in the pattern; `*`, `?`, `**`,
2674    /// or `[...]` will not match. This is useful because such files are
2675    /// conventionally considered hidden on Unix systems and it might be
2676    /// desirable to skip them when listing files.
2677    ///
2678    /// Defaults to `true` on Unix systems and `false` on Windows
2679    // dotfiles are not supposed to be exposed by default on unix
2680    #[serde(alias = "require-literal-leading-dot")]
2681    require_literal_leading_dot: Option<bool>,
2682  },
2683}
2684
2685impl Default for FsScope {
2686  fn default() -> Self {
2687    Self::AllowedPaths(Vec::new())
2688  }
2689}
2690
2691impl FsScope {
2692  /// The list of allowed paths.
2693  pub fn allowed_paths(&self) -> &Vec<PathBuf> {
2694    match self {
2695      Self::AllowedPaths(p) => p,
2696      Self::Scope { allow, .. } => allow,
2697    }
2698  }
2699
2700  /// The list of forbidden paths.
2701  pub fn forbidden_paths(&self) -> Option<&Vec<PathBuf>> {
2702    match self {
2703      Self::AllowedPaths(_) => None,
2704      Self::Scope { deny, .. } => Some(deny),
2705    }
2706  }
2707}
2708
2709/// Config for the asset custom protocol.
2710///
2711/// See more: <https://v2.tauri.app/reference/config/#assetprotocolconfig>
2712#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
2713#[cfg_attr(feature = "schema", derive(JsonSchema))]
2714#[serde(rename_all = "camelCase", deny_unknown_fields)]
2715pub struct AssetProtocolConfig {
2716  /// The access scope for the asset protocol.
2717  #[serde(default)]
2718  pub scope: FsScope,
2719  /// Enables the asset protocol.
2720  #[serde(default)]
2721  pub enable: bool,
2722}
2723
2724/// definition of a header source
2725///
2726/// The header value to a header name
2727#[derive(Debug, PartialEq, Eq, Clone, Deserialize)]
2728#[cfg_attr(feature = "schema", derive(JsonSchema))]
2729#[serde(rename_all = "camelCase", untagged)]
2730pub enum HeaderSource {
2731  /// string version of the header Value
2732  Inline(String),
2733  /// list version of the header value. Item are joined by "," for the real header value
2734  List(Vec<String>),
2735  /// (Rust struct | Json | JavaScript Object) equivalent of the header value. Items are composed from: key + space + value. Item are then joined by ";" for the real header value
2736  Map(HashMap<String, String>),
2737}
2738
2739impl Serialize for HeaderSource {
2740  fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2741  where
2742    S: Serializer,
2743  {
2744    match self {
2745      Self::Inline(s) => serializer.serialize_str(s),
2746      Self::List(l) => l.serialize(serializer),
2747      Self::Map(m) => {
2748        // Serialize through `BTreeMap` so the output is deterministic
2749        // see: https://github.com/tauri-apps/tauri/issues/14978
2750        // TODO: Remove this in v3, use a BTreeMap instead of a HashMap
2751        let btree_map: BTreeMap<_, _> = m.iter().collect();
2752        btree_map.serialize(serializer)
2753      }
2754    }
2755  }
2756}
2757
2758impl Display for HeaderSource {
2759  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2760    match self {
2761      Self::Inline(s) => write!(f, "{s}"),
2762      Self::List(l) => write!(f, "{}", l.join(", ")),
2763      Self::Map(m) => {
2764        // Format through `BTreeMap` so the resulting header value is deterministic
2765        // see: https://github.com/tauri-apps/tauri/issues/14978
2766        // TODO: Remove this in v3, use a BTreeMap instead of a HashMap
2767        let map: BTreeMap<_, _> = m.iter().collect();
2768        let len = map.len();
2769        for (i, (key, value)) in map.into_iter().enumerate() {
2770          write!(f, "{key} {value}")?;
2771          if i + 1 != len {
2772            write!(f, "; ")?;
2773          }
2774        }
2775        Ok(())
2776      }
2777    }
2778  }
2779}
2780
2781/// A trait which implements on the [`Builder`] of the http create
2782///
2783/// Must add headers defined in the tauri configuration file to http responses
2784pub trait HeaderAddition {
2785  /// adds all headers defined on the config file, given the current HeaderConfig
2786  fn add_configured_headers(self, headers: Option<&HeaderConfig>) -> http::response::Builder;
2787}
2788
2789impl HeaderAddition for Builder {
2790  /// Add the headers defined in the tauri configuration file to http responses
2791  ///
2792  /// this is a utility function, which is used in the same way as the `.header(..)` of the rust http library
2793  fn add_configured_headers(mut self, headers: Option<&HeaderConfig>) -> http::response::Builder {
2794    if let Some(headers) = headers {
2795      // Add the header Access-Control-Allow-Credentials, if we find a value for it
2796      if let Some(value) = &headers.access_control_allow_credentials {
2797        self = self.header("Access-Control-Allow-Credentials", value.to_string());
2798      };
2799
2800      // Add the header Access-Control-Allow-Headers, if we find a value for it
2801      if let Some(value) = &headers.access_control_allow_headers {
2802        self = self.header("Access-Control-Allow-Headers", value.to_string());
2803      };
2804
2805      // Add the header Access-Control-Allow-Methods, if we find a value for it
2806      if let Some(value) = &headers.access_control_allow_methods {
2807        self = self.header("Access-Control-Allow-Methods", value.to_string());
2808      };
2809
2810      // Add the header Access-Control-Expose-Headers, if we find a value for it
2811      if let Some(value) = &headers.access_control_expose_headers {
2812        self = self.header("Access-Control-Expose-Headers", value.to_string());
2813      };
2814
2815      // Add the header Access-Control-Max-Age, if we find a value for it
2816      if let Some(value) = &headers.access_control_max_age {
2817        self = self.header("Access-Control-Max-Age", value.to_string());
2818      };
2819
2820      // Add the header Cross-Origin-Embedder-Policy, if we find a value for it
2821      if let Some(value) = &headers.cross_origin_embedder_policy {
2822        self = self.header("Cross-Origin-Embedder-Policy", value.to_string());
2823      };
2824
2825      // Add the header Cross-Origin-Opener-Policy, if we find a value for it
2826      if let Some(value) = &headers.cross_origin_opener_policy {
2827        self = self.header("Cross-Origin-Opener-Policy", value.to_string());
2828      };
2829
2830      // Add the header Cross-Origin-Resource-Policy, if we find a value for it
2831      if let Some(value) = &headers.cross_origin_resource_policy {
2832        self = self.header("Cross-Origin-Resource-Policy", value.to_string());
2833      };
2834
2835      // Add the header Permissions-Policy, if we find a value for it
2836      if let Some(value) = &headers.permissions_policy {
2837        self = self.header("Permissions-Policy", value.to_string());
2838      };
2839
2840      if let Some(value) = &headers.service_worker_allowed {
2841        self = self.header("Service-Worker-Allowed", value.to_string());
2842      }
2843
2844      // Add the header Timing-Allow-Origin, if we find a value for it
2845      if let Some(value) = &headers.timing_allow_origin {
2846        self = self.header("Timing-Allow-Origin", value.to_string());
2847      };
2848
2849      // Add the header X-Content-Type-Options, if we find a value for it
2850      if let Some(value) = &headers.x_content_type_options {
2851        self = self.header("X-Content-Type-Options", value.to_string());
2852      };
2853
2854      // Add the header Tauri-Custom-Header, if we find a value for it
2855      if let Some(value) = &headers.tauri_custom_header {
2856        // Keep in mind to correctly set the Access-Control-Expose-Headers
2857        self = self.header("Tauri-Custom-Header", value.to_string());
2858      };
2859    }
2860    self
2861  }
2862}
2863
2864/// A struct, where the keys are some specific http header names.
2865///
2866/// If the values to those keys are defined, then they will be send as part of a response message.
2867/// This does not include error messages and ipc messages
2868///
2869/// ## Example configuration
2870/// ```javascript
2871/// {
2872///  //..
2873///   app:{
2874///     //..
2875///     security: {
2876///       headers: {
2877///         "Cross-Origin-Opener-Policy": "same-origin",
2878///         "Cross-Origin-Embedder-Policy": "require-corp",
2879///         "Timing-Allow-Origin": [
2880///           "https://developer.mozilla.org",
2881///           "https://example.com",
2882///         ],
2883///         "Access-Control-Expose-Headers": "Tauri-Custom-Header",
2884///         "Tauri-Custom-Header": {
2885///           "key1": "'value1' 'value2'",
2886///           "key2": "'value3'"
2887///         }
2888///       },
2889///       csp: "default-src 'self'; connect-src ipc: http://ipc.localhost",
2890///     }
2891///     //..
2892///   }
2893///  //..
2894/// }
2895/// ```
2896/// In this example `Cross-Origin-Opener-Policy` and `Cross-Origin-Embedder-Policy` are set to allow for the use of [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer).
2897/// The result is, that those headers are then set on every response sent via the `get_response` function in crates/tauri/src/protocol/tauri.rs.
2898/// The Content-Security-Policy header is defined separately, because it is also handled separately.
2899///
2900/// For the helloworld example, this config translates into those response headers:
2901/// ```http
2902/// access-control-allow-origin:  http://tauri.localhost
2903/// access-control-expose-headers: Tauri-Custom-Header
2904/// content-security-policy: default-src 'self'; connect-src ipc: http://ipc.localhost; script-src 'self' 'sha256-Wjjrs6qinmnr+tOry8x8PPwI77eGpUFR3EEGZktjJNs='
2905/// content-type: text/html
2906/// cross-origin-embedder-policy: require-corp
2907/// cross-origin-opener-policy: same-origin
2908/// tauri-custom-header: key1 'value1' 'value2'; key2 'value3'
2909/// timing-allow-origin: https://developer.mozilla.org, https://example.com
2910/// ```
2911/// Since the resulting header values are always 'string-like'. So depending on the what data type the HeaderSource is, they need to be converted.
2912///  - `String`(JS/Rust): stay the same for the resulting header value
2913///  - `Array`(JS)/`Vec\<String\>`(Rust): Item are joined by ", " for the resulting header value
2914///  - `Object`(JS)/ `Hashmap\<String,String\>`(Rust): Items are composed from: key + space + value. Item are then joined by "; " for the resulting header value
2915#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
2916#[cfg_attr(feature = "schema", derive(JsonSchema))]
2917#[serde(deny_unknown_fields)]
2918pub struct HeaderConfig {
2919  /// The Access-Control-Allow-Credentials response header tells browsers whether the
2920  /// server allows cross-origin HTTP requests to include credentials.
2921  ///
2922  /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials>
2923  #[serde(rename = "Access-Control-Allow-Credentials")]
2924  pub access_control_allow_credentials: Option<HeaderSource>,
2925  /// The Access-Control-Allow-Headers response header is used in response
2926  /// to a preflight request which includes the Access-Control-Request-Headers
2927  /// to indicate which HTTP headers can be used during the actual request.
2928  ///
2929  /// This header is required if the request has an Access-Control-Request-Headers header.
2930  ///
2931  /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers>
2932  #[serde(rename = "Access-Control-Allow-Headers")]
2933  pub access_control_allow_headers: Option<HeaderSource>,
2934  /// The Access-Control-Allow-Methods response header specifies one or more methods
2935  /// allowed when accessing a resource in response to a preflight request.
2936  ///
2937  /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods>
2938  #[serde(rename = "Access-Control-Allow-Methods")]
2939  pub access_control_allow_methods: Option<HeaderSource>,
2940  /// The Access-Control-Expose-Headers response header allows a server to indicate
2941  /// which response headers should be made available to scripts running in the browser,
2942  /// in response to a cross-origin request.
2943  ///
2944  /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers>
2945  #[serde(rename = "Access-Control-Expose-Headers")]
2946  pub access_control_expose_headers: Option<HeaderSource>,
2947  /// The Access-Control-Max-Age response header indicates how long the results of a
2948  /// preflight request (that is the information contained in the
2949  /// Access-Control-Allow-Methods and Access-Control-Allow-Headers headers) can
2950  /// be cached.
2951  ///
2952  /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age>
2953  #[serde(rename = "Access-Control-Max-Age")]
2954  pub access_control_max_age: Option<HeaderSource>,
2955  /// The HTTP Cross-Origin-Embedder-Policy (COEP) response header configures embedding
2956  /// cross-origin resources into the document.
2957  ///
2958  /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy>
2959  #[serde(rename = "Cross-Origin-Embedder-Policy")]
2960  pub cross_origin_embedder_policy: Option<HeaderSource>,
2961  /// The HTTP Cross-Origin-Opener-Policy (COOP) response header allows you to ensure a
2962  /// top-level document does not share a browsing context group with cross-origin documents.
2963  /// COOP will process-isolate your document and potential attackers can't access your global
2964  /// object if they were to open it in a popup, preventing a set of cross-origin attacks dubbed XS-Leaks.
2965  ///
2966  /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy>
2967  #[serde(rename = "Cross-Origin-Opener-Policy")]
2968  pub cross_origin_opener_policy: Option<HeaderSource>,
2969  /// The HTTP Cross-Origin-Resource-Policy response header conveys a desire that the
2970  /// browser blocks no-cors cross-origin/cross-site requests to the given resource.
2971  ///
2972  /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Resource-Policy>
2973  #[serde(rename = "Cross-Origin-Resource-Policy")]
2974  pub cross_origin_resource_policy: Option<HeaderSource>,
2975  /// The HTTP Permissions-Policy header provides a mechanism to allow and deny the
2976  /// use of browser features in a document or within any \<iframe\> elements in the document.
2977  ///
2978  /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy>
2979  #[serde(rename = "Permissions-Policy")]
2980  pub permissions_policy: Option<HeaderSource>,
2981  /// The HTTP Service-Worker-Allowed response header is used to broaden the path restriction for a
2982  /// service worker's default scope.
2983  ///
2984  /// By default, the scope for a service worker registration is the directory where the service
2985  /// worker script is located. For example, if the script `sw.js` is located in `/js/sw.js`,
2986  /// it can only control URLs under `/js/` by default. Servers can use the `Service-Worker-Allowed`
2987  /// header to allow a service worker to control URLs outside of its own directory.
2988  ///
2989  /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Service-Worker-Allowed>
2990  #[serde(rename = "Service-Worker-Allowed")]
2991  pub service_worker_allowed: Option<HeaderSource>,
2992  /// The Timing-Allow-Origin response header specifies origins that are allowed to see values
2993  /// of attributes retrieved via features of the Resource Timing API, which would otherwise be
2994  /// reported as zero due to cross-origin restrictions.
2995  ///
2996  /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Timing-Allow-Origin>
2997  #[serde(rename = "Timing-Allow-Origin")]
2998  pub timing_allow_origin: Option<HeaderSource>,
2999  /// The X-Content-Type-Options response HTTP header is a marker used by the server to indicate
3000  /// that the MIME types advertised in the Content-Type headers should be followed and not be
3001  /// changed. The header allows you to avoid MIME type sniffing by saying that the MIME types
3002  /// are deliberately configured.
3003  ///
3004  /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options>
3005  #[serde(rename = "X-Content-Type-Options")]
3006  pub x_content_type_options: Option<HeaderSource>,
3007  /// A custom header field Tauri-Custom-Header, don't use it.
3008  /// Remember to set Access-Control-Expose-Headers accordingly
3009  ///
3010  /// **NOT INTENDED FOR PRODUCTION USE**
3011  #[serde(rename = "Tauri-Custom-Header")]
3012  pub tauri_custom_header: Option<HeaderSource>,
3013}
3014
3015impl HeaderConfig {
3016  /// creates a new header config
3017  pub fn new() -> Self {
3018    HeaderConfig {
3019      access_control_allow_credentials: None,
3020      access_control_allow_methods: None,
3021      access_control_allow_headers: None,
3022      access_control_expose_headers: None,
3023      access_control_max_age: None,
3024      cross_origin_embedder_policy: None,
3025      cross_origin_opener_policy: None,
3026      cross_origin_resource_policy: None,
3027      permissions_policy: None,
3028      service_worker_allowed: None,
3029      timing_allow_origin: None,
3030      x_content_type_options: None,
3031      tauri_custom_header: None,
3032    }
3033  }
3034}
3035
3036/// Security configuration.
3037///
3038/// See more: <https://v2.tauri.app/reference/config/#securityconfig>
3039#[skip_serializing_none]
3040#[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
3041#[cfg_attr(feature = "schema", derive(JsonSchema))]
3042#[serde(rename_all = "camelCase", deny_unknown_fields)]
3043pub struct SecurityConfig {
3044  /// The Content Security Policy that will be injected on all HTML files on the built application.
3045  /// If `devCsp` is not specified, this value is also injected on dev.
3046  ///
3047  /// This is a really important part of the configuration since it helps you ensure your WebView is secured.
3048  /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP>.
3049  pub csp: Option<Csp>,
3050  /// The Content Security Policy that will be injected on all HTML files on development.
3051  ///
3052  /// This is a really important part of the configuration since it helps you ensure your WebView is secured.
3053  /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP>.
3054  #[serde(alias = "dev-csp")]
3055  pub dev_csp: Option<Csp>,
3056  /// Whether `Object.freeze(Object.prototype)` is run as an initialization script on every webview.
3057  ///
3058  /// This hardens the frontend against prototype pollution: once the prototype is frozen,
3059  /// a script cannot add or replace properties on `Object.prototype` and thus cannot tamper
3060  /// with objects it does not own, including the ones used by the Tauri API.
3061  ///
3062  /// The script runs before any of your frontend code, on every webview, regardless of whether
3063  /// the content is served by the custom protocol or by a development server.
3064  ///
3065  /// Defaults to `false`. Note that frontend libraries that extend built-in prototypes
3066  /// (polyfills, some older frameworks) stop working when this is enabled, so test your
3067  /// application with it on before shipping.
3068  #[serde(default, alias = "freeze-prototype")]
3069  pub freeze_prototype: bool,
3070  /// Disables the Tauri-injected CSP sources.
3071  ///
3072  /// At compile time, Tauri parses all the frontend assets and changes the Content-Security-Policy
3073  /// to only allow loading of your own scripts and styles by injecting nonce and hash sources.
3074  /// This stricts your CSP, which may introduce issues when using along with other flexing sources.
3075  ///
3076  /// This configuration option allows both a boolean and a list of strings as value.
3077  /// A boolean instructs Tauri to disable the injection for all CSP injections,
3078  /// and a list of strings indicates the CSP directives that Tauri cannot inject.
3079  ///
3080  /// **WARNING:** Only disable this if you know what you are doing and have properly configured the CSP.
3081  /// Your application might be vulnerable to XSS attacks without this Tauri protection.
3082  #[serde(default, alias = "dangerous-disable-asset-csp-modification")]
3083  pub dangerous_disable_asset_csp_modification: DisabledCspModificationKind,
3084  /// Custom protocol config.
3085  #[serde(default, alias = "asset-protocol")]
3086  pub asset_protocol: AssetProtocolConfig,
3087  /// The application pattern, which defines how the frontend communicates with the Rust core.
3088  ///
3089  /// - `brownfield` (default): the frontend talks to the core directly. Use it unless you need
3090  ///   the extra isolation layer.
3091  /// - `isolation`: every IPC message is routed through a secure JavaScript application you own,
3092  ///   hosted in a sandboxed `<iframe>`, so it can validate or reject messages before they reach
3093  ///   the Rust core. This protects the core from an untrusted or compromised frontend
3094  ///   (for example one that loads third-party scripts), at the cost of an extra build step:
3095  ///   the `dir` value must point at a directory containing the isolation application's `index.html`.
3096  ///
3097  /// See <https://tauri.app/concept/inter-process-communication/isolation/>.
3098  #[serde(default)]
3099  pub pattern: PatternKind,
3100  /// List of capabilities that are enabled on the application.
3101  ///
3102  /// By default (not set or empty list), all capability files from `./capabilities/` are included,
3103  /// by setting values in this entry, you have fine grained control over which capabilities are included
3104  ///
3105  /// You can either reference a capability file defined in `./capabilities/` with its identifier or inline a [`Capability`]
3106  ///
3107  /// ### Example
3108  ///
3109  /// ```json
3110  /// {
3111  ///   "app": {
3112  ///     "security": {
3113  ///       "capabilities": [
3114  ///         "main-window",
3115  ///         {
3116  ///           "identifier": "drag-window",
3117  ///           "permissions": ["core:window:allow-start-dragging"]
3118  ///         }
3119  ///       ]
3120  ///     }
3121  ///   }
3122  /// }
3123  /// ```
3124  #[serde(default)]
3125  pub capabilities: Vec<CapabilityEntry>,
3126  /// The headers, which are added to every http response from tauri to the web view
3127  /// This doesn't include IPC Messages and error responses
3128  #[serde(default)]
3129  pub headers: Option<HeaderConfig>,
3130}
3131
3132/// A capability entry which can be either an inlined capability or a reference to a capability defined on its own file.
3133#[derive(Debug, Clone, PartialEq, Serialize)]
3134#[cfg_attr(feature = "schema", derive(JsonSchema))]
3135#[serde(untagged)]
3136pub enum CapabilityEntry {
3137  /// An inlined capability.
3138  Inlined(Capability),
3139  /// Reference to a capability identifier.
3140  Reference(String),
3141}
3142
3143impl<'de> Deserialize<'de> for CapabilityEntry {
3144  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3145  where
3146    D: Deserializer<'de>,
3147  {
3148    UntaggedEnumVisitor::new()
3149      .string(|string| Ok(Self::Reference(string.to_owned())))
3150      .map(|map| map.deserialize::<Capability>().map(Self::Inlined))
3151      .deserialize(deserializer)
3152  }
3153}
3154
3155/// The application pattern.
3156#[skip_serializing_none]
3157#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize, Default)]
3158#[serde(rename_all = "lowercase", tag = "use", content = "options")]
3159#[cfg_attr(feature = "schema", derive(JsonSchema))]
3160pub enum PatternKind {
3161  /// Brownfield pattern.
3162  #[default]
3163  Brownfield,
3164  /// Isolation pattern. Recommended for security purposes.
3165  Isolation {
3166    /// The dir containing the index.html file that contains the secure isolation application.
3167    dir: PathBuf,
3168  },
3169}
3170
3171/// The base directory variables an [`AppDirectoriesOverride`] path can start with.
3172///
3173/// `$RESOURCE` is excluded because the resource directory is read-only in bundled apps,
3174/// `$EXE`, `$FONT`, `$RUNTIME` and `$TEMPLATE` because they are not available on every desktop platform,
3175/// and the `$APP*` variables because they refer to the directories being overridden.
3176const APP_DIRECTORIES_OVERRIDE_VARIABLES: &[&str] = &[
3177  "$AUDIO",
3178  "$CACHE",
3179  "$CONFIG",
3180  "$DATA",
3181  "$LOCALDATA",
3182  "$DESKTOP",
3183  "$DOCUMENT",
3184  "$DOWNLOAD",
3185  "$HOME",
3186  "$PICTURE",
3187  "$PUBLIC",
3188  "$TEMP",
3189  "$VIDEO",
3190];
3191
3192/// Validates a path used to override an app directory, see [`AppDirectoriesOverride`].
3193fn validate_app_directory_override(path: &Path) -> Result<(), String> {
3194  let mut components = path.components();
3195  let first = components.next();
3196
3197  if let Some(Component::Normal(first)) = first {
3198    if let Some(variable) = first.to_str().filter(|s| s.starts_with('$')) {
3199      if !APP_DIRECTORIES_OVERRIDE_VARIABLES.contains(&variable) {
3200        return Err(format!(
3201          "`{}` starts with the unsupported base directory variable `{variable}`, expected one of {}",
3202          path.display(),
3203          APP_DIRECTORIES_OVERRIDE_VARIABLES
3204            .iter()
3205            .map(|v| format!("`{v}`"))
3206            .collect::<Vec<_>>()
3207            .join(", ")
3208        ));
3209      }
3210      return Ok(());
3211    }
3212  }
3213
3214  // Windows root-relative (`\foo`) and drive-relative (`C:foo`) paths are neither absolute
3215  // nor relative to the executable, so they cannot be resolved predictably
3216  if !path.is_absolute() && (path.has_root() || matches!(first, Some(Component::Prefix(_)))) {
3217    return Err(format!(
3218      "`{}` must be an absolute path, a path relative to the executable or a path starting with a base directory variable",
3219      path.display()
3220    ));
3221  }
3222
3223  Ok(())
3224}
3225
3226/// Overrides the directories returned by the `app_*_dir` path APIs.
3227///
3228/// See the `app > appDirectoriesOverride` config for how each path is resolved.
3229#[derive(Debug, PartialEq, Eq, Clone, Serialize)]
3230#[cfg_attr(feature = "schema", derive(JsonSchema))]
3231#[serde(untagged)]
3232pub enum AppDirectoriesOverride {
3233  /// A single directory that holds all app directories.
3234  ///
3235  /// The config, data and local data directories resolve to this path,
3236  /// the cache directory resolves to `<path>/caches` and the log directory to `<path>/logs`.
3237  Root(PathBuf),
3238  /// Overrides for individual app directories.
3239  ///
3240  /// Directories that are not listed keep their default location.
3241  Directories(AppDirectoryOverrides),
3242}
3243
3244impl AppDirectoriesOverride {
3245  /// The paths configured by this override.
3246  fn paths(&self) -> impl Iterator<Item = &PathBuf> {
3247    match self {
3248      Self::Root(root) => vec![Some(root)],
3249      Self::Directories(directories) => vec![
3250        directories.config.as_ref(),
3251        directories.data.as_ref(),
3252        directories.local_data.as_ref(),
3253        directories.cache.as_ref(),
3254        directories.log.as_ref(),
3255      ],
3256    }
3257    .into_iter()
3258    .flatten()
3259  }
3260}
3261
3262impl<'de> Deserialize<'de> for AppDirectoriesOverride {
3263  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3264  where
3265    D: Deserializer<'de>,
3266  {
3267    let value = UntaggedEnumVisitor::new()
3268      .string(|path| Ok(Self::Root(PathBuf::from(path))))
3269      .map(|map| {
3270        map
3271          .deserialize::<AppDirectoryOverrides>()
3272          .map(Self::Directories)
3273      })
3274      .deserialize(deserializer)?;
3275
3276    for path in value.paths() {
3277      validate_app_directory_override(path).map_err(DeError::custom)?;
3278    }
3279
3280    Ok(value)
3281  }
3282}
3283
3284/// Overrides for individual app directories.
3285#[skip_serializing_none]
3286#[derive(Debug, Default, PartialEq, Eq, Clone, Serialize, Deserialize)]
3287#[cfg_attr(feature = "schema", derive(JsonSchema))]
3288#[serde(rename_all = "camelCase", deny_unknown_fields)]
3289pub struct AppDirectoryOverrides {
3290  /// Overrides the app config directory (`app_config_dir`, `$APPCONFIG`).
3291  pub config: Option<PathBuf>,
3292  /// Overrides the app data directory (`app_data_dir`, `$APPDATA`).
3293  pub data: Option<PathBuf>,
3294  /// Overrides the app local data directory (`app_local_data_dir`, `$APPLOCALDATA`).
3295  ///
3296  /// On Windows and Linux this is also the default data directory of the webviews.
3297  #[serde(alias = "local-data", alias = "local_data")]
3298  pub local_data: Option<PathBuf>,
3299  /// Overrides the app cache directory (`app_cache_dir`, `$APPCACHE`).
3300  pub cache: Option<PathBuf>,
3301  /// Overrides the app log directory (`app_log_dir`, `$APPLOG`).
3302  pub log: Option<PathBuf>,
3303}
3304
3305/// The App configuration object.
3306///
3307/// See more: <https://v2.tauri.app/reference/config/#appconfig>
3308#[skip_serializing_none]
3309#[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
3310#[cfg_attr(feature = "schema", derive(JsonSchema))]
3311#[serde(rename_all = "camelCase", deny_unknown_fields)]
3312pub struct AppConfig {
3313  /// The app windows configuration.
3314  ///
3315  /// ## Example:
3316  ///
3317  /// To create a window at app startup
3318  ///
3319  /// ```json
3320  /// {
3321  ///   "app": {
3322  ///     "windows": [
3323  ///       { "width": 800, "height": 600 }
3324  ///     ]
3325  ///   }
3326  /// }
3327  /// ```
3328  ///
3329  /// If not specified, the window's label (its identifier) defaults to "main",
3330  /// you can use this label to get the window through
3331  /// `app.get_webview_window` in Rust or `WebviewWindow.getByLabel` in JavaScript
3332  ///
3333  /// When working with multiple windows, each window will need an unique label
3334  ///
3335  /// ```json
3336  /// {
3337  ///   "app": {
3338  ///     "windows": [
3339  ///       { "label": "main", "width": 800, "height": 600 },
3340  ///       { "label": "secondary", "width": 800, "height": 600 }
3341  ///     ]
3342  ///   }
3343  /// }
3344  /// ```
3345  ///
3346  /// You can also set `create` to false and use this config through the Rust APIs
3347  ///
3348  /// ```json
3349  /// {
3350  ///   "app": {
3351  ///     "windows": [
3352  ///       { "create": false, "width": 800, "height": 600 }
3353  ///     ]
3354  ///   }
3355  /// }
3356  /// ```
3357  ///
3358  /// and use it like this
3359  ///
3360  /// ```rust
3361  /// tauri::Builder::default()
3362  ///   .setup(|app| {
3363  ///     tauri::WebviewWindowBuilder::from_config(app.handle(), &app.config().app.windows[0])?.build()?;
3364  ///     Ok(())
3365  ///   });
3366  /// ```
3367  #[serde(default)]
3368  pub windows: Vec<WindowConfig>,
3369  /// Security configuration.
3370  #[serde(default)]
3371  pub security: SecurityConfig,
3372  /// Configuration for app tray icon.
3373  #[serde(alias = "tray-icon")]
3374  pub tray_icon: Option<TrayIconConfig>,
3375  /// MacOS private API configuration. Enables the transparent background API and sets the `fullScreenEnabled` preference to `true`.
3376  #[serde(rename = "macOSPrivateApi", alias = "macos-private-api", default)]
3377  pub macos_private_api: bool,
3378  /// Whether we should inject the Tauri API on `window.__TAURI__` or not.
3379  #[serde(default, alias = "with-global-tauri")]
3380  pub with_global_tauri: bool,
3381  /// Whether the application `identifier` is used as the GTK application ID on systems that use GTK.
3382  ///
3383  /// Setting the GTK application ID lets the desktop environment associate the app's windows with
3384  /// its `.desktop` entry of the same name, which is what makes Wayland compositors and GNOME show
3385  /// the correct icon and application name, and group the windows in the dock or taskbar.
3386  ///
3387  /// Defaults to `false`, because registering an application ID also makes GTK register the
3388  /// application on the session bus under that ID, which prevents running more than one instance
3389  /// of the app at the same time.
3390  ///
3391  /// ## Platform-specific
3392  ///
3393  /// - **Linux / FreeBSD / DragonFly / NetBSD / OpenBSD**: The identifier must be a valid GTK
3394  ///   application ID.
3395  /// - **Windows / macOS / Android / iOS**: Unsupported.
3396  #[serde(rename = "enableGTKAppId", alias = "enable-gtk-app-id", default)]
3397  pub enable_gtk_app_id: bool,
3398  /// Overrides the directories returned by the `app_*_dir` path APIs (`app_config_dir`, `app_data_dir`,
3399  /// `app_local_data_dir`, `app_cache_dir` and `app_log_dir`) and the matching `$APPCONFIG`, `$APPDATA`,
3400  /// `$APPLOCALDATA`, `$APPCACHE` and `$APPLOG` base directory variables.
3401  ///
3402  /// This is useful for portable apps that keep all of their data next to the executable,
3403  /// and for apps that want their app directories in a location they choose, such as `$DOCUMENT/my-app`.
3404  /// Everything that resolves paths through these APIs follows the override, including Tauri itself
3405  /// (the default webview data directory on Windows and Linux) and plugins,
3406  /// so the storage locations do not need to be configured one by one.
3407  /// The only exception is a window's `dataDirectory` config, which is not affected.
3408  ///
3409  /// It can also isolate the data of a development build from an installed version of the app,
3410  /// though a distinct `identifier` for development builds achieves that while keeping the production directory layout.
3411  ///
3412  /// The value is either a single path used as the root of every app directory
3413  /// (config, data and local data resolve to the root itself, cache to `<root>/caches` and log to `<root>/logs`),
3414  /// or an object that overrides individual directories (`config`, `data`, `localData`, `cache` and `log`),
3415  /// each resolving to exactly the configured path. Directories that are not listed in the object keep their default location.
3416  ///
3417  /// Each path is resolved as follows:
3418  ///
3419  /// - A path starting with a base directory variable is resolved relative to that directory.
3420  ///   The supported variables are `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`, `$DOCUMENT`,
3421  ///   `$DOWNLOAD`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$TEMP` and `$VIDEO`.
3422  ///   `..` components are kept, so `$DATA/../my-app` refers to a sibling of the data directory.
3423  /// - An absolute path is used as is.
3424  /// - Any other path is resolved relative to the directory containing the executable,
3425  ///   which must be writable, see the platform-specific notes below.
3426  ///
3427  /// ## Examples
3428  ///
3429  /// Keep all data in an `app-data` folder next to the executable, for a portable build:
3430  ///
3431  /// ```json
3432  /// {
3433  ///   "app": {
3434  ///     "appDirectoriesOverride": "./app-data"
3435  ///   }
3436  /// }
3437  /// ```
3438  ///
3439  /// Only move the logs and the cache:
3440  ///
3441  /// ```json
3442  /// {
3443  ///   "app": {
3444  ///     "appDirectoriesOverride": {
3445  ///       "log": "$DATA/my-app/logs",
3446  ///       "cache": "$CACHE/my-app"
3447  ///     }
3448  ///   }
3449  /// }
3450  /// ```
3451  ///
3452  /// Set the override at runtime, for instance from an environment variable, a command line flag
3453  /// or a directory picked by the user, by modifying the config returned by `tauri::generate_context!()`
3454  /// before building the app:
3455  ///
3456  /// ```rust
3457  /// use tauri::utils::config::AppDirectoriesOverride;
3458  ///
3459  /// fn main() {
3460  ///   let mut context = tauri::generate_context!();
3461  ///
3462  ///   if let Ok(data_dir) = std::env::var("MY_APP_DATA_DIR") {
3463  ///     context.config_mut().app.app_directories_override =
3464  ///       Some(AppDirectoriesOverride::Root(data_dir.into()));
3465  ///   }
3466  ///
3467  ///   tauri::Builder::default()
3468  ///     .run(context)
3469  ///     .expect("error while running tauri application");
3470  /// }
3471  /// ```
3472  ///
3473  /// ## Security
3474  ///
3475  /// Scopes and permissions that use the `$APPCONFIG`, `$APPDATA`, `$APPLOCALDATA`, `$APPCACHE` and `$APPLOG`
3476  /// variables follow the override, so the configured paths must be directories dedicated to the app.
3477  /// A single root is used as is for the config, data and local data directories, so a root that is not dedicated
3478  /// to the app, such as `"./"` or `"$DOCUMENT"`, extends those scopes to everything it contains.
3479  /// With `"./"`, `fs:default` (which allows reading the app directories recursively) lets the webview read
3480  /// every file next to the executable, including anything else in the folder the app was run from,
3481  /// such as the downloads folder. If the app also grants write access to an app directory, a compromised webview
3482  /// (e.g. through XSS) can replace files next to the executable, such as dropping a DLL that Windows loads
3483  /// from the executable's directory on the next launch, leading to code execution.
3484  /// Always point the override to a subfolder owned by the app, such as `"./app-data"` or `"$DOCUMENT/my-app"`.
3485  ///
3486  /// ## Platform-specific
3487  ///
3488  /// A path relative to the executable only works where the executable's directory is writable:
3489  /// portable builds, `tauri dev` builds in the `target` directory and the cases listed below.
3490  /// Everywhere else every write to an app directory fails at runtime, so installed apps should use
3491  /// a base directory variable or an absolute path instead. Unless every distribution of the app is portable,
3492  /// keep relative paths out of the shared configuration and apply them to the portable build flavor only,
3493  /// for instance with the CLI's `--config` flag, which accepts a JSON file or an inline JSON string:
3494  ///
3495  /// ```sh
3496  /// tauri build --config '{ "app": { "appDirectoriesOverride": "./app-data" } }'
3497  /// ```
3498  ///
3499  /// - **Linux**: Relative paths only work for AppImages, where they are resolved relative to the AppImage file,
3500  ///   as long as it is kept in a writable directory. `.deb` and `.rpm` packages install the executable to `/usr/bin`.
3501  /// - **macOS**: Relative paths are resolved next to the `.app` bundle. This does not work for installed apps,
3502  ///   since `/Applications` is not writable for standard users, nor for bundles downloaded from the internet,
3503  ///   which run from a random read-only location (App Translocation) until the user moves them out of the quarantined folder.
3504  /// - **Windows**: Relative paths also work for per-user NSIS installers,
3505  ///   but not for per-machine installers in `Program Files`.
3506  /// - **Android / iOS**: Relative paths are not supported, since there is no writable directory next to the executable.
3507  ///   Use a base directory variable or an absolute path instead. `$DESKTOP` is not available on Android.
3508  #[serde(alias = "app-directories-override")]
3509  pub app_directories_override: Option<AppDirectoriesOverride>,
3510}
3511
3512impl AppConfig {
3513  /// Returns all Cargo features.
3514  pub fn all_features() -> Vec<&'static str> {
3515    vec![
3516      "tray-icon",
3517      "macos-private-api",
3518      "protocol-asset",
3519      "isolation",
3520    ]
3521  }
3522
3523  /// Returns the enabled Cargo features.
3524  pub fn features(&self) -> Vec<&str> {
3525    let mut features = Vec::new();
3526    if self.tray_icon.is_some() {
3527      features.push("tray-icon");
3528    }
3529    if self.macos_private_api {
3530      features.push("macos-private-api");
3531    }
3532    if self.security.asset_protocol.enable {
3533      features.push("protocol-asset");
3534    }
3535
3536    if let PatternKind::Isolation { .. } = self.security.pattern {
3537      features.push("isolation");
3538    }
3539
3540    features.sort_unstable();
3541    features
3542  }
3543}
3544
3545/// Configuration for application tray icon.
3546///
3547/// See more: <https://v2.tauri.app/reference/config/#trayiconconfig>
3548#[skip_serializing_none]
3549#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
3550#[cfg_attr(feature = "schema", derive(JsonSchema))]
3551#[serde(rename_all = "camelCase", deny_unknown_fields)]
3552pub struct TrayIconConfig {
3553  /// Set an id for this tray icon so you can reference it later, defaults to `main`.
3554  pub id: Option<String>,
3555  /// Path to the default icon to use for the tray icon.
3556  ///
3557  /// Note: this stores the image in raw pixels to the final binary,
3558  /// so keep the icon size (width and height) small
3559  /// or else it's going to bloat your final executable
3560  #[serde(alias = "icon-path")]
3561  pub icon_path: PathBuf,
3562  /// A Boolean value that determines whether the image represents a [template](https://developer.apple.com/documentation/appkit/nsimage/1520017-template?language=objc) image on macOS.
3563  #[serde(default, alias = "icon-as-template")]
3564  pub icon_as_template: bool,
3565  /// **No longer works since v2.2, use [`Self::show_menu_on_left_click`] instead**
3566  ///
3567  /// A Boolean value that determines whether the menu should appear when the tray icon receives a left click.
3568  ///
3569  /// ## Platform-specific:
3570  ///
3571  /// - **Linux**: Unsupported.
3572  #[serde(default = "default_true", alias = "menu-on-left-click")]
3573  #[deprecated(
3574    since = "2.2.0",
3575    note = "No longer works, use `show_menu_on_left_click` instead."
3576  )]
3577  pub menu_on_left_click: bool,
3578  /// A Boolean value that determines whether the menu should appear when the tray icon receives a left click.
3579  ///
3580  /// ## Platform-specific:
3581  ///
3582  /// - **Linux**: Unsupported.
3583  #[serde(default = "default_true", alias = "show-menu-on-left-click")]
3584  pub show_menu_on_left_click: bool,
3585  /// Title for MacOS tray
3586  pub title: Option<String>,
3587  /// Tray icon tooltip on Windows and macOS
3588  pub tooltip: Option<String>,
3589}
3590
3591/// General configuration for the iOS target.
3592#[skip_serializing_none]
3593#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
3594#[cfg_attr(feature = "schema", derive(JsonSchema))]
3595#[serde(rename_all = "camelCase", deny_unknown_fields)]
3596pub struct IosConfig {
3597  /// A custom [XcodeGen] project.yml template to use.
3598  ///
3599  /// [XcodeGen]: <https://github.com/yonaskolb/XcodeGen>
3600  pub template: Option<PathBuf>,
3601  /// A list of strings indicating any iOS frameworks that need to be bundled with the application.
3602  ///
3603  /// Note that you need to recreate the iOS project for the changes to be applied.
3604  pub frameworks: Option<Vec<String>>,
3605  /// The development team. This value is required for iOS development because code signing is enforced.
3606  /// The `APPLE_DEVELOPMENT_TEAM` environment variable can be set to overwrite it.
3607  #[serde(alias = "development-team")]
3608  pub development_team: Option<String>,
3609  /// The version of the build that identifies an iteration of the bundle.
3610  ///
3611  /// Translates to the bundle's CFBundleVersion property.
3612  #[serde(alias = "bundle-version")]
3613  pub bundle_version: Option<String>,
3614  /// A version string indicating the minimum iOS version that the bundled application supports. Defaults to `15.0`.
3615  ///
3616  /// Maps to the IPHONEOS_DEPLOYMENT_TARGET value.
3617  #[serde(
3618    alias = "minimum-system-version",
3619    default = "ios_minimum_system_version"
3620  )]
3621  pub minimum_system_version: String,
3622  /// Path to a Info.plist file to merge with the default Info.plist.
3623  ///
3624  /// Note that Tauri also looks for a `Info.plist` and `Info.ios.plist` file in the same directory as the Tauri configuration file.
3625  #[serde(alias = "info-plist")]
3626  pub info_plist: Option<PathBuf>,
3627}
3628
3629impl Default for IosConfig {
3630  fn default() -> Self {
3631    Self {
3632      template: None,
3633      frameworks: None,
3634      development_team: None,
3635      bundle_version: None,
3636      minimum_system_version: ios_minimum_system_version(),
3637      info_plist: None,
3638    }
3639  }
3640}
3641
3642/// General configuration for the Android target.
3643#[skip_serializing_none]
3644#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
3645#[cfg_attr(feature = "schema", derive(JsonSchema))]
3646#[serde(rename_all = "camelCase", deny_unknown_fields)]
3647pub struct AndroidConfig {
3648  /// The minimum API level required for the application to run.
3649  /// The Android system will prevent the user from installing the application if the system's API level is lower than the value specified.
3650  #[serde(alias = "min-sdk-version", default = "default_min_sdk_version")]
3651  pub min_sdk_version: u32,
3652
3653  /// The version code of the application.
3654  /// It is limited to 2,100,000,000 as per Google Play Store requirements.
3655  ///
3656  /// By default we use your configured version and perform the following math:
3657  /// versionCode = version.major * 1000000 + version.minor * 1000 + version.patch
3658  #[serde(alias = "version-code")]
3659  #[cfg_attr(feature = "schema", validate(range(min = 1, max = 2_100_000_000)))]
3660  pub version_code: Option<u32>,
3661
3662  /// Whether to automatically increment the `versionCode` on each build.
3663  ///
3664  /// - If `true`, the generator will try to read the last `versionCode` from
3665  ///   `tauri.properties` and increment it by 1 for every build.
3666  /// - If `false` or not set, it falls back to `version_code` or semver-derived logic.
3667  ///
3668  /// Note that to use this feature, you should remove `/tauri.properties` from `src-tauri/gen/android/app/.gitignore` so the current versionCode is committed to the repository.
3669  #[serde(alias = "auto-increment-version-code", default)]
3670  pub auto_increment_version_code: bool,
3671
3672  /// Application ID suffix to append for debug builds.
3673  /// This allows installing debug and release versions side-by-side on the same device.
3674  /// Example: ".debug" will make debug builds use "com.example.app.debug" as the application ID.
3675  #[serde(alias = "debug-application-id-suffix")]
3676  pub debug_application_id_suffix: Option<String>,
3677}
3678
3679impl Default for AndroidConfig {
3680  fn default() -> Self {
3681    Self {
3682      min_sdk_version: default_min_sdk_version(),
3683      version_code: None,
3684      auto_increment_version_code: false,
3685      debug_application_id_suffix: None,
3686    }
3687  }
3688}
3689
3690fn default_min_sdk_version() -> u32 {
3691  24
3692}
3693
3694/// Defines the URL or assets to embed in the application.
3695#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
3696#[cfg_attr(feature = "schema", derive(JsonSchema))]
3697#[serde(untagged, deny_unknown_fields)]
3698#[non_exhaustive]
3699pub enum FrontendDist {
3700  /// An external URL that should be used as the default application URL. No assets are embedded in the app in this case.
3701  Url(Url),
3702  /// Path to a directory containing the frontend dist assets.
3703  Directory(PathBuf),
3704  /// An array of files to embed in the app.
3705  Files(Vec<PathBuf>),
3706}
3707
3708impl std::fmt::Display for FrontendDist {
3709  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3710    match self {
3711      Self::Url(url) => write!(f, "{url}"),
3712      Self::Directory(p) => write!(f, "{}", p.display()),
3713      Self::Files(files) => write!(f, "{}", serde_json::to_string(files).unwrap()),
3714    }
3715  }
3716}
3717
3718/// Describes the shell command to run before `tauri dev`.
3719#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
3720#[cfg_attr(feature = "schema", derive(JsonSchema))]
3721#[serde(rename_all = "camelCase", untagged)]
3722pub enum BeforeDevCommand {
3723  /// Run the given script with the default options.
3724  Script(String),
3725  /// Run the given script with custom options.
3726  ScriptWithOptions {
3727    /// The script to execute.
3728    script: String,
3729    /// The current working directory.
3730    cwd: Option<String>,
3731    /// Whether `tauri dev` should wait for the command to finish or not. Defaults to `false`.
3732    #[serde(default)]
3733    wait: bool,
3734  },
3735}
3736
3737/// Describes a shell command to be executed when a CLI hook is triggered.
3738#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
3739#[cfg_attr(feature = "schema", derive(JsonSchema))]
3740#[serde(rename_all = "camelCase", untagged)]
3741pub enum HookCommand {
3742  /// Run the given script with the default options.
3743  Script(String),
3744  /// Run the given script with custom options.
3745  ScriptWithOptions {
3746    /// The script to execute.
3747    script: String,
3748    /// The current working directory.
3749    cwd: Option<String>,
3750  },
3751}
3752
3753/// The runner configuration.
3754#[skip_serializing_none]
3755#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3756#[cfg_attr(feature = "schema", derive(JsonSchema))]
3757#[serde(untagged)]
3758pub enum RunnerConfig {
3759  /// A string specifying the binary to run.
3760  String(String),
3761  /// An object with advanced configuration options.
3762  Object {
3763    /// The binary to run.
3764    cmd: String,
3765    /// The current working directory to run the command from.
3766    cwd: Option<String>,
3767    /// Arguments to pass to the command.
3768    args: Option<Vec<String>>,
3769  },
3770}
3771
3772impl Default for RunnerConfig {
3773  fn default() -> Self {
3774    RunnerConfig::String("cargo".to_string())
3775  }
3776}
3777
3778impl RunnerConfig {
3779  /// Returns the command to run.
3780  pub fn cmd(&self) -> &str {
3781    match self {
3782      RunnerConfig::String(cmd) => cmd,
3783      RunnerConfig::Object { cmd, .. } => cmd,
3784    }
3785  }
3786
3787  /// Returns the working directory.
3788  pub fn cwd(&self) -> Option<&str> {
3789    match self {
3790      RunnerConfig::String(_) => None,
3791      RunnerConfig::Object { cwd, .. } => cwd.as_deref(),
3792    }
3793  }
3794
3795  /// Returns the arguments.
3796  pub fn args(&self) -> Option<&[String]> {
3797    match self {
3798      RunnerConfig::String(_) => None,
3799      RunnerConfig::Object { args, .. } => args.as_deref(),
3800    }
3801  }
3802}
3803
3804impl std::str::FromStr for RunnerConfig {
3805  type Err = std::convert::Infallible;
3806
3807  fn from_str(s: &str) -> Result<Self, Self::Err> {
3808    Ok(RunnerConfig::String(s.to_string()))
3809  }
3810}
3811
3812impl From<&str> for RunnerConfig {
3813  fn from(s: &str) -> Self {
3814    RunnerConfig::String(s.to_string())
3815  }
3816}
3817
3818impl From<String> for RunnerConfig {
3819  fn from(s: String) -> Self {
3820    RunnerConfig::String(s)
3821  }
3822}
3823
3824/// The Build configuration object.
3825///
3826/// See more: <https://v2.tauri.app/reference/config/#buildconfig>
3827#[skip_serializing_none]
3828#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize, Default)]
3829#[cfg_attr(feature = "schema", derive(JsonSchema))]
3830#[serde(rename_all = "camelCase", deny_unknown_fields)]
3831pub struct BuildConfig {
3832  /// The binary used to build and run the application.
3833  pub runner: Option<RunnerConfig>,
3834  /// The URL to load in development.
3835  ///
3836  /// This is usually an URL to a dev server, which serves your application assets with hot-reload and HMR.
3837  /// Most modern JavaScript bundlers like [Vite](https://vite.dev/guide/) provides a way to start a dev server by default.
3838  ///
3839  /// If you don't have a dev server or don't want to use one, ignore this option and use [`frontendDist`](BuildConfig::frontend_dist)
3840  /// and point to a web assets directory, and Tauri CLI will run its built-in dev server and provide a simple hot-reload experience.
3841  #[serde(alias = "dev-url")]
3842  pub dev_url: Option<Url>,
3843  /// The path to the application assets (usually the `dist` folder of your javascript bundler)
3844  /// or a URL that could be either a custom protocol registered in the tauri app (for example: `myprotocol://`)
3845  /// or a remote URL (for example: `https://site.com/app`).
3846  ///
3847  /// When a path relative to the configuration file is provided,
3848  /// it is read recursively and all files are embedded in the application binary.
3849  /// Tauri then looks for an `index.html` and serves it as the default entry point for your application.
3850  ///
3851  /// You can also provide a list of paths to be embedded, which allows granular control over what files are added to the binary.
3852  /// In this case, all files are added to the root and you must reference it that way in your HTML files.
3853  ///
3854  /// When a URL is provided, the application won't have bundled assets
3855  /// and the application will load that URL by default.
3856  #[serde(alias = "frontend-dist")]
3857  pub frontend_dist: Option<FrontendDist>,
3858  /// A shell command to run before `tauri dev` kicks in.
3859  ///
3860  /// The `TAURI_ENV_PLATFORM`, `TAURI_ENV_ARCH`, `TAURI_ENV_FAMILY`, `TAURI_ENV_PLATFORM_VERSION`
3861  /// and `TAURI_ENV_TARGET_TRIPLE` environment variables are set for the command, so it can
3862  /// adapt its output to the target that is being built.
3863  /// `TAURI_ENV_DEBUG` is set to `true` for debug builds and is not set otherwise.
3864  #[serde(alias = "before-dev-command")]
3865  pub before_dev_command: Option<BeforeDevCommand>,
3866  /// A shell command to run before `tauri build` kicks in.
3867  ///
3868  /// The `TAURI_ENV_PLATFORM`, `TAURI_ENV_ARCH`, `TAURI_ENV_FAMILY`, `TAURI_ENV_PLATFORM_VERSION`
3869  /// and `TAURI_ENV_TARGET_TRIPLE` environment variables are set for the command, so it can
3870  /// adapt its output to the target that is being built.
3871  /// `TAURI_ENV_DEBUG` is set to `true` for debug builds and is not set otherwise.
3872  #[serde(alias = "before-build-command")]
3873  pub before_build_command: Option<HookCommand>,
3874  /// A shell command to run before the bundling phase in `tauri build` kicks in.
3875  ///
3876  /// The `TAURI_ENV_PLATFORM`, `TAURI_ENV_ARCH`, `TAURI_ENV_FAMILY`, `TAURI_ENV_PLATFORM_VERSION`
3877  /// and `TAURI_ENV_TARGET_TRIPLE` environment variables are set for the command, so it can
3878  /// adapt its output to the target that is being built.
3879  /// `TAURI_ENV_DEBUG` is set to `true` for debug builds and is not set otherwise.
3880  #[serde(alias = "before-bundle-command")]
3881  pub before_bundle_command: Option<HookCommand>,
3882  /// Features passed to `cargo` commands.
3883  pub features: Option<Vec<String>>,
3884  /// Try to remove unused commands registered from plugins base on the ACL list during `tauri build`,
3885  /// the way it works is that tauri-cli will read this and set the environment variables for the build script and macros,
3886  /// and they'll try to get all the allowed commands and remove the rest
3887  ///
3888  /// Note:
3889  ///   - This won't be accounting for dynamically added ACLs when you use features from the `dynamic-acl` (currently enabled by default) feature flag, so make sure to check it when using this
3890  ///   - This feature requires tauri-plugin 2.1 and tauri 2.4
3891  #[serde(alias = "remove-unused-commands", default)]
3892  pub remove_unused_commands: bool,
3893  /// Additional paths to watch for changes when running `tauri dev`.
3894  #[serde(
3895    alias = "additional-watch-folders",
3896    alias = "additional-watch-directories",
3897    default
3898  )]
3899  pub additional_watch_folders: Vec<PathBuf>,
3900  /// Windows-specific build configuration.
3901  #[serde(default)]
3902  pub windows: WindowsBuildConfig,
3903}
3904
3905/// Windows-specific build configuration.
3906#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
3907#[cfg_attr(feature = "schema", derive(JsonSchema))]
3908#[serde(rename_all = "camelCase", deny_unknown_fields)]
3909pub struct WindowsBuildConfig {
3910  /// Whether to statically link the Visual C++ runtime into the application binary on Windows MSVC targets.
3911  #[serde(
3912    default = "default_true",
3913    rename = "staticVCRuntime",
3914    alias = "static-vc-runtime",
3915    alias = "staticVcRuntime"
3916  )]
3917  pub static_vc_runtime: bool,
3918}
3919
3920impl Default for WindowsBuildConfig {
3921  fn default() -> Self {
3922    Self {
3923      static_vc_runtime: true,
3924    }
3925  }
3926}
3927
3928#[derive(Debug, PartialEq, Eq)]
3929struct PackageVersion(String);
3930
3931impl<'d> serde::Deserialize<'d> for PackageVersion {
3932  fn deserialize<D: Deserializer<'d>>(deserializer: D) -> Result<Self, D::Error> {
3933    struct PackageVersionVisitor;
3934
3935    impl Visitor<'_> for PackageVersionVisitor {
3936      type Value = PackageVersion;
3937
3938      fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3939        write!(
3940          formatter,
3941          "a semver string or a path to a package.json file"
3942        )
3943      }
3944
3945      fn visit_str<E: DeError>(self, value: &str) -> Result<PackageVersion, E> {
3946        let path = PathBuf::from(value);
3947        if path.exists() {
3948          let json_str = read_to_string(&path)
3949            .map_err(|e| DeError::custom(format!("failed to read version JSON file: {e}")))?;
3950          let package_json: serde_json::Value = serde_json::from_str(&json_str)
3951            .map_err(|e| DeError::custom(format!("failed to read version JSON file: {e}")))?;
3952          if let Some(obj) = package_json.as_object() {
3953            let version = obj
3954              .get("version")
3955              .ok_or_else(|| DeError::custom("JSON must contain a `version` field"))?
3956              .as_str()
3957              .ok_or_else(|| {
3958                DeError::custom(format!("`{} > version` must be a string", path.display()))
3959              })?;
3960            Ok(PackageVersion(
3961              Version::from_str(version)
3962                .map_err(|_| {
3963                  DeError::custom("`tauri.conf.json > version` must be a semver string")
3964                })?
3965                .to_string(),
3966            ))
3967          } else {
3968            Err(DeError::custom(
3969              "`tauri.conf.json > version` value is not a path to a JSON object",
3970            ))
3971          }
3972        } else {
3973          Ok(PackageVersion(
3974            Version::from_str(value)
3975              .map_err(|_| DeError::custom("`tauri.conf.json > version` must be a semver string"))?
3976              .to_string(),
3977          ))
3978        }
3979      }
3980    }
3981
3982    deserializer.deserialize_string(PackageVersionVisitor {})
3983  }
3984}
3985
3986fn version_deserializer<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
3987where
3988  D: Deserializer<'de>,
3989{
3990  Option::<PackageVersion>::deserialize(deserializer).map(|v| v.map(|v| v.0))
3991}
3992
3993/// The Tauri configuration object.
3994/// It is read from a file where you can define your frontend assets,
3995/// configure the bundler and define a tray icon.
3996///
3997/// The configuration file is generated by the
3998/// [`tauri init`](https://v2.tauri.app/reference/cli/#init) command that lives in
3999/// your Tauri application source directory (src-tauri).
4000///
4001/// Once generated, you may modify it at will to customize your Tauri application.
4002///
4003/// ## File Formats
4004///
4005/// By default, the configuration is defined as a JSON file named `tauri.conf.json`.
4006///
4007/// Tauri also supports JSON5 and TOML files via the `config-json5` and `config-toml` Cargo features, respectively.
4008/// The JSON5 file name must be either `tauri.conf.json` or `tauri.conf.json5`.
4009/// The TOML file name is `Tauri.toml`.
4010///
4011/// ## Platform-Specific Configuration
4012///
4013/// In addition to the default configuration file, Tauri can
4014/// read a platform-specific configuration from `tauri.linux.conf.json`,
4015/// `tauri.windows.conf.json`, `tauri.macos.conf.json`, `tauri.android.conf.json` and `tauri.ios.conf.json`
4016/// (or `Tauri.linux.toml`, `Tauri.windows.toml`, `Tauri.macos.toml`, `Tauri.android.toml` and `Tauri.ios.toml` if the `Tauri.toml` format is used),
4017/// which gets merged with the main configuration object.
4018///
4019/// ## Configuration Structure
4020///
4021/// The configuration is composed of the following objects:
4022///
4023/// - [`app`](#appconfig): The Tauri configuration
4024/// - [`build`](#buildconfig): The build configuration
4025/// - [`bundle`](#bundleconfig): The bundle configurations
4026/// - [`plugins`](#pluginconfig): The plugins configuration
4027///
4028/// Example tauri.config.json file:
4029///
4030/// ```json
4031/// {
4032///   "productName": "tauri-app",
4033///   "version": "0.1.0",
4034///   "build": {
4035///     "beforeBuildCommand": "",
4036///     "beforeDevCommand": "",
4037///     "devUrl": "http://localhost:3000",
4038///     "frontendDist": "../dist"
4039///   },
4040///   "app": {
4041///     "security": {
4042///       "csp": null
4043///     },
4044///     "windows": [
4045///       {
4046///         "fullscreen": false,
4047///         "height": 600,
4048///         "resizable": true,
4049///         "title": "Tauri App",
4050///         "width": 800
4051///       }
4052///     ]
4053///   },
4054///   "bundle": {},
4055///   "plugins": {}
4056/// }
4057/// ```
4058#[skip_serializing_none]
4059#[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
4060#[cfg_attr(feature = "schema", derive(JsonSchema))]
4061#[serde(rename_all = "camelCase", deny_unknown_fields)]
4062pub struct Config {
4063  /// The JSON schema for the Tauri config.
4064  #[serde(rename = "$schema")]
4065  pub schema: Option<String>,
4066  /// App name.
4067  ///
4068  /// This is the name your app is known by on the user's system, so it must be changed from the
4069  /// default before publishing. Besides naming the generated bundles, it is written into platform
4070  /// metadata and install paths that are expected to be unique to your application.
4071  ///
4072  /// ## Platform-specific
4073  ///
4074  /// - **macOS**: Names the `.app` bundle and the `.dmg`, and sets the bundle's
4075  ///    `CFBundleDisplayName` and `CFBundleName` properties. `CFBundleName` can be overridden with
4076  ///    [`bundle > macOS > bundleName`](MacConfig::bundle_name).
4077  /// - **Linux**: Kebab-cased for the Debian and RPM package names, used as the `Name` entry of
4078  ///    the desktop file and as the resource directory name under `/usr/lib`.
4079  /// - **Windows**: Names the installers, the installation directory, the Start Menu folder and
4080  ///    the `HKCU\Software\<publisher>\<product name>` registry key. It also derives the default
4081  ///    WiX upgrade code, which must be unique across applications and can be set explicitly with
4082  ///    [`bundle > windows > wix > upgradeCode`](WixConfig::upgrade_code).
4083  #[serde(alias = "product-name")]
4084  #[cfg_attr(feature = "schema", validate(regex(pattern = "^[^/\\:*?\"<>|]+$")))]
4085  pub product_name: Option<String>,
4086  /// Overrides app's main binary filename.
4087  ///
4088  /// By default, Tauri uses the output binary from `cargo`, by setting this, we will rename that binary in `tauri-cli`'s
4089  /// `tauri build` command, and target `tauri bundle` to it
4090  ///
4091  /// If possible, change the [`package name`] or set the [`name field`] instead,
4092  /// and if that's not enough and you're using nightly, consider using the [`different-binary-name`] feature instead
4093  ///
4094  /// Note: this config should not include the binary extension (e.g. `.exe`), we'll add that for you
4095  ///
4096  /// [`package name`]: https://doc.rust-lang.org/cargo/reference/manifest.html#the-name-field
4097  /// [`name field`]: https://doc.rust-lang.org/cargo/reference/cargo-targets.html#the-name-field
4098  /// [`different-binary-name`]: https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#different-binary-name
4099  #[serde(alias = "main-binary-name")]
4100  pub main_binary_name: Option<String>,
4101  /// App version. It is a semver version number or a path to a `package.json` file containing the `version` field.
4102  ///
4103  /// If removed the version number from `Cargo.toml` is used.
4104  /// It's recommended to manage the app versioning in the Tauri config.
4105  ///
4106  /// ## Platform-specific
4107  ///
4108  /// - **macOS**: Translates to the bundle's CFBundleShortVersionString property and is used as the default CFBundleVersion.
4109  ///    You can set an specific bundle version using [`bundle > macOS > bundleVersion`](MacConfig::bundle_version).
4110  /// - **iOS**: Translates to the bundle's CFBundleShortVersionString property and is used as the default CFBundleVersion.
4111  ///    You can set an specific bundle version using [`bundle > iOS > bundleVersion`](IosConfig::bundle_version).
4112  ///    The `tauri ios build` CLI command has a `--build-number <number>` option that lets you append a build number to the app version.
4113  /// - **Android**: By default version 1.0 is used. You can set a version code using [`bundle > android > versionCode`](AndroidConfig::version_code).
4114  ///
4115  /// By default version 1.0 is used on Android.
4116  #[serde(deserialize_with = "version_deserializer", default)]
4117  pub version: Option<String>,
4118  /// The application identifier in reverse domain name notation (e.g. `com.tauri.example`).
4119  /// This string must be unique across applications since it is used in system configurations like
4120  /// the bundle ID and path to the webview data directory.
4121  /// This string must contain only alphanumeric characters (A-Z, a-z, and 0-9), hyphens (-),
4122  /// and periods (.).
4123  /// The default value `com.tauri.dev` is rejected by `tauri build` and must be changed before
4124  /// building your application.
4125  pub identifier: String,
4126  /// The App configuration.
4127  #[serde(default)]
4128  pub app: AppConfig,
4129  /// The build configuration.
4130  #[serde(default)]
4131  pub build: BuildConfig,
4132  /// The bundler configuration.
4133  #[serde(default)]
4134  pub bundle: BundleConfig,
4135  /// The plugins config.
4136  #[serde(default)]
4137  pub plugins: PluginConfig,
4138}
4139
4140/// The plugin configs holds a HashMap mapping a plugin name to its configuration object.
4141///
4142/// See more: <https://v2.tauri.app/reference/config/#pluginconfig>
4143#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
4144#[cfg_attr(feature = "schema", derive(JsonSchema))]
4145pub struct PluginConfig(pub HashMap<String, JsonValue>);
4146
4147impl Serialize for PluginConfig {
4148  fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
4149  where
4150    S: Serializer,
4151  {
4152    // Serialize through `BTreeMap` so the output is deterministic
4153    // see: https://github.com/tauri-apps/tauri/issues/14978
4154    // TODO: Remove this in v3, use a BTreeMap instead of a HashMap
4155    let btree_map: BTreeMap<_, _> = self.0.iter().collect();
4156    btree_map.serialize(serializer)
4157  }
4158}
4159
4160/// Implement `ToTokens` for all config structs, allowing a literal `Config` to be built.
4161///
4162/// This allows for a build script to output the values in a `Config` to a `TokenStream`, which can
4163/// then be consumed by another crate. Useful for passing a config to both the build script and the
4164/// application using tauri while only parsing it once (in the build script).
4165#[cfg(any(feature = "build", feature = "build-2"))]
4166mod build {
4167  use super::*;
4168  use crate::{literal_struct, tokens::*};
4169  use proc_macro2::TokenStream;
4170  use quote::{ToTokens, TokenStreamExt, quote};
4171  use std::convert::identity;
4172
4173  impl ToTokens for WebviewUrl {
4174    fn to_tokens(&self, tokens: &mut TokenStream) {
4175      let prefix = quote! { ::tauri::utils::config::WebviewUrl };
4176
4177      tokens.append_all(match self {
4178        Self::App(path) => {
4179          let path = path_buf_lit(path);
4180          quote! { #prefix::App(#path) }
4181        }
4182        Self::External(url) => {
4183          let url = url_lit(url);
4184          quote! { #prefix::External(#url) }
4185        }
4186        Self::CustomProtocol(url) => {
4187          let url = url_lit(url);
4188          quote! { #prefix::CustomProtocol(#url) }
4189        }
4190      })
4191    }
4192  }
4193
4194  impl ToTokens for BackgroundThrottlingPolicy {
4195    fn to_tokens(&self, tokens: &mut TokenStream) {
4196      let prefix = quote! { ::tauri::utils::config::BackgroundThrottlingPolicy };
4197      tokens.append_all(match self {
4198        Self::Disabled => quote! { #prefix::Disabled },
4199        Self::Throttle => quote! { #prefix::Throttle },
4200        Self::Suspend => quote! { #prefix::Suspend },
4201      })
4202    }
4203  }
4204
4205  impl ToTokens for crate::Theme {
4206    fn to_tokens(&self, tokens: &mut TokenStream) {
4207      let prefix = quote! { ::tauri::utils::Theme };
4208
4209      tokens.append_all(match self {
4210        Self::Light => quote! { #prefix::Light },
4211        Self::Dark => quote! { #prefix::Dark },
4212      })
4213    }
4214  }
4215
4216  impl ToTokens for Color {
4217    fn to_tokens(&self, tokens: &mut TokenStream) {
4218      let Color(r, g, b, a) = self;
4219      tokens.append_all(quote! {::tauri::utils::config::Color(#r,#g,#b,#a)});
4220    }
4221  }
4222  impl ToTokens for WindowEffectsConfig {
4223    fn to_tokens(&self, tokens: &mut TokenStream) {
4224      let effects = vec_lit(self.effects.clone(), |d| d);
4225      let state = opt_lit(self.state.as_ref());
4226      let radius = opt_lit(self.radius.as_ref());
4227      let color = opt_lit(self.color.as_ref());
4228      let interactive = self.interactive;
4229
4230      literal_struct!(
4231        tokens,
4232        ::tauri::utils::config::WindowEffectsConfig,
4233        effects,
4234        state,
4235        radius,
4236        color,
4237        interactive
4238      )
4239    }
4240  }
4241
4242  impl ToTokens for crate::TitleBarStyle {
4243    fn to_tokens(&self, tokens: &mut TokenStream) {
4244      let prefix = quote! { ::tauri::utils::TitleBarStyle };
4245
4246      tokens.append_all(match self {
4247        Self::Visible => quote! { #prefix::Visible },
4248        Self::Transparent => quote! { #prefix::Transparent },
4249        Self::Overlay => quote! { #prefix::Overlay },
4250      })
4251    }
4252  }
4253
4254  impl ToTokens for LogicalPosition {
4255    fn to_tokens(&self, tokens: &mut TokenStream) {
4256      let LogicalPosition { x, y } = self;
4257      literal_struct!(tokens, ::tauri::utils::config::LogicalPosition, x, y)
4258    }
4259  }
4260
4261  impl ToTokens for crate::WindowEffect {
4262    fn to_tokens(&self, tokens: &mut TokenStream) {
4263      let prefix = quote! { ::tauri::utils::WindowEffect };
4264
4265      #[allow(deprecated)]
4266      tokens.append_all(match self {
4267        WindowEffect::AppearanceBased => quote! { #prefix::AppearanceBased},
4268        WindowEffect::Light => quote! { #prefix::Light},
4269        WindowEffect::Dark => quote! { #prefix::Dark},
4270        WindowEffect::MediumLight => quote! { #prefix::MediumLight},
4271        WindowEffect::UltraDark => quote! { #prefix::UltraDark},
4272        WindowEffect::Titlebar => quote! { #prefix::Titlebar},
4273        WindowEffect::Selection => quote! { #prefix::Selection},
4274        WindowEffect::Menu => quote! { #prefix::Menu},
4275        WindowEffect::Popover => quote! { #prefix::Popover},
4276        WindowEffect::Sidebar => quote! { #prefix::Sidebar},
4277        WindowEffect::HeaderView => quote! { #prefix::HeaderView},
4278        WindowEffect::Sheet => quote! { #prefix::Sheet},
4279        WindowEffect::WindowBackground => quote! { #prefix::WindowBackground},
4280        WindowEffect::HudWindow => quote! { #prefix::HudWindow},
4281        WindowEffect::FullScreenUI => quote! { #prefix::FullScreenUI},
4282        WindowEffect::Tooltip => quote! { #prefix::Tooltip},
4283        WindowEffect::ContentBackground => quote! { #prefix::ContentBackground},
4284        WindowEffect::UnderWindowBackground => quote! { #prefix::UnderWindowBackground},
4285        WindowEffect::UnderPageBackground => quote! { #prefix::UnderPageBackground},
4286        WindowEffect::LiquidGlassRegular => quote! { #prefix::LiquidGlassRegular },
4287        WindowEffect::LiquidGlassClear => quote! { #prefix::LiquidGlassClear },
4288        WindowEffect::Mica => quote! { #prefix::Mica},
4289        WindowEffect::MicaDark => quote! { #prefix::MicaDark},
4290        WindowEffect::MicaLight => quote! { #prefix::MicaLight},
4291        WindowEffect::Blur => quote! { #prefix::Blur},
4292        WindowEffect::Acrylic => quote! { #prefix::Acrylic},
4293        WindowEffect::Tabbed => quote! { #prefix::Tabbed },
4294        WindowEffect::TabbedDark => quote! { #prefix::TabbedDark },
4295        WindowEffect::TabbedLight => quote! { #prefix::TabbedLight },
4296      })
4297    }
4298  }
4299
4300  impl ToTokens for crate::WindowEffectState {
4301    fn to_tokens(&self, tokens: &mut TokenStream) {
4302      let prefix = quote! { ::tauri::utils::WindowEffectState };
4303
4304      #[allow(deprecated)]
4305      tokens.append_all(match self {
4306        WindowEffectState::Active => quote! { #prefix::Active},
4307        WindowEffectState::FollowsWindowActiveState => quote! { #prefix::FollowsWindowActiveState},
4308        WindowEffectState::Inactive => quote! { #prefix::Inactive},
4309      })
4310    }
4311  }
4312
4313  impl ToTokens for PreventOverflowMargin {
4314    fn to_tokens(&self, tokens: &mut TokenStream) {
4315      let width = self.width;
4316      let height = self.height;
4317
4318      literal_struct!(
4319        tokens,
4320        ::tauri::utils::config::PreventOverflowMargin,
4321        width,
4322        height
4323      )
4324    }
4325  }
4326
4327  impl ToTokens for PreventOverflowConfig {
4328    fn to_tokens(&self, tokens: &mut TokenStream) {
4329      let prefix = quote! { ::tauri::utils::config::PreventOverflowConfig };
4330
4331      #[allow(deprecated)]
4332      tokens.append_all(match self {
4333        Self::Enable(enable) => quote! { #prefix::Enable(#enable) },
4334        Self::Margin(margin) => quote! { #prefix::Margin(#margin) },
4335      })
4336    }
4337  }
4338
4339  impl ToTokens for ScrollBarStyle {
4340    fn to_tokens(&self, tokens: &mut TokenStream) {
4341      let prefix = quote! { ::tauri::utils::config::ScrollBarStyle };
4342
4343      tokens.append_all(match self {
4344        Self::Default => quote! { #prefix::Default },
4345        Self::FluentOverlay => quote! { #prefix::FluentOverlay },
4346      })
4347    }
4348  }
4349
4350  impl ToTokens for WindowConfig {
4351    fn to_tokens(&self, tokens: &mut TokenStream) {
4352      let label = str_lit(&self.label);
4353      let create = &self.create;
4354      let url = &self.url;
4355      let user_agent = opt_str_lit(self.user_agent.as_ref());
4356      let drag_drop_enabled = self.drag_drop_enabled;
4357      let center = self.center;
4358      let x = opt_lit(self.x.as_ref());
4359      let y = opt_lit(self.y.as_ref());
4360      let width = self.width;
4361      let height = self.height;
4362      let min_width = opt_lit(self.min_width.as_ref());
4363      let min_height = opt_lit(self.min_height.as_ref());
4364      let max_width = opt_lit(self.max_width.as_ref());
4365      let max_height = opt_lit(self.max_height.as_ref());
4366      let prevent_overflow = opt_lit(self.prevent_overflow.as_ref());
4367      let resizable = self.resizable;
4368      let maximizable = self.maximizable;
4369      let minimizable = self.minimizable;
4370      let closable = self.closable;
4371      let title = str_lit(&self.title);
4372      let proxy_url = opt_lit(self.proxy_url.as_ref().map(url_lit).as_ref());
4373      let fullscreen = self.fullscreen;
4374      let focus = self.focus;
4375      let focusable = self.focusable;
4376      let transparent = self.transparent;
4377      let maximized = self.maximized;
4378      let visible = self.visible;
4379      let decorations = self.decorations;
4380      let always_on_bottom = self.always_on_bottom;
4381      let always_on_top = self.always_on_top;
4382      let visible_on_all_workspaces = self.visible_on_all_workspaces;
4383      let content_protected = self.content_protected;
4384      let skip_taskbar = self.skip_taskbar;
4385      let window_classname = opt_str_lit(self.window_classname.as_ref());
4386      let no_redirection_bitmap = self.no_redirection_bitmap;
4387      let theme = opt_lit(self.theme.as_ref());
4388      let title_bar_style = &self.title_bar_style;
4389      let traffic_light_position = opt_lit(self.traffic_light_position.as_ref());
4390      let hidden_title = self.hidden_title;
4391      let accept_first_mouse = self.accept_first_mouse;
4392      let tabbing_identifier = opt_str_lit(self.tabbing_identifier.as_ref());
4393      let additional_browser_args = opt_str_lit(self.additional_browser_args.as_ref());
4394      let shadow = self.shadow;
4395      let window_effects = opt_lit(self.window_effects.as_ref());
4396      let incognito = self.incognito;
4397      let parent = opt_str_lit(self.parent.as_ref());
4398      let zoom_hotkeys_enabled = self.zoom_hotkeys_enabled;
4399      let browser_extensions_enabled = self.browser_extensions_enabled;
4400      let use_https_scheme = self.use_https_scheme;
4401      let devtools = opt_lit(self.devtools.as_ref());
4402      let background_color = opt_lit(self.background_color.as_ref());
4403      let background_throttling = opt_lit(self.background_throttling.as_ref());
4404      let javascript_disabled = self.javascript_disabled;
4405      let allow_link_preview = self.allow_link_preview;
4406      let disable_input_accessory_view = self.disable_input_accessory_view;
4407      let data_directory = opt_lit(self.data_directory.as_ref().map(path_buf_lit).as_ref());
4408      let data_store_identifier = opt_vec_lit(self.data_store_identifier, identity);
4409      let scroll_bar_style = &self.scroll_bar_style;
4410      let limit_navigations_to_app_bound_domains = self.limit_navigations_to_app_bound_domains;
4411      let activity_name = opt_lit(self.activity_name.as_ref());
4412      let created_by_activity_name = opt_lit(self.created_by_activity_name.as_ref());
4413      let requested_by_scene_identifier = opt_lit(self.requested_by_scene_identifier.as_ref());
4414      let general_autofill_enabled = self.general_autofill_enabled;
4415
4416      literal_struct!(
4417        tokens,
4418        ::tauri::utils::config::WindowConfig,
4419        label,
4420        url,
4421        create,
4422        user_agent,
4423        drag_drop_enabled,
4424        center,
4425        x,
4426        y,
4427        width,
4428        height,
4429        min_width,
4430        min_height,
4431        max_width,
4432        max_height,
4433        prevent_overflow,
4434        resizable,
4435        maximizable,
4436        minimizable,
4437        closable,
4438        title,
4439        proxy_url,
4440        fullscreen,
4441        focus,
4442        focusable,
4443        transparent,
4444        maximized,
4445        visible,
4446        decorations,
4447        always_on_bottom,
4448        always_on_top,
4449        visible_on_all_workspaces,
4450        content_protected,
4451        skip_taskbar,
4452        window_classname,
4453        no_redirection_bitmap,
4454        theme,
4455        title_bar_style,
4456        traffic_light_position,
4457        hidden_title,
4458        accept_first_mouse,
4459        tabbing_identifier,
4460        additional_browser_args,
4461        shadow,
4462        window_effects,
4463        incognito,
4464        parent,
4465        zoom_hotkeys_enabled,
4466        browser_extensions_enabled,
4467        use_https_scheme,
4468        devtools,
4469        background_color,
4470        background_throttling,
4471        javascript_disabled,
4472        allow_link_preview,
4473        disable_input_accessory_view,
4474        data_directory,
4475        data_store_identifier,
4476        scroll_bar_style,
4477        limit_navigations_to_app_bound_domains,
4478        activity_name,
4479        created_by_activity_name,
4480        requested_by_scene_identifier,
4481        general_autofill_enabled
4482      );
4483    }
4484  }
4485
4486  impl ToTokens for PatternKind {
4487    fn to_tokens(&self, tokens: &mut TokenStream) {
4488      let prefix = quote! { ::tauri::utils::config::PatternKind };
4489
4490      tokens.append_all(match self {
4491        Self::Brownfield => quote! { #prefix::Brownfield },
4492        #[cfg(not(feature = "isolation"))]
4493        Self::Isolation { dir: _ } => quote! { #prefix::Brownfield },
4494        #[cfg(feature = "isolation")]
4495        Self::Isolation { dir } => {
4496          let dir = path_buf_lit(dir);
4497          quote! { #prefix::Isolation { dir: #dir } }
4498        }
4499      })
4500    }
4501  }
4502
4503  impl ToTokens for WebviewInstallMode {
4504    fn to_tokens(&self, tokens: &mut TokenStream) {
4505      let prefix = quote! { ::tauri::utils::config::WebviewInstallMode };
4506
4507      tokens.append_all(match self {
4508        Self::Skip => quote! { #prefix::Skip },
4509        Self::DownloadBootstrapper { silent } => {
4510          quote! { #prefix::DownloadBootstrapper { silent: #silent } }
4511        }
4512        Self::EmbedBootstrapper { silent } => {
4513          quote! { #prefix::EmbedBootstrapper { silent: #silent } }
4514        }
4515        Self::OfflineInstaller { silent } => {
4516          quote! { #prefix::OfflineInstaller { silent: #silent } }
4517        }
4518        Self::FixedRuntime { path } => {
4519          let path = path_buf_lit(path);
4520          quote! { #prefix::FixedRuntime { path: #path } }
4521        }
4522      })
4523    }
4524  }
4525
4526  impl ToTokens for WindowsConfig {
4527    fn to_tokens(&self, tokens: &mut TokenStream) {
4528      let webview_install_mode = &self.webview_install_mode;
4529      tokens.append_all(quote! { ::tauri::utils::config::WindowsConfig {
4530        webview_install_mode: #webview_install_mode,
4531        ..Default::default()
4532      }})
4533    }
4534  }
4535
4536  impl ToTokens for BundleConfig {
4537    fn to_tokens(&self, tokens: &mut TokenStream) {
4538      let publisher = quote!(None);
4539      let homepage = quote!(None);
4540      let icon = vec_lit(&self.icon, str_lit);
4541      let active = self.active;
4542      let targets = quote!(Default::default());
4543      let create_updater_artifacts = quote!(Default::default());
4544      let resources = quote!(None);
4545      let copyright = quote!(None);
4546      let category = quote!(None);
4547      let file_associations = quote!(None);
4548      let short_description = quote!(None);
4549      let long_description = quote!(None);
4550      let use_local_tools_dir = self.use_local_tools_dir;
4551      let external_bin = opt_vec_lit(self.external_bin.as_ref(), str_lit);
4552      let windows = &self.windows;
4553      let license = opt_str_lit(self.license.as_ref());
4554      let license_file = opt_lit(self.license_file.as_ref().map(path_buf_lit).as_ref());
4555      let linux = quote!(Default::default());
4556      let macos = quote!(Default::default());
4557      let ios = quote!(Default::default());
4558      let android = quote!(Default::default());
4559
4560      literal_struct!(
4561        tokens,
4562        ::tauri::utils::config::BundleConfig,
4563        active,
4564        publisher,
4565        homepage,
4566        icon,
4567        targets,
4568        create_updater_artifacts,
4569        resources,
4570        copyright,
4571        category,
4572        license,
4573        license_file,
4574        file_associations,
4575        short_description,
4576        long_description,
4577        use_local_tools_dir,
4578        external_bin,
4579        windows,
4580        linux,
4581        macos,
4582        ios,
4583        android
4584      );
4585    }
4586  }
4587
4588  impl ToTokens for FrontendDist {
4589    fn to_tokens(&self, tokens: &mut TokenStream) {
4590      let prefix = quote! { ::tauri::utils::config::FrontendDist };
4591
4592      tokens.append_all(match self {
4593        Self::Url(url) => {
4594          let url = url_lit(url);
4595          quote! { #prefix::Url(#url) }
4596        }
4597        Self::Directory(path) => {
4598          let path = path_buf_lit(path);
4599          quote! { #prefix::Directory(#path) }
4600        }
4601        Self::Files(files) => {
4602          let files = vec_lit(files, path_buf_lit);
4603          quote! { #prefix::Files(#files) }
4604        }
4605      })
4606    }
4607  }
4608
4609  impl ToTokens for RunnerConfig {
4610    fn to_tokens(&self, tokens: &mut TokenStream) {
4611      let prefix = quote! { ::tauri::utils::config::RunnerConfig };
4612
4613      tokens.append_all(match self {
4614        Self::String(cmd) => {
4615          let cmd = cmd.as_str();
4616          quote!(#prefix::String(#cmd.into()))
4617        }
4618        Self::Object { cmd, cwd, args } => {
4619          let cmd = cmd.as_str();
4620          let cwd = opt_str_lit(cwd.as_ref());
4621          let args = opt_lit(args.as_ref().map(|v| vec_lit(v, str_lit)).as_ref());
4622          quote!(#prefix::Object {
4623            cmd: #cmd.into(),
4624            cwd: #cwd,
4625            args: #args,
4626          })
4627        }
4628      })
4629    }
4630  }
4631
4632  impl ToTokens for BuildConfig {
4633    fn to_tokens(&self, tokens: &mut TokenStream) {
4634      let dev_url = opt_lit(self.dev_url.as_ref().map(url_lit).as_ref());
4635      let frontend_dist = opt_lit(self.frontend_dist.as_ref());
4636      let runner = opt_lit(self.runner.as_ref());
4637      let before_dev_command = quote!(None);
4638      let before_build_command = quote!(None);
4639      let before_bundle_command = quote!(None);
4640      let features = quote!(None);
4641      let remove_unused_commands = quote!(false);
4642      let additional_watch_folders = quote!(Vec::new());
4643      let windows = &self.windows;
4644
4645      literal_struct!(
4646        tokens,
4647        ::tauri::utils::config::BuildConfig,
4648        runner,
4649        dev_url,
4650        frontend_dist,
4651        before_dev_command,
4652        before_build_command,
4653        before_bundle_command,
4654        features,
4655        remove_unused_commands,
4656        additional_watch_folders,
4657        windows
4658      );
4659    }
4660  }
4661
4662  impl ToTokens for WindowsBuildConfig {
4663    fn to_tokens(&self, tokens: &mut TokenStream) {
4664      let static_vc_runtime = self.static_vc_runtime;
4665
4666      literal_struct!(
4667        tokens,
4668        ::tauri::utils::config::WindowsBuildConfig,
4669        static_vc_runtime
4670      );
4671    }
4672  }
4673
4674  impl ToTokens for CspDirectiveSources {
4675    fn to_tokens(&self, tokens: &mut TokenStream) {
4676      let prefix = quote! { ::tauri::utils::config::CspDirectiveSources };
4677
4678      tokens.append_all(match self {
4679        Self::Inline(sources) => {
4680          let sources = sources.as_str();
4681          quote!(#prefix::Inline(#sources.into()))
4682        }
4683        Self::List(list) => {
4684          let list = vec_lit(list, str_lit);
4685          quote!(#prefix::List(#list))
4686        }
4687      })
4688    }
4689  }
4690
4691  impl ToTokens for Csp {
4692    fn to_tokens(&self, tokens: &mut TokenStream) {
4693      let prefix = quote! { ::tauri::utils::config::Csp };
4694
4695      tokens.append_all(match self {
4696        Self::Policy(policy) => {
4697          let policy = policy.as_str();
4698          quote!(#prefix::Policy(#policy.into()))
4699        }
4700        Self::DirectiveMap(list) => {
4701          // Pass a sorted vec so the HashMap constructor is deterministic
4702          // see: https://github.com/tauri-apps/tauri/issues/14978
4703          // TODO: Remove this in v3, use a BTreeMap instead of a HashMap
4704          let mut sorted: Vec<_> = list.iter().collect();
4705          sorted.sort_by_key(|(k, _)| *k);
4706          let map = map_lit(
4707            quote! { ::std::collections::HashMap },
4708            sorted,
4709            str_lit,
4710            identity,
4711          );
4712          quote!(#prefix::DirectiveMap(#map))
4713        }
4714      })
4715    }
4716  }
4717
4718  impl ToTokens for DisabledCspModificationKind {
4719    fn to_tokens(&self, tokens: &mut TokenStream) {
4720      let prefix = quote! { ::tauri::utils::config::DisabledCspModificationKind };
4721
4722      tokens.append_all(match self {
4723        Self::Flag(flag) => {
4724          quote! { #prefix::Flag(#flag) }
4725        }
4726        Self::List(directives) => {
4727          let directives = vec_lit(directives, str_lit);
4728          quote! { #prefix::List(#directives) }
4729        }
4730      });
4731    }
4732  }
4733
4734  impl ToTokens for CapabilityEntry {
4735    fn to_tokens(&self, tokens: &mut TokenStream) {
4736      let prefix = quote! { ::tauri::utils::config::CapabilityEntry };
4737
4738      tokens.append_all(match self {
4739        Self::Inlined(capability) => {
4740          quote! { #prefix::Inlined(#capability) }
4741        }
4742        Self::Reference(id) => {
4743          let id = str_lit(id);
4744          quote! { #prefix::Reference(#id) }
4745        }
4746      });
4747    }
4748  }
4749
4750  impl ToTokens for HeaderSource {
4751    fn to_tokens(&self, tokens: &mut TokenStream) {
4752      let prefix = quote! { ::tauri::utils::config::HeaderSource };
4753
4754      tokens.append_all(match self {
4755        Self::Inline(s) => {
4756          let line = s.as_str();
4757          quote!(#prefix::Inline(#line.into()))
4758        }
4759        Self::List(l) => {
4760          let list = vec_lit(l, str_lit);
4761          quote!(#prefix::List(#list))
4762        }
4763        Self::Map(m) => {
4764          // Pass a sorted vec so the HashMap constructor is deterministic
4765          // see: https://github.com/tauri-apps/tauri/issues/14978
4766          // TODO: Remove this in v3, use a BTreeMap instead of a HashMap
4767          let mut sorted: Vec<_> = m.iter().collect();
4768          sorted.sort_by_key(|(k, _)| *k);
4769          let map = map_lit(
4770            quote! { ::std::collections::HashMap },
4771            sorted,
4772            str_lit,
4773            str_lit,
4774          );
4775          quote!(#prefix::Map(#map))
4776        }
4777      })
4778    }
4779  }
4780
4781  impl ToTokens for HeaderConfig {
4782    fn to_tokens(&self, tokens: &mut TokenStream) {
4783      let access_control_allow_credentials =
4784        opt_lit(self.access_control_allow_credentials.as_ref());
4785      let access_control_allow_headers = opt_lit(self.access_control_allow_headers.as_ref());
4786      let access_control_allow_methods = opt_lit(self.access_control_allow_methods.as_ref());
4787      let access_control_expose_headers = opt_lit(self.access_control_expose_headers.as_ref());
4788      let access_control_max_age = opt_lit(self.access_control_max_age.as_ref());
4789      let cross_origin_embedder_policy = opt_lit(self.cross_origin_embedder_policy.as_ref());
4790      let cross_origin_opener_policy = opt_lit(self.cross_origin_opener_policy.as_ref());
4791      let cross_origin_resource_policy = opt_lit(self.cross_origin_resource_policy.as_ref());
4792      let permissions_policy = opt_lit(self.permissions_policy.as_ref());
4793      let service_worker_allowed = opt_lit(self.service_worker_allowed.as_ref());
4794      let timing_allow_origin = opt_lit(self.timing_allow_origin.as_ref());
4795      let x_content_type_options = opt_lit(self.x_content_type_options.as_ref());
4796      let tauri_custom_header = opt_lit(self.tauri_custom_header.as_ref());
4797
4798      literal_struct!(
4799        tokens,
4800        ::tauri::utils::config::HeaderConfig,
4801        access_control_allow_credentials,
4802        access_control_allow_headers,
4803        access_control_allow_methods,
4804        access_control_expose_headers,
4805        access_control_max_age,
4806        cross_origin_embedder_policy,
4807        cross_origin_opener_policy,
4808        cross_origin_resource_policy,
4809        permissions_policy,
4810        service_worker_allowed,
4811        timing_allow_origin,
4812        x_content_type_options,
4813        tauri_custom_header
4814      );
4815    }
4816  }
4817
4818  impl ToTokens for SecurityConfig {
4819    fn to_tokens(&self, tokens: &mut TokenStream) {
4820      let csp = opt_lit(self.csp.as_ref());
4821      let dev_csp = opt_lit(self.dev_csp.as_ref());
4822      let freeze_prototype = self.freeze_prototype;
4823      let dangerous_disable_asset_csp_modification = &self.dangerous_disable_asset_csp_modification;
4824      let asset_protocol = &self.asset_protocol;
4825      let pattern = &self.pattern;
4826      let capabilities = vec_lit(&self.capabilities, identity);
4827      let headers = opt_lit(self.headers.as_ref());
4828
4829      literal_struct!(
4830        tokens,
4831        ::tauri::utils::config::SecurityConfig,
4832        csp,
4833        dev_csp,
4834        freeze_prototype,
4835        dangerous_disable_asset_csp_modification,
4836        asset_protocol,
4837        pattern,
4838        capabilities,
4839        headers
4840      );
4841    }
4842  }
4843
4844  impl ToTokens for TrayIconConfig {
4845    fn to_tokens(&self, tokens: &mut TokenStream) {
4846      // For [`Self::menu_on_left_click`]
4847      tokens.append_all(quote!(#[allow(deprecated)]));
4848
4849      let id = opt_str_lit(self.id.as_ref());
4850      let icon_as_template = self.icon_as_template;
4851      #[allow(deprecated)]
4852      let menu_on_left_click = self.menu_on_left_click;
4853      let show_menu_on_left_click = self.show_menu_on_left_click;
4854      let icon_path = path_buf_lit(&self.icon_path);
4855      let title = opt_str_lit(self.title.as_ref());
4856      let tooltip = opt_str_lit(self.tooltip.as_ref());
4857      literal_struct!(
4858        tokens,
4859        ::tauri::utils::config::TrayIconConfig,
4860        id,
4861        icon_path,
4862        icon_as_template,
4863        menu_on_left_click,
4864        show_menu_on_left_click,
4865        title,
4866        tooltip
4867      );
4868    }
4869  }
4870
4871  impl ToTokens for FsScope {
4872    fn to_tokens(&self, tokens: &mut TokenStream) {
4873      let prefix = quote! { ::tauri::utils::config::FsScope };
4874
4875      tokens.append_all(match self {
4876        Self::AllowedPaths(allow) => {
4877          let allowed_paths = vec_lit(allow, path_buf_lit);
4878          quote! { #prefix::AllowedPaths(#allowed_paths) }
4879        }
4880        Self::Scope { allow, deny , require_literal_leading_dot} => {
4881          let allow = vec_lit(allow, path_buf_lit);
4882          let deny = vec_lit(deny, path_buf_lit);
4883          let  require_literal_leading_dot = opt_lit(require_literal_leading_dot.as_ref());
4884          quote! { #prefix::Scope { allow: #allow, deny: #deny, require_literal_leading_dot: #require_literal_leading_dot } }
4885        }
4886      });
4887    }
4888  }
4889
4890  impl ToTokens for AssetProtocolConfig {
4891    fn to_tokens(&self, tokens: &mut TokenStream) {
4892      let scope = &self.scope;
4893      tokens.append_all(quote! { ::tauri::utils::config::AssetProtocolConfig { scope: #scope, ..Default::default() } })
4894    }
4895  }
4896
4897  impl ToTokens for AppDirectoryOverrides {
4898    fn to_tokens(&self, tokens: &mut TokenStream) {
4899      let config = opt_lit_owned(self.config.as_ref().map(path_buf_lit));
4900      let data = opt_lit_owned(self.data.as_ref().map(path_buf_lit));
4901      let local_data = opt_lit_owned(self.local_data.as_ref().map(path_buf_lit));
4902      let cache = opt_lit_owned(self.cache.as_ref().map(path_buf_lit));
4903      let log = opt_lit_owned(self.log.as_ref().map(path_buf_lit));
4904
4905      literal_struct!(
4906        tokens,
4907        ::tauri::utils::config::AppDirectoryOverrides,
4908        config,
4909        data,
4910        local_data,
4911        cache,
4912        log
4913      );
4914    }
4915  }
4916
4917  impl ToTokens for AppDirectoriesOverride {
4918    fn to_tokens(&self, tokens: &mut TokenStream) {
4919      let prefix = quote! { ::tauri::utils::config::AppDirectoriesOverride };
4920
4921      tokens.append_all(match self {
4922        Self::Root(root) => {
4923          let root = path_buf_lit(root);
4924          quote! { #prefix::Root(#root) }
4925        }
4926        Self::Directories(directories) => quote! { #prefix::Directories(#directories) },
4927      })
4928    }
4929  }
4930
4931  impl ToTokens for AppConfig {
4932    fn to_tokens(&self, tokens: &mut TokenStream) {
4933      let windows = vec_lit(&self.windows, identity);
4934      let security = &self.security;
4935      let tray_icon = opt_lit(self.tray_icon.as_ref());
4936      let macos_private_api = self.macos_private_api;
4937      let with_global_tauri = self.with_global_tauri;
4938      let enable_gtk_app_id = self.enable_gtk_app_id;
4939      let app_directories_override = opt_lit(self.app_directories_override.as_ref());
4940
4941      literal_struct!(
4942        tokens,
4943        ::tauri::utils::config::AppConfig,
4944        windows,
4945        security,
4946        tray_icon,
4947        macos_private_api,
4948        with_global_tauri,
4949        enable_gtk_app_id,
4950        app_directories_override
4951      );
4952    }
4953  }
4954
4955  impl ToTokens for PluginConfig {
4956    fn to_tokens(&self, tokens: &mut TokenStream) {
4957      // Pass a sorted vec so the HashMap constructor is deterministic
4958      // see: https://github.com/tauri-apps/tauri/issues/14978
4959      // TODO: Remove this in v3, use a BTreeMap instead of a HashMap
4960      let mut sorted: Vec<_> = self.0.iter().collect();
4961      sorted.sort_by_key(|(k, _)| *k);
4962      let config = map_lit(
4963        quote! { ::std::collections::HashMap },
4964        sorted,
4965        str_lit,
4966        json_value_lit,
4967      );
4968      tokens.append_all(quote! { ::tauri::utils::config::PluginConfig(#config) })
4969    }
4970  }
4971
4972  impl ToTokens for Config {
4973    fn to_tokens(&self, tokens: &mut TokenStream) {
4974      let schema = quote!(None);
4975      let product_name = opt_str_lit(self.product_name.as_ref());
4976      let main_binary_name = opt_str_lit(self.main_binary_name.as_ref());
4977      let version = opt_str_lit(self.version.as_ref());
4978      let identifier = str_lit(&self.identifier);
4979      let app = &self.app;
4980      let build = &self.build;
4981      let bundle = &self.bundle;
4982      let plugins = &self.plugins;
4983
4984      literal_struct!(
4985        tokens,
4986        ::tauri::utils::config::Config,
4987        schema,
4988        product_name,
4989        main_binary_name,
4990        version,
4991        identifier,
4992        app,
4993        build,
4994        bundle,
4995        plugins
4996      );
4997    }
4998  }
4999}
5000
5001#[cfg(test)]
5002mod test {
5003  use super::*;
5004
5005  // TODO: create a test that compares a config to a json config
5006
5007  #[test]
5008  // test all of the default functions
5009  fn test_defaults() {
5010    // get default app config
5011    let a_config = AppConfig::default();
5012    // get default build config
5013    let b_config = BuildConfig::default();
5014    // get default window
5015    let d_windows: Vec<WindowConfig> = vec![];
5016    // get default bundle
5017    let d_bundle = BundleConfig::default();
5018
5019    // create a tauri config.
5020    let app = AppConfig {
5021      windows: vec![],
5022      security: SecurityConfig {
5023        csp: None,
5024        dev_csp: None,
5025        freeze_prototype: false,
5026        dangerous_disable_asset_csp_modification: DisabledCspModificationKind::Flag(false),
5027        asset_protocol: AssetProtocolConfig::default(),
5028        pattern: Default::default(),
5029        capabilities: Vec::new(),
5030        headers: None,
5031      },
5032      tray_icon: None,
5033      macos_private_api: false,
5034      with_global_tauri: false,
5035      enable_gtk_app_id: false,
5036      app_directories_override: None,
5037    };
5038
5039    // create a build config
5040    let build = BuildConfig {
5041      runner: None,
5042      dev_url: None,
5043      frontend_dist: None,
5044      before_dev_command: None,
5045      before_build_command: None,
5046      before_bundle_command: None,
5047      features: None,
5048      remove_unused_commands: false,
5049      additional_watch_folders: Vec::new(),
5050      windows: WindowsBuildConfig::default(),
5051    };
5052
5053    // create a bundle config
5054    let bundle = BundleConfig {
5055      active: false,
5056      targets: Default::default(),
5057      create_updater_artifacts: Default::default(),
5058      publisher: None,
5059      homepage: None,
5060      icon: Vec::new(),
5061      resources: None,
5062      copyright: None,
5063      category: None,
5064      file_associations: None,
5065      short_description: None,
5066      long_description: None,
5067      use_local_tools_dir: false,
5068      license: None,
5069      license_file: None,
5070      linux: Default::default(),
5071      macos: Default::default(),
5072      external_bin: None,
5073      windows: Default::default(),
5074      ios: Default::default(),
5075      android: Default::default(),
5076    };
5077
5078    // test the configs
5079    assert_eq!(a_config, app);
5080    assert_eq!(b_config, build);
5081    assert_eq!(d_bundle, bundle);
5082    assert_eq!(d_windows, app.windows);
5083  }
5084
5085  #[test]
5086  fn app_directories_override_root() {
5087    let config: AppDirectoriesOverride = serde_json::from_str(r#""./""#).unwrap();
5088    assert_eq!(config, AppDirectoriesOverride::Root("./".into()));
5089
5090    let config: AppDirectoriesOverride = serde_json::from_str(r#""$DATA/my-app""#).unwrap();
5091    assert_eq!(config, AppDirectoriesOverride::Root("$DATA/my-app".into()));
5092  }
5093
5094  #[test]
5095  fn app_directories_override_directories() {
5096    let config: AppDirectoriesOverride = serde_json::from_str(
5097      r#"{ "log": "$DATA/logs", "cache": "$CACHE/my-app", "local-data": "data" }"#,
5098    )
5099    .unwrap();
5100    assert_eq!(
5101      config,
5102      AppDirectoriesOverride::Directories(AppDirectoryOverrides {
5103        config: None,
5104        data: None,
5105        local_data: Some("data".into()),
5106        cache: Some("$CACHE/my-app".into()),
5107        log: Some("$DATA/logs".into()),
5108      })
5109    );
5110
5111    let config: AppDirectoriesOverride =
5112      serde_json::from_str(r#"{ "config": "conf", "data": "data", "localData": "local" }"#)
5113        .unwrap();
5114    assert_eq!(
5115      config,
5116      AppDirectoriesOverride::Directories(AppDirectoryOverrides {
5117        config: Some("conf".into()),
5118        data: Some("data".into()),
5119        local_data: Some("local".into()),
5120        cache: None,
5121        log: None,
5122      })
5123    );
5124
5125    let config: AppDirectoriesOverride = serde_json::from_str("{}").unwrap();
5126    assert_eq!(
5127      config,
5128      AppDirectoriesOverride::Directories(AppDirectoryOverrides::default())
5129    );
5130  }
5131
5132  #[test]
5133  fn app_directories_override_rejects_unknown_directories() {
5134    let err = serde_json::from_str::<AppDirectoriesOverride>(r#"{ "logs": "x" }"#).unwrap_err();
5135    assert!(err.to_string().contains("unknown field `logs`"), "{err}");
5136  }
5137
5138  #[test]
5139  fn app_directories_override_accepts_supported_variables() {
5140    for variable in APP_DIRECTORIES_OVERRIDE_VARIABLES {
5141      for path in [
5142        variable.to_string(),
5143        format!("{variable}/my-app"),
5144        format!("{variable}/../my-app"),
5145      ] {
5146        let json = serde_json::to_string(&path).unwrap();
5147        let config: AppDirectoriesOverride = serde_json::from_str(&json).unwrap();
5148        assert_eq!(config, AppDirectoriesOverride::Root(path.into()));
5149      }
5150    }
5151  }
5152
5153  #[test]
5154  fn app_directories_override_rejects_unsupported_variables() {
5155    for variable in [
5156      "$APPCONFIG",
5157      "$APPDATA",
5158      "$APPLOCALDATA",
5159      "$APPCACHE",
5160      "$APPLOG",
5161      "$EXE",
5162      "$FONT",
5163      "$RESOURCE",
5164      "$RUNTIME",
5165      "$TEMPLATE",
5166      "$UNKNOWN",
5167    ] {
5168      let err = serde_json::from_str::<AppDirectoriesOverride>(&format!(r#""{variable}/my-app""#))
5169        .unwrap_err();
5170      assert!(
5171        err
5172          .to_string()
5173          .contains(&format!("unsupported base directory variable `{variable}`")),
5174        "{variable}: {err}"
5175      );
5176
5177      let err =
5178        serde_json::from_str::<AppDirectoriesOverride>(&format!(r#"{{ "log": "{variable}" }}"#))
5179          .unwrap_err();
5180      assert!(
5181        err
5182          .to_string()
5183          .contains("unsupported base directory variable"),
5184        "{variable}: {err}"
5185      );
5186    }
5187  }
5188
5189  #[cfg(windows)]
5190  #[test]
5191  fn app_directories_override_rejects_root_relative_paths() {
5192    for path in [r"\my-app", "C:my-app"] {
5193      let json = serde_json::to_string(path).unwrap();
5194      let err = serde_json::from_str::<AppDirectoriesOverride>(&json).unwrap_err();
5195      assert!(
5196        err.to_string().contains("must be an absolute path"),
5197        "{path}: {err}"
5198      );
5199    }
5200  }
5201
5202  #[cfg(feature = "build")]
5203  #[test]
5204  fn app_directories_override_to_tokens() {
5205    use quote::ToTokens;
5206
5207    let tokens = AppDirectoriesOverride::Root("./".into())
5208      .to_token_stream()
5209      .to_string()
5210      .replace(' ', "");
5211    assert_eq!(
5212      tokens,
5213      r#"::tauri::utils::config::AppDirectoriesOverride::Root(::std::path::PathBuf::from("./"))"#
5214    );
5215
5216    let tokens = AppDirectoriesOverride::Directories(AppDirectoryOverrides {
5217      log: Some("$DATA/logs".into()),
5218      ..Default::default()
5219    })
5220    .to_token_stream()
5221    .to_string()
5222    .replace(' ', "");
5223    assert_eq!(
5224      tokens,
5225      r#"::tauri::utils::config::AppDirectoriesOverride::Directories(::tauri::utils::config::AppDirectoryOverrides{config:::core::option::Option::None,data:::core::option::Option::None,local_data:::core::option::Option::None,cache:::core::option::Option::None,log:::core::option::Option::Some(::std::path::PathBuf::from("$DATA/logs"))})"#
5226    );
5227  }
5228
5229  #[test]
5230  fn parse_hex_color() {
5231    use super::Color;
5232
5233    assert_eq!(Color(255, 255, 255, 255), "fff".parse().unwrap());
5234    assert_eq!(Color(255, 255, 255, 255), "#fff".parse().unwrap());
5235    assert_eq!(Color(0, 0, 0, 255), "#000000".parse().unwrap());
5236    assert_eq!(Color(0, 0, 0, 255), "#000000ff".parse().unwrap());
5237    assert_eq!(Color(0, 255, 0, 255), "#00ff00ff".parse().unwrap());
5238  }
5239
5240  #[test]
5241  fn test_runner_config_string_format() {
5242    use super::RunnerConfig;
5243
5244    // Test string format deserialization
5245    let json = r#""cargo""#;
5246    let runner: RunnerConfig = serde_json::from_str(json).unwrap();
5247
5248    assert_eq!(runner.cmd(), "cargo");
5249    assert_eq!(runner.cwd(), None);
5250    assert_eq!(runner.args(), None);
5251
5252    // Test string format serialization
5253    let serialized = serde_json::to_string(&runner).unwrap();
5254    assert_eq!(serialized, r#""cargo""#);
5255  }
5256
5257  #[test]
5258  fn test_runner_config_object_format_full() {
5259    use super::RunnerConfig;
5260
5261    // Test object format with all fields
5262    let json = r#"{"cmd": "my_runner", "cwd": "/tmp/build", "args": ["--quiet", "--verbose"]}"#;
5263    let runner: RunnerConfig = serde_json::from_str(json).unwrap();
5264
5265    assert_eq!(runner.cmd(), "my_runner");
5266    assert_eq!(runner.cwd(), Some("/tmp/build"));
5267    assert_eq!(
5268      runner.args(),
5269      Some(&["--quiet".to_string(), "--verbose".to_string()][..])
5270    );
5271
5272    // Test object format serialization
5273    let serialized = serde_json::to_string(&runner).unwrap();
5274    let deserialized: RunnerConfig = serde_json::from_str(&serialized).unwrap();
5275    assert_eq!(runner, deserialized);
5276  }
5277
5278  #[test]
5279  fn test_runner_config_object_format_minimal() {
5280    use super::RunnerConfig;
5281
5282    // Test object format with only cmd field
5283    let json = r#"{"cmd": "cross"}"#;
5284    let runner: RunnerConfig = serde_json::from_str(json).unwrap();
5285
5286    assert_eq!(runner.cmd(), "cross");
5287    assert_eq!(runner.cwd(), None);
5288    assert_eq!(runner.args(), None);
5289  }
5290
5291  #[test]
5292  fn test_runner_config_default() {
5293    use super::RunnerConfig;
5294
5295    let default_runner = RunnerConfig::default();
5296    assert_eq!(default_runner.cmd(), "cargo");
5297    assert_eq!(default_runner.cwd(), None);
5298    assert_eq!(default_runner.args(), None);
5299  }
5300
5301  #[test]
5302  fn test_runner_config_from_str() {
5303    use super::RunnerConfig;
5304
5305    // Test From<&str> trait
5306    let runner: RunnerConfig = "my_runner".into();
5307    assert_eq!(runner.cmd(), "my_runner");
5308    assert_eq!(runner.cwd(), None);
5309    assert_eq!(runner.args(), None);
5310  }
5311
5312  #[test]
5313  fn test_runner_config_from_string() {
5314    use super::RunnerConfig;
5315
5316    // Test From<String> trait
5317    let runner: RunnerConfig = "another_runner".to_string().into();
5318    assert_eq!(runner.cmd(), "another_runner");
5319    assert_eq!(runner.cwd(), None);
5320    assert_eq!(runner.args(), None);
5321  }
5322
5323  #[test]
5324  fn test_runner_config_from_str_parse() {
5325    use super::RunnerConfig;
5326    use std::str::FromStr;
5327
5328    // Test FromStr trait
5329    let runner = RunnerConfig::from_str("parsed_runner").unwrap();
5330    assert_eq!(runner.cmd(), "parsed_runner");
5331    assert_eq!(runner.cwd(), None);
5332    assert_eq!(runner.args(), None);
5333  }
5334
5335  #[test]
5336  fn test_runner_config_in_build_config() {
5337    use super::BuildConfig;
5338
5339    // Test string format in BuildConfig
5340    let json = r#"{"runner": "cargo"}"#;
5341    let build_config: BuildConfig = serde_json::from_str(json).unwrap();
5342
5343    let runner = build_config.runner.unwrap();
5344    assert_eq!(runner.cmd(), "cargo");
5345    assert_eq!(runner.cwd(), None);
5346    assert_eq!(runner.args(), None);
5347  }
5348
5349  #[test]
5350  fn test_runner_config_in_build_config_object() {
5351    use super::BuildConfig;
5352
5353    // Test object format in BuildConfig
5354    let json = r#"{"runner": {"cmd": "cross", "cwd": "/workspace", "args": ["--target", "x86_64-unknown-linux-gnu"]}}"#;
5355    let build_config: BuildConfig = serde_json::from_str(json).unwrap();
5356
5357    let runner = build_config.runner.unwrap();
5358    assert_eq!(runner.cmd(), "cross");
5359    assert_eq!(runner.cwd(), Some("/workspace"));
5360    assert_eq!(
5361      runner.args(),
5362      Some(
5363        &[
5364          "--target".to_string(),
5365          "x86_64-unknown-linux-gnu".to_string()
5366        ][..]
5367      )
5368    );
5369  }
5370
5371  #[test]
5372  fn test_runner_config_in_full_config() {
5373    use super::Config;
5374
5375    // Test runner config in full Tauri config
5376    let json = r#"{
5377      "productName": "Test App",
5378      "version": "1.0.0",
5379      "identifier": "com.test.app",
5380      "build": {
5381        "runner": {
5382          "cmd": "my_custom_cargo",
5383          "cwd": "/tmp/build",
5384          "args": ["--quiet", "--verbose"]
5385        }
5386      }
5387    }"#;
5388
5389    let config: Config = serde_json::from_str(json).unwrap();
5390    let runner = config.build.runner.unwrap();
5391
5392    assert_eq!(runner.cmd(), "my_custom_cargo");
5393    assert_eq!(runner.cwd(), Some("/tmp/build"));
5394    assert_eq!(
5395      runner.args(),
5396      Some(&["--quiet".to_string(), "--verbose".to_string()][..])
5397    );
5398  }
5399
5400  #[test]
5401  fn test_runner_config_equality() {
5402    use super::RunnerConfig;
5403
5404    let runner1 = RunnerConfig::String("cargo".to_string());
5405    let runner2 = RunnerConfig::String("cargo".to_string());
5406    let runner3 = RunnerConfig::String("cross".to_string());
5407
5408    assert_eq!(runner1, runner2);
5409    assert_ne!(runner1, runner3);
5410
5411    let runner4 = RunnerConfig::Object {
5412      cmd: "cargo".to_string(),
5413      cwd: Some("/tmp".to_string()),
5414      args: Some(vec!["--quiet".to_string()]),
5415    };
5416    let runner5 = RunnerConfig::Object {
5417      cmd: "cargo".to_string(),
5418      cwd: Some("/tmp".to_string()),
5419      args: Some(vec!["--quiet".to_string()]),
5420    };
5421
5422    assert_eq!(runner4, runner5);
5423    assert_ne!(runner1, runner4);
5424  }
5425
5426  #[test]
5427  fn test_runner_config_untagged_serialization() {
5428    use super::RunnerConfig;
5429
5430    // Test that serde untagged works correctly - string should serialize as string, not object
5431    let string_runner = RunnerConfig::String("cargo".to_string());
5432    let string_json = serde_json::to_string(&string_runner).unwrap();
5433    assert_eq!(string_json, r#""cargo""#);
5434
5435    // Test that object serializes as object
5436    let object_runner = RunnerConfig::Object {
5437      cmd: "cross".to_string(),
5438      cwd: None,
5439      args: None,
5440    };
5441    let object_json = serde_json::to_string(&object_runner).unwrap();
5442    assert!(object_json.contains("\"cmd\":\"cross\""));
5443    // With skip_serializing_none, null values should not be included
5444    assert!(object_json.contains("\"cwd\":null") || !object_json.contains("cwd"));
5445    assert!(object_json.contains("\"args\":null") || !object_json.contains("args"));
5446  }
5447
5448  #[test]
5449  fn header_source_map_display_is_deterministic() {
5450    let map = HashMap::from([
5451      ("key3".to_string(), "'value3'".to_string()),
5452      ("key1".to_string(), "'value1' 'value2'".to_string()),
5453      ("key2".to_string(), "'value4'".to_string()),
5454    ]);
5455
5456    // the value must be sorted by key and stable across runs and across `HashMap` orderings
5457    assert_eq!(
5458      HeaderSource::Map(map.clone()).to_string(),
5459      "key1 'value1' 'value2'; key2 'value4'; key3 'value3'"
5460    );
5461
5462    let expected = HeaderSource::Map(map).to_string();
5463    for _ in 0..10 {
5464      let map = HashMap::from([
5465        ("key2".to_string(), "'value4'".to_string()),
5466        ("key3".to_string(), "'value3'".to_string()),
5467        ("key1".to_string(), "'value1' 'value2'".to_string()),
5468      ]);
5469      assert_eq!(HeaderSource::Map(map).to_string(), expected);
5470    }
5471
5472    // `Serialize` must keep matching `Display`'s ordering
5473    let map = HashMap::from([
5474      ("b".to_string(), "2".to_string()),
5475      ("a".to_string(), "1".to_string()),
5476    ]);
5477    assert_eq!(
5478      serde_json::to_string(&HeaderSource::Map(map)).unwrap(),
5479      r#"{"a":"1","b":"2"}"#
5480    );
5481  }
5482
5483  #[test]
5484  fn header_source_display() {
5485    assert_eq!(
5486      HeaderSource::Inline("same-origin".into()).to_string(),
5487      "same-origin"
5488    );
5489    assert_eq!(
5490      HeaderSource::List(vec!["https://a.example".into(), "https://b.example".into()]).to_string(),
5491      "https://a.example, https://b.example"
5492    );
5493  }
5494
5495  #[test]
5496  fn window_config_default_same_as_deserialize() {
5497    let config_from_deserialization: WindowConfig = serde_json::from_str("{}").unwrap();
5498    let config_from_default: WindowConfig = WindowConfig::default();
5499
5500    assert_eq!(config_from_deserialization, config_from_default);
5501  }
5502}