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;
29use semver::Version;
30use serde::{
31  de::{Deserializer, Error as DeError, Visitor},
32  Deserialize, Serialize, Serializer,
33};
34use serde_json::Value as JsonValue;
35use serde_untagged::UntaggedEnumVisitor;
36use serde_with::skip_serializing_none;
37use url::Url;
38
39use std::{
40  collections::HashMap,
41  fmt::{self, Display},
42  fs::read_to_string,
43  path::PathBuf,
44  str::FromStr,
45};
46
47/// Items to help with parsing content into a [`Config`].
48pub mod parse;
49
50use crate::{acl::capability::Capability, TitleBarStyle, WindowEffect, WindowEffectState};
51
52pub use self::parse::parse;
53
54fn default_true() -> bool {
55  true
56}
57
58/// An URL to open on a Tauri webview window.
59#[derive(PartialEq, Eq, Debug, Clone, Serialize)]
60#[cfg_attr(feature = "schema", derive(JsonSchema))]
61#[serde(untagged)]
62#[non_exhaustive]
63pub enum WebviewUrl {
64  /// An external URL. Must use either the `http` or `https` schemes.
65  External(Url),
66  /// The path portion of an app URL.
67  /// For instance, to load `tauri://localhost/users/john`,
68  /// you can simply provide `users/john` in this configuration.
69  App(PathBuf),
70  /// A custom protocol url, for example, `doom://index.html`
71  CustomProtocol(Url),
72}
73
74impl<'de> Deserialize<'de> for WebviewUrl {
75  fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
76  where
77    D: Deserializer<'de>,
78  {
79    #[derive(Deserialize)]
80    #[serde(untagged)]
81    enum WebviewUrlDeserializer {
82      Url(Url),
83      Path(PathBuf),
84    }
85
86    match WebviewUrlDeserializer::deserialize(deserializer)? {
87      WebviewUrlDeserializer::Url(u) => {
88        if u.scheme() == "https" || u.scheme() == "http" {
89          Ok(Self::External(u))
90        } else {
91          Ok(Self::CustomProtocol(u))
92        }
93      }
94      WebviewUrlDeserializer::Path(p) => Ok(Self::App(p)),
95    }
96  }
97}
98
99impl fmt::Display for WebviewUrl {
100  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101    match self {
102      Self::External(url) | Self::CustomProtocol(url) => write!(f, "{url}"),
103      Self::App(path) => write!(f, "{}", path.display()),
104    }
105  }
106}
107
108impl Default for WebviewUrl {
109  fn default() -> Self {
110    Self::App("index.html".into())
111  }
112}
113
114/// A bundle referenced by tauri-bundler.
115#[derive(Debug, PartialEq, Eq, Clone)]
116#[cfg_attr(feature = "schema", derive(JsonSchema))]
117#[cfg_attr(feature = "schema", schemars(rename_all = "lowercase"))]
118pub enum BundleType {
119  /// The debian bundle (.deb).
120  Deb,
121  /// The RPM bundle (.rpm).
122  Rpm,
123  /// The AppImage bundle (.appimage).
124  AppImage,
125  /// The Microsoft Installer bundle (.msi).
126  Msi,
127  /// The NSIS bundle (.exe).
128  Nsis,
129  /// The macOS application bundle (.app).
130  App,
131  /// The Apple Disk Image bundle (.dmg).
132  Dmg,
133}
134
135impl BundleType {
136  /// All bundle types.
137  fn all() -> &'static [Self] {
138    &[
139      BundleType::Deb,
140      BundleType::Rpm,
141      BundleType::AppImage,
142      BundleType::Msi,
143      BundleType::Nsis,
144      BundleType::App,
145      BundleType::Dmg,
146    ]
147  }
148}
149
150impl Display for BundleType {
151  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
152    write!(
153      f,
154      "{}",
155      match self {
156        Self::Deb => "deb",
157        Self::Rpm => "rpm",
158        Self::AppImage => "appimage",
159        Self::Msi => "msi",
160        Self::Nsis => "nsis",
161        Self::App => "app",
162        Self::Dmg => "dmg",
163      }
164    )
165  }
166}
167
168impl Serialize for BundleType {
169  fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
170  where
171    S: Serializer,
172  {
173    serializer.serialize_str(self.to_string().as_ref())
174  }
175}
176
177impl<'de> Deserialize<'de> for BundleType {
178  fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
179  where
180    D: Deserializer<'de>,
181  {
182    let s = String::deserialize(deserializer)?;
183    match s.to_lowercase().as_str() {
184      "deb" => Ok(Self::Deb),
185      "rpm" => Ok(Self::Rpm),
186      "appimage" => Ok(Self::AppImage),
187      "msi" => Ok(Self::Msi),
188      "nsis" => Ok(Self::Nsis),
189      "app" => Ok(Self::App),
190      "dmg" => Ok(Self::Dmg),
191      _ => Err(DeError::custom(format!("unknown bundle target '{s}'"))),
192    }
193  }
194}
195
196/// Targets to bundle. Each value is case insensitive.
197#[derive(Debug, PartialEq, Eq, Clone)]
198pub enum BundleTarget {
199  /// Bundle all targets.
200  All,
201  /// A list of bundle targets.
202  List(Vec<BundleType>),
203  /// A single bundle target.
204  One(BundleType),
205}
206
207#[cfg(feature = "schema")]
208impl schemars::JsonSchema for BundleTarget {
209  fn schema_name() -> std::string::String {
210    "BundleTarget".to_owned()
211  }
212
213  fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
214    let any_of = vec![
215      schemars::schema::SchemaObject {
216        const_value: Some("all".into()),
217        metadata: Some(Box::new(schemars::schema::Metadata {
218          description: Some("Bundle all targets.".to_owned()),
219          ..Default::default()
220        })),
221        ..Default::default()
222      }
223      .into(),
224      schemars::_private::metadata::add_description(
225        gen.subschema_for::<Vec<BundleType>>(),
226        "A list of bundle targets.",
227      ),
228      schemars::_private::metadata::add_description(
229        gen.subschema_for::<BundleType>(),
230        "A single bundle target.",
231      ),
232    ];
233
234    schemars::schema::SchemaObject {
235      subschemas: Some(Box::new(schemars::schema::SubschemaValidation {
236        any_of: Some(any_of),
237        ..Default::default()
238      })),
239      metadata: Some(Box::new(schemars::schema::Metadata {
240        description: Some("Targets to bundle. Each value is case insensitive.".to_owned()),
241        ..Default::default()
242      })),
243      ..Default::default()
244    }
245    .into()
246  }
247}
248
249impl Default for BundleTarget {
250  fn default() -> Self {
251    Self::All
252  }
253}
254
255impl Serialize for BundleTarget {
256  fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
257  where
258    S: Serializer,
259  {
260    match self {
261      Self::All => serializer.serialize_str("all"),
262      Self::List(l) => l.serialize(serializer),
263      Self::One(t) => serializer.serialize_str(t.to_string().as_ref()),
264    }
265  }
266}
267
268impl<'de> Deserialize<'de> for BundleTarget {
269  fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
270  where
271    D: Deserializer<'de>,
272  {
273    #[derive(Deserialize, Serialize)]
274    #[serde(untagged)]
275    pub enum BundleTargetInner {
276      List(Vec<BundleType>),
277      One(BundleType),
278      All(String),
279    }
280
281    match BundleTargetInner::deserialize(deserializer)? {
282      BundleTargetInner::All(s) if s.to_lowercase() == "all" => Ok(Self::All),
283      BundleTargetInner::All(t) => Err(DeError::custom(format!(
284        "invalid bundle type {t}, expected one of `all`, {}",
285        BundleType::all()
286          .iter()
287          .map(|b| format!("`{b}`"))
288          .collect::<Vec<_>>()
289          .join(", ")
290      ))),
291      BundleTargetInner::List(l) => Ok(Self::List(l)),
292      BundleTargetInner::One(t) => Ok(Self::One(t)),
293    }
294  }
295}
296
297impl BundleTarget {
298  /// Gets the bundle targets as a [`Vec`]. The vector is empty when set to [`BundleTarget::All`].
299  #[allow(dead_code)]
300  pub fn to_vec(&self) -> Vec<BundleType> {
301    match self {
302      Self::All => BundleType::all().to_vec(),
303      Self::List(list) => list.clone(),
304      Self::One(i) => vec![i.clone()],
305    }
306  }
307}
308
309/// Configuration for AppImage bundles.
310///
311/// See more: <https://v2.tauri.app/reference/config/#appimageconfig>
312#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
313#[cfg_attr(feature = "schema", derive(JsonSchema))]
314#[serde(rename_all = "camelCase", deny_unknown_fields)]
315pub struct AppImageConfig {
316  /// Include additional gstreamer dependencies needed for audio and video playback.
317  /// This increases the bundle size by ~15-35MB depending on your build system.
318  #[serde(default, alias = "bundle-media-framework")]
319  pub bundle_media_framework: bool,
320  /// The files to include in the Appimage Binary.
321  #[serde(default)]
322  pub files: HashMap<PathBuf, PathBuf>,
323}
324
325/// Configuration for Debian (.deb) bundles.
326///
327/// See more: <https://v2.tauri.app/reference/config/#debconfig>
328#[skip_serializing_none]
329#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
330#[cfg_attr(feature = "schema", derive(JsonSchema))]
331#[serde(rename_all = "camelCase", deny_unknown_fields)]
332pub struct DebConfig {
333  /// The list of deb dependencies your application relies on.
334  pub depends: Option<Vec<String>>,
335  /// The list of deb dependencies your application recommends.
336  pub recommends: Option<Vec<String>>,
337  /// The list of dependencies the package provides.
338  pub provides: Option<Vec<String>>,
339  /// The list of package conflicts.
340  pub conflicts: Option<Vec<String>>,
341  /// The list of package replaces.
342  pub replaces: Option<Vec<String>>,
343  /// The files to include on the package.
344  #[serde(default)]
345  pub files: HashMap<PathBuf, PathBuf>,
346  /// Define the section in Debian Control file. See : https://www.debian.org/doc/debian-policy/ch-archive.html#s-subsections
347  pub section: Option<String>,
348  /// Change the priority of the Debian Package. By default, it is set to `optional`.
349  /// Recognized Priorities as of now are :  `required`, `important`, `standard`, `optional`, `extra`
350  pub priority: Option<String>,
351  /// Path of the uncompressed Changelog file, to be stored at /usr/share/doc/package-name/changelog.gz. See
352  /// <https://www.debian.org/doc/debian-policy/ch-docs.html#changelog-files-and-release-notes>
353  pub changelog: Option<PathBuf>,
354  /// Path to a custom desktop file Handlebars template.
355  ///
356  /// Available variables: `categories`, `comment` (optional), `exec`, `icon` and `name`.
357  #[serde(alias = "desktop-template")]
358  pub desktop_template: Option<PathBuf>,
359  /// Path to script that will be executed before the package is unpacked. See
360  /// <https://www.debian.org/doc/debian-policy/ch-maintainerscripts.html>
361  #[serde(alias = "pre-install-script")]
362  pub pre_install_script: Option<PathBuf>,
363  /// Path to script that will be executed after the package is unpacked. See
364  /// <https://www.debian.org/doc/debian-policy/ch-maintainerscripts.html>
365  #[serde(alias = "post-install-script")]
366  pub post_install_script: Option<PathBuf>,
367  /// Path to script that will be executed before the package is removed. See
368  /// <https://www.debian.org/doc/debian-policy/ch-maintainerscripts.html>
369  #[serde(alias = "pre-remove-script")]
370  pub pre_remove_script: Option<PathBuf>,
371  /// Path to script that will be executed after the package is removed. See
372  /// <https://www.debian.org/doc/debian-policy/ch-maintainerscripts.html>
373  #[serde(alias = "post-remove-script")]
374  pub post_remove_script: Option<PathBuf>,
375}
376
377/// Configuration for Linux bundles.
378///
379/// See more: <https://v2.tauri.app/reference/config/#linuxconfig>
380#[skip_serializing_none]
381#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
382#[cfg_attr(feature = "schema", derive(JsonSchema))]
383#[serde(rename_all = "camelCase", deny_unknown_fields)]
384pub struct LinuxConfig {
385  /// Configuration for the AppImage bundle.
386  #[serde(default)]
387  pub appimage: AppImageConfig,
388  /// Configuration for the Debian bundle.
389  #[serde(default)]
390  pub deb: DebConfig,
391  /// Configuration for the RPM bundle.
392  #[serde(default)]
393  pub rpm: RpmConfig,
394}
395
396/// Compression algorithms used when bundling RPM packages.
397#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
398#[cfg_attr(feature = "schema", derive(JsonSchema))]
399#[serde(rename_all = "camelCase", deny_unknown_fields, tag = "type")]
400#[non_exhaustive]
401pub enum RpmCompression {
402  /// Gzip compression
403  Gzip {
404    /// Gzip compression level
405    level: u32,
406  },
407  /// Zstd compression
408  Zstd {
409    /// Zstd compression level
410    level: i32,
411  },
412  /// Xz compression
413  Xz {
414    /// Xz compression level
415    level: u32,
416  },
417  /// Bzip2 compression
418  Bzip2 {
419    /// Bzip2 compression level
420    level: u32,
421  },
422  /// Disable compression
423  None,
424}
425
426/// Configuration for RPM bundles.
427#[skip_serializing_none]
428#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
429#[cfg_attr(feature = "schema", derive(JsonSchema))]
430#[serde(rename_all = "camelCase", deny_unknown_fields)]
431pub struct RpmConfig {
432  /// The list of RPM dependencies your application relies on.
433  pub depends: Option<Vec<String>>,
434  /// The list of RPM dependencies your application recommends.
435  pub recommends: Option<Vec<String>>,
436  /// The list of RPM dependencies your application provides.
437  pub provides: Option<Vec<String>>,
438  /// The list of RPM dependencies your application conflicts with. They must not be present
439  /// in order for the package to be installed.
440  pub conflicts: Option<Vec<String>>,
441  /// The list of RPM dependencies your application supersedes - if this package is installed,
442  /// packages listed as "obsoletes" will be automatically removed (if they are present).
443  pub obsoletes: Option<Vec<String>>,
444  /// The RPM release tag.
445  #[serde(default = "default_release")]
446  pub release: String,
447  /// The RPM epoch.
448  #[serde(default)]
449  pub epoch: u32,
450  /// The files to include on the package.
451  #[serde(default)]
452  pub files: HashMap<PathBuf, PathBuf>,
453  /// Path to a custom desktop file Handlebars template.
454  ///
455  /// Available variables: `categories`, `comment` (optional), `exec`, `icon` and `name`.
456  #[serde(alias = "desktop-template")]
457  pub desktop_template: Option<PathBuf>,
458  /// Path to script that will be executed before the package is unpacked. See
459  /// <http://ftp.rpm.org/max-rpm/s1-rpm-inside-scripts.html>
460  #[serde(alias = "pre-install-script")]
461  pub pre_install_script: Option<PathBuf>,
462  /// Path to script that will be executed after the package is unpacked. See
463  /// <http://ftp.rpm.org/max-rpm/s1-rpm-inside-scripts.html>
464  #[serde(alias = "post-install-script")]
465  pub post_install_script: Option<PathBuf>,
466  /// Path to script that will be executed before the package is removed. See
467  /// <http://ftp.rpm.org/max-rpm/s1-rpm-inside-scripts.html>
468  #[serde(alias = "pre-remove-script")]
469  pub pre_remove_script: Option<PathBuf>,
470  /// Path to script that will be executed after the package is removed. See
471  /// <http://ftp.rpm.org/max-rpm/s1-rpm-inside-scripts.html>
472  #[serde(alias = "post-remove-script")]
473  pub post_remove_script: Option<PathBuf>,
474  /// Compression algorithm and level. Defaults to `Gzip` with level 6.
475  pub compression: Option<RpmCompression>,
476}
477
478impl Default for RpmConfig {
479  fn default() -> Self {
480    Self {
481      depends: None,
482      recommends: None,
483      provides: None,
484      conflicts: None,
485      obsoletes: None,
486      release: default_release(),
487      epoch: 0,
488      files: Default::default(),
489      desktop_template: None,
490      pre_install_script: None,
491      post_install_script: None,
492      pre_remove_script: None,
493      post_remove_script: None,
494      compression: None,
495    }
496  }
497}
498
499fn default_release() -> String {
500  "1".into()
501}
502
503/// Position coordinates struct.
504#[derive(Default, Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
505#[cfg_attr(feature = "schema", derive(JsonSchema))]
506#[serde(rename_all = "camelCase", deny_unknown_fields)]
507pub struct Position {
508  /// X coordinate.
509  pub x: u32,
510  /// Y coordinate.
511  pub y: u32,
512}
513
514/// Position coordinates struct.
515#[derive(Default, Debug, PartialEq, Clone, Deserialize, Serialize)]
516#[cfg_attr(feature = "schema", derive(JsonSchema))]
517#[serde(rename_all = "camelCase", deny_unknown_fields)]
518pub struct LogicalPosition {
519  /// X coordinate.
520  pub x: f64,
521  /// Y coordinate.
522  pub y: f64,
523}
524
525/// Size of the window.
526#[derive(Default, Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
527#[cfg_attr(feature = "schema", derive(JsonSchema))]
528#[serde(rename_all = "camelCase", deny_unknown_fields)]
529pub struct Size {
530  /// Width of the window.
531  pub width: u32,
532  /// Height of the window.
533  pub height: u32,
534}
535
536/// Configuration for Apple Disk Image (.dmg) bundles.
537///
538/// See more: <https://v2.tauri.app/reference/config/#dmgconfig>
539#[skip_serializing_none]
540#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
541#[cfg_attr(feature = "schema", derive(JsonSchema))]
542#[serde(rename_all = "camelCase", deny_unknown_fields)]
543pub struct DmgConfig {
544  /// Image to use as the background in dmg file. Accepted formats: `png`/`jpg`/`gif`.
545  pub background: Option<PathBuf>,
546  /// Position of volume window on screen.
547  pub window_position: Option<Position>,
548  /// Size of volume window.
549  #[serde(default = "dmg_window_size", alias = "window-size")]
550  pub window_size: Size,
551  /// Position of app file on window.
552  #[serde(default = "dmg_app_position", alias = "app-position")]
553  pub app_position: Position,
554  /// Position of application folder on window.
555  #[serde(
556    default = "dmg_application_folder_position",
557    alias = "application-folder-position"
558  )]
559  pub application_folder_position: Position,
560}
561
562impl Default for DmgConfig {
563  fn default() -> Self {
564    Self {
565      background: None,
566      window_position: None,
567      window_size: dmg_window_size(),
568      app_position: dmg_app_position(),
569      application_folder_position: dmg_application_folder_position(),
570    }
571  }
572}
573
574fn dmg_window_size() -> Size {
575  Size {
576    width: 660,
577    height: 400,
578  }
579}
580
581fn dmg_app_position() -> Position {
582  Position { x: 180, y: 170 }
583}
584
585fn dmg_application_folder_position() -> Position {
586  Position { x: 480, y: 170 }
587}
588
589fn de_macos_minimum_system_version<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
590where
591  D: Deserializer<'de>,
592{
593  let version = Option::<String>::deserialize(deserializer)?;
594  match version {
595    Some(v) if v.is_empty() => Ok(macos_minimum_system_version()),
596    e => Ok(e),
597  }
598}
599
600/// Configuration for the macOS bundles.
601///
602/// See more: <https://v2.tauri.app/reference/config/#macconfig>
603#[skip_serializing_none]
604#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
605#[cfg_attr(feature = "schema", derive(JsonSchema))]
606#[serde(rename_all = "camelCase", deny_unknown_fields)]
607pub struct MacConfig {
608  /// A list of strings indicating any macOS X frameworks that need to be bundled with the application.
609  ///
610  /// 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.
611  pub frameworks: Option<Vec<String>>,
612  /// The files to include in the application relative to the Contents directory.
613  #[serde(default)]
614  pub files: HashMap<PathBuf, PathBuf>,
615  /// A version string indicating the minimum macOS X version that the bundled application supports. Defaults to `10.13`.
616  ///
617  /// Setting it to `null` completely removes the `LSMinimumSystemVersion` field on the bundle's `Info.plist`
618  /// and the `MACOSX_DEPLOYMENT_TARGET` environment variable.
619  ///
620  /// An empty string is considered an invalid value so the default value is used.
621  #[serde(
622    deserialize_with = "de_macos_minimum_system_version",
623    default = "macos_minimum_system_version",
624    alias = "minimum-system-version"
625  )]
626  pub minimum_system_version: Option<String>,
627  /// Allows your application to communicate with the outside world.
628  /// It should be a lowercase, without port and protocol domain name.
629  #[serde(alias = "exception-domain")]
630  pub exception_domain: Option<String>,
631  /// Identity to use for code signing.
632  #[serde(alias = "signing-identity")]
633  pub signing_identity: Option<String>,
634  /// Whether the codesign should enable [hardened runtime] (for executables) or not.
635  ///
636  /// [hardened runtime]: <https://developer.apple.com/documentation/security/hardened_runtime>
637  #[serde(alias = "hardened-runtime", default = "default_true")]
638  pub hardened_runtime: bool,
639  /// Provider short name for notarization.
640  #[serde(alias = "provider-short-name")]
641  pub provider_short_name: Option<String>,
642  /// Path to the entitlements file.
643  pub entitlements: Option<String>,
644  /// DMG-specific settings.
645  #[serde(default)]
646  pub dmg: DmgConfig,
647}
648
649impl Default for MacConfig {
650  fn default() -> Self {
651    Self {
652      frameworks: None,
653      files: HashMap::new(),
654      minimum_system_version: macos_minimum_system_version(),
655      exception_domain: None,
656      signing_identity: None,
657      hardened_runtime: true,
658      provider_short_name: None,
659      entitlements: None,
660      dmg: Default::default(),
661    }
662  }
663}
664
665fn macos_minimum_system_version() -> Option<String> {
666  Some("10.13".into())
667}
668
669fn ios_minimum_system_version() -> String {
670  "13.0".into()
671}
672
673/// Configuration for a target language for the WiX build.
674///
675/// See more: <https://v2.tauri.app/reference/config/#wixlanguageconfig>
676#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
677#[cfg_attr(feature = "schema", derive(JsonSchema))]
678#[serde(rename_all = "camelCase", deny_unknown_fields)]
679pub struct WixLanguageConfig {
680  /// The path to a locale (`.wxl`) file. See <https://wixtoolset.org/documentation/manual/v3/howtos/ui_and_localization/build_a_localized_version.html>.
681  #[serde(alias = "locale-path")]
682  pub locale_path: Option<String>,
683}
684
685/// The languages to build using WiX.
686#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
687#[cfg_attr(feature = "schema", derive(JsonSchema))]
688#[serde(untagged)]
689pub enum WixLanguage {
690  /// A single language to build, without configuration.
691  One(String),
692  /// A list of languages to build, without configuration.
693  List(Vec<String>),
694  /// A map of languages and its configuration.
695  Localized(HashMap<String, WixLanguageConfig>),
696}
697
698impl Default for WixLanguage {
699  fn default() -> Self {
700    Self::One("en-US".into())
701  }
702}
703
704/// Configuration for the MSI bundle using WiX.
705///
706/// See more: <https://v2.tauri.app/reference/config/#wixconfig>
707#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
708#[cfg_attr(feature = "schema", derive(JsonSchema))]
709#[serde(rename_all = "camelCase", deny_unknown_fields)]
710pub struct WixConfig {
711  /// MSI installer version in the format `major.minor.patch.build` (build is optional).
712  ///
713  /// Because a valid version is required for MSI installer, it will be derived from [`Config::version`] if this field is not set.
714  ///
715  /// 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.
716  /// The third and foruth fields have a maximum value of 65,535.
717  ///
718  /// See <https://learn.microsoft.com/en-us/windows/win32/msi/productversion> for more info.
719  pub version: Option<String>,
720  /// A GUID upgrade code for MSI installer. This code **_must stay the same across all of your updates_**,
721  /// otherwise, Windows will treat your update as a different app and your users will have duplicate versions of your app.
722  ///
723  /// By default, tauri generates this code by generating a Uuid v5 using the string `<productName>.exe.app.x64` in the DNS namespace.
724  /// You can use Tauri's CLI to generate and print this code for you, run `tauri inspect wix-upgrade-code`.
725  ///
726  /// It is recommended that you set this value in your tauri config file to avoid accidental changes in your upgrade code
727  /// whenever you want to change your product name.
728  #[serde(alias = "upgrade-code")]
729  pub upgrade_code: Option<uuid::Uuid>,
730  /// The installer languages to build. See <https://docs.microsoft.com/en-us/windows/win32/msi/localizing-the-error-and-actiontext-tables>.
731  #[serde(default)]
732  pub language: WixLanguage,
733  /// A custom .wxs template to use.
734  pub template: Option<PathBuf>,
735  /// A list of paths to .wxs files with WiX fragments to use.
736  #[serde(default, alias = "fragment-paths")]
737  pub fragment_paths: Vec<PathBuf>,
738  /// The ComponentGroup element ids you want to reference from the fragments.
739  #[serde(default, alias = "component-group-refs")]
740  pub component_group_refs: Vec<String>,
741  /// The Component element ids you want to reference from the fragments.
742  #[serde(default, alias = "component-refs")]
743  pub component_refs: Vec<String>,
744  /// The FeatureGroup element ids you want to reference from the fragments.
745  #[serde(default, alias = "feature-group-refs")]
746  pub feature_group_refs: Vec<String>,
747  /// The Feature element ids you want to reference from the fragments.
748  #[serde(default, alias = "feature-refs")]
749  pub feature_refs: Vec<String>,
750  /// The Merge element ids you want to reference from the fragments.
751  #[serde(default, alias = "merge-refs")]
752  pub merge_refs: Vec<String>,
753  /// Create an elevated update task within Windows Task Scheduler.
754  #[serde(default, alias = "enable-elevated-update-task")]
755  pub enable_elevated_update_task: bool,
756  /// Path to a bitmap file to use as the installation user interface banner.
757  /// This bitmap will appear at the top of all but the first page of the installer.
758  ///
759  /// The required dimensions are 493px × 58px.
760  #[serde(alias = "banner-path")]
761  pub banner_path: Option<PathBuf>,
762  /// Path to a bitmap file to use on the installation user interface dialogs.
763  /// It is used on the welcome and completion dialogs.
764  ///
765  /// The required dimensions are 493px × 312px.
766  #[serde(alias = "dialog-image-path")]
767  pub dialog_image_path: Option<PathBuf>,
768}
769
770/// Compression algorithms used in the NSIS installer.
771///
772/// See <https://nsis.sourceforge.io/Reference/SetCompressor>
773#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
774#[cfg_attr(feature = "schema", derive(JsonSchema))]
775#[serde(rename_all = "camelCase", deny_unknown_fields)]
776pub enum NsisCompression {
777  /// ZLIB uses the deflate algorithm, it is a quick and simple method. With the default compression level it uses about 300 KB of memory.
778  Zlib,
779  /// 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.
780  Bzip2,
781  /// 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.
782  Lzma,
783  /// Disable compression
784  None,
785}
786
787impl Default for NsisCompression {
788  fn default() -> Self {
789    Self::Lzma
790  }
791}
792
793/// Install Modes for the NSIS installer.
794#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
795#[serde(rename_all = "camelCase", deny_unknown_fields)]
796#[cfg_attr(feature = "schema", derive(JsonSchema))]
797pub enum NSISInstallerMode {
798  /// Default mode for the installer.
799  ///
800  /// Install the app by default in a directory that doesn't require Administrator access.
801  ///
802  /// Installer metadata will be saved under the `HKCU` registry path.
803  CurrentUser,
804  /// Install the app by default in the `Program Files` folder directory requires Administrator
805  /// access for the installation.
806  ///
807  /// Installer metadata will be saved under the `HKLM` registry path.
808  PerMachine,
809  /// Combines both modes and allows the user to choose at install time
810  /// whether to install for the current user or per machine. Note that this mode
811  /// will require Administrator access even if the user wants to install it for the current user only.
812  ///
813  /// Installer metadata will be saved under the `HKLM` or `HKCU` registry path based on the user's choice.
814  Both,
815}
816
817impl Default for NSISInstallerMode {
818  fn default() -> Self {
819    Self::CurrentUser
820  }
821}
822
823/// Configuration for the Installer bundle using NSIS.
824#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
825#[cfg_attr(feature = "schema", derive(JsonSchema))]
826#[serde(rename_all = "camelCase", deny_unknown_fields)]
827pub struct NsisConfig {
828  /// A custom .nsi template to use.
829  pub template: Option<PathBuf>,
830  /// The path to a bitmap file to display on the header of installers pages.
831  ///
832  /// The recommended dimensions are 150px x 57px.
833  #[serde(alias = "header-image")]
834  pub header_image: Option<PathBuf>,
835  /// The path to a bitmap file for the Welcome page and the Finish page.
836  ///
837  /// The recommended dimensions are 164px x 314px.
838  #[serde(alias = "sidebar-image")]
839  pub sidebar_image: Option<PathBuf>,
840  /// The path to an icon file used as the installer icon.
841  #[serde(alias = "install-icon")]
842  pub installer_icon: Option<PathBuf>,
843  /// Whether the installation will be for all users or just the current user.
844  #[serde(default, alias = "install-mode")]
845  pub install_mode: NSISInstallerMode,
846  /// A list of installer languages.
847  /// By default the OS language is used. If the OS language is not in the list of languages, the first language will be used.
848  /// To allow the user to select the language, set `display_language_selector` to `true`.
849  ///
850  /// See <https://github.com/kichik/nsis/tree/9465c08046f00ccb6eda985abbdbf52c275c6c4d/Contrib/Language%20files> for the complete list of languages.
851  pub languages: Option<Vec<String>>,
852  /// A key-value pair where the key is the language and the
853  /// value is the path to a custom `.nsh` file that holds the translated text for tauri's custom messages.
854  ///
855  /// See <https://github.com/tauri-apps/tauri/blob/dev/crates/tauri-bundler/src/bundle/windows/nsis/languages/English.nsh> for an example `.nsh` file.
856  ///
857  /// **Note**: the key must be a valid NSIS language and it must be added to [`NsisConfig`] languages array,
858  pub custom_language_files: Option<HashMap<String, PathBuf>>,
859  /// Whether to display a language selector dialog before the installer and uninstaller windows are rendered or not.
860  /// By default the OS language is selected, with a fallback to the first language in the `languages` array.
861  #[serde(default, alias = "display-language-selector")]
862  pub display_language_selector: bool,
863  /// Set the compression algorithm used to compress files in the installer.
864  ///
865  /// See <https://nsis.sourceforge.io/Reference/SetCompressor>
866  #[serde(default)]
867  pub compression: NsisCompression,
868  /// Set the folder name for the start menu shortcut.
869  ///
870  /// Use this option if you have multiple apps and wish to group their shortcuts under one folder
871  /// or if you generally prefer to set your shortcut inside a folder.
872  ///
873  /// Examples:
874  /// - `AwesomePublisher`, shortcut will be placed in `%AppData%\Microsoft\Windows\Start Menu\Programs\AwesomePublisher\<your-app>.lnk`
875  /// - If unset, shortcut will be placed in `%AppData%\Microsoft\Windows\Start Menu\Programs\<your-app>.lnk`
876  #[serde(alias = "start-menu-folder")]
877  pub start_menu_folder: Option<String>,
878  /// A path to a `.nsh` file that contains special NSIS macros to be hooked into the
879  /// main installer.nsi script.
880  ///
881  /// Supported hooks are:
882  /// - `NSIS_HOOK_PREINSTALL`: This hook runs before copying files, setting registry key values and creating shortcuts.
883  /// - `NSIS_HOOK_POSTINSTALL`: This hook runs after the installer has finished copying all files, setting the registry keys and created shortcuts.
884  /// - `NSIS_HOOK_PREUNINSTALL`: This hook runs before removing any files, registry keys and shortcuts.
885  /// - `NSIS_HOOK_POSTUNINSTALL`: This hook runs after files, registry keys and shortcuts have been removed.
886  ///
887  ///
888  /// ### Example
889  ///
890  /// ```nsh
891  /// !macro NSIS_HOOK_PREINSTALL
892  ///   MessageBox MB_OK "PreInstall"
893  /// !macroend
894  ///
895  /// !macro NSIS_HOOK_POSTINSTALL
896  ///   MessageBox MB_OK "PostInstall"
897  /// !macroend
898  ///
899  /// !macro NSIS_HOOK_PREUNINSTALL
900  ///   MessageBox MB_OK "PreUnInstall"
901  /// !macroend
902  ///
903  /// !macro NSIS_HOOK_POSTUNINSTALL
904  ///   MessageBox MB_OK "PostUninstall"
905  /// !macroend
906  ///
907  /// ```
908  #[serde(alias = "installer-hooks")]
909  pub installer_hooks: Option<PathBuf>,
910  /// Try to ensure that the WebView2 version is equal to or newer than this version,
911  /// if the user's WebView2 is older than this version,
912  /// the installer will try to trigger a WebView2 update.
913  #[serde(alias = "minimum-webview2-version")]
914  pub minimum_webview2_version: Option<String>,
915}
916
917/// Install modes for the Webview2 runtime.
918/// Note that for the updater bundle [`Self::DownloadBootstrapper`] is used.
919///
920/// For more information see <https://v2.tauri.app/distribute/windows-installer/#webview2-installation-options>.
921#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
922#[serde(tag = "type", rename_all = "camelCase", deny_unknown_fields)]
923#[cfg_attr(feature = "schema", derive(JsonSchema))]
924pub enum WebviewInstallMode {
925  /// Do not install the Webview2 as part of the Windows Installer.
926  Skip,
927  /// Download the bootstrapper and run it.
928  /// Requires an internet connection.
929  /// Results in a smaller installer size, but is not recommended on Windows 7.
930  DownloadBootstrapper {
931    /// Instructs the installer to run the bootstrapper in silent mode. Defaults to `true`.
932    #[serde(default = "default_true")]
933    silent: bool,
934  },
935  /// Embed the bootstrapper and run it.
936  /// Requires an internet connection.
937  /// Increases the installer size by around 1.8MB, but offers better support on Windows 7.
938  EmbedBootstrapper {
939    /// Instructs the installer to run the bootstrapper in silent mode. Defaults to `true`.
940    #[serde(default = "default_true")]
941    silent: bool,
942  },
943  /// Embed the offline installer and run it.
944  /// Does not require an internet connection.
945  /// Increases the installer size by around 127MB.
946  OfflineInstaller {
947    /// Instructs the installer to run the installer in silent mode. Defaults to `true`.
948    #[serde(default = "default_true")]
949    silent: bool,
950  },
951  /// Embed a fixed webview2 version and use it at runtime.
952  /// Increases the installer size by around 180MB.
953  FixedRuntime {
954    /// The path to the fixed runtime to use.
955    ///
956    /// The fixed version can be downloaded [on the official website](https://developer.microsoft.com/en-us/microsoft-edge/webview2/#download-section).
957    /// The `.cab` file must be extracted to a folder and this folder path must be defined on this field.
958    path: PathBuf,
959  },
960}
961
962impl Default for WebviewInstallMode {
963  fn default() -> Self {
964    Self::DownloadBootstrapper { silent: true }
965  }
966}
967
968/// Custom Signing Command configuration.
969#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
970#[cfg_attr(feature = "schema", derive(JsonSchema))]
971#[serde(rename_all = "camelCase", deny_unknown_fields, untagged)]
972pub enum CustomSignCommandConfig {
973  /// A string notation of the script to execute.
974  ///
975  /// "%1" will be replaced with the path to the binary to be signed.
976  ///
977  /// This is a simpler notation for the command.
978  /// Tauri will split the string with `' '` and use the first element as the command name and the rest as arguments.
979  ///
980  /// If you need to use whitespace in the command or arguments, use the object notation [`Self::ScriptWithOptions`].
981  Command(String),
982  /// An object notation of the command.
983  ///
984  /// This is more complex notation for the command but
985  /// this allows you to use whitespace in the command and arguments.
986  CommandWithOptions {
987    /// The command to run to sign the binary.
988    cmd: String,
989    /// The arguments to pass to the command.
990    ///
991    /// "%1" will be replaced with the path to the binary to be signed.
992    args: Vec<String>,
993  },
994}
995
996/// Windows bundler configuration.
997///
998/// See more: <https://v2.tauri.app/reference/config/#windowsconfig>
999#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1000#[cfg_attr(feature = "schema", derive(JsonSchema))]
1001#[serde(rename_all = "camelCase", deny_unknown_fields)]
1002pub struct WindowsConfig {
1003  /// Specifies the file digest algorithm to use for creating file signatures.
1004  /// Required for code signing. SHA-256 is recommended.
1005  #[serde(alias = "digest-algorithm")]
1006  pub digest_algorithm: Option<String>,
1007  /// Specifies the SHA1 hash of the signing certificate.
1008  #[serde(alias = "certificate-thumbprint")]
1009  pub certificate_thumbprint: Option<String>,
1010  /// Server to use during timestamping.
1011  #[serde(alias = "timestamp-url")]
1012  pub timestamp_url: Option<String>,
1013  /// Whether to use Time-Stamp Protocol (TSP, a.k.a. RFC 3161) for the timestamp server. Your code signing provider may
1014  /// use a TSP timestamp server, like e.g. SSL.com does. If so, enable TSP by setting to true.
1015  #[serde(default)]
1016  pub tsp: bool,
1017  /// The installation mode for the Webview2 runtime.
1018  #[serde(default, alias = "webview-install-mode")]
1019  pub webview_install_mode: WebviewInstallMode,
1020  /// Validates a second app installation, blocking the user from installing an older version if set to `false`.
1021  ///
1022  /// For instance, if `1.2.1` is installed, the user won't be able to install app version `1.2.0` or `1.1.5`.
1023  ///
1024  /// The default value of this flag is `true`.
1025  #[serde(default = "default_true", alias = "allow-downgrades")]
1026  pub allow_downgrades: bool,
1027  /// Configuration for the MSI generated with WiX.
1028  pub wix: Option<WixConfig>,
1029  /// Configuration for the installer generated with NSIS.
1030  pub nsis: Option<NsisConfig>,
1031  /// Specify a custom command to sign the binaries.
1032  /// This command needs to have a `%1` in args which is just a placeholder for the binary path,
1033  /// which we will detect and replace before calling the command.
1034  ///
1035  /// By Default we use `signtool.exe` which can be found only on Windows so
1036  /// if you are on another platform and want to cross-compile and sign you will
1037  /// need to use another tool like `osslsigncode`.
1038  #[serde(alias = "sign-command")]
1039  pub sign_command: Option<CustomSignCommandConfig>,
1040}
1041
1042impl Default for WindowsConfig {
1043  fn default() -> Self {
1044    Self {
1045      digest_algorithm: None,
1046      certificate_thumbprint: None,
1047      timestamp_url: None,
1048      tsp: false,
1049      webview_install_mode: Default::default(),
1050      allow_downgrades: true,
1051      wix: None,
1052      nsis: None,
1053      sign_command: None,
1054    }
1055  }
1056}
1057
1058/// macOS-only. Corresponds to CFBundleTypeRole
1059#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
1060#[cfg_attr(feature = "schema", derive(JsonSchema))]
1061pub enum BundleTypeRole {
1062  /// CFBundleTypeRole.Editor. Files can be read and edited.
1063  #[default]
1064  Editor,
1065  /// CFBundleTypeRole.Viewer. Files can be read.
1066  Viewer,
1067  /// CFBundleTypeRole.Shell
1068  Shell,
1069  /// CFBundleTypeRole.QLGenerator
1070  QLGenerator,
1071  /// CFBundleTypeRole.None
1072  None,
1073}
1074
1075impl Display for BundleTypeRole {
1076  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1077    match self {
1078      Self::Editor => write!(f, "Editor"),
1079      Self::Viewer => write!(f, "Viewer"),
1080      Self::Shell => write!(f, "Shell"),
1081      Self::QLGenerator => write!(f, "QLGenerator"),
1082      Self::None => write!(f, "None"),
1083    }
1084  }
1085}
1086
1087/// An extension for a [`FileAssociation`].
1088///
1089/// A leading `.` is automatically stripped.
1090#[derive(Debug, PartialEq, Eq, Clone, Serialize)]
1091#[cfg_attr(feature = "schema", derive(JsonSchema))]
1092pub struct AssociationExt(pub String);
1093
1094impl fmt::Display for AssociationExt {
1095  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1096    write!(f, "{}", self.0)
1097  }
1098}
1099
1100impl<'d> serde::Deserialize<'d> for AssociationExt {
1101  fn deserialize<D: Deserializer<'d>>(deserializer: D) -> Result<Self, D::Error> {
1102    let ext = String::deserialize(deserializer)?;
1103    if let Some(ext) = ext.strip_prefix('.') {
1104      Ok(AssociationExt(ext.into()))
1105    } else {
1106      Ok(AssociationExt(ext))
1107    }
1108  }
1109}
1110
1111/// File association
1112#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1113#[cfg_attr(feature = "schema", derive(JsonSchema))]
1114#[serde(rename_all = "camelCase", deny_unknown_fields)]
1115pub struct FileAssociation {
1116  /// File extensions to associate with this app. e.g. 'png'
1117  pub ext: Vec<AssociationExt>,
1118  /// The name. Maps to `CFBundleTypeName` on macOS. Default to `ext[0]`
1119  pub name: Option<String>,
1120  /// The association description. Windows-only. It is displayed on the `Type` column on Windows Explorer.
1121  pub description: Option<String>,
1122  /// The app's role with respect to the type. Maps to `CFBundleTypeRole` on macOS.
1123  #[serde(default)]
1124  pub role: BundleTypeRole,
1125  /// The mime-type e.g. 'image/png' or 'text/plain'. Linux-only.
1126  #[serde(alias = "mime-type")]
1127  pub mime_type: Option<String>,
1128}
1129
1130/// Deep link protocol configuration.
1131#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1132#[cfg_attr(feature = "schema", derive(JsonSchema))]
1133#[serde(rename_all = "camelCase", deny_unknown_fields)]
1134pub struct DeepLinkProtocol {
1135  /// URL schemes to associate with this app without `://`. For example `my-app`
1136  pub schemes: Vec<String>,
1137  /// The protocol name. **macOS-only** and maps to `CFBundleTypeName`. Defaults to `<bundle-id>.<schemes[0]>`
1138  pub name: Option<String>,
1139  /// The app's role for these schemes. **macOS-only** and maps to `CFBundleTypeRole`.
1140  #[serde(default)]
1141  pub role: BundleTypeRole,
1142}
1143
1144/// Definition for bundle resources.
1145/// Can be either a list of paths to include or a map of source to target paths.
1146#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1147#[cfg_attr(feature = "schema", derive(JsonSchema))]
1148#[serde(rename_all = "camelCase", deny_unknown_fields, untagged)]
1149pub enum BundleResources {
1150  /// A list of paths to include.
1151  List(Vec<String>),
1152  /// A map of source to target paths.
1153  Map(HashMap<String, String>),
1154}
1155
1156impl BundleResources {
1157  /// Adds a path to the resource collection.
1158  pub fn push(&mut self, path: impl Into<String>) {
1159    match self {
1160      Self::List(l) => l.push(path.into()),
1161      Self::Map(l) => {
1162        let path = path.into();
1163        l.insert(path.clone(), path);
1164      }
1165    }
1166  }
1167}
1168
1169/// Updater type
1170#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1171#[cfg_attr(feature = "schema", derive(JsonSchema))]
1172#[serde(rename_all = "camelCase", deny_unknown_fields, untagged)]
1173pub enum Updater {
1174  /// Generates lagacy zipped v1 compatible updaters
1175  String(V1Compatible),
1176  /// Produce updaters and their signatures or not
1177  // Can't use untagged on enum field here: https://github.com/GREsau/schemars/issues/222
1178  Bool(bool),
1179}
1180
1181impl Default for Updater {
1182  fn default() -> Self {
1183    Self::Bool(false)
1184  }
1185}
1186
1187/// Generates lagacy zipped v1 compatible updaters
1188#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1189#[cfg_attr(feature = "schema", derive(JsonSchema))]
1190#[serde(rename_all = "camelCase", deny_unknown_fields)]
1191pub enum V1Compatible {
1192  /// Generates lagacy zipped v1 compatible updaters
1193  V1Compatible,
1194}
1195
1196/// Configuration for tauri-bundler.
1197///
1198/// See more: <https://v2.tauri.app/reference/config/#bundleconfig>
1199#[skip_serializing_none]
1200#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
1201#[cfg_attr(feature = "schema", derive(JsonSchema))]
1202#[serde(rename_all = "camelCase", deny_unknown_fields)]
1203pub struct BundleConfig {
1204  /// Whether Tauri should bundle your application or just output the executable.
1205  #[serde(default)]
1206  pub active: bool,
1207  /// The bundle targets, currently supports ["deb", "rpm", "appimage", "nsis", "msi", "app", "dmg"] or "all".
1208  #[serde(default)]
1209  pub targets: BundleTarget,
1210  #[serde(default)]
1211  /// Produce updaters and their signatures or not
1212  pub create_updater_artifacts: Updater,
1213  /// The application's publisher. Defaults to the second element in the identifier string.
1214  ///
1215  /// Currently maps to the Manufacturer property of the Windows Installer
1216  /// and the Maintainer field of debian packages if the Cargo.toml does not have the authors field.
1217  pub publisher: Option<String>,
1218  /// A url to the home page of your application. If unset, will
1219  /// fallback to `homepage` defined in `Cargo.toml`.
1220  ///
1221  /// Supported bundle targets: `deb`, `rpm`, `nsis` and `msi`.
1222  pub homepage: Option<String>,
1223  /// The app's icons
1224  #[serde(default)]
1225  pub icon: Vec<String>,
1226  /// App resources to bundle.
1227  /// Each resource is a path to a file or directory.
1228  /// Glob patterns are supported.
1229  pub resources: Option<BundleResources>,
1230  /// A copyright string associated with your application.
1231  pub copyright: Option<String>,
1232  /// The package's license identifier to be included in the appropriate bundles.
1233  /// If not set, defaults to the license from the Cargo.toml file.
1234  pub license: Option<String>,
1235  /// The path to the license file to be included in the appropriate bundles.
1236  #[serde(alias = "license-file")]
1237  pub license_file: Option<PathBuf>,
1238  /// The application kind.
1239  ///
1240  /// Should be one of the following:
1241  /// 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.
1242  pub category: Option<String>,
1243  /// File associations to application.
1244  pub file_associations: Option<Vec<FileAssociation>>,
1245  /// A short description of your application.
1246  #[serde(alias = "short-description")]
1247  pub short_description: Option<String>,
1248  /// A longer, multi-line description of the application.
1249  #[serde(alias = "long-description")]
1250  pub long_description: Option<String>,
1251  /// Whether to use the project's `target` directory, for caching build tools (e.g., Wix and NSIS) when building this application. Defaults to `false`.
1252  ///
1253  /// If true, tools will be cached in `target/.tauri/`.
1254  /// If false, tools will be cached in the current user's platform-specific cache directory.
1255  ///
1256  /// An example where it can be appropriate to set this to `true` is when building this application as a Windows System user (e.g., AWS EC2 workloads),
1257  /// because the Window system's app data directory is restricted.
1258  #[serde(default, alias = "use-local-tools-dir")]
1259  pub use_local_tools_dir: bool,
1260  /// A list of—either absolute or relative—paths to binaries to embed with your application.
1261  ///
1262  /// Note that Tauri will look for system-specific binaries following the pattern "binary-name{-target-triple}{.system-extension}".
1263  ///
1264  /// E.g. for the external binary "my-binary", Tauri looks for:
1265  ///
1266  /// - "my-binary-x86_64-pc-windows-msvc.exe" for Windows
1267  /// - "my-binary-x86_64-apple-darwin" for macOS
1268  /// - "my-binary-x86_64-unknown-linux-gnu" for Linux
1269  ///
1270  /// so don't forget to provide binaries for all targeted platforms.
1271  #[serde(alias = "external-bin")]
1272  pub external_bin: Option<Vec<String>>,
1273  /// Configuration for the Windows bundles.
1274  #[serde(default)]
1275  pub windows: WindowsConfig,
1276  /// Configuration for the Linux bundles.
1277  #[serde(default)]
1278  pub linux: LinuxConfig,
1279  /// Configuration for the macOS bundles.
1280  #[serde(rename = "macOS", alias = "macos", default)]
1281  pub macos: MacConfig,
1282  /// iOS configuration.
1283  #[serde(rename = "iOS", alias = "ios", default)]
1284  pub ios: IosConfig,
1285  /// Android configuration.
1286  #[serde(default)]
1287  pub android: AndroidConfig,
1288}
1289
1290/// A tuple struct of RGBA colors. Each value has minimum of 0 and maximum of 255.
1291#[derive(Debug, PartialEq, Eq, Serialize, Default, Clone, Copy)]
1292#[serde(rename_all = "camelCase", deny_unknown_fields)]
1293pub struct Color(pub u8, pub u8, pub u8, pub u8);
1294
1295impl From<Color> for (u8, u8, u8, u8) {
1296  fn from(value: Color) -> Self {
1297    (value.0, value.1, value.2, value.3)
1298  }
1299}
1300
1301impl From<Color> for (u8, u8, u8) {
1302  fn from(value: Color) -> Self {
1303    (value.0, value.1, value.2)
1304  }
1305}
1306
1307impl From<(u8, u8, u8, u8)> for Color {
1308  fn from(value: (u8, u8, u8, u8)) -> Self {
1309    Color(value.0, value.1, value.2, value.3)
1310  }
1311}
1312
1313impl From<(u8, u8, u8)> for Color {
1314  fn from(value: (u8, u8, u8)) -> Self {
1315    Color(value.0, value.1, value.2, 255)
1316  }
1317}
1318
1319impl From<Color> for [u8; 4] {
1320  fn from(value: Color) -> Self {
1321    [value.0, value.1, value.2, value.3]
1322  }
1323}
1324
1325impl From<Color> for [u8; 3] {
1326  fn from(value: Color) -> Self {
1327    [value.0, value.1, value.2]
1328  }
1329}
1330
1331impl From<[u8; 4]> for Color {
1332  fn from(value: [u8; 4]) -> Self {
1333    Color(value[0], value[1], value[2], value[3])
1334  }
1335}
1336
1337impl From<[u8; 3]> for Color {
1338  fn from(value: [u8; 3]) -> Self {
1339    Color(value[0], value[1], value[2], 255)
1340  }
1341}
1342
1343impl FromStr for Color {
1344  type Err = String;
1345  fn from_str(mut color: &str) -> Result<Self, Self::Err> {
1346    color = color.trim().strip_prefix('#').unwrap_or(color);
1347    let color = match color.len() {
1348      // TODO: use repeat_n once our MSRV is bumped to 1.82
1349      3 => color.chars()
1350            .flat_map(|c| std::iter::repeat(c).take(2))
1351            .chain(std::iter::repeat('f').take(2))
1352            .collect(),
1353      6 => format!("{color}FF"),
1354      8 => color.to_string(),
1355      _ => return Err("Invalid hex color length, must be either 3, 6 or 8, for example: #fff, #ffffff, or #ffffffff".into()),
1356    };
1357
1358    let r = u8::from_str_radix(&color[0..2], 16).map_err(|e| e.to_string())?;
1359    let g = u8::from_str_radix(&color[2..4], 16).map_err(|e| e.to_string())?;
1360    let b = u8::from_str_radix(&color[4..6], 16).map_err(|e| e.to_string())?;
1361    let a = u8::from_str_radix(&color[6..8], 16).map_err(|e| e.to_string())?;
1362
1363    Ok(Color(r, g, b, a))
1364  }
1365}
1366
1367fn default_alpha() -> u8 {
1368  255
1369}
1370
1371#[derive(Deserialize)]
1372#[cfg_attr(feature = "schema", derive(JsonSchema))]
1373#[serde(untagged)]
1374enum InnerColor {
1375  /// Color hex string, for example: #fff, #ffffff, or #ffffffff.
1376  String(String),
1377  /// Array of RGB colors. Each value has minimum of 0 and maximum of 255.
1378  Rgb((u8, u8, u8)),
1379  /// Array of RGBA colors. Each value has minimum of 0 and maximum of 255.
1380  Rgba((u8, u8, u8, u8)),
1381  /// Object of red, green, blue, alpha color values. Each value has minimum of 0 and maximum of 255.
1382  RgbaObject {
1383    red: u8,
1384    green: u8,
1385    blue: u8,
1386    #[serde(default = "default_alpha")]
1387    alpha: u8,
1388  },
1389}
1390
1391impl<'de> Deserialize<'de> for Color {
1392  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1393  where
1394    D: Deserializer<'de>,
1395  {
1396    let color = InnerColor::deserialize(deserializer)?;
1397    let color = match color {
1398      InnerColor::String(string) => string.parse().map_err(serde::de::Error::custom)?,
1399      InnerColor::Rgb(rgb) => Color(rgb.0, rgb.1, rgb.2, 255),
1400      InnerColor::Rgba(rgb) => rgb.into(),
1401      InnerColor::RgbaObject {
1402        red,
1403        green,
1404        blue,
1405        alpha,
1406      } => Color(red, green, blue, alpha),
1407    };
1408
1409    Ok(color)
1410  }
1411}
1412
1413#[cfg(feature = "schema")]
1414impl schemars::JsonSchema for Color {
1415  fn schema_name() -> String {
1416    "Color".to_string()
1417  }
1418
1419  fn json_schema(_gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
1420    let mut schema = schemars::schema_for!(InnerColor).schema;
1421    schema.metadata = None; // Remove `title: InnerColor` from schema
1422
1423    // add hex color pattern validation
1424    let any_of = schema.subschemas().any_of.as_mut().unwrap();
1425    let schemars::schema::Schema::Object(str_schema) = any_of.first_mut().unwrap() else {
1426      unreachable!()
1427    };
1428    str_schema.string().pattern = Some("^#?([A-Fa-f0-9]{3}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{8})$".into());
1429
1430    schema.into()
1431  }
1432}
1433
1434/// Background throttling policy.
1435#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1436#[cfg_attr(feature = "schema", derive(JsonSchema))]
1437#[serde(rename_all = "camelCase", deny_unknown_fields)]
1438pub enum BackgroundThrottlingPolicy {
1439  /// A policy where background throttling is disabled
1440  Disabled,
1441  /// 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.
1442  Suspend,
1443  /// A policy where a web view that’s not in a window limits processing, but does not fully suspend tasks.
1444  Throttle,
1445}
1446
1447/// The window effects configuration object
1448#[skip_serializing_none]
1449#[derive(Debug, PartialEq, Clone, Deserialize, Serialize, Default)]
1450#[cfg_attr(feature = "schema", derive(JsonSchema))]
1451#[serde(rename_all = "camelCase", deny_unknown_fields)]
1452pub struct WindowEffectsConfig {
1453  /// List of Window effects to apply to the Window.
1454  /// Conflicting effects will apply the first one and ignore the rest.
1455  pub effects: Vec<WindowEffect>,
1456  /// Window effect state **macOS Only**
1457  pub state: Option<WindowEffectState>,
1458  /// Window effect corner radius **macOS Only**
1459  pub radius: Option<f64>,
1460  /// Window effect color. Affects [`WindowEffect::Blur`] and [`WindowEffect::Acrylic`] only
1461  /// on Windows 10 v1903+. Doesn't have any effect on Windows 7 or Windows 11.
1462  pub color: Option<Color>,
1463}
1464
1465/// The window configuration object.
1466///
1467/// See more: <https://v2.tauri.app/reference/config/#windowconfig>
1468#[skip_serializing_none]
1469#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
1470#[cfg_attr(feature = "schema", derive(JsonSchema))]
1471#[serde(rename_all = "camelCase", deny_unknown_fields)]
1472pub struct WindowConfig {
1473  /// The window identifier. It must be alphanumeric.
1474  #[serde(default = "default_window_label")]
1475  pub label: String,
1476  /// Whether Tauri should create this window at app startup or not.
1477  ///
1478  /// When this is set to `false` you must manually grab the config object via `app.config().app.windows`
1479  /// and create it with [`WebviewWindowBuilder::from_config`](https://docs.rs/tauri/2/tauri/webview/struct.WebviewWindowBuilder.html#method.from_config).
1480  #[serde(default = "default_true")]
1481  pub create: bool,
1482  /// The window webview URL.
1483  #[serde(default)]
1484  pub url: WebviewUrl,
1485  /// The user agent for the webview
1486  #[serde(alias = "user-agent")]
1487  pub user_agent: Option<String>,
1488  /// Whether the drag and drop is enabled or not on the webview. By default it is enabled.
1489  ///
1490  /// Disabling it is required to use HTML5 drag and drop on the frontend on Windows.
1491  #[serde(default = "default_true", alias = "drag-drop-enabled")]
1492  pub drag_drop_enabled: bool,
1493  /// Whether or not the window starts centered or not.
1494  #[serde(default)]
1495  pub center: bool,
1496  /// The horizontal position of the window's top left corner
1497  pub x: Option<f64>,
1498  /// The vertical position of the window's top left corner
1499  pub y: Option<f64>,
1500  /// The window width.
1501  #[serde(default = "default_width")]
1502  pub width: f64,
1503  /// The window height.
1504  #[serde(default = "default_height")]
1505  pub height: f64,
1506  /// The min window width.
1507  #[serde(alias = "min-width")]
1508  pub min_width: Option<f64>,
1509  /// The min window height.
1510  #[serde(alias = "min-height")]
1511  pub min_height: Option<f64>,
1512  /// The max window width.
1513  #[serde(alias = "max-width")]
1514  pub max_width: Option<f64>,
1515  /// The max window height.
1516  #[serde(alias = "max-height")]
1517  pub max_height: Option<f64>,
1518  /// Whether the window is resizable or not. When resizable is set to false, native window's maximize button is automatically disabled.
1519  #[serde(default = "default_true")]
1520  pub resizable: bool,
1521  /// Whether the window's native maximize button is enabled or not.
1522  /// If resizable is set to false, this setting is ignored.
1523  ///
1524  /// ## Platform-specific
1525  ///
1526  /// - **macOS:** Disables the "zoom" button in the window titlebar, which is also used to enter fullscreen mode.
1527  /// - **Linux / iOS / Android:** Unsupported.
1528  #[serde(default = "default_true")]
1529  pub maximizable: bool,
1530  /// Whether the window's native minimize button is enabled or not.
1531  ///
1532  /// ## Platform-specific
1533  ///
1534  /// - **Linux / iOS / Android:** Unsupported.
1535  #[serde(default = "default_true")]
1536  pub minimizable: bool,
1537  /// Whether the window's native close button is enabled or not.
1538  ///
1539  /// ## Platform-specific
1540  ///
1541  /// - **Linux:** "GTK+ will do its best to convince the window manager not to show a close button.
1542  ///   Depending on the system, this function may not have any effect when called on a window that is already visible"
1543  /// - **iOS / Android:** Unsupported.
1544  #[serde(default = "default_true")]
1545  pub closable: bool,
1546  /// The window title.
1547  #[serde(default = "default_title")]
1548  pub title: String,
1549  /// Whether the window starts as fullscreen or not.
1550  #[serde(default)]
1551  pub fullscreen: bool,
1552  /// Whether the window will be initially focused or not.
1553  #[serde(default = "default_true")]
1554  pub focus: bool,
1555  /// Whether the window is transparent or not.
1556  ///
1557  /// Note that on `macOS` this requires the `macos-private-api` feature flag, enabled under `tauri > macOSPrivateApi`.
1558  /// WARNING: Using private APIs on `macOS` prevents your application from being accepted to the `App Store`.
1559  #[serde(default)]
1560  pub transparent: bool,
1561  /// Whether the window is maximized or not.
1562  #[serde(default)]
1563  pub maximized: bool,
1564  /// Whether the window is visible or not.
1565  #[serde(default = "default_true")]
1566  pub visible: bool,
1567  /// Whether the window should have borders and bars.
1568  #[serde(default = "default_true")]
1569  pub decorations: bool,
1570  /// Whether the window should always be below other windows.
1571  #[serde(default, alias = "always-on-bottom")]
1572  pub always_on_bottom: bool,
1573  /// Whether the window should always be on top of other windows.
1574  #[serde(default, alias = "always-on-top")]
1575  pub always_on_top: bool,
1576  /// Whether the window should be visible on all workspaces or virtual desktops.
1577  ///
1578  /// ## Platform-specific
1579  ///
1580  /// - **Windows / iOS / Android:** Unsupported.
1581  #[serde(default, alias = "visible-on-all-workspaces")]
1582  pub visible_on_all_workspaces: bool,
1583  /// Prevents the window contents from being captured by other apps.
1584  #[serde(default, alias = "content-protected")]
1585  pub content_protected: bool,
1586  /// If `true`, hides the window icon from the taskbar on Windows and Linux.
1587  #[serde(default, alias = "skip-taskbar")]
1588  pub skip_taskbar: bool,
1589  /// The name of the window class created on Windows to create the window. **Windows only**.
1590  pub window_classname: Option<String>,
1591  /// The initial window theme. Defaults to the system theme. Only implemented on Windows and macOS 10.14+.
1592  pub theme: Option<crate::Theme>,
1593  /// The style of the macOS title bar.
1594  #[serde(default, alias = "title-bar-style")]
1595  pub title_bar_style: TitleBarStyle,
1596  /// The position of the window controls on macOS.
1597  ///
1598  /// Requires titleBarStyle: Overlay and decorations: true.
1599  #[serde(default, alias = "traffic-light-position")]
1600  pub traffic_light_position: Option<LogicalPosition>,
1601  /// If `true`, sets the window title to be hidden on macOS.
1602  #[serde(default, alias = "hidden-title")]
1603  pub hidden_title: bool,
1604  /// Whether clicking an inactive window also clicks through to the webview on macOS.
1605  #[serde(default, alias = "accept-first-mouse")]
1606  pub accept_first_mouse: bool,
1607  /// Defines the window [tabbing identifier] for macOS.
1608  ///
1609  /// Windows with matching tabbing identifiers will be grouped together.
1610  /// If the tabbing identifier is not set, automatic tabbing will be disabled.
1611  ///
1612  /// [tabbing identifier]: <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier>
1613  #[serde(default, alias = "tabbing-identifier")]
1614  pub tabbing_identifier: Option<String>,
1615  /// Defines additional browser arguments on Windows. By default wry passes `--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection`
1616  /// so if you use this method, you also need to disable these components by yourself if you want.
1617  #[serde(default, alias = "additional-browser-args")]
1618  pub additional_browser_args: Option<String>,
1619  /// Whether or not the window has shadow.
1620  ///
1621  /// ## Platform-specific
1622  ///
1623  /// - **Windows:**
1624  ///   - `false` has no effect on decorated window, shadow are always ON.
1625  ///   - `true` will make undecorated window have a 1px white border,
1626  /// and on Windows 11, it will have a rounded corners.
1627  /// - **Linux:** Unsupported.
1628  #[serde(default = "default_true")]
1629  pub shadow: bool,
1630  /// Window effects.
1631  ///
1632  /// Requires the window to be transparent.
1633  ///
1634  /// ## Platform-specific:
1635  ///
1636  /// - **Windows**: If using decorations or shadows, you may want to try this workaround <https://github.com/tauri-apps/tao/issues/72#issuecomment-975607891>
1637  /// - **Linux**: Unsupported
1638  #[serde(default, alias = "window-effects")]
1639  pub window_effects: Option<WindowEffectsConfig>,
1640  /// Whether or not the webview should be launched in incognito  mode.
1641  ///
1642  ///  ## Platform-specific:
1643  ///
1644  ///  - **Android**: Unsupported.
1645  #[serde(default)]
1646  pub incognito: bool,
1647  /// Sets the window associated with this label to be the parent of the window to be created.
1648  ///
1649  /// ## Platform-specific
1650  ///
1651  /// - **Windows**: This sets the passed parent as an owner window to the window to be created.
1652  ///   From [MSDN owned windows docs](https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows):
1653  ///     - An owned window is always above its owner in the z-order.
1654  ///     - The system automatically destroys an owned window when its owner is destroyed.
1655  ///     - An owned window is hidden when its owner is minimized.
1656  /// - **Linux**: This makes the new window transient for parent, see <https://docs.gtk.org/gtk3/method.Window.set_transient_for.html>
1657  /// - **macOS**: This adds the window as a child of parent, see <https://developer.apple.com/documentation/appkit/nswindow/1419152-addchildwindow?language=objc>
1658  pub parent: Option<String>,
1659  /// The proxy URL for the WebView for all network requests.
1660  ///
1661  /// Must be either a `http://` or a `socks5://` URL.
1662  ///
1663  /// ## Platform-specific
1664  ///
1665  /// - **macOS**: Requires the `macos-proxy` feature flag and only compiles for macOS 14+.
1666  #[serde(alias = "proxy-url")]
1667  pub proxy_url: Option<Url>,
1668  /// Whether page zooming by hotkeys is enabled
1669  ///
1670  /// ## Platform-specific:
1671  ///
1672  /// - **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.
1673  /// - **MacOS / Linux**: Injects a polyfill that zooms in and out with `ctrl/command` + `-/=`,
1674  /// 20% in each step, ranging from 20% to 1000%. Requires `webview:allow-set-webview-zoom` permission
1675  ///
1676  /// - **Android / iOS**: Unsupported.
1677  #[serde(default, alias = "zoom-hotkeys-enabled")]
1678  pub zoom_hotkeys_enabled: bool,
1679  /// Whether browser extensions can be installed for the webview process
1680  ///
1681  /// ## Platform-specific:
1682  ///
1683  /// - **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)
1684  /// - **MacOS / Linux / iOS / Android** - Unsupported.
1685  #[serde(default, alias = "browser-extensions-enabled")]
1686  pub browser_extensions_enabled: bool,
1687
1688  /// Sets whether the custom protocols should use `https://<scheme>.localhost` instead of the default `http://<scheme>.localhost` on Windows and Android. Defaults to `false`.
1689  ///
1690  /// ## Note
1691  ///
1692  /// 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.
1693  ///
1694  /// ## Warning
1695  ///
1696  /// 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.
1697  #[serde(default, alias = "use-https-scheme")]
1698  pub use_https_scheme: bool,
1699  /// Enable web inspector which is usually called browser devtools. Enabled by default.
1700  ///
1701  /// This API works in **debug** builds, but requires `devtools` feature flag to enable it in **release** builds.
1702  ///
1703  /// ## Platform-specific
1704  ///
1705  /// - macOS: This will call private functions on **macOS**.
1706  /// - Android: Open `chrome://inspect/#devices` in Chrome to get the devtools window. Wry's `WebView` devtools API isn't supported on Android.
1707  /// - iOS: Open Safari > Develop > [Your Device Name] > [Your WebView] to get the devtools window.
1708  pub devtools: Option<bool>,
1709
1710  /// Set the window and webview background color.
1711  ///
1712  /// ## Platform-specific:
1713  ///
1714  /// - **Windows**: alpha channel is ignored for the window layer.
1715  /// - **Windows**: On Windows 7, alpha channel is ignored for the webview layer.
1716  /// - **Windows**: On Windows 8 and newer, if alpha channel is not `0`, it will be ignored for the webview layer.
1717  #[serde(alias = "background-color")]
1718  pub background_color: Option<Color>,
1719
1720  /// Change the default background throttling behaviour.
1721  ///
1722  /// By default, browsers use a suspend policy that will throttle timers and even unload
1723  /// the whole tab (view) to free resources after roughly 5 minutes when a view became
1724  /// minimized or hidden. This will pause all tasks until the documents visibility state
1725  /// changes back from hidden to visible by bringing the view back to the foreground.
1726  ///
1727  /// ## Platform-specific
1728  ///
1729  /// - **Linux / Windows / Android**: Unsupported. Workarounds like a pending WebLock transaction might suffice.
1730  /// - **iOS**: Supported since version 17.0+.
1731  /// - **macOS**: Supported since version 14.0+.
1732  ///
1733  /// see https://github.com/tauri-apps/tauri/issues/5250#issuecomment-2569380578
1734  #[serde(default, alias = "background-throttling")]
1735  pub background_throttling: Option<BackgroundThrottlingPolicy>,
1736  /// Whether we should disable JavaScript code execution on the webview or not.
1737  #[serde(default, alias = "javascript-disabled")]
1738  pub javascript_disabled: bool,
1739}
1740
1741impl Default for WindowConfig {
1742  fn default() -> Self {
1743    Self {
1744      label: default_window_label(),
1745      url: WebviewUrl::default(),
1746      create: true,
1747      user_agent: None,
1748      drag_drop_enabled: true,
1749      center: false,
1750      x: None,
1751      y: None,
1752      width: default_width(),
1753      height: default_height(),
1754      min_width: None,
1755      min_height: None,
1756      max_width: None,
1757      max_height: None,
1758      resizable: true,
1759      maximizable: true,
1760      minimizable: true,
1761      closable: true,
1762      title: default_title(),
1763      fullscreen: false,
1764      focus: false,
1765      transparent: false,
1766      maximized: false,
1767      visible: true,
1768      decorations: true,
1769      always_on_bottom: false,
1770      always_on_top: false,
1771      visible_on_all_workspaces: false,
1772      content_protected: false,
1773      skip_taskbar: false,
1774      window_classname: None,
1775      theme: None,
1776      title_bar_style: Default::default(),
1777      traffic_light_position: None,
1778      hidden_title: false,
1779      accept_first_mouse: false,
1780      tabbing_identifier: None,
1781      additional_browser_args: None,
1782      shadow: true,
1783      window_effects: None,
1784      incognito: false,
1785      parent: None,
1786      proxy_url: None,
1787      zoom_hotkeys_enabled: false,
1788      browser_extensions_enabled: false,
1789      use_https_scheme: false,
1790      devtools: None,
1791      background_color: None,
1792      background_throttling: None,
1793      javascript_disabled: false,
1794    }
1795  }
1796}
1797
1798fn default_window_label() -> String {
1799  "main".to_string()
1800}
1801
1802fn default_width() -> f64 {
1803  800f64
1804}
1805
1806fn default_height() -> f64 {
1807  600f64
1808}
1809
1810fn default_title() -> String {
1811  "Tauri App".to_string()
1812}
1813
1814/// A Content-Security-Policy directive source list.
1815/// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/Sources#sources>.
1816#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1817#[cfg_attr(feature = "schema", derive(JsonSchema))]
1818#[serde(rename_all = "camelCase", untagged)]
1819pub enum CspDirectiveSources {
1820  /// An inline list of CSP sources. Same as [`Self::List`], but concatenated with a space separator.
1821  Inline(String),
1822  /// A list of CSP sources. The collection will be concatenated with a space separator for the CSP string.
1823  List(Vec<String>),
1824}
1825
1826impl Default for CspDirectiveSources {
1827  fn default() -> Self {
1828    Self::List(Vec::new())
1829  }
1830}
1831
1832impl From<CspDirectiveSources> for Vec<String> {
1833  fn from(sources: CspDirectiveSources) -> Self {
1834    match sources {
1835      CspDirectiveSources::Inline(source) => source.split(' ').map(|s| s.to_string()).collect(),
1836      CspDirectiveSources::List(l) => l,
1837    }
1838  }
1839}
1840
1841impl CspDirectiveSources {
1842  /// Whether the given source is configured on this directive or not.
1843  pub fn contains(&self, source: &str) -> bool {
1844    match self {
1845      Self::Inline(s) => s.contains(&format!("{source} ")) || s.contains(&format!(" {source}")),
1846      Self::List(l) => l.contains(&source.into()),
1847    }
1848  }
1849
1850  /// Appends the given source to this directive.
1851  pub fn push<S: AsRef<str>>(&mut self, source: S) {
1852    match self {
1853      Self::Inline(s) => {
1854        s.push(' ');
1855        s.push_str(source.as_ref());
1856      }
1857      Self::List(l) => {
1858        l.push(source.as_ref().to_string());
1859      }
1860    }
1861  }
1862
1863  /// Extends this CSP directive source list with the given array of sources.
1864  pub fn extend(&mut self, sources: Vec<String>) {
1865    for s in sources {
1866      self.push(s);
1867    }
1868  }
1869}
1870
1871/// A Content-Security-Policy definition.
1872/// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP>.
1873#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1874#[cfg_attr(feature = "schema", derive(JsonSchema))]
1875#[serde(rename_all = "camelCase", untagged)]
1876pub enum Csp {
1877  /// The entire CSP policy in a single text string.
1878  Policy(String),
1879  /// An object mapping a directive with its sources values as a list of strings.
1880  DirectiveMap(HashMap<String, CspDirectiveSources>),
1881}
1882
1883impl From<HashMap<String, CspDirectiveSources>> for Csp {
1884  fn from(map: HashMap<String, CspDirectiveSources>) -> Self {
1885    Self::DirectiveMap(map)
1886  }
1887}
1888
1889impl From<Csp> for HashMap<String, CspDirectiveSources> {
1890  fn from(csp: Csp) -> Self {
1891    match csp {
1892      Csp::Policy(policy) => {
1893        let mut map = HashMap::new();
1894        for directive in policy.split(';') {
1895          let mut tokens = directive.trim().split(' ');
1896          if let Some(directive) = tokens.next() {
1897            let sources = tokens.map(|s| s.to_string()).collect::<Vec<String>>();
1898            map.insert(directive.to_string(), CspDirectiveSources::List(sources));
1899          }
1900        }
1901        map
1902      }
1903      Csp::DirectiveMap(m) => m,
1904    }
1905  }
1906}
1907
1908impl Display for Csp {
1909  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1910    match self {
1911      Self::Policy(s) => write!(f, "{s}"),
1912      Self::DirectiveMap(m) => {
1913        let len = m.len();
1914        let mut i = 0;
1915        for (directive, sources) in m {
1916          let sources: Vec<String> = sources.clone().into();
1917          write!(f, "{} {}", directive, sources.join(" "))?;
1918          i += 1;
1919          if i != len {
1920            write!(f, "; ")?;
1921          }
1922        }
1923        Ok(())
1924      }
1925    }
1926  }
1927}
1928
1929/// The possible values for the `dangerous_disable_asset_csp_modification` config option.
1930#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1931#[serde(untagged)]
1932#[cfg_attr(feature = "schema", derive(JsonSchema))]
1933pub enum DisabledCspModificationKind {
1934  /// If `true`, disables all CSP modification.
1935  /// `false` is the default value and it configures Tauri to control the CSP.
1936  Flag(bool),
1937  /// Disables the given list of CSP directives modifications.
1938  List(Vec<String>),
1939}
1940
1941impl DisabledCspModificationKind {
1942  /// Determines whether the given CSP directive can be modified or not.
1943  pub fn can_modify(&self, directive: &str) -> bool {
1944    match self {
1945      Self::Flag(f) => !f,
1946      Self::List(l) => !l.contains(&directive.into()),
1947    }
1948  }
1949}
1950
1951impl Default for DisabledCspModificationKind {
1952  fn default() -> Self {
1953    Self::Flag(false)
1954  }
1955}
1956
1957/// Protocol scope definition.
1958/// It is a list of glob patterns that restrict the API access from the webview.
1959///
1960/// Each pattern can start with a variable that resolves to a system base directory.
1961/// The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`,
1962/// `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`,
1963/// `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$APP`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`,
1964/// `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.
1965#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1966#[serde(untagged)]
1967#[cfg_attr(feature = "schema", derive(JsonSchema))]
1968pub enum FsScope {
1969  /// A list of paths that are allowed by this scope.
1970  AllowedPaths(Vec<PathBuf>),
1971  /// A complete scope configuration.
1972  #[serde(rename_all = "camelCase")]
1973  Scope {
1974    /// A list of paths that are allowed by this scope.
1975    #[serde(default)]
1976    allow: Vec<PathBuf>,
1977    /// A list of paths that are not allowed by this scope.
1978    /// This gets precedence over the [`Self::Scope::allow`] list.
1979    #[serde(default)]
1980    deny: Vec<PathBuf>,
1981    /// Whether or not paths that contain components that start with a `.`
1982    /// will require that `.` appears literally in the pattern; `*`, `?`, `**`,
1983    /// or `[...]` will not match. This is useful because such files are
1984    /// conventionally considered hidden on Unix systems and it might be
1985    /// desirable to skip them when listing files.
1986    ///
1987    /// Defaults to `true` on Unix systems and `false` on Windows
1988    // dotfiles are not supposed to be exposed by default on unix
1989    #[serde(alias = "require-literal-leading-dot")]
1990    require_literal_leading_dot: Option<bool>,
1991  },
1992}
1993
1994impl Default for FsScope {
1995  fn default() -> Self {
1996    Self::AllowedPaths(Vec::new())
1997  }
1998}
1999
2000impl FsScope {
2001  /// The list of allowed paths.
2002  pub fn allowed_paths(&self) -> &Vec<PathBuf> {
2003    match self {
2004      Self::AllowedPaths(p) => p,
2005      Self::Scope { allow, .. } => allow,
2006    }
2007  }
2008
2009  /// The list of forbidden paths.
2010  pub fn forbidden_paths(&self) -> Option<&Vec<PathBuf>> {
2011    match self {
2012      Self::AllowedPaths(_) => None,
2013      Self::Scope { deny, .. } => Some(deny),
2014    }
2015  }
2016}
2017
2018/// Config for the asset custom protocol.
2019///
2020/// See more: <https://v2.tauri.app/reference/config/#assetprotocolconfig>
2021#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
2022#[cfg_attr(feature = "schema", derive(JsonSchema))]
2023#[serde(rename_all = "camelCase", deny_unknown_fields)]
2024pub struct AssetProtocolConfig {
2025  /// The access scope for the asset protocol.
2026  #[serde(default)]
2027  pub scope: FsScope,
2028  /// Enables the asset protocol.
2029  #[serde(default)]
2030  pub enable: bool,
2031}
2032
2033/// definition of a header source
2034///
2035/// The header value to a header name
2036#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
2037#[cfg_attr(feature = "schema", derive(JsonSchema))]
2038#[serde(rename_all = "camelCase", untagged)]
2039pub enum HeaderSource {
2040  /// string version of the header Value
2041  Inline(String),
2042  /// list version of the header value. Item are joined by "," for the real header value
2043  List(Vec<String>),
2044  /// (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
2045  Map(HashMap<String, String>),
2046}
2047
2048impl Display for HeaderSource {
2049  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2050    match self {
2051      Self::Inline(s) => write!(f, "{s}"),
2052      Self::List(l) => write!(f, "{}", l.join(", ")),
2053      Self::Map(m) => {
2054        let len = m.len();
2055        let mut i = 0;
2056        for (key, value) in m {
2057          write!(f, "{} {}", key, value)?;
2058          i += 1;
2059          if i != len {
2060            write!(f, "; ")?;
2061          }
2062        }
2063        Ok(())
2064      }
2065    }
2066  }
2067}
2068
2069/// A trait which implements on the [`Builder`] of the http create
2070///
2071/// Must add headers defined in the tauri configuration file to http responses
2072pub trait HeaderAddition {
2073  /// adds all headers defined on the config file, given the current HeaderConfig
2074  fn add_configured_headers(self, headers: Option<&HeaderConfig>) -> http::response::Builder;
2075}
2076
2077impl HeaderAddition for Builder {
2078  /// Add the headers defined in the tauri configuration file to http responses
2079  ///
2080  /// this is a utility function, which is used in the same way as the `.header(..)` of the rust http library
2081  fn add_configured_headers(mut self, headers: Option<&HeaderConfig>) -> http::response::Builder {
2082    if let Some(headers) = headers {
2083      // Add the header Access-Control-Allow-Credentials, if we find a value for it
2084      if let Some(value) = &headers.access_control_allow_credentials {
2085        self = self.header("Access-Control-Allow-Credentials", value.to_string());
2086      };
2087
2088      // Add the header Access-Control-Allow-Headers, if we find a value for it
2089      if let Some(value) = &headers.access_control_allow_headers {
2090        self = self.header("Access-Control-Allow-Headers", value.to_string());
2091      };
2092
2093      // Add the header Access-Control-Allow-Methods, if we find a value for it
2094      if let Some(value) = &headers.access_control_allow_methods {
2095        self = self.header("Access-Control-Allow-Methods", value.to_string());
2096      };
2097
2098      // Add the header Access-Control-Expose-Headers, if we find a value for it
2099      if let Some(value) = &headers.access_control_expose_headers {
2100        self = self.header("Access-Control-Expose-Headers", value.to_string());
2101      };
2102
2103      // Add the header Access-Control-Max-Age, if we find a value for it
2104      if let Some(value) = &headers.access_control_max_age {
2105        self = self.header("Access-Control-Max-Age", value.to_string());
2106      };
2107
2108      // Add the header Cross-Origin-Embedder-Policy, if we find a value for it
2109      if let Some(value) = &headers.cross_origin_embedder_policy {
2110        self = self.header("Cross-Origin-Embedder-Policy", value.to_string());
2111      };
2112
2113      // Add the header Cross-Origin-Opener-Policy, if we find a value for it
2114      if let Some(value) = &headers.cross_origin_opener_policy {
2115        self = self.header("Cross-Origin-Opener-Policy", value.to_string());
2116      };
2117
2118      // Add the header Cross-Origin-Resource-Policy, if we find a value for it
2119      if let Some(value) = &headers.cross_origin_resource_policy {
2120        self = self.header("Cross-Origin-Resource-Policy", value.to_string());
2121      };
2122
2123      // Add the header Permission-Policy, if we find a value for it
2124      if let Some(value) = &headers.permissions_policy {
2125        self = self.header("Permission-Policy", value.to_string());
2126      };
2127
2128      // Add the header Timing-Allow-Origin, if we find a value for it
2129      if let Some(value) = &headers.timing_allow_origin {
2130        self = self.header("Timing-Allow-Origin", value.to_string());
2131      };
2132
2133      // Add the header X-Content-Type-Options, if we find a value for it
2134      if let Some(value) = &headers.x_content_type_options {
2135        self = self.header("X-Content-Type-Options", value.to_string());
2136      };
2137
2138      // Add the header Tauri-Custom-Header, if we find a value for it
2139      if let Some(value) = &headers.tauri_custom_header {
2140        // Keep in mind to correctly set the Access-Control-Expose-Headers
2141        self = self.header("Tauri-Custom-Header", value.to_string());
2142      };
2143    }
2144    self
2145  }
2146}
2147
2148/// A struct, where the keys are some specific http header names.
2149/// If the values to those keys are defined, then they will be send as part of a response message.
2150/// This does not include error messages and ipc messages
2151///
2152/// ## Example configuration
2153/// ```javascript
2154/// {
2155///  //..
2156///   app:{
2157///     //..
2158///     security: {
2159///       headers: {
2160///         "Cross-Origin-Opener-Policy": "same-origin",
2161///         "Cross-Origin-Embedder-Policy": "require-corp",
2162///         "Timing-Allow-Origin": [
2163///           "https://developer.mozilla.org",
2164///           "https://example.com",
2165///         ],
2166///         "Access-Control-Expose-Headers": "Tauri-Custom-Header",
2167///         "Tauri-Custom-Header": {
2168///           "key1": "'value1' 'value2'",
2169///           "key2": "'value3'"
2170///         }
2171///       },
2172///       csp: "default-src 'self'; connect-src ipc: http://ipc.localhost",
2173///     }
2174///     //..
2175///   }
2176///  //..
2177/// }
2178/// ```
2179/// 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).
2180/// 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.
2181/// The Content-Security-Policy header is defined separately, because it is also handled separately.
2182///
2183/// For the helloworld example, this config translates into those response headers:
2184/// ```http
2185/// access-control-allow-origin:  http://tauri.localhost
2186/// access-control-expose-headers: Tauri-Custom-Header
2187/// content-security-policy: default-src 'self'; connect-src ipc: http://ipc.localhost; script-src 'self' 'sha256-Wjjrs6qinmnr+tOry8x8PPwI77eGpUFR3EEGZktjJNs='
2188/// content-type: text/html
2189/// cross-origin-embedder-policy: require-corp
2190/// cross-origin-opener-policy: same-origin
2191/// tauri-custom-header: key1 'value1' 'value2'; key2 'value3'
2192/// timing-allow-origin: https://developer.mozilla.org, https://example.com
2193/// ```
2194/// Since the resulting header values are always 'string-like'. So depending on the what data type the HeaderSource is, they need to be converted.
2195///  - `String`(JS/Rust): stay the same for the resulting header value
2196///  - `Array`(JS)/`Vec\<String\>`(Rust): Item are joined by ", " for the resulting header value
2197///  - `Object`(JS)/ `Hashmap\<String,String\>`(Rust): Items are composed from: key + space + value. Item are then joined by "; " for the resulting header value
2198#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
2199#[cfg_attr(feature = "schema", derive(JsonSchema))]
2200#[serde(deny_unknown_fields)]
2201pub struct HeaderConfig {
2202  /// The Access-Control-Allow-Credentials response header tells browsers whether the
2203  /// server allows cross-origin HTTP requests to include credentials.
2204  ///
2205  /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials>
2206  #[serde(rename = "Access-Control-Allow-Credentials")]
2207  pub access_control_allow_credentials: Option<HeaderSource>,
2208  /// The Access-Control-Allow-Headers response header is used in response
2209  /// to a preflight request which includes the Access-Control-Request-Headers
2210  /// to indicate which HTTP headers can be used during the actual request.
2211  ///
2212  /// This header is required if the request has an Access-Control-Request-Headers header.
2213  ///
2214  /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers>
2215  #[serde(rename = "Access-Control-Allow-Headers")]
2216  pub access_control_allow_headers: Option<HeaderSource>,
2217  /// The Access-Control-Allow-Methods response header specifies one or more methods
2218  /// allowed when accessing a resource in response to a preflight request.
2219  ///
2220  /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods>
2221  #[serde(rename = "Access-Control-Allow-Methods")]
2222  pub access_control_allow_methods: Option<HeaderSource>,
2223  /// The Access-Control-Expose-Headers response header allows a server to indicate
2224  /// which response headers should be made available to scripts running in the browser,
2225  /// in response to a cross-origin request.
2226  ///
2227  /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers>
2228  #[serde(rename = "Access-Control-Expose-Headers")]
2229  pub access_control_expose_headers: Option<HeaderSource>,
2230  /// The Access-Control-Max-Age response header indicates how long the results of a
2231  /// preflight request (that is the information contained in the
2232  /// Access-Control-Allow-Methods and Access-Control-Allow-Headers headers) can
2233  /// be cached.
2234  ///
2235  /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age>
2236  #[serde(rename = "Access-Control-Max-Age")]
2237  pub access_control_max_age: Option<HeaderSource>,
2238  /// The HTTP Cross-Origin-Embedder-Policy (COEP) response header configures embedding
2239  /// cross-origin resources into the document.
2240  ///
2241  /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy>
2242  #[serde(rename = "Cross-Origin-Embedder-Policy")]
2243  pub cross_origin_embedder_policy: Option<HeaderSource>,
2244  /// The HTTP Cross-Origin-Opener-Policy (COOP) response header allows you to ensure a
2245  /// top-level document does not share a browsing context group with cross-origin documents.
2246  /// COOP will process-isolate your document and potential attackers can't access your global
2247  /// object if they were to open it in a popup, preventing a set of cross-origin attacks dubbed XS-Leaks.
2248  ///
2249  /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy>
2250  #[serde(rename = "Cross-Origin-Opener-Policy")]
2251  pub cross_origin_opener_policy: Option<HeaderSource>,
2252  /// The HTTP Cross-Origin-Resource-Policy response header conveys a desire that the
2253  /// browser blocks no-cors cross-origin/cross-site requests to the given resource.
2254  ///
2255  /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Resource-Policy>
2256  #[serde(rename = "Cross-Origin-Resource-Policy")]
2257  pub cross_origin_resource_policy: Option<HeaderSource>,
2258  /// The HTTP Permissions-Policy header provides a mechanism to allow and deny the
2259  /// use of browser features in a document or within any \<iframe\> elements in the document.
2260  ///
2261  /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy>
2262  #[serde(rename = "Permissions-Policy")]
2263  pub permissions_policy: Option<HeaderSource>,
2264  /// The Timing-Allow-Origin response header specifies origins that are allowed to see values
2265  /// of attributes retrieved via features of the Resource Timing API, which would otherwise be
2266  /// reported as zero due to cross-origin restrictions.
2267  ///
2268  /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Timing-Allow-Origin>
2269  #[serde(rename = "Timing-Allow-Origin")]
2270  pub timing_allow_origin: Option<HeaderSource>,
2271  /// The X-Content-Type-Options response HTTP header is a marker used by the server to indicate
2272  /// that the MIME types advertised in the Content-Type headers should be followed and not be
2273  /// changed. The header allows you to avoid MIME type sniffing by saying that the MIME types
2274  /// are deliberately configured.
2275  ///
2276  /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options>
2277  #[serde(rename = "X-Content-Type-Options")]
2278  pub x_content_type_options: Option<HeaderSource>,
2279  /// A custom header field Tauri-Custom-Header, don't use it.
2280  /// Remember to set Access-Control-Expose-Headers accordingly
2281  ///
2282  /// **NOT INTENDED FOR PRODUCTION USE**
2283  #[serde(rename = "Tauri-Custom-Header")]
2284  pub tauri_custom_header: Option<HeaderSource>,
2285}
2286
2287impl HeaderConfig {
2288  /// creates a new header config
2289  pub fn new() -> Self {
2290    HeaderConfig {
2291      access_control_allow_credentials: None,
2292      access_control_allow_methods: None,
2293      access_control_allow_headers: None,
2294      access_control_expose_headers: None,
2295      access_control_max_age: None,
2296      cross_origin_embedder_policy: None,
2297      cross_origin_opener_policy: None,
2298      cross_origin_resource_policy: None,
2299      permissions_policy: None,
2300      timing_allow_origin: None,
2301      x_content_type_options: None,
2302      tauri_custom_header: None,
2303    }
2304  }
2305}
2306
2307/// Security configuration.
2308///
2309/// See more: <https://v2.tauri.app/reference/config/#securityconfig>
2310#[skip_serializing_none]
2311#[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
2312#[cfg_attr(feature = "schema", derive(JsonSchema))]
2313#[serde(rename_all = "camelCase", deny_unknown_fields)]
2314pub struct SecurityConfig {
2315  /// The Content Security Policy that will be injected on all HTML files on the built application.
2316  /// If [`dev_csp`](#SecurityConfig.devCsp) is not specified, this value is also injected on dev.
2317  ///
2318  /// This is a really important part of the configuration since it helps you ensure your WebView is secured.
2319  /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP>.
2320  pub csp: Option<Csp>,
2321  /// The Content Security Policy that will be injected on all HTML files on development.
2322  ///
2323  /// This is a really important part of the configuration since it helps you ensure your WebView is secured.
2324  /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP>.
2325  #[serde(alias = "dev-csp")]
2326  pub dev_csp: Option<Csp>,
2327  /// Freeze the `Object.prototype` when using the custom protocol.
2328  #[serde(default, alias = "freeze-prototype")]
2329  pub freeze_prototype: bool,
2330  /// Disables the Tauri-injected CSP sources.
2331  ///
2332  /// At compile time, Tauri parses all the frontend assets and changes the Content-Security-Policy
2333  /// to only allow loading of your own scripts and styles by injecting nonce and hash sources.
2334  /// This stricts your CSP, which may introduce issues when using along with other flexing sources.
2335  ///
2336  /// This configuration option allows both a boolean and a list of strings as value.
2337  /// A boolean instructs Tauri to disable the injection for all CSP injections,
2338  /// and a list of strings indicates the CSP directives that Tauri cannot inject.
2339  ///
2340  /// **WARNING:** Only disable this if you know what you are doing and have properly configured the CSP.
2341  /// Your application might be vulnerable to XSS attacks without this Tauri protection.
2342  #[serde(default, alias = "dangerous-disable-asset-csp-modification")]
2343  pub dangerous_disable_asset_csp_modification: DisabledCspModificationKind,
2344  /// Custom protocol config.
2345  #[serde(default, alias = "asset-protocol")]
2346  pub asset_protocol: AssetProtocolConfig,
2347  /// The pattern to use.
2348  #[serde(default)]
2349  pub pattern: PatternKind,
2350  /// List of capabilities that are enabled on the application.
2351  ///
2352  /// If the list is empty, all capabilities are included.
2353  #[serde(default)]
2354  pub capabilities: Vec<CapabilityEntry>,
2355  /// The headers, which are added to every http response from tauri to the web view
2356  /// This doesn't include IPC Messages and error responses
2357  #[serde(default)]
2358  pub headers: Option<HeaderConfig>,
2359}
2360
2361/// A capability entry which can be either an inlined capability or a reference to a capability defined on its own file.
2362#[derive(Debug, Clone, PartialEq, Serialize)]
2363#[cfg_attr(feature = "schema", derive(JsonSchema))]
2364#[serde(untagged)]
2365pub enum CapabilityEntry {
2366  /// An inlined capability.
2367  Inlined(Capability),
2368  /// Reference to a capability identifier.
2369  Reference(String),
2370}
2371
2372impl<'de> Deserialize<'de> for CapabilityEntry {
2373  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2374  where
2375    D: Deserializer<'de>,
2376  {
2377    UntaggedEnumVisitor::new()
2378      .string(|string| Ok(Self::Reference(string.to_owned())))
2379      .map(|map| map.deserialize::<Capability>().map(Self::Inlined))
2380      .deserialize(deserializer)
2381  }
2382}
2383
2384/// The application pattern.
2385#[skip_serializing_none]
2386#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
2387#[serde(rename_all = "lowercase", tag = "use", content = "options")]
2388#[cfg_attr(feature = "schema", derive(JsonSchema))]
2389pub enum PatternKind {
2390  /// Brownfield pattern.
2391  Brownfield,
2392  /// Isolation pattern. Recommended for security purposes.
2393  Isolation {
2394    /// The dir containing the index.html file that contains the secure isolation application.
2395    dir: PathBuf,
2396  },
2397}
2398
2399impl Default for PatternKind {
2400  fn default() -> Self {
2401    Self::Brownfield
2402  }
2403}
2404
2405/// The App configuration object.
2406///
2407/// See more: <https://v2.tauri.app/reference/config/#appconfig>
2408#[skip_serializing_none]
2409#[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
2410#[cfg_attr(feature = "schema", derive(JsonSchema))]
2411#[serde(rename_all = "camelCase", deny_unknown_fields)]
2412pub struct AppConfig {
2413  /// The app windows configuration.
2414  #[serde(default)]
2415  pub windows: Vec<WindowConfig>,
2416  /// Security configuration.
2417  #[serde(default)]
2418  pub security: SecurityConfig,
2419  /// Configuration for app tray icon.
2420  #[serde(alias = "tray-icon")]
2421  pub tray_icon: Option<TrayIconConfig>,
2422  /// MacOS private API configuration. Enables the transparent background API and sets the `fullScreenEnabled` preference to `true`.
2423  #[serde(rename = "macOSPrivateApi", alias = "macos-private-api", default)]
2424  pub macos_private_api: bool,
2425  /// Whether we should inject the Tauri API on `window.__TAURI__` or not.
2426  #[serde(default, alias = "with-global-tauri")]
2427  pub with_global_tauri: bool,
2428  /// If set to true "identifier" will be set as GTK app ID (on systems that use GTK).
2429  #[serde(rename = "enableGTKAppId", alias = "enable-gtk-app-id", default)]
2430  pub enable_gtk_app_id: bool,
2431}
2432
2433impl AppConfig {
2434  /// Returns all Cargo features.
2435  pub fn all_features() -> Vec<&'static str> {
2436    vec![
2437      "tray-icon",
2438      "macos-private-api",
2439      "protocol-asset",
2440      "isolation",
2441    ]
2442  }
2443
2444  /// Returns the enabled Cargo features.
2445  pub fn features(&self) -> Vec<&str> {
2446    let mut features = Vec::new();
2447    if self.tray_icon.is_some() {
2448      features.push("tray-icon");
2449    }
2450    if self.macos_private_api {
2451      features.push("macos-private-api");
2452    }
2453    if self.security.asset_protocol.enable {
2454      features.push("protocol-asset");
2455    }
2456
2457    if let PatternKind::Isolation { .. } = self.security.pattern {
2458      features.push("isolation");
2459    }
2460
2461    features.sort_unstable();
2462    features
2463  }
2464}
2465
2466/// Configuration for application tray icon.
2467///
2468/// See more: <https://v2.tauri.app/reference/config/#trayiconconfig>
2469#[skip_serializing_none]
2470#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
2471#[cfg_attr(feature = "schema", derive(JsonSchema))]
2472#[serde(rename_all = "camelCase", deny_unknown_fields)]
2473pub struct TrayIconConfig {
2474  /// Set an id for this tray icon so you can reference it later, defaults to `main`.
2475  pub id: Option<String>,
2476  /// Path to the default icon to use for the tray icon.
2477  ///
2478  /// Note: this stores the image in raw pixels to the final binary,
2479  /// so keep the icon size (width and height) small
2480  /// or else it's going to bloat your final executable
2481  #[serde(alias = "icon-path")]
2482  pub icon_path: PathBuf,
2483  /// 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.
2484  #[serde(default, alias = "icon-as-template")]
2485  pub icon_as_template: bool,
2486  /// A Boolean value that determines whether the menu should appear when the tray icon receives a left click.
2487  ///
2488  /// ## Platform-specific:
2489  ///
2490  /// - **Linux**: Unsupported.
2491  #[serde(default = "default_true", alias = "menu-on-left-click")]
2492  #[deprecated(since = "2.2.0", note = "Use `show_menu_on_left_click` instead.")]
2493  pub menu_on_left_click: bool,
2494  /// A Boolean value that determines whether the menu should appear when the tray icon receives a left click.
2495  ///
2496  /// ## Platform-specific:
2497  ///
2498  /// - **Linux**: Unsupported.
2499  #[serde(default = "default_true", alias = "show-menu-on-left-click")]
2500  pub show_menu_on_left_click: bool,
2501  /// Title for MacOS tray
2502  pub title: Option<String>,
2503  /// Tray icon tooltip on Windows and macOS
2504  pub tooltip: Option<String>,
2505}
2506
2507/// General configuration for the iOS target.
2508#[skip_serializing_none]
2509#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
2510#[cfg_attr(feature = "schema", derive(JsonSchema))]
2511#[serde(rename_all = "camelCase", deny_unknown_fields)]
2512pub struct IosConfig {
2513  /// A custom [XcodeGen] project.yml template to use.
2514  ///
2515  /// [XcodeGen]: <https://github.com/yonaskolb/XcodeGen>
2516  pub template: Option<PathBuf>,
2517  /// A list of strings indicating any iOS frameworks that need to be bundled with the application.
2518  ///
2519  /// Note that you need to recreate the iOS project for the changes to be applied.
2520  pub frameworks: Option<Vec<String>>,
2521  /// The development team. This value is required for iOS development because code signing is enforced.
2522  /// The `APPLE_DEVELOPMENT_TEAM` environment variable can be set to overwrite it.
2523  #[serde(alias = "development-team")]
2524  pub development_team: Option<String>,
2525  /// A version string indicating the minimum iOS version that the bundled application supports. Defaults to `13.0`.
2526  ///
2527  /// Maps to the IPHONEOS_DEPLOYMENT_TARGET value.
2528  #[serde(
2529    alias = "minimum-system-version",
2530    default = "ios_minimum_system_version"
2531  )]
2532  pub minimum_system_version: String,
2533}
2534
2535impl Default for IosConfig {
2536  fn default() -> Self {
2537    Self {
2538      template: None,
2539      frameworks: None,
2540      development_team: None,
2541      minimum_system_version: ios_minimum_system_version(),
2542    }
2543  }
2544}
2545
2546/// General configuration for the Android target.
2547#[skip_serializing_none]
2548#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
2549#[cfg_attr(feature = "schema", derive(JsonSchema))]
2550#[serde(rename_all = "camelCase", deny_unknown_fields)]
2551pub struct AndroidConfig {
2552  /// The minimum API level required for the application to run.
2553  /// The Android system will prevent the user from installing the application if the system's API level is lower than the value specified.
2554  #[serde(alias = "min-sdk-version", default = "default_min_sdk_version")]
2555  pub min_sdk_version: u32,
2556
2557  /// The version code of the application.
2558  /// It is limited to 2,100,000,000 as per Google Play Store requirements.
2559  ///
2560  /// By default we use your configured version and perform the following math:
2561  /// versionCode = version.major * 1000000 + version.minor * 1000 + version.patch
2562  #[serde(alias = "version-code")]
2563  #[cfg_attr(feature = "schema", validate(range(min = 1, max = 2_100_000_000)))]
2564  pub version_code: Option<u32>,
2565}
2566
2567impl Default for AndroidConfig {
2568  fn default() -> Self {
2569    Self {
2570      min_sdk_version: default_min_sdk_version(),
2571      version_code: None,
2572    }
2573  }
2574}
2575
2576fn default_min_sdk_version() -> u32 {
2577  24
2578}
2579
2580/// Defines the URL or assets to embed in the application.
2581#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
2582#[cfg_attr(feature = "schema", derive(JsonSchema))]
2583#[serde(untagged, deny_unknown_fields)]
2584#[non_exhaustive]
2585pub enum FrontendDist {
2586  /// An external URL that should be used as the default application URL.
2587  Url(Url),
2588  /// Path to a directory containing the frontend dist assets.
2589  Directory(PathBuf),
2590  /// An array of files to embed on the app.
2591  Files(Vec<PathBuf>),
2592}
2593
2594impl std::fmt::Display for FrontendDist {
2595  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2596    match self {
2597      Self::Url(url) => write!(f, "{url}"),
2598      Self::Directory(p) => write!(f, "{}", p.display()),
2599      Self::Files(files) => write!(f, "{}", serde_json::to_string(files).unwrap()),
2600    }
2601  }
2602}
2603
2604/// Describes the shell command to run before `tauri dev`.
2605#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
2606#[cfg_attr(feature = "schema", derive(JsonSchema))]
2607#[serde(rename_all = "camelCase", untagged)]
2608pub enum BeforeDevCommand {
2609  /// Run the given script with the default options.
2610  Script(String),
2611  /// Run the given script with custom options.
2612  ScriptWithOptions {
2613    /// The script to execute.
2614    script: String,
2615    /// The current working directory.
2616    cwd: Option<String>,
2617    /// Whether `tauri dev` should wait for the command to finish or not. Defaults to `false`.
2618    #[serde(default)]
2619    wait: bool,
2620  },
2621}
2622
2623/// Describes a shell command to be executed when a CLI hook is triggered.
2624#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
2625#[cfg_attr(feature = "schema", derive(JsonSchema))]
2626#[serde(rename_all = "camelCase", untagged)]
2627pub enum HookCommand {
2628  /// Run the given script with the default options.
2629  Script(String),
2630  /// Run the given script with custom options.
2631  ScriptWithOptions {
2632    /// The script to execute.
2633    script: String,
2634    /// The current working directory.
2635    cwd: Option<String>,
2636  },
2637}
2638
2639/// The Build configuration object.
2640///
2641/// See more: <https://v2.tauri.app/reference/config/#buildconfig>
2642#[skip_serializing_none]
2643#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize, Default)]
2644#[cfg_attr(feature = "schema", derive(JsonSchema))]
2645#[serde(rename_all = "camelCase", deny_unknown_fields)]
2646pub struct BuildConfig {
2647  /// The binary used to build and run the application.
2648  pub runner: Option<String>,
2649  /// The URL to load in development.
2650  ///
2651  /// This is usually an URL to a dev server, which serves your application assets with hot-reload and HMR.
2652  /// Most modern JavaScript bundlers like [Vite](https://vite.dev/guide/) provides a way to start a dev server by default.
2653  ///
2654  /// If you don't have a dev server or don't want to use one, ignore this option and use [`frontendDist`](BuildConfig::frontend_dist)
2655  /// and point to a web assets directory, and Tauri CLI will run its built-in dev server and provide a simple hot-reload experience.
2656  #[serde(alias = "dev-url")]
2657  pub dev_url: Option<Url>,
2658  /// The path to the application assets (usually the `dist` folder of your javascript bundler)
2659  /// or a URL that could be either a custom protocol registered in the tauri app (for example: `myprotocol://`)
2660  /// or a remote URL (for example: `https://site.com/app`).
2661  ///
2662  /// When a path relative to the configuration file is provided,
2663  /// it is read recursively and all files are embedded in the application binary.
2664  /// Tauri then looks for an `index.html` and serves it as the default entry point for your application.
2665  ///
2666  /// You can also provide a list of paths to be embedded, which allows granular control over what files are added to the binary.
2667  /// In this case, all files are added to the root and you must reference it that way in your HTML files.
2668  ///
2669  /// When a URL is provided, the application won't have bundled assets
2670  /// and the application will load that URL by default.
2671  #[serde(alias = "frontend-dist")]
2672  pub frontend_dist: Option<FrontendDist>,
2673  /// A shell command to run before `tauri dev` kicks in.
2674  ///
2675  /// The TAURI_ENV_PLATFORM, TAURI_ENV_ARCH, TAURI_ENV_FAMILY, TAURI_ENV_PLATFORM_VERSION, TAURI_ENV_PLATFORM_TYPE and TAURI_ENV_DEBUG environment variables are set if you perform conditional compilation.
2676  #[serde(alias = "before-dev-command")]
2677  pub before_dev_command: Option<BeforeDevCommand>,
2678  /// A shell command to run before `tauri build` kicks in.
2679  ///
2680  /// The TAURI_ENV_PLATFORM, TAURI_ENV_ARCH, TAURI_ENV_FAMILY, TAURI_ENV_PLATFORM_VERSION, TAURI_ENV_PLATFORM_TYPE and TAURI_ENV_DEBUG environment variables are set if you perform conditional compilation.
2681  #[serde(alias = "before-build-command")]
2682  pub before_build_command: Option<HookCommand>,
2683  /// A shell command to run before the bundling phase in `tauri build` kicks in.
2684  ///
2685  /// The TAURI_ENV_PLATFORM, TAURI_ENV_ARCH, TAURI_ENV_FAMILY, TAURI_ENV_PLATFORM_VERSION, TAURI_ENV_PLATFORM_TYPE and TAURI_ENV_DEBUG environment variables are set if you perform conditional compilation.
2686  #[serde(alias = "before-bundle-command")]
2687  pub before_bundle_command: Option<HookCommand>,
2688  /// Features passed to `cargo` commands.
2689  pub features: Option<Vec<String>>,
2690  /// Try to remove unused commands registered from plugins base on the ACL list during `tauri build`,
2691  /// the way it works is that tauri-cli will read this and set the environment variables for the build script and macros,
2692  /// and they'll try to get all the allowed commands and remove the rest
2693  ///
2694  /// Note:
2695  ///   - This won't be accounting for dynamically added ACLs so make sure to check it when using this
2696  ///   - This feature requires tauri-plugin 2.1 and tauri 2.4
2697  #[serde(alias = "remove-unused-commands", default)]
2698  pub remove_unused_commands: bool,
2699}
2700
2701#[derive(Debug, PartialEq, Eq)]
2702struct PackageVersion(String);
2703
2704impl<'d> serde::Deserialize<'d> for PackageVersion {
2705  fn deserialize<D: Deserializer<'d>>(deserializer: D) -> Result<Self, D::Error> {
2706    struct PackageVersionVisitor;
2707
2708    impl Visitor<'_> for PackageVersionVisitor {
2709      type Value = PackageVersion;
2710
2711      fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2712        write!(
2713          formatter,
2714          "a semver string or a path to a package.json file"
2715        )
2716      }
2717
2718      fn visit_str<E: DeError>(self, value: &str) -> Result<PackageVersion, E> {
2719        let path = PathBuf::from(value);
2720        if path.exists() {
2721          let json_str = read_to_string(&path)
2722            .map_err(|e| DeError::custom(format!("failed to read version JSON file: {e}")))?;
2723          let package_json: serde_json::Value = serde_json::from_str(&json_str)
2724            .map_err(|e| DeError::custom(format!("failed to read version JSON file: {e}")))?;
2725          if let Some(obj) = package_json.as_object() {
2726            let version = obj
2727              .get("version")
2728              .ok_or_else(|| DeError::custom("JSON must contain a `version` field"))?
2729              .as_str()
2730              .ok_or_else(|| {
2731                DeError::custom(format!("`{} > version` must be a string", path.display()))
2732              })?;
2733            Ok(PackageVersion(
2734              Version::from_str(version)
2735                .map_err(|_| DeError::custom("`package > version` must be a semver string"))?
2736                .to_string(),
2737            ))
2738          } else {
2739            Err(DeError::custom(
2740              "`package > version` value is not a path to a JSON object",
2741            ))
2742          }
2743        } else {
2744          Ok(PackageVersion(
2745            Version::from_str(value)
2746              .map_err(|_| DeError::custom("`package > version` must be a semver string"))?
2747              .to_string(),
2748          ))
2749        }
2750      }
2751    }
2752
2753    deserializer.deserialize_string(PackageVersionVisitor {})
2754  }
2755}
2756
2757fn version_deserializer<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
2758where
2759  D: Deserializer<'de>,
2760{
2761  Option::<PackageVersion>::deserialize(deserializer).map(|v| v.map(|v| v.0))
2762}
2763
2764/// The Tauri configuration object.
2765/// It is read from a file where you can define your frontend assets,
2766/// configure the bundler and define a tray icon.
2767///
2768/// The configuration file is generated by the
2769/// [`tauri init`](https://v2.tauri.app/reference/cli/#init) command that lives in
2770/// your Tauri application source directory (src-tauri).
2771///
2772/// Once generated, you may modify it at will to customize your Tauri application.
2773///
2774/// ## File Formats
2775///
2776/// By default, the configuration is defined as a JSON file named `tauri.conf.json`.
2777///
2778/// Tauri also supports JSON5 and TOML files via the `config-json5` and `config-toml` Cargo features, respectively.
2779/// The JSON5 file name must be either `tauri.conf.json` or `tauri.conf.json5`.
2780/// The TOML file name is `Tauri.toml`.
2781///
2782/// ## Platform-Specific Configuration
2783///
2784/// In addition to the default configuration file, Tauri can
2785/// read a platform-specific configuration from `tauri.linux.conf.json`,
2786/// `tauri.windows.conf.json`, `tauri.macos.conf.json`, `tauri.android.conf.json` and `tauri.ios.conf.json`
2787/// (or `Tauri.linux.toml`, `Tauri.windows.toml`, `Tauri.macos.toml`, `Tauri.android.toml` and `Tauri.ios.toml` if the `Tauri.toml` format is used),
2788/// which gets merged with the main configuration object.
2789///
2790/// ## Configuration Structure
2791///
2792/// The configuration is composed of the following objects:
2793///
2794/// - [`app`](#appconfig): The Tauri configuration
2795/// - [`build`](#buildconfig): The build configuration
2796/// - [`bundle`](#bundleconfig): The bundle configurations
2797/// - [`plugins`](#pluginconfig): The plugins configuration
2798///
2799/// Example tauri.config.json file:
2800///
2801/// ```json
2802/// {
2803///   "productName": "tauri-app",
2804///   "version": "0.1.0",
2805///   "build": {
2806///     "beforeBuildCommand": "",
2807///     "beforeDevCommand": "",
2808///     "devUrl": "http://localhost:3000",
2809///     "frontendDist": "../dist"
2810///   },
2811///   "app": {
2812///     "security": {
2813///       "csp": null
2814///     },
2815///     "windows": [
2816///       {
2817///         "fullscreen": false,
2818///         "height": 600,
2819///         "resizable": true,
2820///         "title": "Tauri App",
2821///         "width": 800
2822///       }
2823///     ]
2824///   },
2825///   "bundle": {},
2826///   "plugins": {}
2827/// }
2828/// ```
2829#[skip_serializing_none]
2830#[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
2831#[cfg_attr(feature = "schema", derive(JsonSchema))]
2832#[serde(rename_all = "camelCase", deny_unknown_fields)]
2833pub struct Config {
2834  /// The JSON schema for the Tauri config.
2835  #[serde(rename = "$schema")]
2836  pub schema: Option<String>,
2837  /// App name.
2838  #[serde(alias = "product-name")]
2839  #[cfg_attr(feature = "schema", validate(regex(pattern = "^[^/\\:*?\"<>|]+$")))]
2840  pub product_name: Option<String>,
2841  /// App main binary filename. Defaults to the name of your cargo crate.
2842  #[serde(alias = "main-binary-name")]
2843  pub main_binary_name: Option<String>,
2844  /// App version. It is a semver version number or a path to a `package.json` file containing the `version` field. If removed the version number from `Cargo.toml` is used.
2845  ///
2846  /// By default version 1.0 is used on Android.
2847  #[serde(deserialize_with = "version_deserializer", default)]
2848  pub version: Option<String>,
2849  /// The application identifier in reverse domain name notation (e.g. `com.tauri.example`).
2850  /// This string must be unique across applications since it is used in system configurations like
2851  /// the bundle ID and path to the webview data directory.
2852  /// This string must contain only alphanumeric characters (A-Z, a-z, and 0-9), hyphens (-),
2853  /// and periods (.).
2854  pub identifier: String,
2855  /// The App configuration.
2856  #[serde(default)]
2857  pub app: AppConfig,
2858  /// The build configuration.
2859  #[serde(default)]
2860  pub build: BuildConfig,
2861  /// The bundler configuration.
2862  #[serde(default)]
2863  pub bundle: BundleConfig,
2864  /// The plugins config.
2865  #[serde(default)]
2866  pub plugins: PluginConfig,
2867}
2868
2869/// The plugin configs holds a HashMap mapping a plugin name to its configuration object.
2870///
2871/// See more: <https://v2.tauri.app/reference/config/#pluginconfig>
2872#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
2873#[cfg_attr(feature = "schema", derive(JsonSchema))]
2874pub struct PluginConfig(pub HashMap<String, JsonValue>);
2875
2876/// Implement `ToTokens` for all config structs, allowing a literal `Config` to be built.
2877///
2878/// This allows for a build script to output the values in a `Config` to a `TokenStream`, which can
2879/// then be consumed by another crate. Useful for passing a config to both the build script and the
2880/// application using tauri while only parsing it once (in the build script).
2881#[cfg(feature = "build")]
2882mod build {
2883  use super::*;
2884  use crate::{literal_struct, tokens::*};
2885  use proc_macro2::TokenStream;
2886  use quote::{quote, ToTokens, TokenStreamExt};
2887  use std::convert::identity;
2888
2889  impl ToTokens for WebviewUrl {
2890    fn to_tokens(&self, tokens: &mut TokenStream) {
2891      let prefix = quote! { ::tauri::utils::config::WebviewUrl };
2892
2893      tokens.append_all(match self {
2894        Self::App(path) => {
2895          let path = path_buf_lit(path);
2896          quote! { #prefix::App(#path) }
2897        }
2898        Self::External(url) => {
2899          let url = url_lit(url);
2900          quote! { #prefix::External(#url) }
2901        }
2902        Self::CustomProtocol(url) => {
2903          let url = url_lit(url);
2904          quote! { #prefix::CustomProtocol(#url) }
2905        }
2906      })
2907    }
2908  }
2909
2910  impl ToTokens for BackgroundThrottlingPolicy {
2911    fn to_tokens(&self, tokens: &mut TokenStream) {
2912      let prefix = quote! { ::tauri::utils::config::BackgroundThrottlingPolicy };
2913      tokens.append_all(match self {
2914        Self::Disabled => quote! { #prefix::Disabled },
2915        Self::Throttle => quote! { #prefix::Throttle },
2916        Self::Suspend => quote! { #prefix::Suspend },
2917      })
2918    }
2919  }
2920
2921  impl ToTokens for crate::Theme {
2922    fn to_tokens(&self, tokens: &mut TokenStream) {
2923      let prefix = quote! { ::tauri::utils::Theme };
2924
2925      tokens.append_all(match self {
2926        Self::Light => quote! { #prefix::Light },
2927        Self::Dark => quote! { #prefix::Dark },
2928      })
2929    }
2930  }
2931
2932  impl ToTokens for Color {
2933    fn to_tokens(&self, tokens: &mut TokenStream) {
2934      let Color(r, g, b, a) = self;
2935      tokens.append_all(quote! {::tauri::utils::config::Color(#r,#g,#b,#a)});
2936    }
2937  }
2938  impl ToTokens for WindowEffectsConfig {
2939    fn to_tokens(&self, tokens: &mut TokenStream) {
2940      let effects = vec_lit(self.effects.clone(), |d| d);
2941      let state = opt_lit(self.state.as_ref());
2942      let radius = opt_lit(self.radius.as_ref());
2943      let color = opt_lit(self.color.as_ref());
2944
2945      literal_struct!(
2946        tokens,
2947        ::tauri::utils::config::WindowEffectsConfig,
2948        effects,
2949        state,
2950        radius,
2951        color
2952      )
2953    }
2954  }
2955
2956  impl ToTokens for crate::TitleBarStyle {
2957    fn to_tokens(&self, tokens: &mut TokenStream) {
2958      let prefix = quote! { ::tauri::utils::TitleBarStyle };
2959
2960      tokens.append_all(match self {
2961        Self::Visible => quote! { #prefix::Visible },
2962        Self::Transparent => quote! { #prefix::Transparent },
2963        Self::Overlay => quote! { #prefix::Overlay },
2964      })
2965    }
2966  }
2967
2968  impl ToTokens for LogicalPosition {
2969    fn to_tokens(&self, tokens: &mut TokenStream) {
2970      let LogicalPosition { x, y } = self;
2971      literal_struct!(tokens, ::tauri::utils::config::LogicalPosition, x, y)
2972    }
2973  }
2974
2975  impl ToTokens for crate::WindowEffect {
2976    fn to_tokens(&self, tokens: &mut TokenStream) {
2977      let prefix = quote! { ::tauri::utils::WindowEffect };
2978
2979      #[allow(deprecated)]
2980      tokens.append_all(match self {
2981        WindowEffect::AppearanceBased => quote! { #prefix::AppearanceBased},
2982        WindowEffect::Light => quote! { #prefix::Light},
2983        WindowEffect::Dark => quote! { #prefix::Dark},
2984        WindowEffect::MediumLight => quote! { #prefix::MediumLight},
2985        WindowEffect::UltraDark => quote! { #prefix::UltraDark},
2986        WindowEffect::Titlebar => quote! { #prefix::Titlebar},
2987        WindowEffect::Selection => quote! { #prefix::Selection},
2988        WindowEffect::Menu => quote! { #prefix::Menu},
2989        WindowEffect::Popover => quote! { #prefix::Popover},
2990        WindowEffect::Sidebar => quote! { #prefix::Sidebar},
2991        WindowEffect::HeaderView => quote! { #prefix::HeaderView},
2992        WindowEffect::Sheet => quote! { #prefix::Sheet},
2993        WindowEffect::WindowBackground => quote! { #prefix::WindowBackground},
2994        WindowEffect::HudWindow => quote! { #prefix::HudWindow},
2995        WindowEffect::FullScreenUI => quote! { #prefix::FullScreenUI},
2996        WindowEffect::Tooltip => quote! { #prefix::Tooltip},
2997        WindowEffect::ContentBackground => quote! { #prefix::ContentBackground},
2998        WindowEffect::UnderWindowBackground => quote! { #prefix::UnderWindowBackground},
2999        WindowEffect::UnderPageBackground => quote! { #prefix::UnderPageBackground},
3000        WindowEffect::Mica => quote! { #prefix::Mica},
3001        WindowEffect::MicaDark => quote! { #prefix::MicaDark},
3002        WindowEffect::MicaLight => quote! { #prefix::MicaLight},
3003        WindowEffect::Blur => quote! { #prefix::Blur},
3004        WindowEffect::Acrylic => quote! { #prefix::Acrylic},
3005        WindowEffect::Tabbed => quote! { #prefix::Tabbed },
3006        WindowEffect::TabbedDark => quote! { #prefix::TabbedDark },
3007        WindowEffect::TabbedLight => quote! { #prefix::TabbedLight },
3008      })
3009    }
3010  }
3011
3012  impl ToTokens for crate::WindowEffectState {
3013    fn to_tokens(&self, tokens: &mut TokenStream) {
3014      let prefix = quote! { ::tauri::utils::WindowEffectState };
3015
3016      #[allow(deprecated)]
3017      tokens.append_all(match self {
3018        WindowEffectState::Active => quote! { #prefix::Active},
3019        WindowEffectState::FollowsWindowActiveState => quote! { #prefix::FollowsWindowActiveState},
3020        WindowEffectState::Inactive => quote! { #prefix::Inactive},
3021      })
3022    }
3023  }
3024
3025  impl ToTokens for WindowConfig {
3026    fn to_tokens(&self, tokens: &mut TokenStream) {
3027      let label = str_lit(&self.label);
3028      let create = &self.create;
3029      let url = &self.url;
3030      let user_agent = opt_str_lit(self.user_agent.as_ref());
3031      let drag_drop_enabled = self.drag_drop_enabled;
3032      let center = self.center;
3033      let x = opt_lit(self.x.as_ref());
3034      let y = opt_lit(self.y.as_ref());
3035      let width = self.width;
3036      let height = self.height;
3037      let min_width = opt_lit(self.min_width.as_ref());
3038      let min_height = opt_lit(self.min_height.as_ref());
3039      let max_width = opt_lit(self.max_width.as_ref());
3040      let max_height = opt_lit(self.max_height.as_ref());
3041      let resizable = self.resizable;
3042      let maximizable = self.maximizable;
3043      let minimizable = self.minimizable;
3044      let closable = self.closable;
3045      let title = str_lit(&self.title);
3046      let proxy_url = opt_lit(self.proxy_url.as_ref().map(url_lit).as_ref());
3047      let fullscreen = self.fullscreen;
3048      let focus = self.focus;
3049      let transparent = self.transparent;
3050      let maximized = self.maximized;
3051      let visible = self.visible;
3052      let decorations = self.decorations;
3053      let always_on_bottom = self.always_on_bottom;
3054      let always_on_top = self.always_on_top;
3055      let visible_on_all_workspaces = self.visible_on_all_workspaces;
3056      let content_protected = self.content_protected;
3057      let skip_taskbar = self.skip_taskbar;
3058      let window_classname = opt_str_lit(self.window_classname.as_ref());
3059      let theme = opt_lit(self.theme.as_ref());
3060      let title_bar_style = &self.title_bar_style;
3061      let traffic_light_position = opt_lit(self.traffic_light_position.as_ref());
3062      let hidden_title = self.hidden_title;
3063      let accept_first_mouse = self.accept_first_mouse;
3064      let tabbing_identifier = opt_str_lit(self.tabbing_identifier.as_ref());
3065      let additional_browser_args = opt_str_lit(self.additional_browser_args.as_ref());
3066      let shadow = self.shadow;
3067      let window_effects = opt_lit(self.window_effects.as_ref());
3068      let incognito = self.incognito;
3069      let parent = opt_str_lit(self.parent.as_ref());
3070      let zoom_hotkeys_enabled = self.zoom_hotkeys_enabled;
3071      let browser_extensions_enabled = self.browser_extensions_enabled;
3072      let use_https_scheme = self.use_https_scheme;
3073      let devtools = opt_lit(self.devtools.as_ref());
3074      let background_color = opt_lit(self.background_color.as_ref());
3075      let background_throttling = opt_lit(self.background_throttling.as_ref());
3076      let javascript_disabled = self.javascript_disabled;
3077
3078      literal_struct!(
3079        tokens,
3080        ::tauri::utils::config::WindowConfig,
3081        label,
3082        url,
3083        create,
3084        user_agent,
3085        drag_drop_enabled,
3086        center,
3087        x,
3088        y,
3089        width,
3090        height,
3091        min_width,
3092        min_height,
3093        max_width,
3094        max_height,
3095        resizable,
3096        maximizable,
3097        minimizable,
3098        closable,
3099        title,
3100        proxy_url,
3101        fullscreen,
3102        focus,
3103        transparent,
3104        maximized,
3105        visible,
3106        decorations,
3107        always_on_bottom,
3108        always_on_top,
3109        visible_on_all_workspaces,
3110        content_protected,
3111        skip_taskbar,
3112        window_classname,
3113        theme,
3114        title_bar_style,
3115        traffic_light_position,
3116        hidden_title,
3117        accept_first_mouse,
3118        tabbing_identifier,
3119        additional_browser_args,
3120        shadow,
3121        window_effects,
3122        incognito,
3123        parent,
3124        zoom_hotkeys_enabled,
3125        browser_extensions_enabled,
3126        use_https_scheme,
3127        devtools,
3128        background_color,
3129        background_throttling,
3130        javascript_disabled
3131      );
3132    }
3133  }
3134
3135  impl ToTokens for PatternKind {
3136    fn to_tokens(&self, tokens: &mut TokenStream) {
3137      let prefix = quote! { ::tauri::utils::config::PatternKind };
3138
3139      tokens.append_all(match self {
3140        Self::Brownfield => quote! { #prefix::Brownfield },
3141        #[cfg(not(feature = "isolation"))]
3142        Self::Isolation { dir: _ } => quote! { #prefix::Brownfield },
3143        #[cfg(feature = "isolation")]
3144        Self::Isolation { dir } => {
3145          let dir = path_buf_lit(dir);
3146          quote! { #prefix::Isolation { dir: #dir } }
3147        }
3148      })
3149    }
3150  }
3151
3152  impl ToTokens for WebviewInstallMode {
3153    fn to_tokens(&self, tokens: &mut TokenStream) {
3154      let prefix = quote! { ::tauri::utils::config::WebviewInstallMode };
3155
3156      tokens.append_all(match self {
3157        Self::Skip => quote! { #prefix::Skip },
3158        Self::DownloadBootstrapper { silent } => {
3159          quote! { #prefix::DownloadBootstrapper { silent: #silent } }
3160        }
3161        Self::EmbedBootstrapper { silent } => {
3162          quote! { #prefix::EmbedBootstrapper { silent: #silent } }
3163        }
3164        Self::OfflineInstaller { silent } => {
3165          quote! { #prefix::OfflineInstaller { silent: #silent } }
3166        }
3167        Self::FixedRuntime { path } => {
3168          let path = path_buf_lit(path);
3169          quote! { #prefix::FixedRuntime { path: #path } }
3170        }
3171      })
3172    }
3173  }
3174
3175  impl ToTokens for WindowsConfig {
3176    fn to_tokens(&self, tokens: &mut TokenStream) {
3177      let webview_install_mode = &self.webview_install_mode;
3178      tokens.append_all(quote! { ::tauri::utils::config::WindowsConfig {
3179        webview_install_mode: #webview_install_mode,
3180        ..Default::default()
3181      }})
3182    }
3183  }
3184
3185  impl ToTokens for BundleConfig {
3186    fn to_tokens(&self, tokens: &mut TokenStream) {
3187      let publisher = quote!(None);
3188      let homepage = quote!(None);
3189      let icon = vec_lit(&self.icon, str_lit);
3190      let active = self.active;
3191      let targets = quote!(Default::default());
3192      let create_updater_artifacts = quote!(Default::default());
3193      let resources = quote!(None);
3194      let copyright = quote!(None);
3195      let category = quote!(None);
3196      let file_associations = quote!(None);
3197      let short_description = quote!(None);
3198      let long_description = quote!(None);
3199      let use_local_tools_dir = self.use_local_tools_dir;
3200      let external_bin = opt_vec_lit(self.external_bin.as_ref(), str_lit);
3201      let windows = &self.windows;
3202      let license = opt_str_lit(self.license.as_ref());
3203      let license_file = opt_lit(self.license_file.as_ref().map(path_buf_lit).as_ref());
3204      let linux = quote!(Default::default());
3205      let macos = quote!(Default::default());
3206      let ios = quote!(Default::default());
3207      let android = quote!(Default::default());
3208
3209      literal_struct!(
3210        tokens,
3211        ::tauri::utils::config::BundleConfig,
3212        active,
3213        publisher,
3214        homepage,
3215        icon,
3216        targets,
3217        create_updater_artifacts,
3218        resources,
3219        copyright,
3220        category,
3221        license,
3222        license_file,
3223        file_associations,
3224        short_description,
3225        long_description,
3226        use_local_tools_dir,
3227        external_bin,
3228        windows,
3229        linux,
3230        macos,
3231        ios,
3232        android
3233      );
3234    }
3235  }
3236
3237  impl ToTokens for FrontendDist {
3238    fn to_tokens(&self, tokens: &mut TokenStream) {
3239      let prefix = quote! { ::tauri::utils::config::FrontendDist };
3240
3241      tokens.append_all(match self {
3242        Self::Url(url) => {
3243          let url = url_lit(url);
3244          quote! { #prefix::Url(#url) }
3245        }
3246        Self::Directory(path) => {
3247          let path = path_buf_lit(path);
3248          quote! { #prefix::Directory(#path) }
3249        }
3250        Self::Files(files) => {
3251          let files = vec_lit(files, path_buf_lit);
3252          quote! { #prefix::Files(#files) }
3253        }
3254      })
3255    }
3256  }
3257
3258  impl ToTokens for BuildConfig {
3259    fn to_tokens(&self, tokens: &mut TokenStream) {
3260      let dev_url = opt_lit(self.dev_url.as_ref().map(url_lit).as_ref());
3261      let frontend_dist = opt_lit(self.frontend_dist.as_ref());
3262      let runner = quote!(None);
3263      let before_dev_command = quote!(None);
3264      let before_build_command = quote!(None);
3265      let before_bundle_command = quote!(None);
3266      let features = quote!(None);
3267      let remove_unused_commands = quote!(false);
3268
3269      literal_struct!(
3270        tokens,
3271        ::tauri::utils::config::BuildConfig,
3272        runner,
3273        dev_url,
3274        frontend_dist,
3275        before_dev_command,
3276        before_build_command,
3277        before_bundle_command,
3278        features,
3279        remove_unused_commands
3280      );
3281    }
3282  }
3283
3284  impl ToTokens for CspDirectiveSources {
3285    fn to_tokens(&self, tokens: &mut TokenStream) {
3286      let prefix = quote! { ::tauri::utils::config::CspDirectiveSources };
3287
3288      tokens.append_all(match self {
3289        Self::Inline(sources) => {
3290          let sources = sources.as_str();
3291          quote!(#prefix::Inline(#sources.into()))
3292        }
3293        Self::List(list) => {
3294          let list = vec_lit(list, str_lit);
3295          quote!(#prefix::List(#list))
3296        }
3297      })
3298    }
3299  }
3300
3301  impl ToTokens for Csp {
3302    fn to_tokens(&self, tokens: &mut TokenStream) {
3303      let prefix = quote! { ::tauri::utils::config::Csp };
3304
3305      tokens.append_all(match self {
3306        Self::Policy(policy) => {
3307          let policy = policy.as_str();
3308          quote!(#prefix::Policy(#policy.into()))
3309        }
3310        Self::DirectiveMap(list) => {
3311          let map = map_lit(
3312            quote! { ::std::collections::HashMap },
3313            list,
3314            str_lit,
3315            identity,
3316          );
3317          quote!(#prefix::DirectiveMap(#map))
3318        }
3319      })
3320    }
3321  }
3322
3323  impl ToTokens for DisabledCspModificationKind {
3324    fn to_tokens(&self, tokens: &mut TokenStream) {
3325      let prefix = quote! { ::tauri::utils::config::DisabledCspModificationKind };
3326
3327      tokens.append_all(match self {
3328        Self::Flag(flag) => {
3329          quote! { #prefix::Flag(#flag) }
3330        }
3331        Self::List(directives) => {
3332          let directives = vec_lit(directives, str_lit);
3333          quote! { #prefix::List(#directives) }
3334        }
3335      });
3336    }
3337  }
3338
3339  impl ToTokens for CapabilityEntry {
3340    fn to_tokens(&self, tokens: &mut TokenStream) {
3341      let prefix = quote! { ::tauri::utils::config::CapabilityEntry };
3342
3343      tokens.append_all(match self {
3344        Self::Inlined(capability) => {
3345          quote! { #prefix::Inlined(#capability) }
3346        }
3347        Self::Reference(id) => {
3348          let id = str_lit(id);
3349          quote! { #prefix::Reference(#id) }
3350        }
3351      });
3352    }
3353  }
3354
3355  impl ToTokens for HeaderSource {
3356    fn to_tokens(&self, tokens: &mut TokenStream) {
3357      let prefix = quote! { ::tauri::utils::config::HeaderSource };
3358
3359      tokens.append_all(match self {
3360        Self::Inline(s) => {
3361          let line = s.as_str();
3362          quote!(#prefix::Inline(#line.into()))
3363        }
3364        Self::List(l) => {
3365          let list = vec_lit(l, str_lit);
3366          quote!(#prefix::List(#list))
3367        }
3368        Self::Map(m) => {
3369          let map = map_lit(quote! { ::std::collections::HashMap }, m, str_lit, str_lit);
3370          quote!(#prefix::Map(#map))
3371        }
3372      })
3373    }
3374  }
3375
3376  impl ToTokens for HeaderConfig {
3377    fn to_tokens(&self, tokens: &mut TokenStream) {
3378      let access_control_allow_credentials =
3379        opt_lit(self.access_control_allow_credentials.as_ref());
3380      let access_control_allow_headers = opt_lit(self.access_control_allow_headers.as_ref());
3381      let access_control_allow_methods = opt_lit(self.access_control_allow_methods.as_ref());
3382      let access_control_expose_headers = opt_lit(self.access_control_expose_headers.as_ref());
3383      let access_control_max_age = opt_lit(self.access_control_max_age.as_ref());
3384      let cross_origin_embedder_policy = opt_lit(self.cross_origin_embedder_policy.as_ref());
3385      let cross_origin_opener_policy = opt_lit(self.cross_origin_opener_policy.as_ref());
3386      let cross_origin_resource_policy = opt_lit(self.cross_origin_resource_policy.as_ref());
3387      let permissions_policy = opt_lit(self.permissions_policy.as_ref());
3388      let timing_allow_origin = opt_lit(self.timing_allow_origin.as_ref());
3389      let x_content_type_options = opt_lit(self.x_content_type_options.as_ref());
3390      let tauri_custom_header = opt_lit(self.tauri_custom_header.as_ref());
3391
3392      literal_struct!(
3393        tokens,
3394        ::tauri::utils::config::HeaderConfig,
3395        access_control_allow_credentials,
3396        access_control_allow_headers,
3397        access_control_allow_methods,
3398        access_control_expose_headers,
3399        access_control_max_age,
3400        cross_origin_embedder_policy,
3401        cross_origin_opener_policy,
3402        cross_origin_resource_policy,
3403        permissions_policy,
3404        timing_allow_origin,
3405        x_content_type_options,
3406        tauri_custom_header
3407      );
3408    }
3409  }
3410
3411  impl ToTokens for SecurityConfig {
3412    fn to_tokens(&self, tokens: &mut TokenStream) {
3413      let csp = opt_lit(self.csp.as_ref());
3414      let dev_csp = opt_lit(self.dev_csp.as_ref());
3415      let freeze_prototype = self.freeze_prototype;
3416      let dangerous_disable_asset_csp_modification = &self.dangerous_disable_asset_csp_modification;
3417      let asset_protocol = &self.asset_protocol;
3418      let pattern = &self.pattern;
3419      let capabilities = vec_lit(&self.capabilities, identity);
3420      let headers = opt_lit(self.headers.as_ref());
3421
3422      literal_struct!(
3423        tokens,
3424        ::tauri::utils::config::SecurityConfig,
3425        csp,
3426        dev_csp,
3427        freeze_prototype,
3428        dangerous_disable_asset_csp_modification,
3429        asset_protocol,
3430        pattern,
3431        capabilities,
3432        headers
3433      );
3434    }
3435  }
3436
3437  impl ToTokens for TrayIconConfig {
3438    fn to_tokens(&self, tokens: &mut TokenStream) {
3439      let id = opt_str_lit(self.id.as_ref());
3440      let icon_as_template = self.icon_as_template;
3441      #[allow(deprecated)]
3442      let menu_on_left_click = self.menu_on_left_click;
3443      let show_menu_on_left_click = self.show_menu_on_left_click;
3444      let icon_path = path_buf_lit(&self.icon_path);
3445      let title = opt_str_lit(self.title.as_ref());
3446      let tooltip = opt_str_lit(self.tooltip.as_ref());
3447      literal_struct!(
3448        tokens,
3449        ::tauri::utils::config::TrayIconConfig,
3450        id,
3451        icon_path,
3452        icon_as_template,
3453        menu_on_left_click,
3454        show_menu_on_left_click,
3455        title,
3456        tooltip
3457      );
3458    }
3459  }
3460
3461  impl ToTokens for FsScope {
3462    fn to_tokens(&self, tokens: &mut TokenStream) {
3463      let prefix = quote! { ::tauri::utils::config::FsScope };
3464
3465      tokens.append_all(match self {
3466        Self::AllowedPaths(allow) => {
3467          let allowed_paths = vec_lit(allow, path_buf_lit);
3468          quote! { #prefix::AllowedPaths(#allowed_paths) }
3469        }
3470        Self::Scope { allow, deny , require_literal_leading_dot} => {
3471          let allow = vec_lit(allow, path_buf_lit);
3472          let deny = vec_lit(deny, path_buf_lit);
3473          let  require_literal_leading_dot = opt_lit(require_literal_leading_dot.as_ref());
3474          quote! { #prefix::Scope { allow: #allow, deny: #deny, require_literal_leading_dot: #require_literal_leading_dot } }
3475        }
3476      });
3477    }
3478  }
3479
3480  impl ToTokens for AssetProtocolConfig {
3481    fn to_tokens(&self, tokens: &mut TokenStream) {
3482      let scope = &self.scope;
3483      tokens.append_all(quote! { ::tauri::utils::config::AssetProtocolConfig { scope: #scope, ..Default::default() } })
3484    }
3485  }
3486
3487  impl ToTokens for AppConfig {
3488    fn to_tokens(&self, tokens: &mut TokenStream) {
3489      let windows = vec_lit(&self.windows, identity);
3490      let security = &self.security;
3491      let tray_icon = opt_lit(self.tray_icon.as_ref());
3492      let macos_private_api = self.macos_private_api;
3493      let with_global_tauri = self.with_global_tauri;
3494      let enable_gtk_app_id = self.enable_gtk_app_id;
3495
3496      literal_struct!(
3497        tokens,
3498        ::tauri::utils::config::AppConfig,
3499        windows,
3500        security,
3501        tray_icon,
3502        macos_private_api,
3503        with_global_tauri,
3504        enable_gtk_app_id
3505      );
3506    }
3507  }
3508
3509  impl ToTokens for PluginConfig {
3510    fn to_tokens(&self, tokens: &mut TokenStream) {
3511      let config = map_lit(
3512        quote! { ::std::collections::HashMap },
3513        &self.0,
3514        str_lit,
3515        json_value_lit,
3516      );
3517      tokens.append_all(quote! { ::tauri::utils::config::PluginConfig(#config) })
3518    }
3519  }
3520
3521  impl ToTokens for Config {
3522    fn to_tokens(&self, tokens: &mut TokenStream) {
3523      let schema = quote!(None);
3524      let product_name = opt_str_lit(self.product_name.as_ref());
3525      let main_binary_name = opt_str_lit(self.main_binary_name.as_ref());
3526      let version = opt_str_lit(self.version.as_ref());
3527      let identifier = str_lit(&self.identifier);
3528      let app = &self.app;
3529      let build = &self.build;
3530      let bundle = &self.bundle;
3531      let plugins = &self.plugins;
3532
3533      literal_struct!(
3534        tokens,
3535        ::tauri::utils::config::Config,
3536        schema,
3537        product_name,
3538        main_binary_name,
3539        version,
3540        identifier,
3541        app,
3542        build,
3543        bundle,
3544        plugins
3545      );
3546    }
3547  }
3548}
3549
3550#[cfg(test)]
3551mod test {
3552  use super::*;
3553
3554  // TODO: create a test that compares a config to a json config
3555
3556  #[test]
3557  // test all of the default functions
3558  fn test_defaults() {
3559    // get default app config
3560    let a_config = AppConfig::default();
3561    // get default build config
3562    let b_config = BuildConfig::default();
3563    // get default window
3564    let d_windows: Vec<WindowConfig> = vec![];
3565    // get default bundle
3566    let d_bundle = BundleConfig::default();
3567
3568    // create a tauri config.
3569    let app = AppConfig {
3570      windows: vec![],
3571      security: SecurityConfig {
3572        csp: None,
3573        dev_csp: None,
3574        freeze_prototype: false,
3575        dangerous_disable_asset_csp_modification: DisabledCspModificationKind::Flag(false),
3576        asset_protocol: AssetProtocolConfig::default(),
3577        pattern: Default::default(),
3578        capabilities: Vec::new(),
3579        headers: None,
3580      },
3581      tray_icon: None,
3582      macos_private_api: false,
3583      with_global_tauri: false,
3584      enable_gtk_app_id: false,
3585    };
3586
3587    // create a build config
3588    let build = BuildConfig {
3589      runner: None,
3590      dev_url: None,
3591      frontend_dist: None,
3592      before_dev_command: None,
3593      before_build_command: None,
3594      before_bundle_command: None,
3595      features: None,
3596      remove_unused_commands: false,
3597    };
3598
3599    // create a bundle config
3600    let bundle = BundleConfig {
3601      active: false,
3602      targets: Default::default(),
3603      create_updater_artifacts: Default::default(),
3604      publisher: None,
3605      homepage: None,
3606      icon: Vec::new(),
3607      resources: None,
3608      copyright: None,
3609      category: None,
3610      file_associations: None,
3611      short_description: None,
3612      long_description: None,
3613      use_local_tools_dir: false,
3614      license: None,
3615      license_file: None,
3616      linux: Default::default(),
3617      macos: Default::default(),
3618      external_bin: None,
3619      windows: Default::default(),
3620      ios: Default::default(),
3621      android: Default::default(),
3622    };
3623
3624    // test the configs
3625    assert_eq!(a_config, app);
3626    assert_eq!(b_config, build);
3627    assert_eq!(d_bundle, bundle);
3628    assert_eq!(d_windows, app.windows);
3629  }
3630
3631  #[test]
3632  fn parse_hex_color() {
3633    use super::Color;
3634
3635    assert_eq!(Color(255, 255, 255, 255), "fff".parse().unwrap());
3636    assert_eq!(Color(255, 255, 255, 255), "#fff".parse().unwrap());
3637    assert_eq!(Color(0, 0, 0, 255), "#000000".parse().unwrap());
3638    assert_eq!(Color(0, 0, 0, 255), "#000000ff".parse().unwrap());
3639    assert_eq!(Color(0, 255, 0, 255), "#00ff00ff".parse().unwrap());
3640  }
3641}