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