1use http::response::Builder;
27#[cfg(feature = "schema")]
28use schemars::JsonSchema;
29#[cfg(feature = "schema")]
30use schemars::schema::Schema;
31use semver::Version;
32use serde::{
33 Deserialize, Serialize, Serializer,
34 de::{Deserializer, Error as DeError, Visitor},
35};
36use serde_json::Value as JsonValue;
37use serde_untagged::UntaggedEnumVisitor;
38use serde_with::skip_serializing_none;
39use url::Url;
40
41use std::{
42 collections::{BTreeMap, HashMap, HashSet},
43 fmt::{self, Display},
44 fs::read_to_string,
45 path::{Component, Path, PathBuf},
46 str::FromStr,
47};
48
49#[cfg(feature = "schema")]
50fn add_description(schema: Schema, description: impl Into<String>) -> Schema {
51 let value = description.into();
52 if value.is_empty() {
53 schema
54 } else {
55 let mut schema_obj = schema.into_object();
56 schema_obj.metadata().description = value.into();
57 Schema::Object(schema_obj)
58 }
59}
60
61pub mod parse;
63
64use crate::{TitleBarStyle, WindowEffect, WindowEffectState, acl::capability::Capability};
65
66pub use self::parse::parse;
67
68fn default_true() -> bool {
69 true
70}
71
72#[derive(PartialEq, Eq, Debug, Clone, Serialize)]
74#[cfg_attr(feature = "schema", derive(JsonSchema))]
75#[serde(untagged)]
76#[non_exhaustive]
77pub enum WebviewUrl {
78 External(Url),
80 App(PathBuf),
84 CustomProtocol(Url),
86}
87
88impl<'de> Deserialize<'de> for WebviewUrl {
89 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
90 where
91 D: Deserializer<'de>,
92 {
93 #[derive(Deserialize)]
94 #[serde(untagged)]
95 enum WebviewUrlDeserializer {
96 Url(Url),
97 Path(PathBuf),
98 }
99
100 match WebviewUrlDeserializer::deserialize(deserializer)? {
101 WebviewUrlDeserializer::Url(u) => {
102 if u.scheme() == "https" || u.scheme() == "http" {
103 Ok(Self::External(u))
104 } else {
105 Ok(Self::CustomProtocol(u))
106 }
107 }
108 WebviewUrlDeserializer::Path(p) => Ok(Self::App(p)),
109 }
110 }
111}
112
113impl fmt::Display for WebviewUrl {
114 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115 match self {
116 Self::External(url) | Self::CustomProtocol(url) => write!(f, "{url}"),
117 Self::App(path) => write!(f, "{}", path.display()),
118 }
119 }
120}
121
122impl Default for WebviewUrl {
123 fn default() -> Self {
124 Self::App("index.html".into())
125 }
126}
127
128#[derive(Debug, PartialEq, Eq, Clone)]
130#[cfg_attr(feature = "schema", derive(JsonSchema))]
131#[cfg_attr(feature = "schema", schemars(rename_all = "lowercase"))]
132pub enum BundleType {
133 Deb,
135 Rpm,
137 AppImage,
139 Msi,
141 Nsis,
143 App,
145 Dmg,
147}
148
149impl BundleType {
150 fn all() -> &'static [Self] {
152 &[
153 BundleType::Deb,
154 BundleType::Rpm,
155 BundleType::AppImage,
156 BundleType::Msi,
157 BundleType::Nsis,
158 BundleType::App,
159 BundleType::Dmg,
160 ]
161 }
162}
163
164impl Display for BundleType {
165 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
166 write!(
167 f,
168 "{}",
169 match self {
170 Self::Deb => "deb",
171 Self::Rpm => "rpm",
172 Self::AppImage => "appimage",
173 Self::Msi => "msi",
174 Self::Nsis => "nsis",
175 Self::App => "app",
176 Self::Dmg => "dmg",
177 }
178 )
179 }
180}
181
182impl Serialize for BundleType {
183 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
184 where
185 S: Serializer,
186 {
187 serializer.serialize_str(self.to_string().as_ref())
188 }
189}
190
191impl<'de> Deserialize<'de> for BundleType {
192 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
193 where
194 D: Deserializer<'de>,
195 {
196 let s = String::deserialize(deserializer)?;
197 match s.to_lowercase().as_str() {
198 "deb" => Ok(Self::Deb),
199 "rpm" => Ok(Self::Rpm),
200 "appimage" => Ok(Self::AppImage),
201 "msi" => Ok(Self::Msi),
202 "nsis" => Ok(Self::Nsis),
203 "app" => Ok(Self::App),
204 "dmg" => Ok(Self::Dmg),
205 _ => Err(DeError::custom(format!("unknown bundle target '{s}'"))),
206 }
207 }
208}
209
210#[derive(Debug, PartialEq, Eq, Clone, Default)]
212pub enum BundleTarget {
213 #[default]
215 All,
216 List(Vec<BundleType>),
218 One(BundleType),
220}
221
222#[cfg(feature = "schema")]
223impl schemars::JsonSchema for BundleTarget {
224 fn schema_name() -> std::string::String {
225 "BundleTarget".to_owned()
226 }
227
228 fn json_schema(generator: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema {
229 let any_of = vec![
230 schemars::schema::SchemaObject {
231 const_value: Some("all".into()),
232 metadata: Some(Box::new(schemars::schema::Metadata {
233 description: Some("Bundle all targets.".to_owned()),
234 ..Default::default()
235 })),
236 ..Default::default()
237 }
238 .into(),
239 add_description(
240 generator.subschema_for::<Vec<BundleType>>(),
241 "A list of bundle targets.",
242 ),
243 add_description(
244 generator.subschema_for::<BundleType>(),
245 "A single bundle target.",
246 ),
247 ];
248
249 schemars::schema::SchemaObject {
250 subschemas: Some(Box::new(schemars::schema::SubschemaValidation {
251 any_of: Some(any_of),
252 ..Default::default()
253 })),
254 metadata: Some(Box::new(schemars::schema::Metadata {
255 description: Some("Targets to bundle. Each value is case insensitive.".to_owned()),
256 ..Default::default()
257 })),
258 ..Default::default()
259 }
260 .into()
261 }
262}
263
264impl Serialize for BundleTarget {
265 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
266 where
267 S: Serializer,
268 {
269 match self {
270 Self::All => serializer.serialize_str("all"),
271 Self::List(l) => l.serialize(serializer),
272 Self::One(t) => serializer.serialize_str(t.to_string().as_ref()),
273 }
274 }
275}
276
277impl<'de> Deserialize<'de> for BundleTarget {
278 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
279 where
280 D: Deserializer<'de>,
281 {
282 #[derive(Deserialize, Serialize)]
283 #[serde(untagged)]
284 pub enum BundleTargetInner {
285 List(Vec<BundleType>),
286 One(BundleType),
287 All(String),
288 }
289
290 match BundleTargetInner::deserialize(deserializer)? {
291 BundleTargetInner::All(s) if s.to_lowercase() == "all" => Ok(Self::All),
292 BundleTargetInner::All(t) => Err(DeError::custom(format!(
293 "invalid bundle type {t}, expected one of `all`, {}",
294 BundleType::all()
295 .iter()
296 .map(|b| format!("`{b}`"))
297 .collect::<Vec<_>>()
298 .join(", ")
299 ))),
300 BundleTargetInner::List(l) => Ok(Self::List(l)),
301 BundleTargetInner::One(t) => Ok(Self::One(t)),
302 }
303 }
304}
305
306impl BundleTarget {
307 #[allow(dead_code)]
309 pub fn to_vec(&self) -> Vec<BundleType> {
310 match self {
311 Self::All => BundleType::all().to_vec(),
312 Self::List(list) => list.clone(),
313 Self::One(i) => vec![i.clone()],
314 }
315 }
316}
317
318#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
322#[cfg_attr(feature = "schema", derive(JsonSchema))]
323#[serde(rename_all = "camelCase", deny_unknown_fields)]
324pub struct AppImageConfig {
325 #[serde(default, alias = "bundle-media-framework")]
328 pub bundle_media_framework: bool,
329 #[serde(default)]
331 pub files: HashMap<PathBuf, PathBuf>,
332}
333
334#[skip_serializing_none]
338#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
339#[cfg_attr(feature = "schema", derive(JsonSchema))]
340#[serde(rename_all = "camelCase", deny_unknown_fields)]
341pub struct DebConfig {
342 pub depends: Option<Vec<String>>,
344 pub recommends: Option<Vec<String>>,
346 pub provides: Option<Vec<String>>,
348 pub conflicts: Option<Vec<String>>,
350 pub replaces: Option<Vec<String>>,
352 #[serde(default)]
354 pub files: HashMap<PathBuf, PathBuf>,
355 pub section: Option<String>,
357 pub priority: Option<String>,
360 pub changelog: Option<PathBuf>,
363 #[serde(alias = "desktop-template")]
367 pub desktop_template: Option<PathBuf>,
368 #[serde(alias = "pre-install-script")]
371 pub pre_install_script: Option<PathBuf>,
372 #[serde(alias = "post-install-script")]
375 pub post_install_script: Option<PathBuf>,
376 #[serde(alias = "pre-remove-script")]
379 pub pre_remove_script: Option<PathBuf>,
380 #[serde(alias = "post-remove-script")]
383 pub post_remove_script: Option<PathBuf>,
384}
385
386#[skip_serializing_none]
390#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
391#[cfg_attr(feature = "schema", derive(JsonSchema))]
392#[serde(rename_all = "camelCase", deny_unknown_fields)]
393pub struct LinuxConfig {
394 #[serde(default)]
396 pub appimage: AppImageConfig,
397 #[serde(default)]
399 pub deb: DebConfig,
400 #[serde(default)]
402 pub rpm: RpmConfig,
403}
404
405#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
407#[cfg_attr(feature = "schema", derive(JsonSchema))]
408#[serde(rename_all = "camelCase", deny_unknown_fields, tag = "type")]
409#[non_exhaustive]
410pub enum RpmCompression {
411 Gzip {
413 level: u32,
415 },
416 Zstd {
418 level: i32,
420 },
421 Xz {
423 level: u32,
425 },
426 Bzip2 {
428 level: u32,
430 },
431 None,
433}
434
435#[skip_serializing_none]
437#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
438#[cfg_attr(feature = "schema", derive(JsonSchema))]
439#[serde(rename_all = "camelCase", deny_unknown_fields)]
440pub struct RpmConfig {
441 pub depends: Option<Vec<String>>,
443 pub recommends: Option<Vec<String>>,
445 pub provides: Option<Vec<String>>,
447 pub conflicts: Option<Vec<String>>,
450 pub obsoletes: Option<Vec<String>>,
453 #[serde(default = "default_release")]
455 pub release: String,
456 #[serde(default)]
458 pub epoch: u32,
459 #[serde(default)]
461 pub files: HashMap<PathBuf, PathBuf>,
462 #[serde(alias = "desktop-template")]
466 pub desktop_template: Option<PathBuf>,
467 #[serde(alias = "pre-install-script")]
470 pub pre_install_script: Option<PathBuf>,
471 #[serde(alias = "post-install-script")]
474 pub post_install_script: Option<PathBuf>,
475 #[serde(alias = "pre-remove-script")]
478 pub pre_remove_script: Option<PathBuf>,
479 #[serde(alias = "post-remove-script")]
482 pub post_remove_script: Option<PathBuf>,
483 pub compression: Option<RpmCompression>,
485}
486
487impl Default for RpmConfig {
488 fn default() -> Self {
489 Self {
490 depends: None,
491 recommends: None,
492 provides: None,
493 conflicts: None,
494 obsoletes: None,
495 release: default_release(),
496 epoch: 0,
497 files: Default::default(),
498 desktop_template: None,
499 pre_install_script: None,
500 post_install_script: None,
501 pre_remove_script: None,
502 post_remove_script: None,
503 compression: None,
504 }
505 }
506}
507
508fn default_release() -> String {
509 "1".into()
510}
511
512#[derive(Default, Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
514#[cfg_attr(feature = "schema", derive(JsonSchema))]
515#[serde(rename_all = "camelCase", deny_unknown_fields)]
516pub struct Position {
517 pub x: u32,
519 pub y: u32,
521}
522
523#[derive(Default, Debug, PartialEq, Clone, Deserialize, Serialize)]
525#[cfg_attr(feature = "schema", derive(JsonSchema))]
526#[serde(rename_all = "camelCase", deny_unknown_fields)]
527pub struct LogicalPosition {
528 pub x: f64,
530 pub y: f64,
532}
533
534#[derive(Default, Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
536#[cfg_attr(feature = "schema", derive(JsonSchema))]
537#[serde(rename_all = "camelCase", deny_unknown_fields)]
538pub struct Size {
539 pub width: u32,
541 pub height: u32,
543}
544
545#[skip_serializing_none]
549#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
550#[cfg_attr(feature = "schema", derive(JsonSchema))]
551#[serde(rename_all = "camelCase", deny_unknown_fields)]
552pub struct DmgConfig {
553 pub background: Option<PathBuf>,
555 pub window_position: Option<Position>,
557 #[serde(default = "dmg_window_size", alias = "window-size")]
559 pub window_size: Size,
560 #[serde(default = "dmg_app_position", alias = "app-position")]
562 pub app_position: Position,
563 #[serde(
565 default = "dmg_application_folder_position",
566 alias = "application-folder-position"
567 )]
568 pub application_folder_position: Position,
569}
570
571impl Default for DmgConfig {
572 fn default() -> Self {
573 Self {
574 background: None,
575 window_position: None,
576 window_size: dmg_window_size(),
577 app_position: dmg_app_position(),
578 application_folder_position: dmg_application_folder_position(),
579 }
580 }
581}
582
583fn dmg_window_size() -> Size {
584 Size {
585 width: 660,
586 height: 400,
587 }
588}
589
590fn dmg_app_position() -> Position {
591 Position { x: 180, y: 170 }
592}
593
594fn dmg_application_folder_position() -> Position {
595 Position { x: 480, y: 170 }
596}
597
598fn de_macos_minimum_system_version<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
599where
600 D: Deserializer<'de>,
601{
602 let version = Option::<String>::deserialize(deserializer)?;
603 match version {
604 Some(v) if v.is_empty() => Ok(macos_minimum_system_version()),
605 e => Ok(e),
606 }
607}
608
609#[skip_serializing_none]
613#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
614#[cfg_attr(feature = "schema", derive(JsonSchema))]
615#[serde(rename_all = "camelCase", deny_unknown_fields)]
616pub struct MacConfig {
617 pub frameworks: Option<Vec<String>>,
621 #[serde(default)]
623 pub files: HashMap<PathBuf, PathBuf>,
624 #[serde(alias = "bundle-version")]
628 pub bundle_version: Option<String>,
629 #[serde(alias = "bundle-name")]
635 pub bundle_name: Option<String>,
636 #[serde(
645 deserialize_with = "de_macos_minimum_system_version",
646 default = "macos_minimum_system_version",
647 alias = "minimum-system-version"
648 )]
649 pub minimum_system_version: Option<String>,
650 #[serde(alias = "exception-domain")]
653 pub exception_domain: Option<String>,
654 #[serde(alias = "signing-identity")]
656 pub signing_identity: Option<String>,
657 #[serde(alias = "hardened-runtime", default = "default_true")]
659 pub hardened_runtime: bool,
660 #[serde(alias = "provider-short-name")]
662 pub provider_short_name: Option<String>,
663 pub entitlements: Option<String>,
665 #[serde(alias = "info-plist")]
669 pub info_plist: Option<PathBuf>,
670 #[serde(default)]
672 pub dmg: DmgConfig,
673}
674
675impl Default for MacConfig {
676 fn default() -> Self {
677 Self {
678 frameworks: None,
679 files: HashMap::new(),
680 bundle_version: None,
681 bundle_name: None,
682 minimum_system_version: macos_minimum_system_version(),
683 exception_domain: None,
684 signing_identity: None,
685 hardened_runtime: true,
686 provider_short_name: None,
687 entitlements: None,
688 info_plist: None,
689 dmg: Default::default(),
690 }
691 }
692}
693
694fn macos_minimum_system_version() -> Option<String> {
695 Some("10.13".into())
696}
697
698fn ios_minimum_system_version() -> String {
699 "15.0".into()
700}
701
702#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
706#[cfg_attr(feature = "schema", derive(JsonSchema))]
707#[serde(rename_all = "camelCase", deny_unknown_fields)]
708pub struct WixLanguageConfig {
709 #[serde(alias = "locale-path")]
711 pub locale_path: Option<String>,
712}
713
714#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
716#[cfg_attr(feature = "schema", derive(JsonSchema))]
717#[serde(untagged)]
718pub enum WixLanguage {
719 One(String),
721 List(Vec<String>),
723 Localized(HashMap<String, WixLanguageConfig>),
725}
726
727impl Default for WixLanguage {
728 fn default() -> Self {
729 Self::One("en-US".into())
730 }
731}
732
733#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
737#[cfg_attr(feature = "schema", derive(JsonSchema))]
738#[serde(rename_all = "camelCase", deny_unknown_fields)]
739pub struct WixConfig {
740 pub version: Option<String>,
749 #[serde(alias = "upgrade-code")]
758 pub upgrade_code: Option<uuid::Uuid>,
759 #[serde(default)]
761 pub language: WixLanguage,
762 pub template: Option<PathBuf>,
764 #[serde(default, alias = "fragment-paths")]
766 pub fragment_paths: Vec<PathBuf>,
767 #[serde(default, alias = "component-group-refs")]
769 pub component_group_refs: Vec<String>,
770 #[serde(default, alias = "component-refs")]
772 pub component_refs: Vec<String>,
773 #[serde(default, alias = "feature-group-refs")]
775 pub feature_group_refs: Vec<String>,
776 #[serde(default, alias = "feature-refs")]
778 pub feature_refs: Vec<String>,
779 #[serde(default, alias = "merge-refs")]
781 pub merge_refs: Vec<String>,
782 #[serde(default, alias = "enable-elevated-update-task")]
784 pub enable_elevated_update_task: bool,
785 #[serde(alias = "banner-path")]
790 pub banner_path: Option<PathBuf>,
791 #[serde(alias = "dialog-image-path")]
796 pub dialog_image_path: Option<PathBuf>,
797 #[serde(default, alias = "fips-compliant")]
800 pub fips_compliant: bool,
801}
802
803#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize, Default)]
807#[cfg_attr(feature = "schema", derive(JsonSchema))]
808#[serde(rename_all = "camelCase", deny_unknown_fields)]
809pub enum NsisCompression {
810 Zlib,
812 Bzip2,
814 #[default]
816 Lzma,
817 None,
819}
820
821#[derive(Default, Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
823#[serde(rename_all = "camelCase", deny_unknown_fields)]
824#[cfg_attr(feature = "schema", derive(JsonSchema))]
825pub enum NSISInstallerMode {
826 #[default]
832 CurrentUser,
833 PerMachine,
838 Both,
844}
845
846#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
848#[cfg_attr(feature = "schema", derive(JsonSchema))]
849#[serde(rename_all = "camelCase", deny_unknown_fields)]
850pub struct NsisConfig {
851 pub template: Option<PathBuf>,
853 #[serde(alias = "header-image")]
857 pub header_image: Option<PathBuf>,
858 #[serde(alias = "sidebar-image")]
862 pub sidebar_image: Option<PathBuf>,
863 #[serde(alias = "install-icon")]
866 pub installer_icon: Option<PathBuf>,
867 #[serde(alias = "uninstaller-icon")]
869 pub uninstaller_icon: Option<PathBuf>,
870 #[serde(alias = "uninstaller-header-image")]
875 pub uninstaller_header_image: Option<PathBuf>,
876 #[serde(default, alias = "install-mode")]
878 pub install_mode: NSISInstallerMode,
879 pub languages: Option<Vec<String>>,
886 pub custom_language_files: Option<HashMap<String, PathBuf>>,
893 #[serde(default, alias = "display-language-selector")]
896 pub display_language_selector: bool,
897 #[serde(default)]
901 pub compression: NsisCompression,
902 #[serde(alias = "start-menu-folder")]
911 pub start_menu_folder: Option<String>,
912 #[serde(alias = "installer-hooks")]
942 pub installer_hooks: Option<PathBuf>,
943 #[deprecated(
949 since = "2.10.0",
950 note = "Use `WindowsConfig::minimum_webview2_version` instead."
951 )]
952 #[serde(alias = "minimum-webview2-version")]
953 pub minimum_webview2_version: Option<String>,
954}
955
956#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
961#[serde(tag = "type", rename_all = "camelCase", deny_unknown_fields)]
962#[cfg_attr(feature = "schema", derive(JsonSchema))]
963pub enum WebviewInstallMode {
964 Skip,
966 DownloadBootstrapper {
970 #[serde(default = "default_true")]
972 silent: bool,
973 },
974 EmbedBootstrapper {
978 #[serde(default = "default_true")]
980 silent: bool,
981 },
982 OfflineInstaller {
986 #[serde(default = "default_true")]
988 silent: bool,
989 },
990 FixedRuntime {
993 path: PathBuf,
998 },
999}
1000
1001impl Default for WebviewInstallMode {
1002 fn default() -> Self {
1003 Self::DownloadBootstrapper { silent: true }
1004 }
1005}
1006
1007#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1009#[cfg_attr(feature = "schema", derive(JsonSchema))]
1010#[serde(rename_all = "camelCase", deny_unknown_fields, untagged)]
1011pub enum CustomSignCommandConfig {
1012 Command(String),
1021 CommandWithOptions {
1026 cmd: String,
1028 args: Vec<String>,
1032 },
1033}
1034
1035#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1039#[cfg_attr(feature = "schema", derive(JsonSchema))]
1040#[serde(rename_all = "camelCase", deny_unknown_fields)]
1041pub struct WindowsConfig {
1042 #[serde(alias = "digest-algorithm")]
1045 pub digest_algorithm: Option<String>,
1046 #[serde(alias = "certificate-thumbprint")]
1048 pub certificate_thumbprint: Option<String>,
1049 #[serde(alias = "timestamp-url")]
1051 pub timestamp_url: Option<String>,
1052 #[serde(default)]
1055 pub tsp: bool,
1056 #[serde(default, alias = "webview-install-mode")]
1058 pub webview_install_mode: WebviewInstallMode,
1059 #[serde(default = "default_true", alias = "allow-downgrades")]
1069 pub allow_downgrades: bool,
1070 #[serde(alias = "minimum-webview2-version")]
1074 pub minimum_webview2_version: Option<String>,
1075 pub wix: Option<WixConfig>,
1077 pub nsis: Option<NsisConfig>,
1079 #[serde(alias = "sign-command")]
1087 pub sign_command: Option<CustomSignCommandConfig>,
1088 #[serde(
1095 default,
1096 rename = "bundleVCRuntime",
1097 alias = "bundle-vc-runtime",
1098 alias = "bundleVcRuntime"
1099 )]
1100 pub bundle_vc_runtime: bool,
1101}
1102
1103impl Default for WindowsConfig {
1104 fn default() -> Self {
1105 Self {
1106 digest_algorithm: None,
1107 certificate_thumbprint: None,
1108 timestamp_url: None,
1109 tsp: false,
1110 webview_install_mode: Default::default(),
1111 allow_downgrades: true,
1112 minimum_webview2_version: None,
1113 wix: None,
1114 nsis: None,
1115 sign_command: None,
1116 bundle_vc_runtime: false,
1117 }
1118 }
1119}
1120
1121#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
1123#[cfg_attr(feature = "schema", derive(JsonSchema))]
1124pub enum BundleTypeRole {
1125 #[default]
1127 Editor,
1128 Viewer,
1130 Shell,
1132 QLGenerator,
1134 None,
1136}
1137
1138impl Display for BundleTypeRole {
1139 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1140 match self {
1141 Self::Editor => write!(f, "Editor"),
1142 Self::Viewer => write!(f, "Viewer"),
1143 Self::Shell => write!(f, "Shell"),
1144 Self::QLGenerator => write!(f, "QLGenerator"),
1145 Self::None => write!(f, "None"),
1146 }
1147 }
1148}
1149
1150#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
1154#[cfg_attr(feature = "schema", derive(JsonSchema))]
1155pub enum HandlerRank {
1156 #[default]
1158 Default,
1159 Owner,
1161 Alternate,
1163 None,
1165}
1166
1167impl Display for HandlerRank {
1168 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1169 match self {
1170 Self::Default => write!(f, "Default"),
1171 Self::Owner => write!(f, "Owner"),
1172 Self::Alternate => write!(f, "Alternate"),
1173 Self::None => write!(f, "None"),
1174 }
1175 }
1176}
1177
1178#[derive(Debug, PartialEq, Eq, Clone, Serialize)]
1182#[cfg_attr(feature = "schema", derive(JsonSchema))]
1183pub struct AssociationExt(pub String);
1184
1185impl fmt::Display for AssociationExt {
1186 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1187 write!(f, "{}", self.0)
1188 }
1189}
1190
1191impl<'d> serde::Deserialize<'d> for AssociationExt {
1192 fn deserialize<D: Deserializer<'d>>(deserializer: D) -> Result<Self, D::Error> {
1193 let ext = String::deserialize(deserializer)?;
1194 if let Some(ext) = ext.strip_prefix('.') {
1195 Ok(AssociationExt(ext.into()))
1196 } else {
1197 Ok(AssociationExt(ext))
1198 }
1199 }
1200}
1201
1202#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1204#[cfg_attr(feature = "schema", derive(JsonSchema))]
1205#[serde(rename_all = "camelCase", deny_unknown_fields)]
1206pub struct FileAssociation {
1207 pub ext: Vec<AssociationExt>,
1209 #[serde(alias = "content-types")]
1214 pub content_types: Option<Vec<String>>,
1215 pub name: Option<String>,
1217 pub description: Option<String>,
1219 #[serde(default)]
1221 pub role: BundleTypeRole,
1222 #[serde(alias = "mime-type")]
1230 pub mime_type: Option<String>,
1231 #[serde(default)]
1233 pub rank: HandlerRank,
1234 pub exported_type: Option<ExportedFileAssociation>,
1238 #[serde(alias = "android-intent-action-filters")]
1242 pub android_intent_action_filters: Option<Vec<AndroidIntentAction>>,
1243}
1244
1245#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize, Hash)]
1247#[cfg_attr(feature = "schema", derive(JsonSchema))]
1248#[serde(rename_all = "camelCase")]
1249#[non_exhaustive]
1250pub enum AndroidIntentAction {
1251 Send,
1255 SendMultiple,
1259 View,
1263}
1264
1265#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1267#[cfg_attr(feature = "schema", derive(JsonSchema))]
1268#[serde(rename_all = "camelCase", deny_unknown_fields)]
1269pub struct ExportedFileAssociation {
1270 pub identifier: String,
1272 #[serde(alias = "conforms-to")]
1276 pub conforms_to: Option<Vec<String>>,
1277}
1278
1279impl FileAssociation {
1280 pub fn infer_content_types(&self) -> HashSet<String> {
1287 let mut content_types = HashSet::new();
1288
1289 if let Some(exported_type) = &self.exported_type {
1291 content_types.insert(exported_type.identifier.clone());
1292 return content_types;
1293 }
1294
1295 if let Some(explicit_types) = &self.content_types {
1297 content_types.extend(explicit_types.iter().cloned());
1298 }
1299
1300 for ext in &self.ext {
1302 if let Some(uti) = extension_to_uti(&ext.0) {
1303 content_types.insert(uti.to_string());
1304 }
1305 }
1306
1307 if let Some(mime_type) = &self.mime_type {
1309 if let Some(uti) = mime_type_to_uti(mime_type) {
1310 content_types.insert(uti.to_string());
1311 }
1312 }
1313
1314 content_types
1315 }
1316}
1317
1318pub fn file_associations_plist(associations: &[FileAssociation]) -> Option<plist::Value> {
1324 use plist::{Dictionary, Value};
1325
1326 if associations.is_empty() {
1327 return None;
1328 }
1329
1330 let exported_associations = associations
1331 .iter()
1332 .filter_map(|association| {
1333 association.exported_type.as_ref().map(|exported_type| {
1334 let mut dict = Dictionary::new();
1335
1336 dict.insert(
1337 "UTTypeIdentifier".into(),
1338 exported_type.identifier.clone().into(),
1339 );
1340 if let Some(description) = &association.description {
1341 dict.insert("UTTypeDescription".into(), description.clone().into());
1342 }
1343 if let Some(conforms_to) = &exported_type.conforms_to {
1344 dict.insert(
1345 "UTTypeConformsTo".into(),
1346 Value::Array(conforms_to.iter().map(|s| s.clone().into()).collect()),
1347 );
1348 }
1349
1350 let mut specification = Dictionary::new();
1351 specification.insert(
1352 "public.filename-extension".into(),
1353 Value::Array(
1354 association
1355 .ext
1356 .iter()
1357 .map(|s| s.to_string().into())
1358 .collect(),
1359 ),
1360 );
1361 if let Some(mime_type) = &association.mime_type {
1362 specification.insert("public.mime-type".into(), mime_type.clone().into());
1363 }
1364
1365 dict.insert("UTTypeTagSpecification".into(), specification.into());
1366
1367 Value::Dictionary(dict)
1368 })
1369 })
1370 .collect::<Vec<_>>();
1371
1372 let document_types = associations
1373 .iter()
1374 .map(|association| {
1375 let mut dict = Dictionary::new();
1376
1377 if !association.ext.is_empty() {
1378 dict.insert(
1379 "CFBundleTypeExtensions".into(),
1380 Value::Array(
1381 association
1382 .ext
1383 .iter()
1384 .map(|ext| ext.to_string().into())
1385 .collect(),
1386 ),
1387 );
1388 }
1389
1390 let content_types = association.infer_content_types();
1392
1393 if !content_types.is_empty() {
1395 dict.insert(
1396 "LSItemContentTypes".into(),
1397 Value::Array(content_types.iter().map(|s| s.clone().into()).collect()),
1398 );
1399 }
1400
1401 let type_name = association
1402 .name
1403 .clone()
1404 .or_else(|| association.ext.first().map(|ext| ext.0.clone()))
1405 .unwrap_or_default();
1406 dict.insert("CFBundleTypeName".into(), type_name.into());
1407 dict.insert(
1408 "CFBundleTypeRole".into(),
1409 association.role.to_string().into(),
1410 );
1411 dict.insert("LSHandlerRank".into(), association.rank.to_string().into());
1412
1413 Value::Dictionary(dict)
1414 })
1415 .collect::<Vec<_>>();
1416
1417 if exported_associations.is_empty() && document_types.is_empty() {
1418 return None;
1419 }
1420
1421 let mut plist = Dictionary::new();
1422 if !exported_associations.is_empty() {
1423 plist.insert(
1424 "UTExportedTypeDeclarations".into(),
1425 Value::Array(exported_associations),
1426 );
1427 }
1428 if !document_types.is_empty() {
1429 plist.insert("CFBundleDocumentTypes".into(), Value::Array(document_types));
1430 }
1431
1432 Some(Value::Dictionary(plist))
1433}
1434
1435fn extension_to_uti(ext: &str) -> Option<&'static str> {
1437 match ext.to_lowercase().as_str() {
1438 "png" => Some("public.png"),
1440 "jpg" | "jpeg" => Some("public.jpeg"),
1441 "gif" => Some("com.compuserve.gif"),
1442 "bmp" => Some("com.microsoft.bmp"),
1443 "tiff" | "tif" => Some("public.tiff"),
1444 "ico" => Some("com.microsoft.ico"),
1445 "heic" | "heif" => Some("public.heif-standard-image"),
1446 "webp" => Some("org.webmproject.webp"),
1447 "svg" => Some("public.svg-image"),
1448 "mp4" => Some("public.mpeg-4"),
1450 "mov" => Some("com.apple.quicktime-movie"),
1451 "avi" => Some("public.avi"),
1452 "mkv" => Some("public.mpeg-4"),
1453 "mp3" => Some("public.mp3"),
1455 "wav" => Some("com.microsoft.waveform-audio"),
1456 "aac" => Some("public.aac-audio"),
1457 "m4a" => Some("public.mpeg-4-audio"),
1458 "pdf" => Some("com.adobe.pdf"),
1460 "txt" => Some("public.plain-text"),
1461 "rtf" => Some("public.rtf"),
1462 "html" | "htm" => Some("public.html"),
1463 "json" => Some("public.json"),
1464 "xml" => Some("public.xml"),
1465 _ => None,
1466 }
1467}
1468
1469fn mime_type_to_uti(mime_type: &str) -> Option<&'static str> {
1471 match mime_type {
1472 "image/png" => Some("public.png"),
1473 "image/jpeg" | "image/jpg" => Some("public.jpeg"),
1474 "image/gif" => Some("com.compuserve.gif"),
1475 "image/bmp" => Some("com.microsoft.bmp"),
1476 "image/tiff" => Some("public.tiff"),
1477 "image/heic" | "image/heif" => Some("public.heif-standard-image"),
1478 "image/webp" => Some("org.webmproject.webp"),
1479 "image/svg+xml" => Some("public.svg-image"),
1480 mime if mime.starts_with("image/") => Some("public.image"),
1481 "video/mp4" => Some("public.mpeg-4"),
1482 "video/quicktime" => Some("com.apple.quicktime-movie"),
1483 "video/x-msvideo" => Some("public.avi"),
1484 mime if mime.starts_with("video/") => Some("public.movie"),
1485 "audio/mpeg" | "audio/mp3" => Some("public.mp3"),
1486 "audio/wav" | "audio/wave" => Some("com.microsoft.waveform-audio"),
1487 "audio/aac" => Some("public.aac-audio"),
1488 "audio/mp4" => Some("public.mpeg-4-audio"),
1489 mime if mime.starts_with("audio/") => Some("public.audio"),
1490 "application/pdf" => Some("com.adobe.pdf"),
1491 "text/plain" => Some("public.plain-text"),
1492 "text/rtf" => Some("public.rtf"),
1493 "text/html" => Some("public.html"),
1494 "application/json" => Some("public.json"),
1495 "application/xml" | "text/xml" => Some("public.xml"),
1496 _ => None,
1497 }
1498}
1499
1500#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1502#[cfg_attr(feature = "schema", derive(JsonSchema))]
1503#[serde(rename_all = "camelCase", deny_unknown_fields)]
1504pub struct DeepLinkProtocol {
1505 #[serde(default)]
1507 pub schemes: Vec<String>,
1508 #[serde(default)]
1516 pub domains: Vec<String>,
1517 pub name: Option<String>,
1519 #[serde(default)]
1521 pub role: BundleTypeRole,
1522}
1523
1524#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1527#[cfg_attr(feature = "schema", derive(JsonSchema))]
1528#[serde(rename_all = "camelCase", deny_unknown_fields, untagged)]
1529pub enum BundleResources {
1530 List(Vec<String>),
1532 Map(HashMap<String, String>),
1534}
1535
1536impl BundleResources {
1537 pub fn push(&mut self, path: impl Into<String>) {
1539 match self {
1540 Self::List(l) => l.push(path.into()),
1541 Self::Map(l) => {
1542 let path = path.into();
1543 l.insert(path.clone(), path);
1544 }
1545 }
1546 }
1547}
1548
1549#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1551#[cfg_attr(feature = "schema", derive(JsonSchema))]
1552#[serde(rename_all = "camelCase", deny_unknown_fields, untagged)]
1553pub enum Updater {
1554 String(V1Compatible),
1556 Bool(bool),
1559}
1560
1561impl Default for Updater {
1562 fn default() -> Self {
1563 Self::Bool(false)
1564 }
1565}
1566
1567#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1569#[cfg_attr(feature = "schema", derive(JsonSchema))]
1570#[serde(rename_all = "camelCase", deny_unknown_fields)]
1571pub enum V1Compatible {
1572 V1Compatible,
1574}
1575
1576#[skip_serializing_none]
1580#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
1581#[cfg_attr(feature = "schema", derive(JsonSchema))]
1582#[serde(rename_all = "camelCase", deny_unknown_fields)]
1583pub struct BundleConfig {
1584 #[serde(default)]
1586 pub active: bool,
1587 #[serde(default)]
1589 pub targets: BundleTarget,
1590 #[serde(default)]
1591 pub create_updater_artifacts: Updater,
1593 pub publisher: Option<String>,
1598 pub homepage: Option<String>,
1603 #[serde(default)]
1605 pub icon: Vec<String>,
1606 pub resources: Option<BundleResources>,
1651 pub copyright: Option<String>,
1653 pub license: Option<String>,
1656 #[serde(alias = "license-file")]
1658 pub license_file: Option<PathBuf>,
1659 pub category: Option<String>,
1664 pub file_associations: Option<Vec<FileAssociation>>,
1666 #[serde(alias = "short-description")]
1668 pub short_description: Option<String>,
1669 #[serde(alias = "long-description")]
1671 pub long_description: Option<String>,
1672 #[serde(default, alias = "use-local-tools-dir")]
1682 pub use_local_tools_dir: bool,
1683 #[serde(alias = "external-bin")]
1695 pub external_bin: Option<Vec<String>>,
1696 #[serde(default)]
1698 pub windows: WindowsConfig,
1699 #[serde(default)]
1701 pub linux: LinuxConfig,
1702 #[serde(rename = "macOS", alias = "macos", default)]
1704 pub macos: MacConfig,
1705 #[serde(rename = "iOS", alias = "ios", default)]
1707 pub ios: IosConfig,
1708 #[serde(default)]
1710 pub android: AndroidConfig,
1711}
1712
1713#[derive(Debug, PartialEq, Eq, Serialize, Default, Clone, Copy)]
1715#[serde(rename_all = "camelCase", deny_unknown_fields)]
1716pub struct Color(pub u8, pub u8, pub u8, pub u8);
1717
1718impl From<Color> for (u8, u8, u8, u8) {
1719 fn from(value: Color) -> Self {
1720 (value.0, value.1, value.2, value.3)
1721 }
1722}
1723
1724impl From<Color> for (u8, u8, u8) {
1725 fn from(value: Color) -> Self {
1726 (value.0, value.1, value.2)
1727 }
1728}
1729
1730impl From<(u8, u8, u8, u8)> for Color {
1731 fn from(value: (u8, u8, u8, u8)) -> Self {
1732 Color(value.0, value.1, value.2, value.3)
1733 }
1734}
1735
1736impl From<(u8, u8, u8)> for Color {
1737 fn from(value: (u8, u8, u8)) -> Self {
1738 Color(value.0, value.1, value.2, 255)
1739 }
1740}
1741
1742impl From<Color> for [u8; 4] {
1743 fn from(value: Color) -> Self {
1744 [value.0, value.1, value.2, value.3]
1745 }
1746}
1747
1748impl From<Color> for [u8; 3] {
1749 fn from(value: Color) -> Self {
1750 [value.0, value.1, value.2]
1751 }
1752}
1753
1754impl From<[u8; 4]> for Color {
1755 fn from(value: [u8; 4]) -> Self {
1756 Color(value[0], value[1], value[2], value[3])
1757 }
1758}
1759
1760impl From<[u8; 3]> for Color {
1761 fn from(value: [u8; 3]) -> Self {
1762 Color(value[0], value[1], value[2], 255)
1763 }
1764}
1765
1766impl FromStr for Color {
1767 type Err = String;
1768 fn from_str(color: &str) -> Result<Self, Self::Err> {
1769 let color = color.trim();
1770 let color = color.strip_prefix('#').unwrap_or(color);
1771 if !color.bytes().all(|b| b.is_ascii_hexdigit()) {
1772 return Err("Invalid hex color, must only contain hexadecimal digits, for example: #fff, #ffffff, or #ffffffff".into());
1773 }
1774 let color = match color.len() {
1775 3 => color.chars()
1776 .flat_map(|c| std::iter::repeat_n(c, 2))
1777 .chain(std::iter::repeat_n('f', 2))
1778 .collect(),
1779 6 => format!("{color}FF"),
1780 8 => color.to_string(),
1781 _ => return Err("Invalid hex color length, must be either 3, 6 or 8, for example: #fff, #ffffff, or #ffffffff".into()),
1782 };
1783
1784 let r = u8::from_str_radix(&color[0..2], 16).map_err(|e| e.to_string())?;
1785 let g = u8::from_str_radix(&color[2..4], 16).map_err(|e| e.to_string())?;
1786 let b = u8::from_str_radix(&color[4..6], 16).map_err(|e| e.to_string())?;
1787 let a = u8::from_str_radix(&color[6..8], 16).map_err(|e| e.to_string())?;
1788
1789 Ok(Color(r, g, b, a))
1790 }
1791}
1792
1793fn default_alpha() -> u8 {
1794 255
1795}
1796
1797#[derive(Deserialize)]
1798#[cfg_attr(feature = "schema", derive(JsonSchema))]
1799#[serde(untagged)]
1800enum InnerColor {
1801 String(String),
1803 Rgb((u8, u8, u8)),
1805 Rgba((u8, u8, u8, u8)),
1807 RgbaObject {
1809 red: u8,
1810 green: u8,
1811 blue: u8,
1812 #[serde(default = "default_alpha")]
1813 alpha: u8,
1814 },
1815}
1816
1817impl<'de> Deserialize<'de> for Color {
1818 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1819 where
1820 D: Deserializer<'de>,
1821 {
1822 let color = InnerColor::deserialize(deserializer)?;
1823 let color = match color {
1824 InnerColor::String(string) => string.parse().map_err(serde::de::Error::custom)?,
1825 InnerColor::Rgb(rgb) => Color(rgb.0, rgb.1, rgb.2, 255),
1826 InnerColor::Rgba(rgb) => rgb.into(),
1827 InnerColor::RgbaObject {
1828 red,
1829 green,
1830 blue,
1831 alpha,
1832 } => Color(red, green, blue, alpha),
1833 };
1834
1835 Ok(color)
1836 }
1837}
1838
1839#[cfg(feature = "schema")]
1840impl schemars::JsonSchema for Color {
1841 fn schema_name() -> String {
1842 "Color".to_string()
1843 }
1844
1845 fn json_schema(_generator: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema {
1846 let mut schema = schemars::schema_for!(InnerColor).schema;
1847 schema.metadata = None; let any_of = schema.subschemas().any_of.as_mut().unwrap();
1851 let schemars::schema::Schema::Object(str_schema) = any_of.first_mut().unwrap() else {
1852 unreachable!()
1853 };
1854 str_schema.string().pattern = Some("^#?([A-Fa-f0-9]{3}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{8})$".into());
1855
1856 schema.into()
1857 }
1858}
1859
1860#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1862#[cfg_attr(feature = "schema", derive(JsonSchema))]
1863#[serde(rename_all = "camelCase", deny_unknown_fields)]
1864pub enum BackgroundThrottlingPolicy {
1865 Disabled,
1867 Suspend,
1869 Throttle,
1871}
1872
1873#[skip_serializing_none]
1875#[derive(Debug, PartialEq, Clone, Deserialize, Serialize, Default)]
1876#[cfg_attr(feature = "schema", derive(JsonSchema))]
1877#[serde(rename_all = "camelCase", deny_unknown_fields)]
1878pub struct WindowEffectsConfig {
1879 pub effects: Vec<WindowEffect>,
1885 pub state: Option<WindowEffectState>,
1887 pub radius: Option<f64>,
1889 pub color: Option<Color>,
1897 #[serde(default)]
1901 pub interactive: bool,
1902}
1903
1904#[derive(Debug, PartialEq, Clone, Deserialize, Serialize, Default)]
1907#[cfg_attr(feature = "schema", derive(JsonSchema))]
1908#[serde(rename_all = "camelCase", deny_unknown_fields)]
1909pub struct PreventOverflowMargin {
1910 pub width: u32,
1912 pub height: u32,
1914}
1915
1916#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
1918#[cfg_attr(feature = "schema", derive(JsonSchema))]
1919#[serde(untagged)]
1920pub enum PreventOverflowConfig {
1921 Enable(bool),
1923 Margin(PreventOverflowMargin),
1926}
1927
1928#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Default)]
1934#[cfg_attr(feature = "schema", derive(JsonSchema))]
1935#[serde(rename_all = "camelCase", deny_unknown_fields)]
1936#[non_exhaustive]
1937pub enum ScrollBarStyle {
1938 #[default]
1939 Default,
1943
1944 FluentOverlay,
1949}
1950
1951#[skip_serializing_none]
1955#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
1956#[cfg_attr(feature = "schema", derive(JsonSchema))]
1957#[serde(rename_all = "camelCase", deny_unknown_fields)]
1958pub struct WindowConfig {
1959 #[serde(default = "default_window_label")]
1961 pub label: String,
1962 #[serde(default = "default_true")]
1977 pub create: bool,
1978 #[serde(default)]
1980 pub url: WebviewUrl,
1981 #[serde(alias = "user-agent")]
1983 pub user_agent: Option<String>,
1984 #[serde(default = "default_true", alias = "drag-drop-enabled")]
1994 pub drag_drop_enabled: bool,
1995 #[serde(default)]
1997 pub center: bool,
1998 pub x: Option<f64>,
2000 pub y: Option<f64>,
2002 #[serde(default = "default_width")]
2004 pub width: f64,
2005 #[serde(default = "default_height")]
2007 pub height: f64,
2008 #[serde(alias = "min-width")]
2010 pub min_width: Option<f64>,
2011 #[serde(alias = "min-height")]
2013 pub min_height: Option<f64>,
2014 #[serde(alias = "max-width")]
2016 pub max_width: Option<f64>,
2017 #[serde(alias = "max-height")]
2019 pub max_height: Option<f64>,
2020 #[serde(alias = "prevent-overflow")]
2026 pub prevent_overflow: Option<PreventOverflowConfig>,
2027 #[serde(default = "default_true")]
2029 pub resizable: bool,
2030 #[serde(default = "default_true")]
2038 pub maximizable: bool,
2039 #[serde(default = "default_true")]
2045 pub minimizable: bool,
2046 #[serde(default = "default_true")]
2054 pub closable: bool,
2055 #[serde(default = "default_title")]
2057 pub title: String,
2058 #[serde(default)]
2060 pub fullscreen: bool,
2061 #[serde(default = "default_true")]
2063 pub focus: bool,
2064 #[serde(default = "default_true")]
2066 pub focusable: bool,
2067 #[serde(default)]
2073 pub transparent: bool,
2074 #[serde(default)]
2076 pub maximized: bool,
2077 #[serde(default = "default_true")]
2079 pub visible: bool,
2080 #[serde(default = "default_true")]
2082 pub decorations: bool,
2083 #[serde(default, alias = "always-on-bottom")]
2085 pub always_on_bottom: bool,
2086 #[serde(default, alias = "always-on-top")]
2088 pub always_on_top: bool,
2089 #[serde(default, alias = "visible-on-all-workspaces")]
2095 pub visible_on_all_workspaces: bool,
2096 #[serde(default, alias = "content-protected")]
2098 pub content_protected: bool,
2099 #[serde(default, alias = "skip-taskbar")]
2101 pub skip_taskbar: bool,
2102 pub window_classname: Option<String>,
2104 #[serde(default, alias = "no-redirection-bitmap")]
2109 pub no_redirection_bitmap: bool,
2110 pub theme: Option<crate::Theme>,
2112 #[serde(default, alias = "title-bar-style")]
2114 pub title_bar_style: TitleBarStyle,
2115 #[serde(default, alias = "traffic-light-position")]
2119 pub traffic_light_position: Option<LogicalPosition>,
2120 #[serde(default, alias = "hidden-title")]
2122 pub hidden_title: bool,
2123 #[serde(default, alias = "accept-first-mouse")]
2125 pub accept_first_mouse: bool,
2126 #[serde(default, alias = "tabbing-identifier")]
2133 pub tabbing_identifier: Option<String>,
2134 #[serde(default, alias = "additional-browser-args")]
2143 pub additional_browser_args: Option<String>,
2144 #[serde(default = "default_true")]
2154 pub shadow: bool,
2155 #[serde(default, alias = "window-effects")]
2164 pub window_effects: Option<WindowEffectsConfig>,
2165 #[serde(default)]
2171 pub incognito: bool,
2172 pub parent: Option<String>,
2184 #[serde(alias = "proxy-url")]
2192 pub proxy_url: Option<Url>,
2193 #[serde(default, alias = "zoom-hotkeys-enabled")]
2203 pub zoom_hotkeys_enabled: bool,
2204 #[serde(default, alias = "browser-extensions-enabled")]
2211 pub browser_extensions_enabled: bool,
2212
2213 #[serde(default, alias = "use-https-scheme")]
2223 pub use_https_scheme: bool,
2224 pub devtools: Option<bool>,
2234
2235 #[serde(alias = "background-color")]
2243 pub background_color: Option<Color>,
2244
2245 #[serde(default, alias = "background-throttling")]
2260 pub background_throttling: Option<BackgroundThrottlingPolicy>,
2261 #[serde(default, alias = "javascript-disabled")]
2263 pub javascript_disabled: bool,
2264 #[serde(default = "default_true", alias = "allow-link-preview")]
2267 pub allow_link_preview: bool,
2268 #[serde(
2273 default,
2274 alias = "disable-input-accessory-view",
2275 alias = "disable_input_accessory_view"
2276 )]
2277 pub disable_input_accessory_view: bool,
2278 #[serde(default, alias = "data-directory")]
2293 pub data_directory: Option<PathBuf>,
2294 #[serde(default, alias = "data-store-identifier")]
2306 pub data_store_identifier: Option<[u8; 16]>,
2307
2308 #[serde(default, alias = "scroll-bar-style")]
2321 pub scroll_bar_style: ScrollBarStyle,
2322
2323 #[serde(default, alias = "limit-navigations-to-app-bound-domains")]
2370 pub limit_navigations_to_app_bound_domains: bool,
2371 #[serde(default, alias = "activity-name")]
2373 pub activity_name: Option<String>,
2374 #[serde(default, alias = "created-by-activity-name")]
2378 pub created_by_activity_name: Option<String>,
2379
2380 #[serde(default, alias = "requested-by-scene-identifier")]
2385 pub requested_by_scene_identifier: Option<String>,
2386 #[serde(default = "default_true", alias = "general-autofill-enabled")]
2404 pub general_autofill_enabled: bool,
2405}
2406
2407impl Default for WindowConfig {
2408 fn default() -> Self {
2409 Self {
2410 label: default_window_label(),
2411 url: WebviewUrl::default(),
2412 create: true,
2413 user_agent: None,
2414 drag_drop_enabled: true,
2415 center: false,
2416 x: None,
2417 y: None,
2418 width: default_width(),
2419 height: default_height(),
2420 min_width: None,
2421 min_height: None,
2422 max_width: None,
2423 max_height: None,
2424 prevent_overflow: None,
2425 resizable: true,
2426 maximizable: true,
2427 minimizable: true,
2428 closable: true,
2429 title: default_title(),
2430 fullscreen: false,
2431 focus: true,
2432 focusable: true,
2433 transparent: false,
2434 maximized: false,
2435 visible: true,
2436 decorations: true,
2437 always_on_bottom: false,
2438 always_on_top: false,
2439 visible_on_all_workspaces: false,
2440 content_protected: false,
2441 skip_taskbar: false,
2442 window_classname: None,
2443 no_redirection_bitmap: false,
2444 theme: None,
2445 title_bar_style: Default::default(),
2446 traffic_light_position: None,
2447 hidden_title: false,
2448 accept_first_mouse: false,
2449 tabbing_identifier: None,
2450 additional_browser_args: None,
2451 shadow: true,
2452 window_effects: None,
2453 incognito: false,
2454 parent: None,
2455 proxy_url: None,
2456 zoom_hotkeys_enabled: false,
2457 browser_extensions_enabled: false,
2458 use_https_scheme: false,
2459 devtools: None,
2460 background_color: None,
2461 background_throttling: None,
2462 javascript_disabled: false,
2463 allow_link_preview: true,
2464 disable_input_accessory_view: false,
2465 data_directory: None,
2466 data_store_identifier: None,
2467 scroll_bar_style: ScrollBarStyle::Default,
2468 limit_navigations_to_app_bound_domains: false,
2469 activity_name: None,
2470 created_by_activity_name: None,
2471 requested_by_scene_identifier: None,
2472 general_autofill_enabled: true,
2473 }
2474 }
2475}
2476
2477fn default_window_label() -> String {
2478 "main".to_string()
2479}
2480
2481fn default_width() -> f64 {
2482 800.
2483}
2484
2485fn default_height() -> f64 {
2486 600.
2487}
2488
2489fn default_title() -> String {
2490 "Tauri App".to_string()
2491}
2492
2493#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
2496#[cfg_attr(feature = "schema", derive(JsonSchema))]
2497#[serde(rename_all = "camelCase", untagged)]
2498pub enum CspDirectiveSources {
2499 Inline(String),
2501 List(Vec<String>),
2503}
2504
2505impl Default for CspDirectiveSources {
2506 fn default() -> Self {
2507 Self::List(Vec::new())
2508 }
2509}
2510
2511impl From<CspDirectiveSources> for Vec<String> {
2512 fn from(sources: CspDirectiveSources) -> Self {
2513 match sources {
2514 CspDirectiveSources::Inline(source) => source.split(' ').map(|s| s.to_string()).collect(),
2515 CspDirectiveSources::List(l) => l,
2516 }
2517 }
2518}
2519
2520impl CspDirectiveSources {
2521 pub fn contains(&self, source: &str) -> bool {
2523 match self {
2524 Self::Inline(s) => s.contains(&format!("{source} ")) || s.contains(&format!(" {source}")),
2525 Self::List(l) => l.contains(&source.into()),
2526 }
2527 }
2528
2529 pub fn push<S: AsRef<str>>(&mut self, source: S) {
2531 match self {
2532 Self::Inline(s) => {
2533 s.push(' ');
2534 s.push_str(source.as_ref());
2535 }
2536 Self::List(l) => {
2537 l.push(source.as_ref().to_string());
2538 }
2539 }
2540 }
2541
2542 pub fn extend(&mut self, sources: Vec<String>) {
2544 for s in sources {
2545 self.push(s);
2546 }
2547 }
2548}
2549
2550#[derive(Debug, PartialEq, Eq, Clone, Deserialize)]
2553#[cfg_attr(feature = "schema", derive(JsonSchema))]
2554#[serde(rename_all = "camelCase", untagged)]
2555pub enum Csp {
2556 Policy(String),
2558 DirectiveMap(HashMap<String, CspDirectiveSources>),
2560}
2561
2562impl Serialize for Csp {
2563 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2564 where
2565 S: Serializer,
2566 {
2567 match self {
2568 Self::Policy(policy) => serializer.serialize_str(policy),
2569 Self::DirectiveMap(map) => {
2570 let btree_map: BTreeMap<_, _> = map.iter().collect();
2574 btree_map.serialize(serializer)
2575 }
2576 }
2577 }
2578}
2579
2580impl From<HashMap<String, CspDirectiveSources>> for Csp {
2581 fn from(map: HashMap<String, CspDirectiveSources>) -> Self {
2582 Self::DirectiveMap(map)
2583 }
2584}
2585
2586impl From<Csp> for HashMap<String, CspDirectiveSources> {
2587 fn from(csp: Csp) -> Self {
2588 match csp {
2589 Csp::Policy(policy) => {
2590 let mut map = HashMap::new();
2591 for directive in policy.split(';') {
2592 let mut tokens = directive.trim().split(' ');
2593 if let Some(directive) = tokens.next() {
2594 let sources = tokens.map(|s| s.to_string()).collect::<Vec<String>>();
2595 map.insert(directive.to_string(), CspDirectiveSources::List(sources));
2596 }
2597 }
2598 map
2599 }
2600 Csp::DirectiveMap(m) => m,
2601 }
2602 }
2603}
2604
2605impl Display for Csp {
2606 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2607 match self {
2608 Self::Policy(s) => write!(f, "{s}"),
2609 Self::DirectiveMap(m) => {
2610 let len = m.len();
2611 let mut i = 0;
2612 for (directive, sources) in m {
2613 let sources: Vec<String> = sources.clone().into();
2614 write!(f, "{} {}", directive, sources.join(" "))?;
2615 i += 1;
2616 if i != len {
2617 write!(f, "; ")?;
2618 }
2619 }
2620 Ok(())
2621 }
2622 }
2623 }
2624}
2625
2626#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
2628#[serde(untagged)]
2629#[cfg_attr(feature = "schema", derive(JsonSchema))]
2630pub enum DisabledCspModificationKind {
2631 Flag(bool),
2634 List(Vec<String>),
2636}
2637
2638impl DisabledCspModificationKind {
2639 pub fn can_modify(&self, directive: &str) -> bool {
2641 match self {
2642 Self::Flag(f) => !f,
2643 Self::List(l) => !l.contains(&directive.into()),
2644 }
2645 }
2646}
2647
2648impl Default for DisabledCspModificationKind {
2649 fn default() -> Self {
2650 Self::Flag(false)
2651 }
2652}
2653
2654#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
2663#[serde(untagged)]
2664#[cfg_attr(feature = "schema", derive(JsonSchema))]
2665pub enum FsScope {
2666 AllowedPaths(Vec<PathBuf>),
2668 #[serde(rename_all = "camelCase")]
2670 Scope {
2671 #[serde(default)]
2673 allow: Vec<PathBuf>,
2674 #[serde(default)]
2677 deny: Vec<PathBuf>,
2678 #[serde(alias = "require-literal-leading-dot")]
2687 require_literal_leading_dot: Option<bool>,
2688 },
2689}
2690
2691impl Default for FsScope {
2692 fn default() -> Self {
2693 Self::AllowedPaths(Vec::new())
2694 }
2695}
2696
2697impl FsScope {
2698 pub fn allowed_paths(&self) -> &Vec<PathBuf> {
2700 match self {
2701 Self::AllowedPaths(p) => p,
2702 Self::Scope { allow, .. } => allow,
2703 }
2704 }
2705
2706 pub fn forbidden_paths(&self) -> Option<&Vec<PathBuf>> {
2708 match self {
2709 Self::AllowedPaths(_) => None,
2710 Self::Scope { deny, .. } => Some(deny),
2711 }
2712 }
2713}
2714
2715#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
2719#[cfg_attr(feature = "schema", derive(JsonSchema))]
2720#[serde(rename_all = "camelCase", deny_unknown_fields)]
2721pub struct AssetProtocolConfig {
2722 #[serde(default)]
2724 pub scope: FsScope,
2725 #[serde(default)]
2727 pub enable: bool,
2728}
2729
2730#[derive(Debug, PartialEq, Eq, Clone, Deserialize)]
2734#[cfg_attr(feature = "schema", derive(JsonSchema))]
2735#[serde(rename_all = "camelCase", untagged)]
2736pub enum HeaderSource {
2737 Inline(String),
2739 List(Vec<String>),
2741 Map(HashMap<String, String>),
2743}
2744
2745impl Serialize for HeaderSource {
2746 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2747 where
2748 S: Serializer,
2749 {
2750 match self {
2751 Self::Inline(s) => serializer.serialize_str(s),
2752 Self::List(l) => l.serialize(serializer),
2753 Self::Map(m) => {
2754 let btree_map: BTreeMap<_, _> = m.iter().collect();
2758 btree_map.serialize(serializer)
2759 }
2760 }
2761 }
2762}
2763
2764impl Display for HeaderSource {
2765 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2766 match self {
2767 Self::Inline(s) => write!(f, "{s}"),
2768 Self::List(l) => write!(f, "{}", l.join(", ")),
2769 Self::Map(m) => {
2770 let map: BTreeMap<_, _> = m.iter().collect();
2774 let len = map.len();
2775 for (i, (key, value)) in map.into_iter().enumerate() {
2776 write!(f, "{key} {value}")?;
2777 if i + 1 != len {
2778 write!(f, "; ")?;
2779 }
2780 }
2781 Ok(())
2782 }
2783 }
2784 }
2785}
2786
2787pub trait HeaderAddition {
2791 fn add_configured_headers(self, headers: Option<&HeaderConfig>) -> http::response::Builder;
2793}
2794
2795impl HeaderAddition for Builder {
2796 fn add_configured_headers(mut self, headers: Option<&HeaderConfig>) -> http::response::Builder {
2800 if let Some(headers) = headers {
2801 if let Some(value) = &headers.access_control_allow_credentials {
2803 self = self.header("Access-Control-Allow-Credentials", value.to_string());
2804 };
2805
2806 if let Some(value) = &headers.access_control_allow_headers {
2808 self = self.header("Access-Control-Allow-Headers", value.to_string());
2809 };
2810
2811 if let Some(value) = &headers.access_control_allow_methods {
2813 self = self.header("Access-Control-Allow-Methods", value.to_string());
2814 };
2815
2816 if let Some(value) = &headers.access_control_expose_headers {
2818 self = self.header("Access-Control-Expose-Headers", value.to_string());
2819 };
2820
2821 if let Some(value) = &headers.access_control_max_age {
2823 self = self.header("Access-Control-Max-Age", value.to_string());
2824 };
2825
2826 if let Some(value) = &headers.cross_origin_embedder_policy {
2828 self = self.header("Cross-Origin-Embedder-Policy", value.to_string());
2829 };
2830
2831 if let Some(value) = &headers.cross_origin_opener_policy {
2833 self = self.header("Cross-Origin-Opener-Policy", value.to_string());
2834 };
2835
2836 if let Some(value) = &headers.cross_origin_resource_policy {
2838 self = self.header("Cross-Origin-Resource-Policy", value.to_string());
2839 };
2840
2841 if let Some(value) = &headers.permissions_policy {
2843 self = self.header("Permissions-Policy", value.to_string());
2844 };
2845
2846 if let Some(value) = &headers.service_worker_allowed {
2847 self = self.header("Service-Worker-Allowed", value.to_string());
2848 }
2849
2850 if let Some(value) = &headers.timing_allow_origin {
2852 self = self.header("Timing-Allow-Origin", value.to_string());
2853 };
2854
2855 if let Some(value) = &headers.x_content_type_options {
2857 self = self.header("X-Content-Type-Options", value.to_string());
2858 };
2859
2860 if let Some(value) = &headers.tauri_custom_header {
2862 self = self.header("Tauri-Custom-Header", value.to_string());
2864 };
2865 }
2866 self
2867 }
2868}
2869
2870#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
2922#[cfg_attr(feature = "schema", derive(JsonSchema))]
2923#[serde(deny_unknown_fields)]
2924pub struct HeaderConfig {
2925 #[serde(rename = "Access-Control-Allow-Credentials")]
2930 pub access_control_allow_credentials: Option<HeaderSource>,
2931 #[serde(rename = "Access-Control-Allow-Headers")]
2939 pub access_control_allow_headers: Option<HeaderSource>,
2940 #[serde(rename = "Access-Control-Allow-Methods")]
2945 pub access_control_allow_methods: Option<HeaderSource>,
2946 #[serde(rename = "Access-Control-Expose-Headers")]
2952 pub access_control_expose_headers: Option<HeaderSource>,
2953 #[serde(rename = "Access-Control-Max-Age")]
2960 pub access_control_max_age: Option<HeaderSource>,
2961 #[serde(rename = "Cross-Origin-Embedder-Policy")]
2966 pub cross_origin_embedder_policy: Option<HeaderSource>,
2967 #[serde(rename = "Cross-Origin-Opener-Policy")]
2974 pub cross_origin_opener_policy: Option<HeaderSource>,
2975 #[serde(rename = "Cross-Origin-Resource-Policy")]
2980 pub cross_origin_resource_policy: Option<HeaderSource>,
2981 #[serde(rename = "Permissions-Policy")]
2986 pub permissions_policy: Option<HeaderSource>,
2987 #[serde(rename = "Service-Worker-Allowed")]
2997 pub service_worker_allowed: Option<HeaderSource>,
2998 #[serde(rename = "Timing-Allow-Origin")]
3004 pub timing_allow_origin: Option<HeaderSource>,
3005 #[serde(rename = "X-Content-Type-Options")]
3012 pub x_content_type_options: Option<HeaderSource>,
3013 #[serde(rename = "Tauri-Custom-Header")]
3018 pub tauri_custom_header: Option<HeaderSource>,
3019}
3020
3021impl HeaderConfig {
3022 pub fn new() -> Self {
3024 HeaderConfig {
3025 access_control_allow_credentials: None,
3026 access_control_allow_methods: None,
3027 access_control_allow_headers: None,
3028 access_control_expose_headers: None,
3029 access_control_max_age: None,
3030 cross_origin_embedder_policy: None,
3031 cross_origin_opener_policy: None,
3032 cross_origin_resource_policy: None,
3033 permissions_policy: None,
3034 service_worker_allowed: None,
3035 timing_allow_origin: None,
3036 x_content_type_options: None,
3037 tauri_custom_header: None,
3038 }
3039 }
3040}
3041
3042#[skip_serializing_none]
3046#[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
3047#[cfg_attr(feature = "schema", derive(JsonSchema))]
3048#[serde(rename_all = "camelCase", deny_unknown_fields)]
3049pub struct SecurityConfig {
3050 pub csp: Option<Csp>,
3056 #[serde(alias = "dev-csp")]
3061 pub dev_csp: Option<Csp>,
3062 #[serde(default, alias = "freeze-prototype")]
3075 pub freeze_prototype: bool,
3076 #[serde(default, alias = "dangerous-disable-asset-csp-modification")]
3089 pub dangerous_disable_asset_csp_modification: DisabledCspModificationKind,
3090 #[serde(default, alias = "asset-protocol")]
3092 pub asset_protocol: AssetProtocolConfig,
3093 #[serde(default)]
3105 pub pattern: PatternKind,
3106 #[serde(default)]
3131 pub capabilities: Vec<CapabilityEntry>,
3132 #[serde(default)]
3135 pub headers: Option<HeaderConfig>,
3136}
3137
3138#[derive(Debug, Clone, PartialEq, Serialize)]
3140#[cfg_attr(feature = "schema", derive(JsonSchema))]
3141#[serde(untagged)]
3142pub enum CapabilityEntry {
3143 Inlined(Capability),
3145 Reference(String),
3147}
3148
3149impl<'de> Deserialize<'de> for CapabilityEntry {
3150 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3151 where
3152 D: Deserializer<'de>,
3153 {
3154 UntaggedEnumVisitor::new()
3155 .string(|string| Ok(Self::Reference(string.to_owned())))
3156 .map(|map| map.deserialize::<Capability>().map(Self::Inlined))
3157 .deserialize(deserializer)
3158 }
3159}
3160
3161#[skip_serializing_none]
3163#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize, Default)]
3164#[serde(rename_all = "lowercase", tag = "use", content = "options")]
3165#[cfg_attr(feature = "schema", derive(JsonSchema))]
3166pub enum PatternKind {
3167 #[default]
3169 Brownfield,
3170 Isolation {
3172 dir: PathBuf,
3174 },
3175}
3176
3177const APP_DIRECTORIES_OVERRIDE_VARIABLES: &[&str] = &[
3183 "$AUDIO",
3184 "$CACHE",
3185 "$CONFIG",
3186 "$DATA",
3187 "$LOCALDATA",
3188 "$DESKTOP",
3189 "$DOCUMENT",
3190 "$DOWNLOAD",
3191 "$HOME",
3192 "$PICTURE",
3193 "$PUBLIC",
3194 "$TEMP",
3195 "$VIDEO",
3196];
3197
3198fn validate_app_directory_override(path: &Path) -> Result<(), String> {
3200 let mut components = path.components();
3201 let first = components.next();
3202
3203 if let Some(Component::Normal(first)) = first {
3204 if let Some(variable) = first.to_str().filter(|s| s.starts_with('$')) {
3205 if !APP_DIRECTORIES_OVERRIDE_VARIABLES.contains(&variable) {
3206 return Err(format!(
3207 "`{}` starts with the unsupported base directory variable `{variable}`, expected one of {}",
3208 path.display(),
3209 APP_DIRECTORIES_OVERRIDE_VARIABLES
3210 .iter()
3211 .map(|v| format!("`{v}`"))
3212 .collect::<Vec<_>>()
3213 .join(", ")
3214 ));
3215 }
3216 return Ok(());
3217 }
3218 }
3219
3220 if !path.is_absolute() && (path.has_root() || matches!(first, Some(Component::Prefix(_)))) {
3223 return Err(format!(
3224 "`{}` must be an absolute path, a path relative to the executable or a path starting with a base directory variable",
3225 path.display()
3226 ));
3227 }
3228
3229 Ok(())
3230}
3231
3232#[derive(Debug, PartialEq, Eq, Clone, Serialize)]
3236#[cfg_attr(feature = "schema", derive(JsonSchema))]
3237#[serde(untagged)]
3238pub enum AppDirectoriesOverride {
3239 Root(PathBuf),
3244 Directories(AppDirectoryOverrides),
3248}
3249
3250impl AppDirectoriesOverride {
3251 fn paths(&self) -> impl Iterator<Item = &PathBuf> {
3253 match self {
3254 Self::Root(root) => vec![Some(root)],
3255 Self::Directories(directories) => vec![
3256 directories.config.as_ref(),
3257 directories.data.as_ref(),
3258 directories.local_data.as_ref(),
3259 directories.cache.as_ref(),
3260 directories.log.as_ref(),
3261 ],
3262 }
3263 .into_iter()
3264 .flatten()
3265 }
3266}
3267
3268impl<'de> Deserialize<'de> for AppDirectoriesOverride {
3269 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3270 where
3271 D: Deserializer<'de>,
3272 {
3273 let value = UntaggedEnumVisitor::new()
3274 .string(|path| Ok(Self::Root(PathBuf::from(path))))
3275 .map(|map| {
3276 map
3277 .deserialize::<AppDirectoryOverrides>()
3278 .map(Self::Directories)
3279 })
3280 .deserialize(deserializer)?;
3281
3282 for path in value.paths() {
3283 validate_app_directory_override(path).map_err(DeError::custom)?;
3284 }
3285
3286 Ok(value)
3287 }
3288}
3289
3290#[skip_serializing_none]
3292#[derive(Debug, Default, PartialEq, Eq, Clone, Serialize, Deserialize)]
3293#[cfg_attr(feature = "schema", derive(JsonSchema))]
3294#[serde(rename_all = "camelCase", deny_unknown_fields)]
3295pub struct AppDirectoryOverrides {
3296 pub config: Option<PathBuf>,
3298 pub data: Option<PathBuf>,
3300 #[serde(alias = "local-data", alias = "local_data")]
3304 pub local_data: Option<PathBuf>,
3305 pub cache: Option<PathBuf>,
3307 pub log: Option<PathBuf>,
3309}
3310
3311#[skip_serializing_none]
3315#[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
3316#[cfg_attr(feature = "schema", derive(JsonSchema))]
3317#[serde(rename_all = "camelCase", deny_unknown_fields)]
3318pub struct AppConfig {
3319 #[serde(default)]
3374 pub windows: Vec<WindowConfig>,
3375 #[serde(default)]
3377 pub security: SecurityConfig,
3378 #[serde(alias = "tray-icon")]
3380 pub tray_icon: Option<TrayIconConfig>,
3381 #[serde(rename = "macOSPrivateApi", alias = "macos-private-api", default)]
3385 pub macos_private_api: bool,
3386 #[serde(default, alias = "with-global-tauri")]
3388 pub with_global_tauri: bool,
3389 #[serde(rename = "enableGTKAppId", alias = "enable-gtk-app-id", default)]
3405 pub enable_gtk_app_id: bool,
3406 #[serde(alias = "app-directories-override")]
3518 pub app_directories_override: Option<AppDirectoriesOverride>,
3519}
3520
3521impl AppConfig {
3522 pub fn all_features() -> Vec<&'static str> {
3524 vec![
3525 "tray-icon",
3526 "macos-private-api",
3528 "protocol-asset",
3529 "isolation",
3530 ]
3531 }
3532
3533 pub fn features(&self) -> Vec<&str> {
3535 let mut features = Vec::new();
3536 if self.tray_icon.is_some() {
3537 features.push("tray-icon");
3538 }
3539 if self.macos_private_api {
3541 features.push("macos-private-api");
3542 }
3543 if self.security.asset_protocol.enable {
3544 features.push("protocol-asset");
3545 }
3546
3547 if let PatternKind::Isolation { .. } = self.security.pattern {
3548 features.push("isolation");
3549 }
3550
3551 features.sort_unstable();
3552 features
3553 }
3554}
3555
3556#[skip_serializing_none]
3560#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
3561#[cfg_attr(feature = "schema", derive(JsonSchema))]
3562#[serde(rename_all = "camelCase", deny_unknown_fields)]
3563pub struct TrayIconConfig {
3564 pub id: Option<String>,
3566 #[serde(alias = "icon-path")]
3572 pub icon_path: PathBuf,
3573 #[serde(default, alias = "icon-as-template")]
3575 pub icon_as_template: bool,
3576 #[serde(default = "default_true", alias = "menu-on-left-click")]
3584 #[deprecated(
3585 since = "2.2.0",
3586 note = "No longer works, use `show_menu_on_left_click` instead."
3587 )]
3588 pub menu_on_left_click: bool,
3589 #[serde(default = "default_true", alias = "show-menu-on-left-click")]
3595 pub show_menu_on_left_click: bool,
3596 pub title: Option<String>,
3598 pub tooltip: Option<String>,
3600}
3601
3602#[skip_serializing_none]
3604#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
3605#[cfg_attr(feature = "schema", derive(JsonSchema))]
3606#[serde(rename_all = "camelCase", deny_unknown_fields)]
3607pub struct IosConfig {
3608 pub template: Option<PathBuf>,
3612 pub frameworks: Option<Vec<String>>,
3616 #[serde(alias = "development-team")]
3619 pub development_team: Option<String>,
3620 #[serde(alias = "bundle-version")]
3624 pub bundle_version: Option<String>,
3625 #[serde(
3629 alias = "minimum-system-version",
3630 default = "ios_minimum_system_version"
3631 )]
3632 pub minimum_system_version: String,
3633 #[serde(alias = "info-plist")]
3637 pub info_plist: Option<PathBuf>,
3638}
3639
3640impl Default for IosConfig {
3641 fn default() -> Self {
3642 Self {
3643 template: None,
3644 frameworks: None,
3645 development_team: None,
3646 bundle_version: None,
3647 minimum_system_version: ios_minimum_system_version(),
3648 info_plist: None,
3649 }
3650 }
3651}
3652
3653#[skip_serializing_none]
3655#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
3656#[cfg_attr(feature = "schema", derive(JsonSchema))]
3657#[serde(rename_all = "camelCase", deny_unknown_fields)]
3658pub struct AndroidConfig {
3659 #[serde(alias = "min-sdk-version", default = "default_min_sdk_version")]
3662 pub min_sdk_version: u32,
3663
3664 #[serde(alias = "version-code")]
3670 #[cfg_attr(feature = "schema", validate(range(min = 1, max = 2_100_000_000)))]
3671 pub version_code: Option<u32>,
3672
3673 #[serde(alias = "auto-increment-version-code", default)]
3681 pub auto_increment_version_code: bool,
3682
3683 #[serde(alias = "debug-application-id-suffix")]
3687 pub debug_application_id_suffix: Option<String>,
3688}
3689
3690impl Default for AndroidConfig {
3691 fn default() -> Self {
3692 Self {
3693 min_sdk_version: default_min_sdk_version(),
3694 version_code: None,
3695 auto_increment_version_code: false,
3696 debug_application_id_suffix: None,
3697 }
3698 }
3699}
3700
3701fn default_min_sdk_version() -> u32 {
3702 24
3703}
3704
3705#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
3707#[cfg_attr(feature = "schema", derive(JsonSchema))]
3708#[serde(untagged, deny_unknown_fields)]
3709#[non_exhaustive]
3710pub enum FrontendDist {
3711 Url(Url),
3713 Directory(PathBuf),
3715 Files(Vec<PathBuf>),
3717}
3718
3719impl std::fmt::Display for FrontendDist {
3720 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3721 match self {
3722 Self::Url(url) => write!(f, "{url}"),
3723 Self::Directory(p) => write!(f, "{}", p.display()),
3724 Self::Files(files) => write!(f, "{}", serde_json::to_string(files).unwrap()),
3725 }
3726 }
3727}
3728
3729#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
3731#[cfg_attr(feature = "schema", derive(JsonSchema))]
3732#[serde(rename_all = "camelCase", untagged)]
3733pub enum BeforeDevCommand {
3734 Script(String),
3736 ScriptWithOptions {
3738 script: String,
3740 cwd: Option<String>,
3742 #[serde(default)]
3744 wait: bool,
3745 },
3746}
3747
3748#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
3750#[cfg_attr(feature = "schema", derive(JsonSchema))]
3751#[serde(rename_all = "camelCase", untagged)]
3752pub enum HookCommand {
3753 Script(String),
3755 ScriptWithOptions {
3757 script: String,
3759 cwd: Option<String>,
3761 },
3762}
3763
3764#[skip_serializing_none]
3766#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3767#[cfg_attr(feature = "schema", derive(JsonSchema))]
3768#[serde(untagged)]
3769pub enum RunnerConfig {
3770 String(String),
3772 Object {
3774 cmd: String,
3776 cwd: Option<String>,
3778 args: Option<Vec<String>>,
3780 },
3781}
3782
3783impl Default for RunnerConfig {
3784 fn default() -> Self {
3785 RunnerConfig::String("cargo".to_string())
3786 }
3787}
3788
3789impl RunnerConfig {
3790 pub fn cmd(&self) -> &str {
3792 match self {
3793 RunnerConfig::String(cmd) => cmd,
3794 RunnerConfig::Object { cmd, .. } => cmd,
3795 }
3796 }
3797
3798 pub fn cwd(&self) -> Option<&str> {
3800 match self {
3801 RunnerConfig::String(_) => None,
3802 RunnerConfig::Object { cwd, .. } => cwd.as_deref(),
3803 }
3804 }
3805
3806 pub fn args(&self) -> Option<&[String]> {
3808 match self {
3809 RunnerConfig::String(_) => None,
3810 RunnerConfig::Object { args, .. } => args.as_deref(),
3811 }
3812 }
3813}
3814
3815impl std::str::FromStr for RunnerConfig {
3816 type Err = std::convert::Infallible;
3817
3818 fn from_str(s: &str) -> Result<Self, Self::Err> {
3819 Ok(RunnerConfig::String(s.to_string()))
3820 }
3821}
3822
3823impl From<&str> for RunnerConfig {
3824 fn from(s: &str) -> Self {
3825 RunnerConfig::String(s.to_string())
3826 }
3827}
3828
3829impl From<String> for RunnerConfig {
3830 fn from(s: String) -> Self {
3831 RunnerConfig::String(s)
3832 }
3833}
3834
3835#[skip_serializing_none]
3839#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize, Default)]
3840#[cfg_attr(feature = "schema", derive(JsonSchema))]
3841#[serde(rename_all = "camelCase", deny_unknown_fields)]
3842pub struct BuildConfig {
3843 pub runner: Option<RunnerConfig>,
3845 #[serde(alias = "dev-url")]
3853 pub dev_url: Option<Url>,
3854 #[serde(alias = "frontend-dist")]
3868 pub frontend_dist: Option<FrontendDist>,
3869 #[serde(alias = "before-dev-command")]
3876 pub before_dev_command: Option<BeforeDevCommand>,
3877 #[serde(alias = "before-build-command")]
3884 pub before_build_command: Option<HookCommand>,
3885 #[serde(alias = "before-bundle-command")]
3892 pub before_bundle_command: Option<HookCommand>,
3893 pub features: Option<Vec<String>>,
3895 #[serde(alias = "remove-unused-commands", default)]
3903 pub remove_unused_commands: bool,
3904 #[serde(
3906 alias = "additional-watch-folders",
3907 alias = "additional-watch-directories",
3908 default
3909 )]
3910 pub additional_watch_folders: Vec<PathBuf>,
3911 #[serde(default)]
3913 pub windows: WindowsBuildConfig,
3914}
3915
3916#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
3918#[cfg_attr(feature = "schema", derive(JsonSchema))]
3919#[serde(rename_all = "camelCase", deny_unknown_fields)]
3920pub struct WindowsBuildConfig {
3921 #[serde(
3923 default = "default_true",
3924 rename = "staticVCRuntime",
3925 alias = "static-vc-runtime",
3926 alias = "staticVcRuntime"
3927 )]
3928 pub static_vc_runtime: bool,
3929}
3930
3931impl Default for WindowsBuildConfig {
3932 fn default() -> Self {
3933 Self {
3934 static_vc_runtime: true,
3935 }
3936 }
3937}
3938
3939#[derive(Debug, PartialEq, Eq)]
3940struct PackageVersion(String);
3941
3942impl<'d> serde::Deserialize<'d> for PackageVersion {
3943 fn deserialize<D: Deserializer<'d>>(deserializer: D) -> Result<Self, D::Error> {
3944 struct PackageVersionVisitor;
3945
3946 impl Visitor<'_> for PackageVersionVisitor {
3947 type Value = PackageVersion;
3948
3949 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3950 write!(
3951 formatter,
3952 "a semver string or a path to a package.json file"
3953 )
3954 }
3955
3956 fn visit_str<E: DeError>(self, value: &str) -> Result<PackageVersion, E> {
3957 let path = PathBuf::from(value);
3958 if path.exists() {
3959 let json_str = read_to_string(&path)
3960 .map_err(|e| DeError::custom(format!("failed to read version JSON file: {e}")))?;
3961 let package_json: serde_json::Value = serde_json::from_str(&json_str)
3962 .map_err(|e| DeError::custom(format!("failed to read version JSON file: {e}")))?;
3963 if let Some(obj) = package_json.as_object() {
3964 let version = obj
3965 .get("version")
3966 .ok_or_else(|| DeError::custom("JSON must contain a `version` field"))?
3967 .as_str()
3968 .ok_or_else(|| {
3969 DeError::custom(format!("`{} > version` must be a string", path.display()))
3970 })?;
3971 Ok(PackageVersion(
3972 Version::from_str(version)
3973 .map_err(|_| {
3974 DeError::custom("`tauri.conf.json > version` must be a semver string")
3975 })?
3976 .to_string(),
3977 ))
3978 } else {
3979 Err(DeError::custom(
3980 "`tauri.conf.json > version` value is not a path to a JSON object",
3981 ))
3982 }
3983 } else {
3984 Ok(PackageVersion(
3985 Version::from_str(value)
3986 .map_err(|_| DeError::custom("`tauri.conf.json > version` must be a semver string"))?
3987 .to_string(),
3988 ))
3989 }
3990 }
3991 }
3992
3993 deserializer.deserialize_string(PackageVersionVisitor {})
3994 }
3995}
3996
3997fn version_deserializer<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
3998where
3999 D: Deserializer<'de>,
4000{
4001 Option::<PackageVersion>::deserialize(deserializer).map(|v| v.map(|v| v.0))
4002}
4003
4004#[skip_serializing_none]
4070#[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
4071#[cfg_attr(feature = "schema", derive(JsonSchema))]
4072#[serde(rename_all = "camelCase", deny_unknown_fields)]
4073pub struct Config {
4074 #[serde(rename = "$schema")]
4076 pub schema: Option<String>,
4077 #[serde(alias = "product-name")]
4095 #[cfg_attr(feature = "schema", validate(regex(pattern = "^[^/\\:*?\"<>|]+$")))]
4096 pub product_name: Option<String>,
4097 #[serde(alias = "main-binary-name")]
4111 pub main_binary_name: Option<String>,
4112 #[serde(deserialize_with = "version_deserializer", default)]
4128 pub version: Option<String>,
4129 pub identifier: String,
4137 #[serde(default)]
4139 pub app: AppConfig,
4140 #[serde(default)]
4142 pub build: BuildConfig,
4143 #[serde(default)]
4145 pub bundle: BundleConfig,
4146 #[serde(default)]
4148 pub plugins: PluginConfig,
4149}
4150
4151#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
4155#[cfg_attr(feature = "schema", derive(JsonSchema))]
4156pub struct PluginConfig(pub HashMap<String, JsonValue>);
4157
4158impl Serialize for PluginConfig {
4159 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
4160 where
4161 S: Serializer,
4162 {
4163 let btree_map: BTreeMap<_, _> = self.0.iter().collect();
4167 btree_map.serialize(serializer)
4168 }
4169}
4170
4171#[cfg(any(feature = "build", feature = "build-2"))]
4177mod build {
4178 use super::*;
4179 use crate::{literal_struct, tokens::*};
4180 use proc_macro2::TokenStream;
4181 use quote::{ToTokens, TokenStreamExt, quote};
4182 use std::convert::identity;
4183
4184 impl ToTokens for WebviewUrl {
4185 fn to_tokens(&self, tokens: &mut TokenStream) {
4186 let prefix = quote! { ::tauri::utils::config::WebviewUrl };
4187
4188 tokens.append_all(match self {
4189 Self::App(path) => {
4190 let path = path_buf_lit(path);
4191 quote! { #prefix::App(#path) }
4192 }
4193 Self::External(url) => {
4194 let url = url_lit(url);
4195 quote! { #prefix::External(#url) }
4196 }
4197 Self::CustomProtocol(url) => {
4198 let url = url_lit(url);
4199 quote! { #prefix::CustomProtocol(#url) }
4200 }
4201 })
4202 }
4203 }
4204
4205 impl ToTokens for BackgroundThrottlingPolicy {
4206 fn to_tokens(&self, tokens: &mut TokenStream) {
4207 let prefix = quote! { ::tauri::utils::config::BackgroundThrottlingPolicy };
4208 tokens.append_all(match self {
4209 Self::Disabled => quote! { #prefix::Disabled },
4210 Self::Throttle => quote! { #prefix::Throttle },
4211 Self::Suspend => quote! { #prefix::Suspend },
4212 })
4213 }
4214 }
4215
4216 impl ToTokens for crate::Theme {
4217 fn to_tokens(&self, tokens: &mut TokenStream) {
4218 let prefix = quote! { ::tauri::utils::Theme };
4219
4220 tokens.append_all(match self {
4221 Self::Light => quote! { #prefix::Light },
4222 Self::Dark => quote! { #prefix::Dark },
4223 })
4224 }
4225 }
4226
4227 impl ToTokens for Color {
4228 fn to_tokens(&self, tokens: &mut TokenStream) {
4229 let Color(r, g, b, a) = self;
4230 tokens.append_all(quote! {::tauri::utils::config::Color(#r,#g,#b,#a)});
4231 }
4232 }
4233 impl ToTokens for WindowEffectsConfig {
4234 fn to_tokens(&self, tokens: &mut TokenStream) {
4235 let effects = vec_lit(self.effects.clone(), |d| d);
4236 let state = opt_lit(self.state.as_ref());
4237 let radius = opt_lit(self.radius.as_ref());
4238 let color = opt_lit(self.color.as_ref());
4239 let interactive = self.interactive;
4240
4241 literal_struct!(
4242 tokens,
4243 ::tauri::utils::config::WindowEffectsConfig,
4244 effects,
4245 state,
4246 radius,
4247 color,
4248 interactive
4249 )
4250 }
4251 }
4252
4253 impl ToTokens for crate::TitleBarStyle {
4254 fn to_tokens(&self, tokens: &mut TokenStream) {
4255 let prefix = quote! { ::tauri::utils::TitleBarStyle };
4256
4257 tokens.append_all(match self {
4258 Self::Visible => quote! { #prefix::Visible },
4259 Self::Transparent => quote! { #prefix::Transparent },
4260 Self::Overlay => quote! { #prefix::Overlay },
4261 })
4262 }
4263 }
4264
4265 impl ToTokens for LogicalPosition {
4266 fn to_tokens(&self, tokens: &mut TokenStream) {
4267 let LogicalPosition { x, y } = self;
4268 literal_struct!(tokens, ::tauri::utils::config::LogicalPosition, x, y)
4269 }
4270 }
4271
4272 impl ToTokens for crate::WindowEffect {
4273 fn to_tokens(&self, tokens: &mut TokenStream) {
4274 let prefix = quote! { ::tauri::utils::WindowEffect };
4275
4276 #[allow(deprecated)]
4277 tokens.append_all(match self {
4278 WindowEffect::AppearanceBased => quote! { #prefix::AppearanceBased},
4279 WindowEffect::Light => quote! { #prefix::Light},
4280 WindowEffect::Dark => quote! { #prefix::Dark},
4281 WindowEffect::MediumLight => quote! { #prefix::MediumLight},
4282 WindowEffect::UltraDark => quote! { #prefix::UltraDark},
4283 WindowEffect::Titlebar => quote! { #prefix::Titlebar},
4284 WindowEffect::Selection => quote! { #prefix::Selection},
4285 WindowEffect::Menu => quote! { #prefix::Menu},
4286 WindowEffect::Popover => quote! { #prefix::Popover},
4287 WindowEffect::Sidebar => quote! { #prefix::Sidebar},
4288 WindowEffect::HeaderView => quote! { #prefix::HeaderView},
4289 WindowEffect::Sheet => quote! { #prefix::Sheet},
4290 WindowEffect::WindowBackground => quote! { #prefix::WindowBackground},
4291 WindowEffect::HudWindow => quote! { #prefix::HudWindow},
4292 WindowEffect::FullScreenUI => quote! { #prefix::FullScreenUI},
4293 WindowEffect::Tooltip => quote! { #prefix::Tooltip},
4294 WindowEffect::ContentBackground => quote! { #prefix::ContentBackground},
4295 WindowEffect::UnderWindowBackground => quote! { #prefix::UnderWindowBackground},
4296 WindowEffect::UnderPageBackground => quote! { #prefix::UnderPageBackground},
4297 WindowEffect::LiquidGlassRegular => quote! { #prefix::LiquidGlassRegular },
4298 WindowEffect::LiquidGlassClear => quote! { #prefix::LiquidGlassClear },
4299 WindowEffect::Mica => quote! { #prefix::Mica},
4300 WindowEffect::MicaDark => quote! { #prefix::MicaDark},
4301 WindowEffect::MicaLight => quote! { #prefix::MicaLight},
4302 WindowEffect::Blur => quote! { #prefix::Blur},
4303 WindowEffect::Acrylic => quote! { #prefix::Acrylic},
4304 WindowEffect::Tabbed => quote! { #prefix::Tabbed },
4305 WindowEffect::TabbedDark => quote! { #prefix::TabbedDark },
4306 WindowEffect::TabbedLight => quote! { #prefix::TabbedLight },
4307 })
4308 }
4309 }
4310
4311 impl ToTokens for crate::WindowEffectState {
4312 fn to_tokens(&self, tokens: &mut TokenStream) {
4313 let prefix = quote! { ::tauri::utils::WindowEffectState };
4314
4315 #[allow(deprecated)]
4316 tokens.append_all(match self {
4317 WindowEffectState::Active => quote! { #prefix::Active},
4318 WindowEffectState::FollowsWindowActiveState => quote! { #prefix::FollowsWindowActiveState},
4319 WindowEffectState::Inactive => quote! { #prefix::Inactive},
4320 })
4321 }
4322 }
4323
4324 impl ToTokens for PreventOverflowMargin {
4325 fn to_tokens(&self, tokens: &mut TokenStream) {
4326 let width = self.width;
4327 let height = self.height;
4328
4329 literal_struct!(
4330 tokens,
4331 ::tauri::utils::config::PreventOverflowMargin,
4332 width,
4333 height
4334 )
4335 }
4336 }
4337
4338 impl ToTokens for PreventOverflowConfig {
4339 fn to_tokens(&self, tokens: &mut TokenStream) {
4340 let prefix = quote! { ::tauri::utils::config::PreventOverflowConfig };
4341
4342 #[allow(deprecated)]
4343 tokens.append_all(match self {
4344 Self::Enable(enable) => quote! { #prefix::Enable(#enable) },
4345 Self::Margin(margin) => quote! { #prefix::Margin(#margin) },
4346 })
4347 }
4348 }
4349
4350 impl ToTokens for ScrollBarStyle {
4351 fn to_tokens(&self, tokens: &mut TokenStream) {
4352 let prefix = quote! { ::tauri::utils::config::ScrollBarStyle };
4353
4354 tokens.append_all(match self {
4355 Self::Default => quote! { #prefix::Default },
4356 Self::FluentOverlay => quote! { #prefix::FluentOverlay },
4357 })
4358 }
4359 }
4360
4361 impl ToTokens for WindowConfig {
4362 fn to_tokens(&self, tokens: &mut TokenStream) {
4363 let label = str_lit(&self.label);
4364 let create = &self.create;
4365 let url = &self.url;
4366 let user_agent = opt_str_lit(self.user_agent.as_ref());
4367 let drag_drop_enabled = self.drag_drop_enabled;
4368 let center = self.center;
4369 let x = opt_lit(self.x.as_ref());
4370 let y = opt_lit(self.y.as_ref());
4371 let width = self.width;
4372 let height = self.height;
4373 let min_width = opt_lit(self.min_width.as_ref());
4374 let min_height = opt_lit(self.min_height.as_ref());
4375 let max_width = opt_lit(self.max_width.as_ref());
4376 let max_height = opt_lit(self.max_height.as_ref());
4377 let prevent_overflow = opt_lit(self.prevent_overflow.as_ref());
4378 let resizable = self.resizable;
4379 let maximizable = self.maximizable;
4380 let minimizable = self.minimizable;
4381 let closable = self.closable;
4382 let title = str_lit(&self.title);
4383 let proxy_url = opt_lit(self.proxy_url.as_ref().map(url_lit).as_ref());
4384 let fullscreen = self.fullscreen;
4385 let focus = self.focus;
4386 let focusable = self.focusable;
4387 let transparent = self.transparent;
4388 let maximized = self.maximized;
4389 let visible = self.visible;
4390 let decorations = self.decorations;
4391 let always_on_bottom = self.always_on_bottom;
4392 let always_on_top = self.always_on_top;
4393 let visible_on_all_workspaces = self.visible_on_all_workspaces;
4394 let content_protected = self.content_protected;
4395 let skip_taskbar = self.skip_taskbar;
4396 let window_classname = opt_str_lit(self.window_classname.as_ref());
4397 let no_redirection_bitmap = self.no_redirection_bitmap;
4398 let theme = opt_lit(self.theme.as_ref());
4399 let title_bar_style = &self.title_bar_style;
4400 let traffic_light_position = opt_lit(self.traffic_light_position.as_ref());
4401 let hidden_title = self.hidden_title;
4402 let accept_first_mouse = self.accept_first_mouse;
4403 let tabbing_identifier = opt_str_lit(self.tabbing_identifier.as_ref());
4404 let additional_browser_args = opt_str_lit(self.additional_browser_args.as_ref());
4405 let shadow = self.shadow;
4406 let window_effects = opt_lit(self.window_effects.as_ref());
4407 let incognito = self.incognito;
4408 let parent = opt_str_lit(self.parent.as_ref());
4409 let zoom_hotkeys_enabled = self.zoom_hotkeys_enabled;
4410 let browser_extensions_enabled = self.browser_extensions_enabled;
4411 let use_https_scheme = self.use_https_scheme;
4412 let devtools = opt_lit(self.devtools.as_ref());
4413 let background_color = opt_lit(self.background_color.as_ref());
4414 let background_throttling = opt_lit(self.background_throttling.as_ref());
4415 let javascript_disabled = self.javascript_disabled;
4416 let allow_link_preview = self.allow_link_preview;
4417 let disable_input_accessory_view = self.disable_input_accessory_view;
4418 let data_directory = opt_lit(self.data_directory.as_ref().map(path_buf_lit).as_ref());
4419 let data_store_identifier = opt_vec_lit(self.data_store_identifier, identity);
4420 let scroll_bar_style = &self.scroll_bar_style;
4421 let limit_navigations_to_app_bound_domains = self.limit_navigations_to_app_bound_domains;
4422 let activity_name = opt_lit(self.activity_name.as_ref());
4423 let created_by_activity_name = opt_lit(self.created_by_activity_name.as_ref());
4424 let requested_by_scene_identifier = opt_lit(self.requested_by_scene_identifier.as_ref());
4425 let general_autofill_enabled = self.general_autofill_enabled;
4426
4427 literal_struct!(
4428 tokens,
4429 ::tauri::utils::config::WindowConfig,
4430 label,
4431 url,
4432 create,
4433 user_agent,
4434 drag_drop_enabled,
4435 center,
4436 x,
4437 y,
4438 width,
4439 height,
4440 min_width,
4441 min_height,
4442 max_width,
4443 max_height,
4444 prevent_overflow,
4445 resizable,
4446 maximizable,
4447 minimizable,
4448 closable,
4449 title,
4450 proxy_url,
4451 fullscreen,
4452 focus,
4453 focusable,
4454 transparent,
4455 maximized,
4456 visible,
4457 decorations,
4458 always_on_bottom,
4459 always_on_top,
4460 visible_on_all_workspaces,
4461 content_protected,
4462 skip_taskbar,
4463 window_classname,
4464 no_redirection_bitmap,
4465 theme,
4466 title_bar_style,
4467 traffic_light_position,
4468 hidden_title,
4469 accept_first_mouse,
4470 tabbing_identifier,
4471 additional_browser_args,
4472 shadow,
4473 window_effects,
4474 incognito,
4475 parent,
4476 zoom_hotkeys_enabled,
4477 browser_extensions_enabled,
4478 use_https_scheme,
4479 devtools,
4480 background_color,
4481 background_throttling,
4482 javascript_disabled,
4483 allow_link_preview,
4484 disable_input_accessory_view,
4485 data_directory,
4486 data_store_identifier,
4487 scroll_bar_style,
4488 limit_navigations_to_app_bound_domains,
4489 activity_name,
4490 created_by_activity_name,
4491 requested_by_scene_identifier,
4492 general_autofill_enabled
4493 );
4494 }
4495 }
4496
4497 impl ToTokens for PatternKind {
4498 fn to_tokens(&self, tokens: &mut TokenStream) {
4499 let prefix = quote! { ::tauri::utils::config::PatternKind };
4500
4501 tokens.append_all(match self {
4502 Self::Brownfield => quote! { #prefix::Brownfield },
4503 #[cfg(not(feature = "isolation"))]
4504 Self::Isolation { dir: _ } => quote! { #prefix::Brownfield },
4505 #[cfg(feature = "isolation")]
4506 Self::Isolation { dir } => {
4507 let dir = path_buf_lit(dir);
4508 quote! { #prefix::Isolation { dir: #dir } }
4509 }
4510 })
4511 }
4512 }
4513
4514 impl ToTokens for WebviewInstallMode {
4515 fn to_tokens(&self, tokens: &mut TokenStream) {
4516 let prefix = quote! { ::tauri::utils::config::WebviewInstallMode };
4517
4518 tokens.append_all(match self {
4519 Self::Skip => quote! { #prefix::Skip },
4520 Self::DownloadBootstrapper { silent } => {
4521 quote! { #prefix::DownloadBootstrapper { silent: #silent } }
4522 }
4523 Self::EmbedBootstrapper { silent } => {
4524 quote! { #prefix::EmbedBootstrapper { silent: #silent } }
4525 }
4526 Self::OfflineInstaller { silent } => {
4527 quote! { #prefix::OfflineInstaller { silent: #silent } }
4528 }
4529 Self::FixedRuntime { path } => {
4530 let path = path_buf_lit(path);
4531 quote! { #prefix::FixedRuntime { path: #path } }
4532 }
4533 })
4534 }
4535 }
4536
4537 impl ToTokens for WindowsConfig {
4538 fn to_tokens(&self, tokens: &mut TokenStream) {
4539 let webview_install_mode = &self.webview_install_mode;
4540 tokens.append_all(quote! { ::tauri::utils::config::WindowsConfig {
4541 webview_install_mode: #webview_install_mode,
4542 ..Default::default()
4543 }})
4544 }
4545 }
4546
4547 impl ToTokens for BundleConfig {
4548 fn to_tokens(&self, tokens: &mut TokenStream) {
4549 let publisher = quote!(None);
4550 let homepage = quote!(None);
4551 let icon = vec_lit(&self.icon, str_lit);
4552 let active = self.active;
4553 let targets = quote!(Default::default());
4554 let create_updater_artifacts = quote!(Default::default());
4555 let resources = quote!(None);
4556 let copyright = quote!(None);
4557 let category = quote!(None);
4558 let file_associations = quote!(None);
4559 let short_description = quote!(None);
4560 let long_description = quote!(None);
4561 let use_local_tools_dir = self.use_local_tools_dir;
4562 let external_bin = opt_vec_lit(self.external_bin.as_ref(), str_lit);
4563 let windows = &self.windows;
4564 let license = opt_str_lit(self.license.as_ref());
4565 let license_file = opt_lit(self.license_file.as_ref().map(path_buf_lit).as_ref());
4566 let linux = quote!(Default::default());
4567 let macos = quote!(Default::default());
4568 let ios = quote!(Default::default());
4569 let android = quote!(Default::default());
4570
4571 literal_struct!(
4572 tokens,
4573 ::tauri::utils::config::BundleConfig,
4574 active,
4575 publisher,
4576 homepage,
4577 icon,
4578 targets,
4579 create_updater_artifacts,
4580 resources,
4581 copyright,
4582 category,
4583 license,
4584 license_file,
4585 file_associations,
4586 short_description,
4587 long_description,
4588 use_local_tools_dir,
4589 external_bin,
4590 windows,
4591 linux,
4592 macos,
4593 ios,
4594 android
4595 );
4596 }
4597 }
4598
4599 impl ToTokens for FrontendDist {
4600 fn to_tokens(&self, tokens: &mut TokenStream) {
4601 let prefix = quote! { ::tauri::utils::config::FrontendDist };
4602
4603 tokens.append_all(match self {
4604 Self::Url(url) => {
4605 let url = url_lit(url);
4606 quote! { #prefix::Url(#url) }
4607 }
4608 Self::Directory(path) => {
4609 let path = path_buf_lit(path);
4610 quote! { #prefix::Directory(#path) }
4611 }
4612 Self::Files(files) => {
4613 let files = vec_lit(files, path_buf_lit);
4614 quote! { #prefix::Files(#files) }
4615 }
4616 })
4617 }
4618 }
4619
4620 impl ToTokens for RunnerConfig {
4621 fn to_tokens(&self, tokens: &mut TokenStream) {
4622 let prefix = quote! { ::tauri::utils::config::RunnerConfig };
4623
4624 tokens.append_all(match self {
4625 Self::String(cmd) => {
4626 let cmd = cmd.as_str();
4627 quote!(#prefix::String(#cmd.into()))
4628 }
4629 Self::Object { cmd, cwd, args } => {
4630 let cmd = cmd.as_str();
4631 let cwd = opt_str_lit(cwd.as_ref());
4632 let args = opt_lit(args.as_ref().map(|v| vec_lit(v, str_lit)).as_ref());
4633 quote!(#prefix::Object {
4634 cmd: #cmd.into(),
4635 cwd: #cwd,
4636 args: #args,
4637 })
4638 }
4639 })
4640 }
4641 }
4642
4643 impl ToTokens for BuildConfig {
4644 fn to_tokens(&self, tokens: &mut TokenStream) {
4645 let dev_url = opt_lit(self.dev_url.as_ref().map(url_lit).as_ref());
4646 let frontend_dist = opt_lit(self.frontend_dist.as_ref());
4647 let runner = opt_lit(self.runner.as_ref());
4648 let before_dev_command = quote!(None);
4649 let before_build_command = quote!(None);
4650 let before_bundle_command = quote!(None);
4651 let features = quote!(None);
4652 let remove_unused_commands = quote!(false);
4653 let additional_watch_folders = quote!(Vec::new());
4654 let windows = &self.windows;
4655
4656 literal_struct!(
4657 tokens,
4658 ::tauri::utils::config::BuildConfig,
4659 runner,
4660 dev_url,
4661 frontend_dist,
4662 before_dev_command,
4663 before_build_command,
4664 before_bundle_command,
4665 features,
4666 remove_unused_commands,
4667 additional_watch_folders,
4668 windows
4669 );
4670 }
4671 }
4672
4673 impl ToTokens for WindowsBuildConfig {
4674 fn to_tokens(&self, tokens: &mut TokenStream) {
4675 let static_vc_runtime = self.static_vc_runtime;
4676
4677 literal_struct!(
4678 tokens,
4679 ::tauri::utils::config::WindowsBuildConfig,
4680 static_vc_runtime
4681 );
4682 }
4683 }
4684
4685 impl ToTokens for CspDirectiveSources {
4686 fn to_tokens(&self, tokens: &mut TokenStream) {
4687 let prefix = quote! { ::tauri::utils::config::CspDirectiveSources };
4688
4689 tokens.append_all(match self {
4690 Self::Inline(sources) => {
4691 let sources = sources.as_str();
4692 quote!(#prefix::Inline(#sources.into()))
4693 }
4694 Self::List(list) => {
4695 let list = vec_lit(list, str_lit);
4696 quote!(#prefix::List(#list))
4697 }
4698 })
4699 }
4700 }
4701
4702 impl ToTokens for Csp {
4703 fn to_tokens(&self, tokens: &mut TokenStream) {
4704 let prefix = quote! { ::tauri::utils::config::Csp };
4705
4706 tokens.append_all(match self {
4707 Self::Policy(policy) => {
4708 let policy = policy.as_str();
4709 quote!(#prefix::Policy(#policy.into()))
4710 }
4711 Self::DirectiveMap(list) => {
4712 let mut sorted: Vec<_> = list.iter().collect();
4716 sorted.sort_by_key(|(k, _)| *k);
4717 let map = map_lit(
4718 quote! { ::std::collections::HashMap },
4719 sorted,
4720 str_lit,
4721 identity,
4722 );
4723 quote!(#prefix::DirectiveMap(#map))
4724 }
4725 })
4726 }
4727 }
4728
4729 impl ToTokens for DisabledCspModificationKind {
4730 fn to_tokens(&self, tokens: &mut TokenStream) {
4731 let prefix = quote! { ::tauri::utils::config::DisabledCspModificationKind };
4732
4733 tokens.append_all(match self {
4734 Self::Flag(flag) => {
4735 quote! { #prefix::Flag(#flag) }
4736 }
4737 Self::List(directives) => {
4738 let directives = vec_lit(directives, str_lit);
4739 quote! { #prefix::List(#directives) }
4740 }
4741 });
4742 }
4743 }
4744
4745 impl ToTokens for CapabilityEntry {
4746 fn to_tokens(&self, tokens: &mut TokenStream) {
4747 let prefix = quote! { ::tauri::utils::config::CapabilityEntry };
4748
4749 tokens.append_all(match self {
4750 Self::Inlined(capability) => {
4751 quote! { #prefix::Inlined(#capability) }
4752 }
4753 Self::Reference(id) => {
4754 let id = str_lit(id);
4755 quote! { #prefix::Reference(#id) }
4756 }
4757 });
4758 }
4759 }
4760
4761 impl ToTokens for HeaderSource {
4762 fn to_tokens(&self, tokens: &mut TokenStream) {
4763 let prefix = quote! { ::tauri::utils::config::HeaderSource };
4764
4765 tokens.append_all(match self {
4766 Self::Inline(s) => {
4767 let line = s.as_str();
4768 quote!(#prefix::Inline(#line.into()))
4769 }
4770 Self::List(l) => {
4771 let list = vec_lit(l, str_lit);
4772 quote!(#prefix::List(#list))
4773 }
4774 Self::Map(m) => {
4775 let mut sorted: Vec<_> = m.iter().collect();
4779 sorted.sort_by_key(|(k, _)| *k);
4780 let map = map_lit(
4781 quote! { ::std::collections::HashMap },
4782 sorted,
4783 str_lit,
4784 str_lit,
4785 );
4786 quote!(#prefix::Map(#map))
4787 }
4788 })
4789 }
4790 }
4791
4792 impl ToTokens for HeaderConfig {
4793 fn to_tokens(&self, tokens: &mut TokenStream) {
4794 let access_control_allow_credentials =
4795 opt_lit(self.access_control_allow_credentials.as_ref());
4796 let access_control_allow_headers = opt_lit(self.access_control_allow_headers.as_ref());
4797 let access_control_allow_methods = opt_lit(self.access_control_allow_methods.as_ref());
4798 let access_control_expose_headers = opt_lit(self.access_control_expose_headers.as_ref());
4799 let access_control_max_age = opt_lit(self.access_control_max_age.as_ref());
4800 let cross_origin_embedder_policy = opt_lit(self.cross_origin_embedder_policy.as_ref());
4801 let cross_origin_opener_policy = opt_lit(self.cross_origin_opener_policy.as_ref());
4802 let cross_origin_resource_policy = opt_lit(self.cross_origin_resource_policy.as_ref());
4803 let permissions_policy = opt_lit(self.permissions_policy.as_ref());
4804 let service_worker_allowed = opt_lit(self.service_worker_allowed.as_ref());
4805 let timing_allow_origin = opt_lit(self.timing_allow_origin.as_ref());
4806 let x_content_type_options = opt_lit(self.x_content_type_options.as_ref());
4807 let tauri_custom_header = opt_lit(self.tauri_custom_header.as_ref());
4808
4809 literal_struct!(
4810 tokens,
4811 ::tauri::utils::config::HeaderConfig,
4812 access_control_allow_credentials,
4813 access_control_allow_headers,
4814 access_control_allow_methods,
4815 access_control_expose_headers,
4816 access_control_max_age,
4817 cross_origin_embedder_policy,
4818 cross_origin_opener_policy,
4819 cross_origin_resource_policy,
4820 permissions_policy,
4821 service_worker_allowed,
4822 timing_allow_origin,
4823 x_content_type_options,
4824 tauri_custom_header
4825 );
4826 }
4827 }
4828
4829 impl ToTokens for SecurityConfig {
4830 fn to_tokens(&self, tokens: &mut TokenStream) {
4831 let csp = opt_lit(self.csp.as_ref());
4832 let dev_csp = opt_lit(self.dev_csp.as_ref());
4833 let freeze_prototype = self.freeze_prototype;
4834 let dangerous_disable_asset_csp_modification = &self.dangerous_disable_asset_csp_modification;
4835 let asset_protocol = &self.asset_protocol;
4836 let pattern = &self.pattern;
4837 let capabilities = vec_lit(&self.capabilities, identity);
4838 let headers = opt_lit(self.headers.as_ref());
4839
4840 literal_struct!(
4841 tokens,
4842 ::tauri::utils::config::SecurityConfig,
4843 csp,
4844 dev_csp,
4845 freeze_prototype,
4846 dangerous_disable_asset_csp_modification,
4847 asset_protocol,
4848 pattern,
4849 capabilities,
4850 headers
4851 );
4852 }
4853 }
4854
4855 impl ToTokens for TrayIconConfig {
4856 fn to_tokens(&self, tokens: &mut TokenStream) {
4857 tokens.append_all(quote!(#[allow(deprecated)]));
4859
4860 let id = opt_str_lit(self.id.as_ref());
4861 let icon_as_template = self.icon_as_template;
4862 #[allow(deprecated)]
4863 let menu_on_left_click = self.menu_on_left_click;
4864 let show_menu_on_left_click = self.show_menu_on_left_click;
4865 let icon_path = path_buf_lit(&self.icon_path);
4866 let title = opt_str_lit(self.title.as_ref());
4867 let tooltip = opt_str_lit(self.tooltip.as_ref());
4868 literal_struct!(
4869 tokens,
4870 ::tauri::utils::config::TrayIconConfig,
4871 id,
4872 icon_path,
4873 icon_as_template,
4874 menu_on_left_click,
4875 show_menu_on_left_click,
4876 title,
4877 tooltip
4878 );
4879 }
4880 }
4881
4882 impl ToTokens for FsScope {
4883 fn to_tokens(&self, tokens: &mut TokenStream) {
4884 let prefix = quote! { ::tauri::utils::config::FsScope };
4885
4886 tokens.append_all(match self {
4887 Self::AllowedPaths(allow) => {
4888 let allowed_paths = vec_lit(allow, path_buf_lit);
4889 quote! { #prefix::AllowedPaths(#allowed_paths) }
4890 }
4891 Self::Scope { allow, deny , require_literal_leading_dot} => {
4892 let allow = vec_lit(allow, path_buf_lit);
4893 let deny = vec_lit(deny, path_buf_lit);
4894 let require_literal_leading_dot = opt_lit(require_literal_leading_dot.as_ref());
4895 quote! { #prefix::Scope { allow: #allow, deny: #deny, require_literal_leading_dot: #require_literal_leading_dot } }
4896 }
4897 });
4898 }
4899 }
4900
4901 impl ToTokens for AssetProtocolConfig {
4902 fn to_tokens(&self, tokens: &mut TokenStream) {
4903 let scope = &self.scope;
4904 tokens.append_all(quote! { ::tauri::utils::config::AssetProtocolConfig { scope: #scope, ..Default::default() } })
4905 }
4906 }
4907
4908 impl ToTokens for AppDirectoryOverrides {
4909 fn to_tokens(&self, tokens: &mut TokenStream) {
4910 let config = opt_lit_owned(self.config.as_ref().map(path_buf_lit));
4911 let data = opt_lit_owned(self.data.as_ref().map(path_buf_lit));
4912 let local_data = opt_lit_owned(self.local_data.as_ref().map(path_buf_lit));
4913 let cache = opt_lit_owned(self.cache.as_ref().map(path_buf_lit));
4914 let log = opt_lit_owned(self.log.as_ref().map(path_buf_lit));
4915
4916 literal_struct!(
4917 tokens,
4918 ::tauri::utils::config::AppDirectoryOverrides,
4919 config,
4920 data,
4921 local_data,
4922 cache,
4923 log
4924 );
4925 }
4926 }
4927
4928 impl ToTokens for AppDirectoriesOverride {
4929 fn to_tokens(&self, tokens: &mut TokenStream) {
4930 let prefix = quote! { ::tauri::utils::config::AppDirectoriesOverride };
4931
4932 tokens.append_all(match self {
4933 Self::Root(root) => {
4934 let root = path_buf_lit(root);
4935 quote! { #prefix::Root(#root) }
4936 }
4937 Self::Directories(directories) => quote! { #prefix::Directories(#directories) },
4938 })
4939 }
4940 }
4941
4942 impl ToTokens for AppConfig {
4943 fn to_tokens(&self, tokens: &mut TokenStream) {
4944 let windows = vec_lit(&self.windows, identity);
4945 let security = &self.security;
4946 let tray_icon = opt_lit(self.tray_icon.as_ref());
4947 let macos_private_api = self.macos_private_api;
4948 let with_global_tauri = self.with_global_tauri;
4949 let enable_gtk_app_id = self.enable_gtk_app_id;
4950 let app_directories_override = opt_lit(self.app_directories_override.as_ref());
4951
4952 literal_struct!(
4953 tokens,
4954 ::tauri::utils::config::AppConfig,
4955 windows,
4956 security,
4957 tray_icon,
4958 macos_private_api,
4959 with_global_tauri,
4960 enable_gtk_app_id,
4961 app_directories_override
4962 );
4963 }
4964 }
4965
4966 impl ToTokens for PluginConfig {
4967 fn to_tokens(&self, tokens: &mut TokenStream) {
4968 let mut sorted: Vec<_> = self.0.iter().collect();
4972 sorted.sort_by_key(|(k, _)| *k);
4973 let config = map_lit(
4974 quote! { ::std::collections::HashMap },
4975 sorted,
4976 str_lit,
4977 json_value_lit,
4978 );
4979 tokens.append_all(quote! { ::tauri::utils::config::PluginConfig(#config) })
4980 }
4981 }
4982
4983 impl ToTokens for Config {
4984 fn to_tokens(&self, tokens: &mut TokenStream) {
4985 let schema = quote!(None);
4986 let product_name = opt_str_lit(self.product_name.as_ref());
4987 let main_binary_name = opt_str_lit(self.main_binary_name.as_ref());
4988 let version = opt_str_lit(self.version.as_ref());
4989 let identifier = str_lit(&self.identifier);
4990 let app = &self.app;
4991 let build = &self.build;
4992 let bundle = &self.bundle;
4993 let plugins = &self.plugins;
4994
4995 literal_struct!(
4996 tokens,
4997 ::tauri::utils::config::Config,
4998 schema,
4999 product_name,
5000 main_binary_name,
5001 version,
5002 identifier,
5003 app,
5004 build,
5005 bundle,
5006 plugins
5007 );
5008 }
5009 }
5010}
5011
5012#[cfg(test)]
5013mod test {
5014 use super::*;
5015
5016 #[test]
5019 fn test_defaults() {
5021 let a_config = AppConfig::default();
5023 let b_config = BuildConfig::default();
5025 let d_windows: Vec<WindowConfig> = vec![];
5027 let d_bundle = BundleConfig::default();
5029
5030 let app = AppConfig {
5032 windows: vec![],
5033 security: SecurityConfig {
5034 csp: None,
5035 dev_csp: None,
5036 freeze_prototype: false,
5037 dangerous_disable_asset_csp_modification: DisabledCspModificationKind::Flag(false),
5038 asset_protocol: AssetProtocolConfig::default(),
5039 pattern: Default::default(),
5040 capabilities: Vec::new(),
5041 headers: None,
5042 },
5043 tray_icon: None,
5044 macos_private_api: false,
5045 with_global_tauri: false,
5046 enable_gtk_app_id: false,
5047 app_directories_override: None,
5048 };
5049
5050 let build = BuildConfig {
5052 runner: None,
5053 dev_url: None,
5054 frontend_dist: None,
5055 before_dev_command: None,
5056 before_build_command: None,
5057 before_bundle_command: None,
5058 features: None,
5059 remove_unused_commands: false,
5060 additional_watch_folders: Vec::new(),
5061 windows: WindowsBuildConfig::default(),
5062 };
5063
5064 let bundle = BundleConfig {
5066 active: false,
5067 targets: Default::default(),
5068 create_updater_artifacts: Default::default(),
5069 publisher: None,
5070 homepage: None,
5071 icon: Vec::new(),
5072 resources: None,
5073 copyright: None,
5074 category: None,
5075 file_associations: None,
5076 short_description: None,
5077 long_description: None,
5078 use_local_tools_dir: false,
5079 license: None,
5080 license_file: None,
5081 linux: Default::default(),
5082 macos: Default::default(),
5083 external_bin: None,
5084 windows: Default::default(),
5085 ios: Default::default(),
5086 android: Default::default(),
5087 };
5088
5089 assert_eq!(a_config, app);
5091 assert_eq!(b_config, build);
5092 assert_eq!(d_bundle, bundle);
5093 assert_eq!(d_windows, app.windows);
5094 }
5095
5096 #[test]
5097 fn app_directories_override_root() {
5098 let config: AppDirectoriesOverride = serde_json::from_str(r#""./""#).unwrap();
5099 assert_eq!(config, AppDirectoriesOverride::Root("./".into()));
5100
5101 let config: AppDirectoriesOverride = serde_json::from_str(r#""$DATA/my-app""#).unwrap();
5102 assert_eq!(config, AppDirectoriesOverride::Root("$DATA/my-app".into()));
5103 }
5104
5105 #[test]
5106 fn app_directories_override_directories() {
5107 let config: AppDirectoriesOverride = serde_json::from_str(
5108 r#"{ "log": "$DATA/logs", "cache": "$CACHE/my-app", "local-data": "data" }"#,
5109 )
5110 .unwrap();
5111 assert_eq!(
5112 config,
5113 AppDirectoriesOverride::Directories(AppDirectoryOverrides {
5114 config: None,
5115 data: None,
5116 local_data: Some("data".into()),
5117 cache: Some("$CACHE/my-app".into()),
5118 log: Some("$DATA/logs".into()),
5119 })
5120 );
5121
5122 let config: AppDirectoriesOverride =
5123 serde_json::from_str(r#"{ "config": "conf", "data": "data", "localData": "local" }"#)
5124 .unwrap();
5125 assert_eq!(
5126 config,
5127 AppDirectoriesOverride::Directories(AppDirectoryOverrides {
5128 config: Some("conf".into()),
5129 data: Some("data".into()),
5130 local_data: Some("local".into()),
5131 cache: None,
5132 log: None,
5133 })
5134 );
5135
5136 let config: AppDirectoriesOverride = serde_json::from_str("{}").unwrap();
5137 assert_eq!(
5138 config,
5139 AppDirectoriesOverride::Directories(AppDirectoryOverrides::default())
5140 );
5141 }
5142
5143 #[test]
5144 fn app_directories_override_rejects_unknown_directories() {
5145 let err = serde_json::from_str::<AppDirectoriesOverride>(r#"{ "logs": "x" }"#).unwrap_err();
5146 assert!(err.to_string().contains("unknown field `logs`"), "{err}");
5147 }
5148
5149 #[test]
5150 fn app_directories_override_accepts_supported_variables() {
5151 for variable in APP_DIRECTORIES_OVERRIDE_VARIABLES {
5152 for path in [
5153 variable.to_string(),
5154 format!("{variable}/my-app"),
5155 format!("{variable}/../my-app"),
5156 ] {
5157 let json = serde_json::to_string(&path).unwrap();
5158 let config: AppDirectoriesOverride = serde_json::from_str(&json).unwrap();
5159 assert_eq!(config, AppDirectoriesOverride::Root(path.into()));
5160 }
5161 }
5162 }
5163
5164 #[test]
5165 fn app_directories_override_rejects_unsupported_variables() {
5166 for variable in [
5167 "$APPCONFIG",
5168 "$APPDATA",
5169 "$APPLOCALDATA",
5170 "$APPCACHE",
5171 "$APPLOG",
5172 "$EXE",
5173 "$FONT",
5174 "$RESOURCE",
5175 "$RUNTIME",
5176 "$TEMPLATE",
5177 "$UNKNOWN",
5178 ] {
5179 let err = serde_json::from_str::<AppDirectoriesOverride>(&format!(r#""{variable}/my-app""#))
5180 .unwrap_err();
5181 assert!(
5182 err
5183 .to_string()
5184 .contains(&format!("unsupported base directory variable `{variable}`")),
5185 "{variable}: {err}"
5186 );
5187
5188 let err =
5189 serde_json::from_str::<AppDirectoriesOverride>(&format!(r#"{{ "log": "{variable}" }}"#))
5190 .unwrap_err();
5191 assert!(
5192 err
5193 .to_string()
5194 .contains("unsupported base directory variable"),
5195 "{variable}: {err}"
5196 );
5197 }
5198 }
5199
5200 #[cfg(windows)]
5201 #[test]
5202 fn app_directories_override_rejects_root_relative_paths() {
5203 for path in [r"\my-app", "C:my-app"] {
5204 let json = serde_json::to_string(path).unwrap();
5205 let err = serde_json::from_str::<AppDirectoriesOverride>(&json).unwrap_err();
5206 assert!(
5207 err.to_string().contains("must be an absolute path"),
5208 "{path}: {err}"
5209 );
5210 }
5211 }
5212
5213 #[cfg(feature = "build")]
5214 #[test]
5215 fn app_directories_override_to_tokens() {
5216 use quote::ToTokens;
5217
5218 let tokens = AppDirectoriesOverride::Root("./".into())
5219 .to_token_stream()
5220 .to_string()
5221 .replace(' ', "");
5222 assert_eq!(
5223 tokens,
5224 r#"::tauri::utils::config::AppDirectoriesOverride::Root(::std::path::PathBuf::from("./"))"#
5225 );
5226
5227 let tokens = AppDirectoriesOverride::Directories(AppDirectoryOverrides {
5228 log: Some("$DATA/logs".into()),
5229 ..Default::default()
5230 })
5231 .to_token_stream()
5232 .to_string()
5233 .replace(' ', "");
5234 assert_eq!(
5235 tokens,
5236 r#"::tauri::utils::config::AppDirectoriesOverride::Directories(::tauri::utils::config::AppDirectoryOverrides{config:::core::option::Option::None,data:::core::option::Option::None,local_data:::core::option::Option::None,cache:::core::option::Option::None,log:::core::option::Option::Some(::std::path::PathBuf::from("$DATA/logs"))})"#
5237 );
5238 }
5239
5240 #[test]
5241 fn parse_hex_color() {
5242 use super::Color;
5243
5244 assert_eq!(Color(255, 255, 255, 255), "fff".parse().unwrap());
5245 assert_eq!(Color(255, 255, 255, 255), "#fff".parse().unwrap());
5246 assert_eq!(Color(0, 0, 0, 255), "#000000".parse().unwrap());
5247 assert_eq!(Color(0, 0, 0, 255), "#000000ff".parse().unwrap());
5248 assert_eq!(Color(0, 255, 0, 255), "#00ff00ff".parse().unwrap());
5249
5250 assert!("#€€".parse::<Color>().is_err());
5251 assert!("#€".parse::<Color>().is_err());
5252 assert!("#+f+f+f".parse::<Color>().is_err());
5253 assert_eq!(Color(255, 255, 255, 255), " fff ".parse().unwrap());
5254 }
5255
5256 #[test]
5257 fn test_runner_config_string_format() {
5258 use super::RunnerConfig;
5259
5260 let json = r#""cargo""#;
5262 let runner: RunnerConfig = serde_json::from_str(json).unwrap();
5263
5264 assert_eq!(runner.cmd(), "cargo");
5265 assert_eq!(runner.cwd(), None);
5266 assert_eq!(runner.args(), None);
5267
5268 let serialized = serde_json::to_string(&runner).unwrap();
5270 assert_eq!(serialized, r#""cargo""#);
5271 }
5272
5273 #[test]
5274 fn test_runner_config_object_format_full() {
5275 use super::RunnerConfig;
5276
5277 let json = r#"{"cmd": "my_runner", "cwd": "/tmp/build", "args": ["--quiet", "--verbose"]}"#;
5279 let runner: RunnerConfig = serde_json::from_str(json).unwrap();
5280
5281 assert_eq!(runner.cmd(), "my_runner");
5282 assert_eq!(runner.cwd(), Some("/tmp/build"));
5283 assert_eq!(
5284 runner.args(),
5285 Some(&["--quiet".to_string(), "--verbose".to_string()][..])
5286 );
5287
5288 let serialized = serde_json::to_string(&runner).unwrap();
5290 let deserialized: RunnerConfig = serde_json::from_str(&serialized).unwrap();
5291 assert_eq!(runner, deserialized);
5292 }
5293
5294 #[test]
5295 fn test_runner_config_object_format_minimal() {
5296 use super::RunnerConfig;
5297
5298 let json = r#"{"cmd": "cross"}"#;
5300 let runner: RunnerConfig = serde_json::from_str(json).unwrap();
5301
5302 assert_eq!(runner.cmd(), "cross");
5303 assert_eq!(runner.cwd(), None);
5304 assert_eq!(runner.args(), None);
5305 }
5306
5307 #[test]
5308 fn test_runner_config_default() {
5309 use super::RunnerConfig;
5310
5311 let default_runner = RunnerConfig::default();
5312 assert_eq!(default_runner.cmd(), "cargo");
5313 assert_eq!(default_runner.cwd(), None);
5314 assert_eq!(default_runner.args(), None);
5315 }
5316
5317 #[test]
5318 fn test_runner_config_from_str() {
5319 use super::RunnerConfig;
5320
5321 let runner: RunnerConfig = "my_runner".into();
5323 assert_eq!(runner.cmd(), "my_runner");
5324 assert_eq!(runner.cwd(), None);
5325 assert_eq!(runner.args(), None);
5326 }
5327
5328 #[test]
5329 fn test_runner_config_from_string() {
5330 use super::RunnerConfig;
5331
5332 let runner: RunnerConfig = "another_runner".to_string().into();
5334 assert_eq!(runner.cmd(), "another_runner");
5335 assert_eq!(runner.cwd(), None);
5336 assert_eq!(runner.args(), None);
5337 }
5338
5339 #[test]
5340 fn test_runner_config_from_str_parse() {
5341 use super::RunnerConfig;
5342 use std::str::FromStr;
5343
5344 let runner = RunnerConfig::from_str("parsed_runner").unwrap();
5346 assert_eq!(runner.cmd(), "parsed_runner");
5347 assert_eq!(runner.cwd(), None);
5348 assert_eq!(runner.args(), None);
5349 }
5350
5351 #[test]
5352 fn test_runner_config_in_build_config() {
5353 use super::BuildConfig;
5354
5355 let json = r#"{"runner": "cargo"}"#;
5357 let build_config: BuildConfig = serde_json::from_str(json).unwrap();
5358
5359 let runner = build_config.runner.unwrap();
5360 assert_eq!(runner.cmd(), "cargo");
5361 assert_eq!(runner.cwd(), None);
5362 assert_eq!(runner.args(), None);
5363 }
5364
5365 #[test]
5366 fn test_runner_config_in_build_config_object() {
5367 use super::BuildConfig;
5368
5369 let json = r#"{"runner": {"cmd": "cross", "cwd": "/workspace", "args": ["--target", "x86_64-unknown-linux-gnu"]}}"#;
5371 let build_config: BuildConfig = serde_json::from_str(json).unwrap();
5372
5373 let runner = build_config.runner.unwrap();
5374 assert_eq!(runner.cmd(), "cross");
5375 assert_eq!(runner.cwd(), Some("/workspace"));
5376 assert_eq!(
5377 runner.args(),
5378 Some(
5379 &[
5380 "--target".to_string(),
5381 "x86_64-unknown-linux-gnu".to_string()
5382 ][..]
5383 )
5384 );
5385 }
5386
5387 #[test]
5388 fn test_runner_config_in_full_config() {
5389 use super::Config;
5390
5391 let json = r#"{
5393 "productName": "Test App",
5394 "version": "1.0.0",
5395 "identifier": "com.test.app",
5396 "build": {
5397 "runner": {
5398 "cmd": "my_custom_cargo",
5399 "cwd": "/tmp/build",
5400 "args": ["--quiet", "--verbose"]
5401 }
5402 }
5403 }"#;
5404
5405 let config: Config = serde_json::from_str(json).unwrap();
5406 let runner = config.build.runner.unwrap();
5407
5408 assert_eq!(runner.cmd(), "my_custom_cargo");
5409 assert_eq!(runner.cwd(), Some("/tmp/build"));
5410 assert_eq!(
5411 runner.args(),
5412 Some(&["--quiet".to_string(), "--verbose".to_string()][..])
5413 );
5414 }
5415
5416 #[test]
5417 fn test_runner_config_equality() {
5418 use super::RunnerConfig;
5419
5420 let runner1 = RunnerConfig::String("cargo".to_string());
5421 let runner2 = RunnerConfig::String("cargo".to_string());
5422 let runner3 = RunnerConfig::String("cross".to_string());
5423
5424 assert_eq!(runner1, runner2);
5425 assert_ne!(runner1, runner3);
5426
5427 let runner4 = RunnerConfig::Object {
5428 cmd: "cargo".to_string(),
5429 cwd: Some("/tmp".to_string()),
5430 args: Some(vec!["--quiet".to_string()]),
5431 };
5432 let runner5 = RunnerConfig::Object {
5433 cmd: "cargo".to_string(),
5434 cwd: Some("/tmp".to_string()),
5435 args: Some(vec!["--quiet".to_string()]),
5436 };
5437
5438 assert_eq!(runner4, runner5);
5439 assert_ne!(runner1, runner4);
5440 }
5441
5442 #[test]
5443 fn test_runner_config_untagged_serialization() {
5444 use super::RunnerConfig;
5445
5446 let string_runner = RunnerConfig::String("cargo".to_string());
5448 let string_json = serde_json::to_string(&string_runner).unwrap();
5449 assert_eq!(string_json, r#""cargo""#);
5450
5451 let object_runner = RunnerConfig::Object {
5453 cmd: "cross".to_string(),
5454 cwd: None,
5455 args: None,
5456 };
5457 let object_json = serde_json::to_string(&object_runner).unwrap();
5458 assert!(object_json.contains("\"cmd\":\"cross\""));
5459 assert!(object_json.contains("\"cwd\":null") || !object_json.contains("cwd"));
5461 assert!(object_json.contains("\"args\":null") || !object_json.contains("args"));
5462 }
5463
5464 #[test]
5465 fn header_source_map_display_is_deterministic() {
5466 let map = HashMap::from([
5467 ("key3".to_string(), "'value3'".to_string()),
5468 ("key1".to_string(), "'value1' 'value2'".to_string()),
5469 ("key2".to_string(), "'value4'".to_string()),
5470 ]);
5471
5472 assert_eq!(
5474 HeaderSource::Map(map.clone()).to_string(),
5475 "key1 'value1' 'value2'; key2 'value4'; key3 'value3'"
5476 );
5477
5478 let expected = HeaderSource::Map(map).to_string();
5479 for _ in 0..10 {
5480 let map = HashMap::from([
5481 ("key2".to_string(), "'value4'".to_string()),
5482 ("key3".to_string(), "'value3'".to_string()),
5483 ("key1".to_string(), "'value1' 'value2'".to_string()),
5484 ]);
5485 assert_eq!(HeaderSource::Map(map).to_string(), expected);
5486 }
5487
5488 let map = HashMap::from([
5490 ("b".to_string(), "2".to_string()),
5491 ("a".to_string(), "1".to_string()),
5492 ]);
5493 assert_eq!(
5494 serde_json::to_string(&HeaderSource::Map(map)).unwrap(),
5495 r#"{"a":"1","b":"2"}"#
5496 );
5497 }
5498
5499 #[test]
5500 fn header_source_display() {
5501 assert_eq!(
5502 HeaderSource::Inline("same-origin".into()).to_string(),
5503 "same-origin"
5504 );
5505 assert_eq!(
5506 HeaderSource::List(vec!["https://a.example".into(), "https://b.example".into()]).to_string(),
5507 "https://a.example, https://b.example"
5508 );
5509 }
5510
5511 #[test]
5512 fn window_config_default_same_as_deserialize() {
5513 let config_from_deserialization: WindowConfig = serde_json::from_str("{}").unwrap();
5514 let config_from_default: WindowConfig = WindowConfig::default();
5515
5516 assert_eq!(config_from_deserialization, config_from_default);
5517 }
5518}