config.rs 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796
  1. // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. //! The Tauri configuration used at runtime.
  5. //!
  6. //! It is pulled from a `tauri.conf.json` file and the [`Config`] struct is generated at compile time.
  7. //!
  8. //! # Stability
  9. //! This is a core functionality that is not considered part of the stable API.
  10. //! If you use it, note that it may include breaking changes in the future.
  11. #[cfg(feature = "schema")]
  12. use schemars::JsonSchema;
  13. use semver::Version;
  14. use serde::{
  15. de::{Deserializer, Error as DeError, Visitor},
  16. Deserialize, Serialize, Serializer,
  17. };
  18. use serde_json::Value as JsonValue;
  19. use serde_with::skip_serializing_none;
  20. use url::Url;
  21. use std::{
  22. collections::HashMap,
  23. fmt::{self, Display},
  24. fs::read_to_string,
  25. path::PathBuf,
  26. str::FromStr,
  27. };
  28. /// Items to help with parsing content into a [`Config`].
  29. pub mod parse;
  30. use crate::{acl::capability::Capability, TitleBarStyle, WindowEffect, WindowEffectState};
  31. pub use self::parse::parse;
  32. fn default_true() -> bool {
  33. true
  34. }
  35. /// An URL to open on a Tauri webview window.
  36. #[derive(PartialEq, Eq, Debug, Clone, Serialize)]
  37. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  38. #[serde(untagged)]
  39. #[non_exhaustive]
  40. pub enum WebviewUrl {
  41. /// An external URL. Must use either the `http` or `https` schemes.
  42. External(Url),
  43. /// The path portion of an app URL.
  44. /// For instance, to load `tauri://localhost/users/john`,
  45. /// you can simply provide `users/john` in this configuration.
  46. App(PathBuf),
  47. /// A custom protocol url, for example, `doom://index.html`
  48. CustomProtocol(Url),
  49. }
  50. impl<'de> Deserialize<'de> for WebviewUrl {
  51. fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
  52. where
  53. D: Deserializer<'de>,
  54. {
  55. #[derive(Deserialize)]
  56. #[serde(untagged)]
  57. enum WebviewUrlDeserializer {
  58. Url(Url),
  59. Path(PathBuf),
  60. }
  61. match WebviewUrlDeserializer::deserialize(deserializer)? {
  62. WebviewUrlDeserializer::Url(u) => {
  63. if u.scheme() == "https" || u.scheme() == "http" {
  64. Ok(Self::External(u))
  65. } else {
  66. Ok(Self::CustomProtocol(u))
  67. }
  68. }
  69. WebviewUrlDeserializer::Path(p) => Ok(Self::App(p)),
  70. }
  71. }
  72. }
  73. impl fmt::Display for WebviewUrl {
  74. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  75. match self {
  76. Self::External(url) | Self::CustomProtocol(url) => write!(f, "{url}"),
  77. Self::App(path) => write!(f, "{}", path.display()),
  78. }
  79. }
  80. }
  81. impl Default for WebviewUrl {
  82. fn default() -> Self {
  83. Self::App("index.html".into())
  84. }
  85. }
  86. /// A bundle referenced by tauri-bundler.
  87. #[derive(Debug, PartialEq, Eq, Clone)]
  88. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  89. #[cfg_attr(feature = "schema", schemars(rename_all = "lowercase"))]
  90. pub enum BundleType {
  91. /// The debian bundle (.deb).
  92. Deb,
  93. /// The RPM bundle (.rpm).
  94. Rpm,
  95. /// The AppImage bundle (.appimage).
  96. AppImage,
  97. /// The Microsoft Installer bundle (.msi).
  98. Msi,
  99. /// The NSIS bundle (.exe).
  100. Nsis,
  101. /// The macOS application bundle (.app).
  102. App,
  103. /// The Apple Disk Image bundle (.dmg).
  104. Dmg,
  105. /// The Tauri updater bundle.
  106. Updater,
  107. }
  108. impl BundleType {
  109. /// All bundle types.
  110. fn all() -> &'static [Self] {
  111. &[
  112. BundleType::Deb,
  113. BundleType::Rpm,
  114. BundleType::AppImage,
  115. BundleType::Msi,
  116. BundleType::Nsis,
  117. BundleType::App,
  118. BundleType::Dmg,
  119. BundleType::Updater,
  120. ]
  121. }
  122. }
  123. impl Display for BundleType {
  124. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  125. write!(
  126. f,
  127. "{}",
  128. match self {
  129. Self::Deb => "deb",
  130. Self::Rpm => "rpm",
  131. Self::AppImage => "appimage",
  132. Self::Msi => "msi",
  133. Self::Nsis => "nsis",
  134. Self::App => "app",
  135. Self::Dmg => "dmg",
  136. Self::Updater => "updater",
  137. }
  138. )
  139. }
  140. }
  141. impl Serialize for BundleType {
  142. fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
  143. where
  144. S: Serializer,
  145. {
  146. serializer.serialize_str(self.to_string().as_ref())
  147. }
  148. }
  149. impl<'de> Deserialize<'de> for BundleType {
  150. fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
  151. where
  152. D: Deserializer<'de>,
  153. {
  154. let s = String::deserialize(deserializer)?;
  155. match s.to_lowercase().as_str() {
  156. "deb" => Ok(Self::Deb),
  157. "rpm" => Ok(Self::Rpm),
  158. "appimage" => Ok(Self::AppImage),
  159. "msi" => Ok(Self::Msi),
  160. "nsis" => Ok(Self::Nsis),
  161. "app" => Ok(Self::App),
  162. "dmg" => Ok(Self::Dmg),
  163. "updater" => Ok(Self::Updater),
  164. _ => Err(DeError::custom(format!("unknown bundle target '{s}'"))),
  165. }
  166. }
  167. }
  168. /// Targets to bundle. Each value is case insensitive.
  169. #[derive(Debug, PartialEq, Eq, Clone)]
  170. pub enum BundleTarget {
  171. /// Bundle all targets.
  172. All,
  173. /// A list of bundle targets.
  174. List(Vec<BundleType>),
  175. /// A single bundle target.
  176. One(BundleType),
  177. }
  178. #[cfg(feature = "schema")]
  179. impl schemars::JsonSchema for BundleTarget {
  180. fn schema_name() -> std::string::String {
  181. "BundleTarget".to_owned()
  182. }
  183. fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
  184. let any_of = vec![
  185. schemars::schema::SchemaObject {
  186. enum_values: Some(vec!["all".into()]),
  187. metadata: Some(Box::new(schemars::schema::Metadata {
  188. description: Some("Bundle all targets.".to_owned()),
  189. ..Default::default()
  190. })),
  191. ..Default::default()
  192. }
  193. .into(),
  194. schemars::_private::metadata::add_description(
  195. gen.subschema_for::<Vec<BundleType>>(),
  196. "A list of bundle targets.",
  197. ),
  198. schemars::_private::metadata::add_description(
  199. gen.subschema_for::<BundleType>(),
  200. "A single bundle target.",
  201. ),
  202. ];
  203. schemars::schema::SchemaObject {
  204. subschemas: Some(Box::new(schemars::schema::SubschemaValidation {
  205. any_of: Some(any_of),
  206. ..Default::default()
  207. })),
  208. metadata: Some(Box::new(schemars::schema::Metadata {
  209. description: Some("Targets to bundle. Each value is case insensitive.".to_owned()),
  210. ..Default::default()
  211. })),
  212. ..Default::default()
  213. }
  214. .into()
  215. }
  216. }
  217. impl Default for BundleTarget {
  218. fn default() -> Self {
  219. Self::All
  220. }
  221. }
  222. impl Serialize for BundleTarget {
  223. fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
  224. where
  225. S: Serializer,
  226. {
  227. match self {
  228. Self::All => serializer.serialize_str("all"),
  229. Self::List(l) => l.serialize(serializer),
  230. Self::One(t) => serializer.serialize_str(t.to_string().as_ref()),
  231. }
  232. }
  233. }
  234. impl<'de> Deserialize<'de> for BundleTarget {
  235. fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
  236. where
  237. D: Deserializer<'de>,
  238. {
  239. #[derive(Deserialize, Serialize)]
  240. #[serde(untagged)]
  241. pub enum BundleTargetInner {
  242. List(Vec<BundleType>),
  243. One(BundleType),
  244. All(String),
  245. }
  246. match BundleTargetInner::deserialize(deserializer)? {
  247. BundleTargetInner::All(s) if s.to_lowercase() == "all" => Ok(Self::All),
  248. BundleTargetInner::All(t) => Err(DeError::custom(format!("invalid bundle type {t}"))),
  249. BundleTargetInner::List(l) => Ok(Self::List(l)),
  250. BundleTargetInner::One(t) => Ok(Self::One(t)),
  251. }
  252. }
  253. }
  254. impl BundleTarget {
  255. /// Gets the bundle targets as a [`Vec`]. The vector is empty when set to [`BundleTarget::All`].
  256. #[allow(dead_code)]
  257. pub fn to_vec(&self) -> Vec<BundleType> {
  258. match self {
  259. Self::All => BundleType::all().to_vec(),
  260. Self::List(list) => list.clone(),
  261. Self::One(i) => vec![i.clone()],
  262. }
  263. }
  264. }
  265. /// Configuration for AppImage bundles.
  266. ///
  267. /// See more: <https://tauri.app/v1/api/config#appimageconfig>
  268. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  269. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  270. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  271. pub struct AppImageConfig {
  272. /// Include additional gstreamer dependencies needed for audio and video playback.
  273. /// This increases the bundle size by ~15-35MB depending on your build system.
  274. #[serde(default, alias = "bundle-media-framework")]
  275. pub bundle_media_framework: bool,
  276. /// The files to include in the Appimage Binary.
  277. #[serde(default)]
  278. pub files: HashMap<PathBuf, PathBuf>,
  279. }
  280. /// Configuration for Debian (.deb) bundles.
  281. ///
  282. /// See more: <https://tauri.app/v1/api/config#debconfig>
  283. #[skip_serializing_none]
  284. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  285. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  286. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  287. pub struct DebConfig {
  288. /// The list of deb dependencies your application relies on.
  289. pub depends: Option<Vec<String>>,
  290. /// The list of dependencies the package provides.
  291. pub provides: Option<Vec<String>>,
  292. /// The list of package conflicts.
  293. pub conflicts: Option<Vec<String>>,
  294. /// The list of package replaces.
  295. pub replaces: Option<Vec<String>>,
  296. /// The files to include on the package.
  297. #[serde(default)]
  298. pub files: HashMap<PathBuf, PathBuf>,
  299. /// Define the section in Debian Control file. See : https://www.debian.org/doc/debian-policy/ch-archive.html#s-subsections
  300. pub section: Option<String>,
  301. /// Change the priority of the Debian Package. By default, it is set to `optional`.
  302. /// Recognized Priorities as of now are : `required`, `important`, `standard`, `optional`, `extra`
  303. pub priority: Option<String>,
  304. /// Path of the uncompressed Changelog file, to be stored at /usr/share/doc/package-name/changelog.gz. See
  305. /// https://www.debian.org/doc/debian-policy/ch-docs.html#changelog-files-and-release-notes
  306. pub changelog: Option<PathBuf>,
  307. /// Path to a custom desktop file Handlebars template.
  308. ///
  309. /// Available variables: `categories`, `comment` (optional), `exec`, `icon` and `name`.
  310. #[serde(alias = "desktop-template")]
  311. pub desktop_template: Option<PathBuf>,
  312. /// Path to script that will be executed before the package is unpacked. See
  313. /// https://www.debian.org/doc/debian-policy/ch-maintainerscripts.html
  314. #[serde(alias = "pre-install-script")]
  315. pub pre_install_script: Option<PathBuf>,
  316. /// Path to script that will be executed after the package is unpacked. See
  317. /// https://www.debian.org/doc/debian-policy/ch-maintainerscripts.html
  318. #[serde(alias = "post-install-script")]
  319. pub post_install_script: Option<PathBuf>,
  320. /// Path to script that will be executed before the package is removed. See
  321. /// https://www.debian.org/doc/debian-policy/ch-maintainerscripts.html
  322. #[serde(alias = "pre-remove-script")]
  323. pub pre_remove_script: Option<PathBuf>,
  324. /// Path to script that will be executed after the package is removed. See
  325. /// https://www.debian.org/doc/debian-policy/ch-maintainerscripts.html
  326. #[serde(alias = "post-remove-script")]
  327. pub post_remove_script: Option<PathBuf>,
  328. }
  329. /// Configuration for Linux bundles.
  330. ///
  331. /// See more: <https://tauri.app/v1/api/config#linuxconfig>
  332. #[skip_serializing_none]
  333. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  334. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  335. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  336. pub struct LinuxConfig {
  337. /// Configuration for the AppImage bundle.
  338. #[serde(default)]
  339. pub appimage: AppImageConfig,
  340. /// Configuration for the Debian bundle.
  341. #[serde(default)]
  342. pub deb: DebConfig,
  343. /// Configuration for the RPM bundle.
  344. #[serde(default)]
  345. pub rpm: RpmConfig,
  346. }
  347. /// Configuration for RPM bundles.
  348. #[skip_serializing_none]
  349. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  350. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  351. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  352. pub struct RpmConfig {
  353. /// The list of RPM dependencies your application relies on.
  354. pub depends: Option<Vec<String>>,
  355. /// The list of RPM dependencies your application provides.
  356. pub provides: Option<Vec<String>>,
  357. /// The list of RPM dependencies your application conflicts with. They must not be present
  358. /// in order for the package to be installed.
  359. pub conflicts: Option<Vec<String>>,
  360. /// The list of RPM dependencies your application supersedes - if this package is installed,
  361. /// packages listed as “obsoletes” will be automatically removed (if they are present).
  362. pub obsoletes: Option<Vec<String>>,
  363. /// The RPM release tag.
  364. #[serde(default = "default_release")]
  365. pub release: String,
  366. /// The RPM epoch.
  367. #[serde(default)]
  368. pub epoch: u32,
  369. /// The files to include on the package.
  370. #[serde(default)]
  371. pub files: HashMap<PathBuf, PathBuf>,
  372. /// Path to a custom desktop file Handlebars template.
  373. ///
  374. /// Available variables: `categories`, `comment` (optional), `exec`, `icon` and `name`.
  375. #[serde(alias = "desktop-template")]
  376. pub desktop_template: Option<PathBuf>,
  377. /// Path to script that will be executed before the package is unpacked. See
  378. /// http://ftp.rpm.org/max-rpm/s1-rpm-inside-scripts.html
  379. #[serde(alias = "pre-install-script")]
  380. pub pre_install_script: Option<PathBuf>,
  381. /// Path to script that will be executed after the package is unpacked. See
  382. /// http://ftp.rpm.org/max-rpm/s1-rpm-inside-scripts.html
  383. #[serde(alias = "post-install-script")]
  384. pub post_install_script: Option<PathBuf>,
  385. /// Path to script that will be executed before the package is removed. See
  386. /// http://ftp.rpm.org/max-rpm/s1-rpm-inside-scripts.html
  387. #[serde(alias = "pre-remove-script")]
  388. pub pre_remove_script: Option<PathBuf>,
  389. /// Path to script that will be executed after the package is removed. See
  390. /// http://ftp.rpm.org/max-rpm/s1-rpm-inside-scripts.html
  391. #[serde(alias = "post-remove-script")]
  392. pub post_remove_script: Option<PathBuf>,
  393. }
  394. impl Default for RpmConfig {
  395. fn default() -> Self {
  396. Self {
  397. depends: None,
  398. provides: None,
  399. conflicts: None,
  400. obsoletes: None,
  401. release: default_release(),
  402. epoch: 0,
  403. files: Default::default(),
  404. desktop_template: None,
  405. pre_install_script: None,
  406. post_install_script: None,
  407. pre_remove_script: None,
  408. post_remove_script: None,
  409. }
  410. }
  411. }
  412. fn default_release() -> String {
  413. "1".into()
  414. }
  415. /// Position coordinates struct.
  416. #[derive(Default, Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  417. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  418. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  419. pub struct Position {
  420. /// X coordinate.
  421. pub x: u32,
  422. /// Y coordinate.
  423. pub y: u32,
  424. }
  425. /// Size of the window.
  426. #[derive(Default, Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  427. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  428. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  429. pub struct Size {
  430. /// Width of the window.
  431. pub width: u32,
  432. /// Height of the window.
  433. pub height: u32,
  434. }
  435. /// Configuration for Apple Disk Image (.dmg) bundles.
  436. ///
  437. /// See more: <https://tauri.app/v1/api/config#dmgconfig>
  438. #[skip_serializing_none]
  439. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  440. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  441. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  442. pub struct DmgConfig {
  443. /// Image to use as the background in dmg file. Accepted formats: `png`/`jpg`/`gif`.
  444. pub background: Option<PathBuf>,
  445. /// Position of volume window on screen.
  446. pub window_position: Option<Position>,
  447. /// Size of volume window.
  448. #[serde(default = "dmg_window_size", alias = "window-size")]
  449. pub window_size: Size,
  450. /// Position of app file on window.
  451. #[serde(default = "dmg_app_position", alias = "app-position")]
  452. pub app_position: Position,
  453. /// Position of application folder on window.
  454. #[serde(
  455. default = "dmg_application_folder_position",
  456. alias = "application-folder-position"
  457. )]
  458. pub application_folder_position: Position,
  459. }
  460. impl Default for DmgConfig {
  461. fn default() -> Self {
  462. Self {
  463. background: None,
  464. window_position: None,
  465. window_size: dmg_window_size(),
  466. app_position: dmg_app_position(),
  467. application_folder_position: dmg_application_folder_position(),
  468. }
  469. }
  470. }
  471. fn dmg_window_size() -> Size {
  472. Size {
  473. width: 660,
  474. height: 400,
  475. }
  476. }
  477. fn dmg_app_position() -> Position {
  478. Position { x: 180, y: 170 }
  479. }
  480. fn dmg_application_folder_position() -> Position {
  481. Position { x: 480, y: 170 }
  482. }
  483. fn de_minimum_system_version<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
  484. where
  485. D: Deserializer<'de>,
  486. {
  487. let version = Option::<String>::deserialize(deserializer)?;
  488. match version {
  489. Some(v) if v.is_empty() => Ok(minimum_system_version()),
  490. e => Ok(e),
  491. }
  492. }
  493. /// Configuration for the macOS bundles.
  494. ///
  495. /// See more: <https://tauri.app/v1/api/config#macconfig>
  496. #[skip_serializing_none]
  497. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  498. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  499. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  500. pub struct MacConfig {
  501. /// A list of strings indicating any macOS X frameworks that need to be bundled with the application.
  502. ///
  503. /// If a name is used, ".framework" must be omitted and it will look for standard install locations. You may also use a path to a specific framework.
  504. pub frameworks: Option<Vec<String>>,
  505. /// The files to include in the application relative to the Contents directory.
  506. #[serde(default)]
  507. pub files: HashMap<PathBuf, PathBuf>,
  508. /// A version string indicating the minimum macOS X version that the bundled application supports. Defaults to `10.13`.
  509. ///
  510. /// Setting it to `null` completely removes the `LSMinimumSystemVersion` field on the bundle's `Info.plist`
  511. /// and the `MACOSX_DEPLOYMENT_TARGET` environment variable.
  512. ///
  513. /// An empty string is considered an invalid value so the default value is used.
  514. #[serde(
  515. deserialize_with = "de_minimum_system_version",
  516. default = "minimum_system_version",
  517. alias = "minimum-system-version"
  518. )]
  519. pub minimum_system_version: Option<String>,
  520. /// Allows your application to communicate with the outside world.
  521. /// It should be a lowercase, without port and protocol domain name.
  522. #[serde(alias = "exception-domain")]
  523. pub exception_domain: Option<String>,
  524. /// Identity to use for code signing.
  525. #[serde(alias = "signing-identity")]
  526. pub signing_identity: Option<String>,
  527. /// Whether the codesign should enable [hardened runtime] (for executables) or not.
  528. ///
  529. /// [hardened runtime]: <https://developer.apple.com/documentation/security/hardened_runtime>
  530. #[serde(alias = "hardened-runtime", default = "default_true")]
  531. pub hardened_runtime: bool,
  532. /// Provider short name for notarization.
  533. #[serde(alias = "provider-short-name")]
  534. pub provider_short_name: Option<String>,
  535. /// Path to the entitlements file.
  536. pub entitlements: Option<String>,
  537. /// DMG-specific settings.
  538. #[serde(default)]
  539. pub dmg: DmgConfig,
  540. }
  541. impl Default for MacConfig {
  542. fn default() -> Self {
  543. Self {
  544. frameworks: None,
  545. files: HashMap::new(),
  546. minimum_system_version: minimum_system_version(),
  547. exception_domain: None,
  548. signing_identity: None,
  549. hardened_runtime: true,
  550. provider_short_name: None,
  551. entitlements: None,
  552. dmg: Default::default(),
  553. }
  554. }
  555. }
  556. fn minimum_system_version() -> Option<String> {
  557. Some("10.13".into())
  558. }
  559. /// Configuration for a target language for the WiX build.
  560. ///
  561. /// See more: <https://tauri.app/v1/api/config#wixlanguageconfig>
  562. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  563. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  564. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  565. pub struct WixLanguageConfig {
  566. /// The path to a locale (`.wxl`) file. See <https://wixtoolset.org/documentation/manual/v3/howtos/ui_and_localization/build_a_localized_version.html>.
  567. #[serde(alias = "locale-path")]
  568. pub locale_path: Option<String>,
  569. }
  570. /// The languages to build using WiX.
  571. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  572. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  573. #[serde(untagged)]
  574. pub enum WixLanguage {
  575. /// A single language to build, without configuration.
  576. One(String),
  577. /// A list of languages to build, without configuration.
  578. List(Vec<String>),
  579. /// A map of languages and its configuration.
  580. Localized(HashMap<String, WixLanguageConfig>),
  581. }
  582. impl Default for WixLanguage {
  583. fn default() -> Self {
  584. Self::One("en-US".into())
  585. }
  586. }
  587. /// Configuration for the MSI bundle using WiX.
  588. ///
  589. /// See more: <https://tauri.app/v1/api/config#wixconfig>
  590. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  591. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  592. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  593. pub struct WixConfig {
  594. /// The installer languages to build. See <https://docs.microsoft.com/en-us/windows/win32/msi/localizing-the-error-and-actiontext-tables>.
  595. #[serde(default)]
  596. pub language: WixLanguage,
  597. /// A custom .wxs template to use.
  598. pub template: Option<PathBuf>,
  599. /// A list of paths to .wxs files with WiX fragments to use.
  600. #[serde(default, alias = "fragment-paths")]
  601. pub fragment_paths: Vec<PathBuf>,
  602. /// The ComponentGroup element ids you want to reference from the fragments.
  603. #[serde(default, alias = "component-group-refs")]
  604. pub component_group_refs: Vec<String>,
  605. /// The Component element ids you want to reference from the fragments.
  606. #[serde(default, alias = "component-refs")]
  607. pub component_refs: Vec<String>,
  608. /// The FeatureGroup element ids you want to reference from the fragments.
  609. #[serde(default, alias = "feature-group-refs")]
  610. pub feature_group_refs: Vec<String>,
  611. /// The Feature element ids you want to reference from the fragments.
  612. #[serde(default, alias = "feature-refs")]
  613. pub feature_refs: Vec<String>,
  614. /// The Merge element ids you want to reference from the fragments.
  615. #[serde(default, alias = "merge-refs")]
  616. pub merge_refs: Vec<String>,
  617. /// Create an elevated update task within Windows Task Scheduler.
  618. #[serde(default, alias = "enable-elevated-update-task")]
  619. pub enable_elevated_update_task: bool,
  620. /// Path to a bitmap file to use as the installation user interface banner.
  621. /// This bitmap will appear at the top of all but the first page of the installer.
  622. ///
  623. /// The required dimensions are 493px × 58px.
  624. #[serde(alias = "banner-path")]
  625. pub banner_path: Option<PathBuf>,
  626. /// Path to a bitmap file to use on the installation user interface dialogs.
  627. /// It is used on the welcome and completion dialogs.
  628. /// The required dimensions are 493px × 312px.
  629. #[serde(alias = "dialog-image-path")]
  630. pub dialog_image_path: Option<PathBuf>,
  631. }
  632. /// Compression algorithms used in the NSIS installer.
  633. ///
  634. /// See <https://nsis.sourceforge.io/Reference/SetCompressor>
  635. #[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
  636. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  637. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  638. pub enum NsisCompression {
  639. /// ZLIB uses the deflate algorithm, it is a quick and simple method. With the default compression level it uses about 300 KB of memory.
  640. Zlib,
  641. /// BZIP2 usually gives better compression ratios than ZLIB, but it is a bit slower and uses more memory. With the default compression level it uses about 4 MB of memory.
  642. Bzip2,
  643. /// LZMA (default) is a new compression method that gives very good compression ratios. The decompression speed is high (10-20 MB/s on a 2 GHz CPU), the compression speed is lower. The memory size that will be used for decompression is the dictionary size plus a few KBs, the default is 8 MB.
  644. Lzma,
  645. }
  646. /// Configuration for the Installer bundle using NSIS.
  647. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  648. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  649. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  650. pub struct NsisConfig {
  651. /// A custom .nsi template to use.
  652. pub template: Option<PathBuf>,
  653. /// The path to a bitmap file to display on the header of installers pages.
  654. ///
  655. /// The recommended dimensions are 150px x 57px.
  656. #[serde(alias = "header-image")]
  657. pub header_image: Option<PathBuf>,
  658. /// The path to a bitmap file for the Welcome page and the Finish page.
  659. ///
  660. /// The recommended dimensions are 164px x 314px.
  661. #[serde(alias = "sidebar-image")]
  662. pub sidebar_image: Option<PathBuf>,
  663. /// The path to an icon file used as the installer icon.
  664. #[serde(alias = "install-icon")]
  665. pub installer_icon: Option<PathBuf>,
  666. /// Whether the installation will be for all users or just the current user.
  667. #[serde(default, alias = "install-mode")]
  668. pub install_mode: NSISInstallerMode,
  669. /// A list of installer languages.
  670. /// By default the OS language is used. If the OS language is not in the list of languages, the first language will be used.
  671. /// To allow the user to select the language, set `display_language_selector` to `true`.
  672. ///
  673. /// See <https://github.com/kichik/nsis/tree/9465c08046f00ccb6eda985abbdbf52c275c6c4d/Contrib/Language%20files> for the complete list of languages.
  674. pub languages: Option<Vec<String>>,
  675. /// A key-value pair where the key is the language and the
  676. /// value is the path to a custom `.nsh` file that holds the translated text for tauri's custom messages.
  677. ///
  678. /// See <https://github.com/tauri-apps/tauri/blob/dev/tooling/bundler/src/bundle/windows/templates/nsis-languages/English.nsh> for an example `.nsh` file.
  679. ///
  680. /// **Note**: the key must be a valid NSIS language and it must be added to [`NsisConfig`] languages array,
  681. pub custom_language_files: Option<HashMap<String, PathBuf>>,
  682. /// Whether to display a language selector dialog before the installer and uninstaller windows are rendered or not.
  683. /// By default the OS language is selected, with a fallback to the first language in the `languages` array.
  684. #[serde(default, alias = "display-language-selector")]
  685. pub display_language_selector: bool,
  686. /// Set the compression algorithm used to compress files in the installer.
  687. ///
  688. /// See <https://nsis.sourceforge.io/Reference/SetCompressor>
  689. pub compression: Option<NsisCompression>,
  690. /// A path to a `.nsh` file that contains special NSIS macros to be hooked into the
  691. /// main installer.nsi script.
  692. ///
  693. /// Supported hooks are:
  694. /// - `NSIS_HOOK_PREINSTALL`: This hook runs before copying files, setting registry key values and creating shortcuts.
  695. /// - `NSIS_HOOK_POSTINSTALL`: This hook runs after the installer has finished copying all files, setting the registry keys and created shortcuts.
  696. /// - `NSIS_HOOK_PREUNINSTALL`: This hook runs before removing any files, registry keys and shortcuts.
  697. /// - `NSIS_HOOK_POSTUNINSTALL`: This hook runs after files, registry keys and shortcuts have been removed.
  698. ///
  699. ///
  700. /// ### Example
  701. ///
  702. /// ```nsh
  703. /// !define NSIS_HOOK_PREINSTALL "NSIS_HOOK_PREINSTALL_"
  704. /// !macro NSIS_HOOK_PREINSTALL_
  705. /// MessageBox MB_OK "PreInstall"
  706. /// !macroend
  707. ///
  708. /// !define NSIS_HOOK_POSTINSTALL "NSIS_HOOK_POSTINSTALL_"
  709. /// !macro NSIS_HOOK_POSTINSTALL_
  710. /// MessageBox MB_OK "PostInstall"
  711. /// !macroend
  712. ///
  713. /// !define NSIS_HOOK_PREUNINSTALL "NSIS_HOOK_PREUNINSTALL_"
  714. /// !macro NSIS_HOOK_PREUNINSTALL_
  715. /// MessageBox MB_OK "PreUnInstall"
  716. /// !macroend
  717. ///
  718. /// !define NSIS_HOOK_POSTUNINSTALL "NSIS_HOOK_POSTUNINSTALL_"
  719. /// !macro NSIS_HOOK_POSTUNINSTALL_
  720. /// MessageBox MB_OK "PostUninstall"
  721. /// !macroend
  722. ///
  723. /// ```
  724. #[serde(alias = "installer-hooks")]
  725. pub installer_hooks: Option<PathBuf>,
  726. }
  727. /// Install Modes for the NSIS installer.
  728. #[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
  729. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  730. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  731. pub enum NSISInstallerMode {
  732. /// Default mode for the installer.
  733. ///
  734. /// Install the app by default in a directory that doesn't require Administrator access.
  735. ///
  736. /// Installer metadata will be saved under the `HKCU` registry path.
  737. CurrentUser,
  738. /// Install the app by default in the `Program Files` folder directory requires Administrator
  739. /// access for the installation.
  740. ///
  741. /// Installer metadata will be saved under the `HKLM` registry path.
  742. PerMachine,
  743. /// Combines both modes and allows the user to choose at install time
  744. /// whether to install for the current user or per machine. Note that this mode
  745. /// will require Administrator access even if the user wants to install it for the current user only.
  746. ///
  747. /// Installer metadata will be saved under the `HKLM` or `HKCU` registry path based on the user's choice.
  748. Both,
  749. }
  750. impl Default for NSISInstallerMode {
  751. fn default() -> Self {
  752. Self::CurrentUser
  753. }
  754. }
  755. /// Install modes for the Webview2 runtime.
  756. /// Note that for the updater bundle [`Self::DownloadBootstrapper`] is used.
  757. ///
  758. /// For more information see <https://tauri.app/v1/guides/building/windows>.
  759. #[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
  760. #[serde(tag = "type", rename_all = "camelCase", deny_unknown_fields)]
  761. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  762. pub enum WebviewInstallMode {
  763. /// Do not install the Webview2 as part of the Windows Installer.
  764. Skip,
  765. /// Download the bootstrapper and run it.
  766. /// Requires an internet connection.
  767. /// Results in a smaller installer size, but is not recommended on Windows 7.
  768. DownloadBootstrapper {
  769. /// Instructs the installer to run the bootstrapper in silent mode. Defaults to `true`.
  770. #[serde(default = "default_true")]
  771. silent: bool,
  772. },
  773. /// Embed the bootstrapper and run it.
  774. /// Requires an internet connection.
  775. /// Increases the installer size by around 1.8MB, but offers better support on Windows 7.
  776. EmbedBootstrapper {
  777. /// Instructs the installer to run the bootstrapper in silent mode. Defaults to `true`.
  778. #[serde(default = "default_true")]
  779. silent: bool,
  780. },
  781. /// Embed the offline installer and run it.
  782. /// Does not require an internet connection.
  783. /// Increases the installer size by around 127MB.
  784. OfflineInstaller {
  785. /// Instructs the installer to run the installer in silent mode. Defaults to `true`.
  786. #[serde(default = "default_true")]
  787. silent: bool,
  788. },
  789. /// Embed a fixed webview2 version and use it at runtime.
  790. /// Increases the installer size by around 180MB.
  791. FixedRuntime {
  792. /// The path to the fixed runtime to use.
  793. ///
  794. /// The fixed version can be downloaded [on the official website](https://developer.microsoft.com/en-us/microsoft-edge/webview2/#download-section).
  795. /// The `.cab` file must be extracted to a folder and this folder path must be defined on this field.
  796. path: PathBuf,
  797. },
  798. }
  799. impl Default for WebviewInstallMode {
  800. fn default() -> Self {
  801. Self::DownloadBootstrapper { silent: true }
  802. }
  803. }
  804. /// Windows bundler configuration.
  805. ///
  806. /// See more: <https://tauri.app/v1/api/config#windowsconfig>
  807. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  808. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  809. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  810. pub struct WindowsConfig {
  811. /// Specifies the file digest algorithm to use for creating file signatures.
  812. /// Required for code signing. SHA-256 is recommended.
  813. #[serde(alias = "digest-algorithm")]
  814. pub digest_algorithm: Option<String>,
  815. /// Specifies the SHA1 hash of the signing certificate.
  816. #[serde(alias = "certificate-thumbprint")]
  817. pub certificate_thumbprint: Option<String>,
  818. /// Server to use during timestamping.
  819. #[serde(alias = "timestamp-url")]
  820. pub timestamp_url: Option<String>,
  821. /// Whether to use Time-Stamp Protocol (TSP, a.k.a. RFC 3161) for the timestamp server. Your code signing provider may
  822. /// use a TSP timestamp server, like e.g. SSL.com does. If so, enable TSP by setting to true.
  823. #[serde(default)]
  824. pub tsp: bool,
  825. /// The installation mode for the Webview2 runtime.
  826. #[serde(default, alias = "webview-install-mode")]
  827. pub webview_install_mode: WebviewInstallMode,
  828. /// Path to the webview fixed runtime to use. Overwrites [`Self::webview_install_mode`] if set.
  829. ///
  830. /// Will be removed in v2, prefer the [`Self::webview_install_mode`] option.
  831. ///
  832. /// The fixed version can be downloaded [on the official website](https://developer.microsoft.com/en-us/microsoft-edge/webview2/#download-section).
  833. /// The `.cab` file must be extracted to a folder and this folder path must be defined on this field.
  834. #[serde(alias = "webview-fixed-runtime-path")]
  835. pub webview_fixed_runtime_path: Option<PathBuf>,
  836. /// Validates a second app installation, blocking the user from installing an older version if set to `false`.
  837. ///
  838. /// For instance, if `1.2.1` is installed, the user won't be able to install app version `1.2.0` or `1.1.5`.
  839. ///
  840. /// The default value of this flag is `true`.
  841. #[serde(default = "default_true", alias = "allow-downgrades")]
  842. pub allow_downgrades: bool,
  843. /// Configuration for the MSI generated with WiX.
  844. pub wix: Option<WixConfig>,
  845. /// Configuration for the installer generated with NSIS.
  846. pub nsis: Option<NsisConfig>,
  847. /// Specify a custom command to sign the binaries.
  848. /// This command needs to have a `%1` in it which is just a placeholder for the binary path,
  849. /// which we will detect and replace before calling the command.
  850. ///
  851. /// Example:
  852. /// ```text
  853. /// sign-cli --arg1 --arg2 %1
  854. /// ```
  855. ///
  856. /// By Default we use `signtool.exe` which can be found only on Windows so
  857. /// if you are on another platform and want to cross-compile and sign you will
  858. /// need to use another tool like `osslsigncode`.
  859. #[serde(alias = "sign-command")]
  860. pub sign_command: Option<String>,
  861. }
  862. impl Default for WindowsConfig {
  863. fn default() -> Self {
  864. Self {
  865. digest_algorithm: None,
  866. certificate_thumbprint: None,
  867. timestamp_url: None,
  868. tsp: false,
  869. webview_install_mode: Default::default(),
  870. webview_fixed_runtime_path: None,
  871. allow_downgrades: true,
  872. wix: None,
  873. nsis: None,
  874. sign_command: None,
  875. }
  876. }
  877. }
  878. /// macOS-only. Corresponds to CFBundleTypeRole
  879. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  880. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  881. pub enum BundleTypeRole {
  882. /// CFBundleTypeRole.Editor. Files can be read and edited.
  883. #[default]
  884. Editor,
  885. /// CFBundleTypeRole.Viewer. Files can be read.
  886. Viewer,
  887. /// CFBundleTypeRole.Shell
  888. Shell,
  889. /// CFBundleTypeRole.QLGenerator
  890. QLGenerator,
  891. /// CFBundleTypeRole.None
  892. None,
  893. }
  894. impl Display for BundleTypeRole {
  895. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  896. match self {
  897. Self::Editor => write!(f, "Editor"),
  898. Self::Viewer => write!(f, "Viewer"),
  899. Self::Shell => write!(f, "Shell"),
  900. Self::QLGenerator => write!(f, "QLGenerator"),
  901. Self::None => write!(f, "None"),
  902. }
  903. }
  904. }
  905. /// An extension for a [`FileAssociation`].
  906. ///
  907. /// A leading `.` is automatically stripped.
  908. #[derive(Debug, PartialEq, Eq, Clone, Serialize)]
  909. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  910. pub struct AssociationExt(pub String);
  911. impl fmt::Display for AssociationExt {
  912. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  913. write!(f, "{}", self.0)
  914. }
  915. }
  916. impl<'d> serde::Deserialize<'d> for AssociationExt {
  917. fn deserialize<D: Deserializer<'d>>(deserializer: D) -> Result<Self, D::Error> {
  918. let ext = String::deserialize(deserializer)?;
  919. if let Some(ext) = ext.strip_prefix('.') {
  920. Ok(AssociationExt(ext.into()))
  921. } else {
  922. Ok(AssociationExt(ext))
  923. }
  924. }
  925. }
  926. /// File association
  927. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  928. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  929. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  930. pub struct FileAssociation {
  931. /// File extensions to associate with this app. e.g. 'png'
  932. pub ext: Vec<AssociationExt>,
  933. /// The name. Maps to `CFBundleTypeName` on macOS. Default to `ext[0]`
  934. pub name: Option<String>,
  935. /// The association description. Windows-only. It is displayed on the `Type` column on Windows Explorer.
  936. pub description: Option<String>,
  937. /// The app's role with respect to the type. Maps to `CFBundleTypeRole` on macOS.
  938. #[serde(default)]
  939. pub role: BundleTypeRole,
  940. /// The mime-type e.g. 'image/png' or 'text/plain'. Linux-only.
  941. #[serde(alias = "mime-type")]
  942. pub mime_type: Option<String>,
  943. }
  944. /// File association
  945. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  946. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  947. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  948. pub struct DeepLinkProtocol {
  949. /// URL schemes to associate with this app without `://`. For example `my-app`
  950. pub schemes: Vec<String>,
  951. /// The protocol name. **macOS-only** and maps to `CFBundleTypeName`. Defaults to `<bundle-id>.<schemes[0]>`
  952. pub name: Option<String>,
  953. /// The app's role for these schemes. **macOS-only** and maps to `CFBundleTypeRole`.
  954. #[serde(default)]
  955. pub role: BundleTypeRole,
  956. }
  957. /// Definition for bundle resources.
  958. /// Can be either a list of paths to include or a map of source to target paths.
  959. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  960. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  961. #[serde(rename_all = "camelCase", deny_unknown_fields, untagged)]
  962. pub enum BundleResources {
  963. /// A list of paths to include.
  964. List(Vec<String>),
  965. /// A map of source to target paths.
  966. Map(HashMap<String, String>),
  967. }
  968. impl BundleResources {
  969. /// Adds a path to the resource collection.
  970. pub fn push(&mut self, path: impl Into<String>) {
  971. match self {
  972. Self::List(l) => l.push(path.into()),
  973. Self::Map(l) => {
  974. let path = path.into();
  975. l.insert(path.clone(), path);
  976. }
  977. }
  978. }
  979. }
  980. /// Configuration for tauri-bundler.
  981. ///
  982. /// See more: <https://tauri.app/v1/api/config#bundleconfig>
  983. #[skip_serializing_none]
  984. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  985. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  986. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  987. pub struct BundleConfig {
  988. /// Whether Tauri should bundle your application or just output the executable.
  989. #[serde(default)]
  990. pub active: bool,
  991. /// The bundle targets, currently supports ["deb", "rpm", "appimage", "nsis", "msi", "app", "dmg", "updater"] or "all".
  992. #[serde(default)]
  993. pub targets: BundleTarget,
  994. /// The application's publisher. Defaults to the second element in the identifier string.
  995. /// Currently maps to the Manufacturer property of the Windows Installer.
  996. pub publisher: Option<String>,
  997. /// A url to the home page of your application. If unset, will
  998. /// fallback to `homepage` defined in `Cargo.toml`.
  999. ///
  1000. /// Supported bundle targets: `deb`, `rpm`, `nsis` and `msi`.
  1001. pub homepage: Option<String>,
  1002. /// The app's icons
  1003. #[serde(default)]
  1004. pub icon: Vec<String>,
  1005. /// App resources to bundle.
  1006. /// Each resource is a path to a file or directory.
  1007. /// Glob patterns are supported.
  1008. pub resources: Option<BundleResources>,
  1009. /// A copyright string associated with your application.
  1010. pub copyright: Option<String>,
  1011. /// The package's license identifier to be included in the appropriate bundles.
  1012. /// If not set, defaults to the license from the Cargo.toml file.
  1013. pub license: Option<String>,
  1014. /// The path to the license file to be included in the appropriate bundles.
  1015. #[serde(alias = "license-file")]
  1016. pub license_file: Option<PathBuf>,
  1017. /// The application kind.
  1018. ///
  1019. /// Should be one of the following:
  1020. /// Business, DeveloperTool, Education, Entertainment, Finance, Game, ActionGame, AdventureGame, ArcadeGame, BoardGame, CardGame, CasinoGame, DiceGame, EducationalGame, FamilyGame, KidsGame, MusicGame, PuzzleGame, RacingGame, RolePlayingGame, SimulationGame, SportsGame, StrategyGame, TriviaGame, WordGame, GraphicsAndDesign, HealthcareAndFitness, Lifestyle, Medical, Music, News, Photography, Productivity, Reference, SocialNetworking, Sports, Travel, Utility, Video, Weather.
  1021. pub category: Option<String>,
  1022. /// File associations to application.
  1023. pub file_associations: Option<Vec<FileAssociation>>,
  1024. /// A short description of your application.
  1025. #[serde(alias = "short-description")]
  1026. pub short_description: Option<String>,
  1027. /// A longer, multi-line description of the application.
  1028. #[serde(alias = "long-description")]
  1029. pub long_description: Option<String>,
  1030. /// A list of—either absolute or relative—paths to binaries to embed with your application.
  1031. ///
  1032. /// Note that Tauri will look for system-specific binaries following the pattern "binary-name{-target-triple}{.system-extension}".
  1033. ///
  1034. /// E.g. for the external binary "my-binary", Tauri looks for:
  1035. ///
  1036. /// - "my-binary-x86_64-pc-windows-msvc.exe" for Windows
  1037. /// - "my-binary-x86_64-apple-darwin" for macOS
  1038. /// - "my-binary-x86_64-unknown-linux-gnu" for Linux
  1039. ///
  1040. /// so don't forget to provide binaries for all targeted platforms.
  1041. #[serde(alias = "external-bin")]
  1042. pub external_bin: Option<Vec<String>>,
  1043. /// Configuration for the Windows bundles.
  1044. #[serde(default)]
  1045. pub windows: WindowsConfig,
  1046. /// Configuration for the Linux bundles.
  1047. #[serde(default)]
  1048. pub linux: LinuxConfig,
  1049. /// Configuration for the macOS bundles.
  1050. #[serde(rename = "macOS", alias = "macos", default)]
  1051. pub macos: MacConfig,
  1052. /// iOS configuration.
  1053. #[serde(rename = "iOS", alias = "ios", default)]
  1054. pub ios: IosConfig,
  1055. /// Android configuration.
  1056. #[serde(default)]
  1057. pub android: AndroidConfig,
  1058. }
  1059. /// a tuple struct of RGBA colors. Each value has minimum of 0 and maximum of 255.
  1060. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize, Default)]
  1061. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1062. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1063. pub struct Color(pub u8, pub u8, pub u8, pub u8);
  1064. impl From<Color> for (u8, u8, u8, u8) {
  1065. fn from(value: Color) -> Self {
  1066. (value.0, value.1, value.2, value.3)
  1067. }
  1068. }
  1069. /// The window effects configuration object
  1070. #[skip_serializing_none]
  1071. #[derive(Debug, PartialEq, Clone, Deserialize, Serialize, Default)]
  1072. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1073. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1074. pub struct WindowEffectsConfig {
  1075. /// List of Window effects to apply to the Window.
  1076. /// Conflicting effects will apply the first one and ignore the rest.
  1077. pub effects: Vec<WindowEffect>,
  1078. /// Window effect state **macOS Only**
  1079. pub state: Option<WindowEffectState>,
  1080. /// Window effect corner radius **macOS Only**
  1081. pub radius: Option<f64>,
  1082. /// Window effect color. Affects [`WindowEffect::Blur`] and [`WindowEffect::Acrylic`] only
  1083. /// on Windows 10 v1903+. Doesn't have any effect on Windows 7 or Windows 11.
  1084. pub color: Option<Color>,
  1085. }
  1086. /// The window configuration object.
  1087. ///
  1088. /// See more: <https://tauri.app/v1/api/config#windowconfig>
  1089. #[skip_serializing_none]
  1090. #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
  1091. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1092. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1093. pub struct WindowConfig {
  1094. /// The window identifier. It must be alphanumeric.
  1095. #[serde(default = "default_window_label")]
  1096. pub label: String,
  1097. /// The window webview URL.
  1098. #[serde(default)]
  1099. pub url: WebviewUrl,
  1100. /// The user agent for the webview
  1101. #[serde(alias = "user-agent")]
  1102. pub user_agent: Option<String>,
  1103. /// Whether the drag and drop is enabled or not on the webview. By default it is enabled.
  1104. ///
  1105. /// Disabling it is required to use HTML5 drag and drop on the frontend on Windows.
  1106. #[serde(default = "default_true", alias = "drag-drop-enabled")]
  1107. pub drag_drop_enabled: bool,
  1108. /// Whether or not the window starts centered or not.
  1109. #[serde(default)]
  1110. pub center: bool,
  1111. /// The horizontal position of the window's top left corner
  1112. pub x: Option<f64>,
  1113. /// The vertical position of the window's top left corner
  1114. pub y: Option<f64>,
  1115. /// The window width.
  1116. #[serde(default = "default_width")]
  1117. pub width: f64,
  1118. /// The window height.
  1119. #[serde(default = "default_height")]
  1120. pub height: f64,
  1121. /// The min window width.
  1122. #[serde(alias = "min-width")]
  1123. pub min_width: Option<f64>,
  1124. /// The min window height.
  1125. #[serde(alias = "min-height")]
  1126. pub min_height: Option<f64>,
  1127. /// The max window width.
  1128. #[serde(alias = "max-width")]
  1129. pub max_width: Option<f64>,
  1130. /// The max window height.
  1131. #[serde(alias = "max-height")]
  1132. pub max_height: Option<f64>,
  1133. /// Whether the window is resizable or not. When resizable is set to false, native window's maximize button is automatically disabled.
  1134. #[serde(default = "default_true")]
  1135. pub resizable: bool,
  1136. /// Whether the window's native maximize button is enabled or not.
  1137. /// If resizable is set to false, this setting is ignored.
  1138. ///
  1139. /// ## Platform-specific
  1140. ///
  1141. /// - **macOS:** Disables the "zoom" button in the window titlebar, which is also used to enter fullscreen mode.
  1142. /// - **Linux / iOS / Android:** Unsupported.
  1143. #[serde(default = "default_true")]
  1144. pub maximizable: bool,
  1145. /// Whether the window's native minimize button is enabled or not.
  1146. ///
  1147. /// ## Platform-specific
  1148. ///
  1149. /// - **Linux / iOS / Android:** Unsupported.
  1150. #[serde(default = "default_true")]
  1151. pub minimizable: bool,
  1152. /// Whether the window's native close button is enabled or not.
  1153. ///
  1154. /// ## Platform-specific
  1155. ///
  1156. /// - **Linux:** "GTK+ will do its best to convince the window manager not to show a close button.
  1157. /// Depending on the system, this function may not have any effect when called on a window that is already visible"
  1158. /// - **iOS / Android:** Unsupported.
  1159. #[serde(default = "default_true")]
  1160. pub closable: bool,
  1161. /// The window title.
  1162. #[serde(default = "default_title")]
  1163. pub title: String,
  1164. /// Whether the window starts as fullscreen or not.
  1165. #[serde(default)]
  1166. pub fullscreen: bool,
  1167. /// Whether the window will be initially focused or not.
  1168. #[serde(default = "default_true")]
  1169. pub focus: bool,
  1170. /// Whether the window is transparent or not.
  1171. ///
  1172. /// Note that on `macOS` this requires the `macos-private-api` feature flag, enabled under `tauri > macOSPrivateApi`.
  1173. /// WARNING: Using private APIs on `macOS` prevents your application from being accepted to the `App Store`.
  1174. #[serde(default)]
  1175. pub transparent: bool,
  1176. /// Whether the window is maximized or not.
  1177. #[serde(default)]
  1178. pub maximized: bool,
  1179. /// Whether the window is visible or not.
  1180. #[serde(default = "default_true")]
  1181. pub visible: bool,
  1182. /// Whether the window should have borders and bars.
  1183. #[serde(default = "default_true")]
  1184. pub decorations: bool,
  1185. /// Whether the window should always be below other windows.
  1186. #[serde(default, alias = "always-on-bottom")]
  1187. pub always_on_bottom: bool,
  1188. /// Whether the window should always be on top of other windows.
  1189. #[serde(default, alias = "always-on-top")]
  1190. pub always_on_top: bool,
  1191. /// Whether the window should be visible on all workspaces or virtual desktops.
  1192. ///
  1193. /// ## Platform-specific
  1194. ///
  1195. /// - **Windows / iOS / Android:** Unsupported.
  1196. #[serde(default, alias = "visible-on-all-workspaces")]
  1197. pub visible_on_all_workspaces: bool,
  1198. /// Prevents the window contents from being captured by other apps.
  1199. #[serde(default, alias = "content-protected")]
  1200. pub content_protected: bool,
  1201. /// If `true`, hides the window icon from the taskbar on Windows and Linux.
  1202. #[serde(default, alias = "skip-taskbar")]
  1203. pub skip_taskbar: bool,
  1204. /// The initial window theme. Defaults to the system theme. Only implemented on Windows and macOS 10.14+.
  1205. pub theme: Option<crate::Theme>,
  1206. /// The style of the macOS title bar.
  1207. #[serde(default, alias = "title-bar-style")]
  1208. pub title_bar_style: TitleBarStyle,
  1209. /// If `true`, sets the window title to be hidden on macOS.
  1210. #[serde(default, alias = "hidden-title")]
  1211. pub hidden_title: bool,
  1212. /// Whether clicking an inactive window also clicks through to the webview on macOS.
  1213. #[serde(default, alias = "accept-first-mouse")]
  1214. pub accept_first_mouse: bool,
  1215. /// Defines the window [tabbing identifier] for macOS.
  1216. ///
  1217. /// Windows with matching tabbing identifiers will be grouped together.
  1218. /// If the tabbing identifier is not set, automatic tabbing will be disabled.
  1219. ///
  1220. /// [tabbing identifier]: <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier>
  1221. #[serde(default, alias = "tabbing-identifier")]
  1222. pub tabbing_identifier: Option<String>,
  1223. /// Defines additional browser arguments on Windows. By default wry passes `--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection`
  1224. /// so if you use this method, you also need to disable these components by yourself if you want.
  1225. #[serde(default, alias = "additional-browser-args")]
  1226. pub additional_browser_args: Option<String>,
  1227. /// Whether or not the window has shadow.
  1228. ///
  1229. /// ## Platform-specific
  1230. ///
  1231. /// - **Windows:**
  1232. /// - `false` has no effect on decorated window, shadow are always ON.
  1233. /// - `true` will make ndecorated window have a 1px white border,
  1234. /// and on Windows 11, it will have a rounded corners.
  1235. /// - **Linux:** Unsupported.
  1236. #[serde(default = "default_true")]
  1237. pub shadow: bool,
  1238. /// Window effects.
  1239. ///
  1240. /// Requires the window to be transparent.
  1241. ///
  1242. /// ## Platform-specific:
  1243. ///
  1244. /// - **Windows**: If using decorations or shadows, you may want to try this workaround <https://github.com/tauri-apps/tao/issues/72#issuecomment-975607891>
  1245. /// - **Linux**: Unsupported
  1246. #[serde(default, alias = "window-effects")]
  1247. pub window_effects: Option<WindowEffectsConfig>,
  1248. /// Whether or not the webview should be launched in incognito mode.
  1249. ///
  1250. /// ## Platform-specific:
  1251. ///
  1252. /// - **Android**: Unsupported.
  1253. #[serde(default)]
  1254. pub incognito: bool,
  1255. /// Sets the window associated with this label to be the parent of the window to be created.
  1256. ///
  1257. /// ## Platform-specific
  1258. ///
  1259. /// - **Windows**: This sets the passed parent as an owner window to the window to be created.
  1260. /// From [MSDN owned windows docs](https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows):
  1261. /// - An owned window is always above its owner in the z-order.
  1262. /// - The system automatically destroys an owned window when its owner is destroyed.
  1263. /// - An owned window is hidden when its owner is minimized.
  1264. /// - **Linux**: This makes the new window transient for parent, see <https://docs.gtk.org/gtk3/method.Window.set_transient_for.html>
  1265. /// - **macOS**: This adds the window as a child of parent, see <https://developer.apple.com/documentation/appkit/nswindow/1419152-addchildwindow?language=objc>
  1266. pub parent: Option<String>,
  1267. /// The proxy URL for the WebView for all network requests.
  1268. ///
  1269. /// Must be either a `http://` or a `socks5://` URL.
  1270. ///
  1271. /// ## Platform-specific
  1272. ///
  1273. /// - **macOS**: Requires the `macos-proxy` feature flag and only compiles for macOS 14+.
  1274. pub proxy_url: Option<Url>,
  1275. /// Whether page zooming by hotkeys is enabled
  1276. ///
  1277. /// ## Platform-specific:
  1278. ///
  1279. /// - **Windows**: Controls WebView2's [`IsZoomControlEnabled`](https://learn.microsoft.com/en-us/microsoft-edge/webview2/reference/winrt/microsoft_web_webview2_core/corewebview2settings?view=webview2-winrt-1.0.2420.47#iszoomcontrolenabled) setting.
  1280. /// - **MacOS / Linux**: Injects a polyfill that zooms in and out with `ctrl/command` + `-/=`,
  1281. /// 20% in each step, ranging from 20% to 1000%. Requires `webview:allow-set-webview-zoom` permission
  1282. ///
  1283. /// - **Android / iOS**: Unsupported.
  1284. #[serde(default)]
  1285. pub zoom_hotkeys_enabled: bool,
  1286. }
  1287. impl Default for WindowConfig {
  1288. fn default() -> Self {
  1289. Self {
  1290. label: default_window_label(),
  1291. url: WebviewUrl::default(),
  1292. user_agent: None,
  1293. drag_drop_enabled: true,
  1294. center: false,
  1295. x: None,
  1296. y: None,
  1297. width: default_width(),
  1298. height: default_height(),
  1299. min_width: None,
  1300. min_height: None,
  1301. max_width: None,
  1302. max_height: None,
  1303. resizable: true,
  1304. maximizable: true,
  1305. minimizable: true,
  1306. closable: true,
  1307. title: default_title(),
  1308. fullscreen: false,
  1309. focus: false,
  1310. transparent: false,
  1311. maximized: false,
  1312. visible: true,
  1313. decorations: true,
  1314. always_on_bottom: false,
  1315. always_on_top: false,
  1316. visible_on_all_workspaces: false,
  1317. content_protected: false,
  1318. skip_taskbar: false,
  1319. theme: None,
  1320. title_bar_style: Default::default(),
  1321. hidden_title: false,
  1322. accept_first_mouse: false,
  1323. tabbing_identifier: None,
  1324. additional_browser_args: None,
  1325. shadow: true,
  1326. window_effects: None,
  1327. incognito: false,
  1328. parent: None,
  1329. proxy_url: None,
  1330. zoom_hotkeys_enabled: false,
  1331. }
  1332. }
  1333. }
  1334. fn default_window_label() -> String {
  1335. "main".to_string()
  1336. }
  1337. fn default_width() -> f64 {
  1338. 800f64
  1339. }
  1340. fn default_height() -> f64 {
  1341. 600f64
  1342. }
  1343. fn default_title() -> String {
  1344. "Tauri App".to_string()
  1345. }
  1346. /// A Content-Security-Policy directive source list.
  1347. /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/Sources#sources>.
  1348. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1349. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1350. #[serde(rename_all = "camelCase", untagged)]
  1351. pub enum CspDirectiveSources {
  1352. /// An inline list of CSP sources. Same as [`Self::List`], but concatenated with a space separator.
  1353. Inline(String),
  1354. /// A list of CSP sources. The collection will be concatenated with a space separator for the CSP string.
  1355. List(Vec<String>),
  1356. }
  1357. impl Default for CspDirectiveSources {
  1358. fn default() -> Self {
  1359. Self::List(Vec::new())
  1360. }
  1361. }
  1362. impl From<CspDirectiveSources> for Vec<String> {
  1363. fn from(sources: CspDirectiveSources) -> Self {
  1364. match sources {
  1365. CspDirectiveSources::Inline(source) => source.split(' ').map(|s| s.to_string()).collect(),
  1366. CspDirectiveSources::List(l) => l,
  1367. }
  1368. }
  1369. }
  1370. impl CspDirectiveSources {
  1371. /// Whether the given source is configured on this directive or not.
  1372. pub fn contains(&self, source: &str) -> bool {
  1373. match self {
  1374. Self::Inline(s) => s.contains(&format!("{source} ")) || s.contains(&format!(" {source}")),
  1375. Self::List(l) => l.contains(&source.into()),
  1376. }
  1377. }
  1378. /// Appends the given source to this directive.
  1379. pub fn push<S: AsRef<str>>(&mut self, source: S) {
  1380. match self {
  1381. Self::Inline(s) => {
  1382. s.push(' ');
  1383. s.push_str(source.as_ref());
  1384. }
  1385. Self::List(l) => {
  1386. l.push(source.as_ref().to_string());
  1387. }
  1388. }
  1389. }
  1390. /// Extends this CSP directive source list with the given array of sources.
  1391. pub fn extend(&mut self, sources: Vec<String>) {
  1392. for s in sources {
  1393. self.push(s);
  1394. }
  1395. }
  1396. }
  1397. /// A Content-Security-Policy definition.
  1398. /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP>.
  1399. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1400. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1401. #[serde(rename_all = "camelCase", untagged)]
  1402. pub enum Csp {
  1403. /// The entire CSP policy in a single text string.
  1404. Policy(String),
  1405. /// An object mapping a directive with its sources values as a list of strings.
  1406. DirectiveMap(HashMap<String, CspDirectiveSources>),
  1407. }
  1408. impl From<HashMap<String, CspDirectiveSources>> for Csp {
  1409. fn from(map: HashMap<String, CspDirectiveSources>) -> Self {
  1410. Self::DirectiveMap(map)
  1411. }
  1412. }
  1413. impl From<Csp> for HashMap<String, CspDirectiveSources> {
  1414. fn from(csp: Csp) -> Self {
  1415. match csp {
  1416. Csp::Policy(policy) => {
  1417. let mut map = HashMap::new();
  1418. for directive in policy.split(';') {
  1419. let mut tokens = directive.trim().split(' ');
  1420. if let Some(directive) = tokens.next() {
  1421. let sources = tokens.map(|s| s.to_string()).collect::<Vec<String>>();
  1422. map.insert(directive.to_string(), CspDirectiveSources::List(sources));
  1423. }
  1424. }
  1425. map
  1426. }
  1427. Csp::DirectiveMap(m) => m,
  1428. }
  1429. }
  1430. }
  1431. impl Display for Csp {
  1432. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  1433. match self {
  1434. Self::Policy(s) => write!(f, "{s}"),
  1435. Self::DirectiveMap(m) => {
  1436. let len = m.len();
  1437. let mut i = 0;
  1438. for (directive, sources) in m {
  1439. let sources: Vec<String> = sources.clone().into();
  1440. write!(f, "{} {}", directive, sources.join(" "))?;
  1441. i += 1;
  1442. if i != len {
  1443. write!(f, "; ")?;
  1444. }
  1445. }
  1446. Ok(())
  1447. }
  1448. }
  1449. }
  1450. }
  1451. /// The possible values for the `dangerous_disable_asset_csp_modification` config option.
  1452. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1453. #[serde(untagged)]
  1454. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1455. pub enum DisabledCspModificationKind {
  1456. /// If `true`, disables all CSP modification.
  1457. /// `false` is the default value and it configures Tauri to control the CSP.
  1458. Flag(bool),
  1459. /// Disables the given list of CSP directives modifications.
  1460. List(Vec<String>),
  1461. }
  1462. impl DisabledCspModificationKind {
  1463. /// Determines whether the given CSP directive can be modified or not.
  1464. pub fn can_modify(&self, directive: &str) -> bool {
  1465. match self {
  1466. Self::Flag(f) => !f,
  1467. Self::List(l) => !l.contains(&directive.into()),
  1468. }
  1469. }
  1470. }
  1471. impl Default for DisabledCspModificationKind {
  1472. fn default() -> Self {
  1473. Self::Flag(false)
  1474. }
  1475. }
  1476. /// Protocol scope definition.
  1477. /// It is a list of glob patterns that restrict the API access from the webview.
  1478. ///
  1479. /// Each pattern can start with a variable that resolves to a system base directory.
  1480. /// The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`,
  1481. /// `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`,
  1482. /// `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$APP`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`,
  1483. /// `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.
  1484. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1485. #[serde(untagged)]
  1486. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1487. pub enum FsScope {
  1488. /// A list of paths that are allowed by this scope.
  1489. AllowedPaths(Vec<PathBuf>),
  1490. /// A complete scope configuration.
  1491. #[serde(rename_all = "camelCase")]
  1492. Scope {
  1493. /// A list of paths that are allowed by this scope.
  1494. #[serde(default)]
  1495. allow: Vec<PathBuf>,
  1496. /// A list of paths that are not allowed by this scope.
  1497. /// This gets precedence over the [`Self::Scope::allow`] list.
  1498. #[serde(default)]
  1499. deny: Vec<PathBuf>,
  1500. /// Whether or not paths that contain components that start with a `.`
  1501. /// will require that `.` appears literally in the pattern; `*`, `?`, `**`,
  1502. /// or `[...]` will not match. This is useful because such files are
  1503. /// conventionally considered hidden on Unix systems and it might be
  1504. /// desirable to skip them when listing files.
  1505. ///
  1506. /// Defaults to `true` on Unix systems and `false` on Windows
  1507. // dotfiles are not supposed to be exposed by default on unix
  1508. #[serde(alias = "require-literal-leading-dot")]
  1509. require_literal_leading_dot: Option<bool>,
  1510. },
  1511. }
  1512. impl Default for FsScope {
  1513. fn default() -> Self {
  1514. Self::AllowedPaths(Vec::new())
  1515. }
  1516. }
  1517. impl FsScope {
  1518. /// The list of allowed paths.
  1519. pub fn allowed_paths(&self) -> &Vec<PathBuf> {
  1520. match self {
  1521. Self::AllowedPaths(p) => p,
  1522. Self::Scope { allow, .. } => allow,
  1523. }
  1524. }
  1525. /// The list of forbidden paths.
  1526. pub fn forbidden_paths(&self) -> Option<&Vec<PathBuf>> {
  1527. match self {
  1528. Self::AllowedPaths(_) => None,
  1529. Self::Scope { deny, .. } => Some(deny),
  1530. }
  1531. }
  1532. }
  1533. /// Config for the asset custom protocol.
  1534. ///
  1535. /// See more: <https://tauri.app/v1/api/config#assetprotocolconfig>
  1536. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1537. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1538. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1539. pub struct AssetProtocolConfig {
  1540. /// The access scope for the asset protocol.
  1541. #[serde(default)]
  1542. pub scope: FsScope,
  1543. /// Enables the asset protocol.
  1544. #[serde(default)]
  1545. pub enable: bool,
  1546. }
  1547. /// Security configuration.
  1548. ///
  1549. /// See more: <https://tauri.app/v1/api/config#securityconfig>
  1550. #[skip_serializing_none]
  1551. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  1552. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1553. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1554. pub struct SecurityConfig {
  1555. /// The Content Security Policy that will be injected on all HTML files on the built application.
  1556. /// If [`dev_csp`](#SecurityConfig.devCsp) is not specified, this value is also injected on dev.
  1557. ///
  1558. /// This is a really important part of the configuration since it helps you ensure your WebView is secured.
  1559. /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP>.
  1560. pub csp: Option<Csp>,
  1561. /// The Content Security Policy that will be injected on all HTML files on development.
  1562. ///
  1563. /// This is a really important part of the configuration since it helps you ensure your WebView is secured.
  1564. /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP>.
  1565. #[serde(alias = "dev-csp")]
  1566. pub dev_csp: Option<Csp>,
  1567. /// Freeze the `Object.prototype` when using the custom protocol.
  1568. #[serde(default, alias = "freeze-prototype")]
  1569. pub freeze_prototype: bool,
  1570. /// Disables the Tauri-injected CSP sources.
  1571. ///
  1572. /// At compile time, Tauri parses all the frontend assets and changes the Content-Security-Policy
  1573. /// to only allow loading of your own scripts and styles by injecting nonce and hash sources.
  1574. /// This stricts your CSP, which may introduce issues when using along with other flexing sources.
  1575. ///
  1576. /// This configuration option allows both a boolean and a list of strings as value.
  1577. /// A boolean instructs Tauri to disable the injection for all CSP injections,
  1578. /// and a list of strings indicates the CSP directives that Tauri cannot inject.
  1579. ///
  1580. /// **WARNING:** Only disable this if you know what you are doing and have properly configured the CSP.
  1581. /// Your application might be vulnerable to XSS attacks without this Tauri protection.
  1582. #[serde(default, alias = "dangerous-disable-asset-csp-modification")]
  1583. pub dangerous_disable_asset_csp_modification: DisabledCspModificationKind,
  1584. /// Custom protocol config.
  1585. #[serde(default, alias = "asset-protocol")]
  1586. pub asset_protocol: AssetProtocolConfig,
  1587. /// The pattern to use.
  1588. #[serde(default)]
  1589. pub pattern: PatternKind,
  1590. /// List of capabilities that are enabled on the application.
  1591. ///
  1592. /// If the list is empty, all capabilities are included.
  1593. #[serde(default)]
  1594. pub capabilities: Vec<CapabilityEntry>,
  1595. }
  1596. /// A capability entry which can be either an inlined capability or a reference to a capability defined on its own file.
  1597. #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
  1598. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1599. #[serde(rename_all = "camelCase", untagged)]
  1600. pub enum CapabilityEntry {
  1601. /// An inlined capability.
  1602. Inlined(Capability),
  1603. /// Reference to a capability identifier.
  1604. Reference(String),
  1605. }
  1606. /// The application pattern.
  1607. #[skip_serializing_none]
  1608. #[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
  1609. #[serde(rename_all = "lowercase", tag = "use", content = "options")]
  1610. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1611. pub enum PatternKind {
  1612. /// Brownfield pattern.
  1613. Brownfield,
  1614. /// Isolation pattern. Recommended for security purposes.
  1615. Isolation {
  1616. /// The dir containing the index.html file that contains the secure isolation application.
  1617. dir: PathBuf,
  1618. },
  1619. }
  1620. impl Default for PatternKind {
  1621. fn default() -> Self {
  1622. Self::Brownfield
  1623. }
  1624. }
  1625. /// The App configuration object.
  1626. ///
  1627. /// See more: <https://tauri.app/v1/api/config#appconfig>
  1628. #[skip_serializing_none]
  1629. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  1630. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1631. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1632. pub struct AppConfig {
  1633. /// The windows configuration.
  1634. #[serde(default)]
  1635. pub windows: Vec<WindowConfig>,
  1636. /// Security configuration.
  1637. #[serde(default)]
  1638. pub security: SecurityConfig,
  1639. /// Configuration for app tray icon.
  1640. #[serde(alias = "tray-icon")]
  1641. pub tray_icon: Option<TrayIconConfig>,
  1642. /// MacOS private API configuration. Enables the transparent background API and sets the `fullScreenEnabled` preference to `true`.
  1643. #[serde(rename = "macOSPrivateApi", alias = "macos-private-api", default)]
  1644. pub macos_private_api: bool,
  1645. /// Whether we should inject the Tauri API on `window.__TAURI__` or not.
  1646. #[serde(default, alias = "with-global-tauri")]
  1647. pub with_global_tauri: bool,
  1648. }
  1649. impl AppConfig {
  1650. /// Returns all Cargo features.
  1651. pub fn all_features() -> Vec<&'static str> {
  1652. vec![
  1653. "tray-icon",
  1654. "macos-private-api",
  1655. "protocol-asset",
  1656. "isolation",
  1657. ]
  1658. }
  1659. /// Returns the enabled Cargo features.
  1660. pub fn features(&self) -> Vec<&str> {
  1661. let mut features = Vec::new();
  1662. if self.tray_icon.is_some() {
  1663. features.push("tray-icon");
  1664. }
  1665. if self.macos_private_api {
  1666. features.push("macos-private-api");
  1667. }
  1668. if self.security.asset_protocol.enable {
  1669. features.push("protocol-asset");
  1670. }
  1671. if let PatternKind::Isolation { .. } = self.security.pattern {
  1672. features.push("isolation");
  1673. }
  1674. features.sort_unstable();
  1675. features
  1676. }
  1677. }
  1678. /// Configuration for application tray icon.
  1679. ///
  1680. /// See more: <https://tauri.app/v1/api/config#trayiconconfig>
  1681. #[skip_serializing_none]
  1682. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1683. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1684. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1685. pub struct TrayIconConfig {
  1686. /// Set an id for this tray icon so you can reference it later, defaults to `main`.
  1687. pub id: Option<String>,
  1688. /// Path to the default icon to use for the tray icon.
  1689. #[serde(alias = "icon-path")]
  1690. pub icon_path: PathBuf,
  1691. /// A Boolean value that determines whether the image represents a [template](https://developer.apple.com/documentation/appkit/nsimage/1520017-template?language=objc) image on macOS.
  1692. #[serde(default, alias = "icon-as-template")]
  1693. pub icon_as_template: bool,
  1694. /// A Boolean value that determines whether the menu should appear when the tray icon receives a left click on macOS.
  1695. #[serde(default = "default_true", alias = "menu-on-left-click")]
  1696. pub menu_on_left_click: bool,
  1697. /// Title for MacOS tray
  1698. pub title: Option<String>,
  1699. /// Tray icon tooltip on Windows and macOS
  1700. pub tooltip: Option<String>,
  1701. }
  1702. /// General configuration for the iOS target.
  1703. #[skip_serializing_none]
  1704. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1705. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1706. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1707. pub struct IosConfig {
  1708. /// The development team. This value is required for iOS development because code signing is enforced.
  1709. /// The `APPLE_DEVELOPMENT_TEAM` environment variable can be set to overwrite it.
  1710. #[serde(alias = "development-team")]
  1711. pub development_team: Option<String>,
  1712. }
  1713. /// General configuration for the iOS target.
  1714. #[skip_serializing_none]
  1715. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1716. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1717. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1718. pub struct AndroidConfig {
  1719. /// The minimum API level required for the application to run.
  1720. /// The Android system will prevent the user from installing the application if the system's API level is lower than the value specified.
  1721. #[serde(alias = "min-sdk-version", default = "default_min_sdk_version")]
  1722. pub min_sdk_version: u32,
  1723. /// The version code of the application.
  1724. /// It is limited to 2,100,000,000 as per Google Play Store requirements.
  1725. ///
  1726. /// By default we use your configured version and perform the following math:
  1727. /// versionCode = version.major * 1000000 + version.minor * 1000 + version.patch
  1728. #[serde(alias = "version-code")]
  1729. #[cfg_attr(feature = "schema", validate(range(min = 1, max = 2_100_000_000)))]
  1730. pub version_code: Option<u32>,
  1731. }
  1732. impl Default for AndroidConfig {
  1733. fn default() -> Self {
  1734. Self {
  1735. min_sdk_version: default_min_sdk_version(),
  1736. version_code: None,
  1737. }
  1738. }
  1739. }
  1740. fn default_min_sdk_version() -> u32 {
  1741. 24
  1742. }
  1743. /// Defines the URL or assets to embed in the application.
  1744. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1745. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1746. #[serde(untagged, deny_unknown_fields)]
  1747. #[non_exhaustive]
  1748. pub enum FrontendDist {
  1749. /// An external URL that should be used as the default application URL.
  1750. Url(Url),
  1751. /// Path to a directory containing the frontend dist assets.
  1752. Directory(PathBuf),
  1753. /// An array of files to embed on the app.
  1754. Files(Vec<PathBuf>),
  1755. }
  1756. impl std::fmt::Display for FrontendDist {
  1757. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  1758. match self {
  1759. Self::Url(url) => write!(f, "{url}"),
  1760. Self::Directory(p) => write!(f, "{}", p.display()),
  1761. Self::Files(files) => write!(f, "{}", serde_json::to_string(files).unwrap()),
  1762. }
  1763. }
  1764. }
  1765. /// Describes the shell command to run before `tauri dev`.
  1766. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1767. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1768. #[serde(rename_all = "camelCase", untagged)]
  1769. pub enum BeforeDevCommand {
  1770. /// Run the given script with the default options.
  1771. Script(String),
  1772. /// Run the given script with custom options.
  1773. ScriptWithOptions {
  1774. /// The script to execute.
  1775. script: String,
  1776. /// The current working directory.
  1777. cwd: Option<String>,
  1778. /// Whether `tauri dev` should wait for the command to finish or not. Defaults to `false`.
  1779. #[serde(default)]
  1780. wait: bool,
  1781. },
  1782. }
  1783. /// Describes a shell command to be executed when a CLI hook is triggered.
  1784. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1785. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1786. #[serde(rename_all = "camelCase", untagged)]
  1787. pub enum HookCommand {
  1788. /// Run the given script with the default options.
  1789. Script(String),
  1790. /// Run the given script with custom options.
  1791. ScriptWithOptions {
  1792. /// The script to execute.
  1793. script: String,
  1794. /// The current working directory.
  1795. cwd: Option<String>,
  1796. },
  1797. }
  1798. /// The Build configuration object.
  1799. ///
  1800. /// See more: <https://tauri.app/v1/api/config#buildconfig>
  1801. #[skip_serializing_none]
  1802. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize, Default)]
  1803. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1804. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1805. pub struct BuildConfig {
  1806. /// The binary used to build and run the application.
  1807. pub runner: Option<String>,
  1808. /// The URL to load in development.
  1809. ///
  1810. /// This is usually an URL to a dev server, which serves your application assets with hot-reload and HMR.
  1811. /// Most modern JavaScript bundlers like [vite](https://vitejs.dev/guide/) provides a way to start a dev server by default.
  1812. ///
  1813. /// If you don't have a dev server or don't want to use one, ignore this option and use [`frontendDist`](BuildConfig::frontend_dist)
  1814. /// and point to a web assets directory, and Tauri CLI will run its built-in dev server and provide a simple hot-reload experience.
  1815. #[serde(alias = "dev-url")]
  1816. pub dev_url: Option<Url>,
  1817. /// The path to the application assets (usually the `dist` folder of your javascript bundler)
  1818. /// or a URL that could be either a custom protocol registered in the tauri app (for example: `myprotocol://`)
  1819. /// or a remote URL (for example: `https://site.com/app`).
  1820. ///
  1821. /// When a path relative to the configuration file is provided,
  1822. /// it is read recursively and all files are embedded in the application binary.
  1823. /// Tauri then looks for an `index.html` and serves it as the default entry point for your application.
  1824. ///
  1825. /// You can also provide a list of paths to be embedded, which allows granular control over what files are added to the binary.
  1826. /// In this case, all files are added to the root and you must reference it that way in your HTML files.
  1827. ///
  1828. /// When a URL is provided, the application won't have bundled assets
  1829. /// and the application will load that URL by default.
  1830. #[serde(alias = "frontend-dist")]
  1831. pub frontend_dist: Option<FrontendDist>,
  1832. /// A shell command to run before `tauri dev` kicks in.
  1833. ///
  1834. /// The TAURI_ENV_PLATFORM, TAURI_ENV_ARCH, TAURI_ENV_FAMILY, TAURI_ENV_PLATFORM_VERSION, TAURI_ENV_PLATFORM_TYPE and TAURI_ENV_DEBUG environment variables are set if you perform conditional compilation.
  1835. #[serde(alias = "before-dev-command")]
  1836. pub before_dev_command: Option<BeforeDevCommand>,
  1837. /// A shell command to run before `tauri build` kicks in.
  1838. ///
  1839. /// The TAURI_ENV_PLATFORM, TAURI_ENV_ARCH, TAURI_ENV_FAMILY, TAURI_ENV_PLATFORM_VERSION, TAURI_ENV_PLATFORM_TYPE and TAURI_ENV_DEBUG environment variables are set if you perform conditional compilation.
  1840. #[serde(alias = "before-build-command")]
  1841. pub before_build_command: Option<HookCommand>,
  1842. /// A shell command to run before the bundling phase in `tauri build` kicks in.
  1843. ///
  1844. /// The TAURI_ENV_PLATFORM, TAURI_ENV_ARCH, TAURI_ENV_FAMILY, TAURI_ENV_PLATFORM_VERSION, TAURI_ENV_PLATFORM_TYPE and TAURI_ENV_DEBUG environment variables are set if you perform conditional compilation.
  1845. #[serde(alias = "before-bundle-command")]
  1846. pub before_bundle_command: Option<HookCommand>,
  1847. /// Features passed to `cargo` commands.
  1848. pub features: Option<Vec<String>>,
  1849. }
  1850. #[derive(Debug, PartialEq, Eq)]
  1851. struct PackageVersion(String);
  1852. impl<'d> serde::Deserialize<'d> for PackageVersion {
  1853. fn deserialize<D: Deserializer<'d>>(deserializer: D) -> Result<Self, D::Error> {
  1854. struct PackageVersionVisitor;
  1855. impl<'d> Visitor<'d> for PackageVersionVisitor {
  1856. type Value = PackageVersion;
  1857. fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
  1858. write!(
  1859. formatter,
  1860. "a semver string or a path to a package.json file"
  1861. )
  1862. }
  1863. fn visit_str<E: DeError>(self, value: &str) -> Result<PackageVersion, E> {
  1864. let path = PathBuf::from(value);
  1865. if path.exists() {
  1866. let json_str = read_to_string(&path)
  1867. .map_err(|e| DeError::custom(format!("failed to read version JSON file: {e}")))?;
  1868. let package_json: serde_json::Value = serde_json::from_str(&json_str)
  1869. .map_err(|e| DeError::custom(format!("failed to read version JSON file: {e}")))?;
  1870. if let Some(obj) = package_json.as_object() {
  1871. let version = obj
  1872. .get("version")
  1873. .ok_or_else(|| DeError::custom("JSON must contain a `version` field"))?
  1874. .as_str()
  1875. .ok_or_else(|| {
  1876. DeError::custom(format!("`{} > version` must be a string", path.display()))
  1877. })?;
  1878. Ok(PackageVersion(
  1879. Version::from_str(version)
  1880. .map_err(|_| DeError::custom("`package > version` must be a semver string"))?
  1881. .to_string(),
  1882. ))
  1883. } else {
  1884. Err(DeError::custom(
  1885. "`package > version` value is not a path to a JSON object",
  1886. ))
  1887. }
  1888. } else {
  1889. Ok(PackageVersion(
  1890. Version::from_str(value)
  1891. .map_err(|_| DeError::custom("`package > version` must be a semver string"))?
  1892. .to_string(),
  1893. ))
  1894. }
  1895. }
  1896. }
  1897. deserializer.deserialize_string(PackageVersionVisitor {})
  1898. }
  1899. }
  1900. fn version_deserializer<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
  1901. where
  1902. D: Deserializer<'de>,
  1903. {
  1904. Option::<PackageVersion>::deserialize(deserializer).map(|v| v.map(|v| v.0))
  1905. }
  1906. /// The Tauri configuration object.
  1907. /// It is read from a file where you can define your frontend assets,
  1908. /// configure the bundler and define a tray icon.
  1909. ///
  1910. /// The configuration file is generated by the
  1911. /// [`tauri init`](https://tauri.app/v1/api/cli#init) command that lives in
  1912. /// your Tauri application source directory (src-tauri).
  1913. ///
  1914. /// Once generated, you may modify it at will to customize your Tauri application.
  1915. ///
  1916. /// ## File Formats
  1917. ///
  1918. /// By default, the configuration is defined as a JSON file named `tauri.conf.json`.
  1919. ///
  1920. /// Tauri also supports JSON5 and TOML files via the `config-json5` and `config-toml` Cargo features, respectively.
  1921. /// The JSON5 file name must be either `tauri.conf.json` or `tauri.conf.json5`.
  1922. /// The TOML file name is `Tauri.toml`.
  1923. ///
  1924. /// ## Platform-Specific Configuration
  1925. ///
  1926. /// In addition to the default configuration file, Tauri can
  1927. /// read a platform-specific configuration from `tauri.linux.conf.json`,
  1928. /// `tauri.windows.conf.json`, `tauri.macos.conf.json`, `tauri.android.conf.json` and `tauri.ios.conf.json`
  1929. /// (or `Tauri.linux.toml`, `Tauri.windows.toml`, `Tauri.macos.toml`, `Tauri.android.toml` and `Tauri.ios.toml` if the `Tauri.toml` format is used),
  1930. /// which gets merged with the main configuration object.
  1931. ///
  1932. /// ## Configuration Structure
  1933. ///
  1934. /// The configuration is composed of the following objects:
  1935. ///
  1936. /// - [`app`](#appconfig): The Tauri configuration
  1937. /// - [`build`](#buildconfig): The build configuration
  1938. /// - [`bundle`](#bundleconfig): The bundle configurations
  1939. /// - [`plugins`](#pluginconfig): The plugins configuration
  1940. ///
  1941. /// ```json title="Example tauri.config.json file"
  1942. /// {
  1943. /// "productName": "tauri-app",
  1944. /// "version": "0.1.0"
  1945. /// "build": {
  1946. /// "beforeBuildCommand": "",
  1947. /// "beforeDevCommand": "",
  1948. /// "devUrl": "../dist",
  1949. /// "frontendDist": "../dist"
  1950. /// },
  1951. /// "app": {
  1952. /// "security": {
  1953. /// "csp": null
  1954. /// },
  1955. /// "windows": [
  1956. /// {
  1957. /// "fullscreen": false,
  1958. /// "height": 600,
  1959. /// "resizable": true,
  1960. /// "title": "Tauri App",
  1961. /// "width": 800
  1962. /// }
  1963. /// ]
  1964. /// },
  1965. /// "bundle": {},
  1966. /// "plugins": {}
  1967. /// }
  1968. /// ```
  1969. #[skip_serializing_none]
  1970. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  1971. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1972. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1973. pub struct Config {
  1974. /// The JSON schema for the Tauri config.
  1975. #[serde(rename = "$schema")]
  1976. pub schema: Option<String>,
  1977. /// App name.
  1978. #[serde(alias = "product-name")]
  1979. #[cfg_attr(feature = "schema", validate(regex(pattern = "^[^/\\:*?\"<>|]+$")))]
  1980. pub product_name: Option<String>,
  1981. /// App version. It is a semver version number or a path to a `package.json` file containing the `version` field. If removed the version number from `Cargo.toml` is used.
  1982. ///
  1983. /// By default version 1.0 is used on Android.
  1984. #[serde(deserialize_with = "version_deserializer", default)]
  1985. pub version: Option<String>,
  1986. /// The application identifier in reverse domain name notation (e.g. `com.tauri.example`).
  1987. /// This string must be unique across applications since it is used in system configurations like
  1988. /// the bundle ID and path to the webview data directory.
  1989. /// This string must contain only alphanumeric characters (A–Z, a–z, and 0–9), hyphens (-),
  1990. /// and periods (.).
  1991. #[serde(default)]
  1992. pub identifier: String,
  1993. /// The App configuration.
  1994. #[serde(default)]
  1995. pub app: AppConfig,
  1996. /// The build configuration.
  1997. #[serde(default = "default_build")]
  1998. pub build: BuildConfig,
  1999. /// The bundler configuration.
  2000. #[serde(default)]
  2001. pub bundle: BundleConfig,
  2002. /// The plugins config.
  2003. #[serde(default)]
  2004. pub plugins: PluginConfig,
  2005. }
  2006. /// The plugin configs holds a HashMap mapping a plugin name to its configuration object.
  2007. ///
  2008. /// See more: <https://tauri.app/v1/api/config#pluginconfig>
  2009. #[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
  2010. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  2011. pub struct PluginConfig(pub HashMap<String, JsonValue>);
  2012. fn default_build() -> BuildConfig {
  2013. BuildConfig {
  2014. runner: None,
  2015. dev_url: None,
  2016. frontend_dist: None,
  2017. before_dev_command: None,
  2018. before_build_command: None,
  2019. before_bundle_command: None,
  2020. features: None,
  2021. }
  2022. }
  2023. /// Implement `ToTokens` for all config structs, allowing a literal `Config` to be built.
  2024. ///
  2025. /// This allows for a build script to output the values in a `Config` to a `TokenStream`, which can
  2026. /// then be consumed by another crate. Useful for passing a config to both the build script and the
  2027. /// application using tauri while only parsing it once (in the build script).
  2028. #[cfg(feature = "build")]
  2029. mod build {
  2030. use super::*;
  2031. use crate::{literal_struct, tokens::*};
  2032. use proc_macro2::TokenStream;
  2033. use quote::{quote, ToTokens, TokenStreamExt};
  2034. use std::convert::identity;
  2035. impl ToTokens for WebviewUrl {
  2036. fn to_tokens(&self, tokens: &mut TokenStream) {
  2037. let prefix = quote! { ::tauri::utils::config::WebviewUrl };
  2038. tokens.append_all(match self {
  2039. Self::App(path) => {
  2040. let path = path_buf_lit(path);
  2041. quote! { #prefix::App(#path) }
  2042. }
  2043. Self::External(url) => {
  2044. let url = url_lit(url);
  2045. quote! { #prefix::External(#url) }
  2046. }
  2047. Self::CustomProtocol(url) => {
  2048. let url = url_lit(url);
  2049. quote! { #prefix::CustomProtocol(#url) }
  2050. }
  2051. })
  2052. }
  2053. }
  2054. impl ToTokens for crate::Theme {
  2055. fn to_tokens(&self, tokens: &mut TokenStream) {
  2056. let prefix = quote! { ::tauri::utils::Theme };
  2057. tokens.append_all(match self {
  2058. Self::Light => quote! { #prefix::Light },
  2059. Self::Dark => quote! { #prefix::Dark },
  2060. })
  2061. }
  2062. }
  2063. impl ToTokens for Color {
  2064. fn to_tokens(&self, tokens: &mut TokenStream) {
  2065. let Color(r, g, b, a) = self;
  2066. tokens.append_all(quote! {::tauri::utils::config::Color(#r,#g,#b,#a)});
  2067. }
  2068. }
  2069. impl ToTokens for WindowEffectsConfig {
  2070. fn to_tokens(&self, tokens: &mut TokenStream) {
  2071. let effects = vec_lit(self.effects.clone(), |d| d);
  2072. let state = opt_lit(self.state.as_ref());
  2073. let radius = opt_lit(self.radius.as_ref());
  2074. let color = opt_lit(self.color.as_ref());
  2075. literal_struct!(
  2076. tokens,
  2077. ::tauri::utils::config::WindowEffectsConfig,
  2078. effects,
  2079. state,
  2080. radius,
  2081. color
  2082. )
  2083. }
  2084. }
  2085. impl ToTokens for crate::TitleBarStyle {
  2086. fn to_tokens(&self, tokens: &mut TokenStream) {
  2087. let prefix = quote! { ::tauri::utils::TitleBarStyle };
  2088. tokens.append_all(match self {
  2089. Self::Visible => quote! { #prefix::Visible },
  2090. Self::Transparent => quote! { #prefix::Transparent },
  2091. Self::Overlay => quote! { #prefix::Overlay },
  2092. })
  2093. }
  2094. }
  2095. impl ToTokens for crate::WindowEffect {
  2096. fn to_tokens(&self, tokens: &mut TokenStream) {
  2097. let prefix = quote! { ::tauri::utils::WindowEffect };
  2098. #[allow(deprecated)]
  2099. tokens.append_all(match self {
  2100. WindowEffect::AppearanceBased => quote! { #prefix::AppearanceBased},
  2101. WindowEffect::Light => quote! { #prefix::Light},
  2102. WindowEffect::Dark => quote! { #prefix::Dark},
  2103. WindowEffect::MediumLight => quote! { #prefix::MediumLight},
  2104. WindowEffect::UltraDark => quote! { #prefix::UltraDark},
  2105. WindowEffect::Titlebar => quote! { #prefix::Titlebar},
  2106. WindowEffect::Selection => quote! { #prefix::Selection},
  2107. WindowEffect::Menu => quote! { #prefix::Menu},
  2108. WindowEffect::Popover => quote! { #prefix::Popover},
  2109. WindowEffect::Sidebar => quote! { #prefix::Sidebar},
  2110. WindowEffect::HeaderView => quote! { #prefix::HeaderView},
  2111. WindowEffect::Sheet => quote! { #prefix::Sheet},
  2112. WindowEffect::WindowBackground => quote! { #prefix::WindowBackground},
  2113. WindowEffect::HudWindow => quote! { #prefix::HudWindow},
  2114. WindowEffect::FullScreenUI => quote! { #prefix::FullScreenUI},
  2115. WindowEffect::Tooltip => quote! { #prefix::Tooltip},
  2116. WindowEffect::ContentBackground => quote! { #prefix::ContentBackground},
  2117. WindowEffect::UnderWindowBackground => quote! { #prefix::UnderWindowBackground},
  2118. WindowEffect::UnderPageBackground => quote! { #prefix::UnderPageBackground},
  2119. WindowEffect::Mica => quote! { #prefix::Mica},
  2120. WindowEffect::MicaDark => quote! { #prefix::MicaDark},
  2121. WindowEffect::MicaLight => quote! { #prefix::MicaLight},
  2122. WindowEffect::Blur => quote! { #prefix::Blur},
  2123. WindowEffect::Acrylic => quote! { #prefix::Acrylic},
  2124. WindowEffect::Tabbed => quote! { #prefix::Tabbed },
  2125. WindowEffect::TabbedDark => quote! { #prefix::TabbedDark },
  2126. WindowEffect::TabbedLight => quote! { #prefix::TabbedLight },
  2127. })
  2128. }
  2129. }
  2130. impl ToTokens for crate::WindowEffectState {
  2131. fn to_tokens(&self, tokens: &mut TokenStream) {
  2132. let prefix = quote! { ::tauri::utils::WindowEffectState };
  2133. #[allow(deprecated)]
  2134. tokens.append_all(match self {
  2135. WindowEffectState::Active => quote! { #prefix::Active},
  2136. WindowEffectState::FollowsWindowActiveState => quote! { #prefix::FollowsWindowActiveState},
  2137. WindowEffectState::Inactive => quote! { #prefix::Inactive},
  2138. })
  2139. }
  2140. }
  2141. impl ToTokens for WindowConfig {
  2142. fn to_tokens(&self, tokens: &mut TokenStream) {
  2143. let label = str_lit(&self.label);
  2144. let url = &self.url;
  2145. let user_agent = opt_str_lit(self.user_agent.as_ref());
  2146. let drag_drop_enabled = self.drag_drop_enabled;
  2147. let center = self.center;
  2148. let x = opt_lit(self.x.as_ref());
  2149. let y = opt_lit(self.y.as_ref());
  2150. let width = self.width;
  2151. let height = self.height;
  2152. let min_width = opt_lit(self.min_width.as_ref());
  2153. let min_height = opt_lit(self.min_height.as_ref());
  2154. let max_width = opt_lit(self.max_width.as_ref());
  2155. let max_height = opt_lit(self.max_height.as_ref());
  2156. let resizable = self.resizable;
  2157. let maximizable = self.maximizable;
  2158. let minimizable = self.minimizable;
  2159. let closable = self.closable;
  2160. let title = str_lit(&self.title);
  2161. let proxy_url = opt_lit(self.proxy_url.as_ref().map(url_lit).as_ref());
  2162. let fullscreen = self.fullscreen;
  2163. let focus = self.focus;
  2164. let transparent = self.transparent;
  2165. let maximized = self.maximized;
  2166. let visible = self.visible;
  2167. let decorations = self.decorations;
  2168. let always_on_bottom = self.always_on_bottom;
  2169. let always_on_top = self.always_on_top;
  2170. let visible_on_all_workspaces = self.visible_on_all_workspaces;
  2171. let content_protected = self.content_protected;
  2172. let skip_taskbar = self.skip_taskbar;
  2173. let theme = opt_lit(self.theme.as_ref());
  2174. let title_bar_style = &self.title_bar_style;
  2175. let hidden_title = self.hidden_title;
  2176. let accept_first_mouse = self.accept_first_mouse;
  2177. let tabbing_identifier = opt_str_lit(self.tabbing_identifier.as_ref());
  2178. let additional_browser_args = opt_str_lit(self.additional_browser_args.as_ref());
  2179. let shadow = self.shadow;
  2180. let window_effects = opt_lit(self.window_effects.as_ref());
  2181. let incognito = self.incognito;
  2182. let parent = opt_str_lit(self.parent.as_ref());
  2183. let zoom_hotkeys_enabled = self.zoom_hotkeys_enabled;
  2184. literal_struct!(
  2185. tokens,
  2186. ::tauri::utils::config::WindowConfig,
  2187. label,
  2188. url,
  2189. user_agent,
  2190. drag_drop_enabled,
  2191. center,
  2192. x,
  2193. y,
  2194. width,
  2195. height,
  2196. min_width,
  2197. min_height,
  2198. max_width,
  2199. max_height,
  2200. resizable,
  2201. maximizable,
  2202. minimizable,
  2203. closable,
  2204. title,
  2205. proxy_url,
  2206. fullscreen,
  2207. focus,
  2208. transparent,
  2209. maximized,
  2210. visible,
  2211. decorations,
  2212. always_on_bottom,
  2213. always_on_top,
  2214. visible_on_all_workspaces,
  2215. content_protected,
  2216. skip_taskbar,
  2217. theme,
  2218. title_bar_style,
  2219. hidden_title,
  2220. accept_first_mouse,
  2221. tabbing_identifier,
  2222. additional_browser_args,
  2223. shadow,
  2224. window_effects,
  2225. incognito,
  2226. parent,
  2227. zoom_hotkeys_enabled
  2228. );
  2229. }
  2230. }
  2231. impl ToTokens for PatternKind {
  2232. fn to_tokens(&self, tokens: &mut TokenStream) {
  2233. let prefix = quote! { ::tauri::utils::config::PatternKind };
  2234. tokens.append_all(match self {
  2235. Self::Brownfield => quote! { #prefix::Brownfield },
  2236. #[cfg(not(feature = "isolation"))]
  2237. Self::Isolation { dir: _ } => quote! { #prefix::Brownfield },
  2238. #[cfg(feature = "isolation")]
  2239. Self::Isolation { dir } => {
  2240. let dir = path_buf_lit(dir);
  2241. quote! { #prefix::Isolation { dir: #dir } }
  2242. }
  2243. })
  2244. }
  2245. }
  2246. impl ToTokens for WebviewInstallMode {
  2247. fn to_tokens(&self, tokens: &mut TokenStream) {
  2248. let prefix = quote! { ::tauri::utils::config::WebviewInstallMode };
  2249. tokens.append_all(match self {
  2250. Self::Skip => quote! { #prefix::Skip },
  2251. Self::DownloadBootstrapper { silent } => {
  2252. quote! { #prefix::DownloadBootstrapper { silent: #silent } }
  2253. }
  2254. Self::EmbedBootstrapper { silent } => {
  2255. quote! { #prefix::EmbedBootstrapper { silent: #silent } }
  2256. }
  2257. Self::OfflineInstaller { silent } => {
  2258. quote! { #prefix::OfflineInstaller { silent: #silent } }
  2259. }
  2260. Self::FixedRuntime { path } => {
  2261. let path = path_buf_lit(path);
  2262. quote! { #prefix::FixedRuntime { path: #path } }
  2263. }
  2264. })
  2265. }
  2266. }
  2267. impl ToTokens for WindowsConfig {
  2268. fn to_tokens(&self, tokens: &mut TokenStream) {
  2269. let webview_install_mode = if let Some(fixed_runtime_path) = &self.webview_fixed_runtime_path
  2270. {
  2271. WebviewInstallMode::FixedRuntime {
  2272. path: fixed_runtime_path.clone(),
  2273. }
  2274. } else {
  2275. self.webview_install_mode.clone()
  2276. };
  2277. tokens.append_all(quote! { ::tauri::utils::config::WindowsConfig {
  2278. webview_install_mode: #webview_install_mode,
  2279. ..Default::default()
  2280. }})
  2281. }
  2282. }
  2283. impl ToTokens for BundleConfig {
  2284. fn to_tokens(&self, tokens: &mut TokenStream) {
  2285. let publisher = quote!(None);
  2286. let homepage = quote!(None);
  2287. let icon = vec_lit(&self.icon, str_lit);
  2288. let active = self.active;
  2289. let targets = quote!(Default::default());
  2290. let resources = quote!(None);
  2291. let copyright = quote!(None);
  2292. let category = quote!(None);
  2293. let file_associations = quote!(None);
  2294. let short_description = quote!(None);
  2295. let long_description = quote!(None);
  2296. let external_bin = opt_vec_lit(self.external_bin.as_ref(), str_lit);
  2297. let windows = &self.windows;
  2298. let license = opt_str_lit(self.license.as_ref());
  2299. let license_file = opt_lit(self.license_file.as_ref().map(path_buf_lit).as_ref());
  2300. let linux = quote!(Default::default());
  2301. let macos = quote!(Default::default());
  2302. let ios = quote!(Default::default());
  2303. let android = quote!(Default::default());
  2304. literal_struct!(
  2305. tokens,
  2306. ::tauri::utils::config::BundleConfig,
  2307. active,
  2308. publisher,
  2309. homepage,
  2310. icon,
  2311. targets,
  2312. resources,
  2313. copyright,
  2314. category,
  2315. license,
  2316. license_file,
  2317. file_associations,
  2318. short_description,
  2319. long_description,
  2320. external_bin,
  2321. windows,
  2322. linux,
  2323. macos,
  2324. ios,
  2325. android
  2326. );
  2327. }
  2328. }
  2329. impl ToTokens for FrontendDist {
  2330. fn to_tokens(&self, tokens: &mut TokenStream) {
  2331. let prefix = quote! { ::tauri::utils::config::FrontendDist };
  2332. tokens.append_all(match self {
  2333. Self::Url(url) => {
  2334. let url = url_lit(url);
  2335. quote! { #prefix::Url(#url) }
  2336. }
  2337. Self::Directory(path) => {
  2338. let path = path_buf_lit(path);
  2339. quote! { #prefix::Directory(#path) }
  2340. }
  2341. Self::Files(files) => {
  2342. let files = vec_lit(files, path_buf_lit);
  2343. quote! { #prefix::Files(#files) }
  2344. }
  2345. })
  2346. }
  2347. }
  2348. impl ToTokens for BuildConfig {
  2349. fn to_tokens(&self, tokens: &mut TokenStream) {
  2350. let dev_url = opt_lit(self.dev_url.as_ref().map(url_lit).as_ref());
  2351. let frontend_dist = opt_lit(self.frontend_dist.as_ref());
  2352. let runner = quote!(None);
  2353. let before_dev_command = quote!(None);
  2354. let before_build_command = quote!(None);
  2355. let before_bundle_command = quote!(None);
  2356. let features = quote!(None);
  2357. literal_struct!(
  2358. tokens,
  2359. ::tauri::utils::config::BuildConfig,
  2360. runner,
  2361. dev_url,
  2362. frontend_dist,
  2363. before_dev_command,
  2364. before_build_command,
  2365. before_bundle_command,
  2366. features
  2367. );
  2368. }
  2369. }
  2370. impl ToTokens for CspDirectiveSources {
  2371. fn to_tokens(&self, tokens: &mut TokenStream) {
  2372. let prefix = quote! { ::tauri::utils::config::CspDirectiveSources };
  2373. tokens.append_all(match self {
  2374. Self::Inline(sources) => {
  2375. let sources = sources.as_str();
  2376. quote!(#prefix::Inline(#sources.into()))
  2377. }
  2378. Self::List(list) => {
  2379. let list = vec_lit(list, str_lit);
  2380. quote!(#prefix::List(#list))
  2381. }
  2382. })
  2383. }
  2384. }
  2385. impl ToTokens for Csp {
  2386. fn to_tokens(&self, tokens: &mut TokenStream) {
  2387. let prefix = quote! { ::tauri::utils::config::Csp };
  2388. tokens.append_all(match self {
  2389. Self::Policy(policy) => {
  2390. let policy = policy.as_str();
  2391. quote!(#prefix::Policy(#policy.into()))
  2392. }
  2393. Self::DirectiveMap(list) => {
  2394. let map = map_lit(
  2395. quote! { ::std::collections::HashMap },
  2396. list,
  2397. str_lit,
  2398. identity,
  2399. );
  2400. quote!(#prefix::DirectiveMap(#map))
  2401. }
  2402. })
  2403. }
  2404. }
  2405. impl ToTokens for DisabledCspModificationKind {
  2406. fn to_tokens(&self, tokens: &mut TokenStream) {
  2407. let prefix = quote! { ::tauri::utils::config::DisabledCspModificationKind };
  2408. tokens.append_all(match self {
  2409. Self::Flag(flag) => {
  2410. quote! { #prefix::Flag(#flag) }
  2411. }
  2412. Self::List(directives) => {
  2413. let directives = vec_lit(directives, str_lit);
  2414. quote! { #prefix::List(#directives) }
  2415. }
  2416. });
  2417. }
  2418. }
  2419. impl ToTokens for CapabilityEntry {
  2420. fn to_tokens(&self, tokens: &mut TokenStream) {
  2421. let prefix = quote! { ::tauri::utils::config::CapabilityEntry };
  2422. tokens.append_all(match self {
  2423. Self::Inlined(capability) => {
  2424. quote! { #prefix::Inlined(#capability) }
  2425. }
  2426. Self::Reference(id) => {
  2427. let id = str_lit(id);
  2428. quote! { #prefix::Reference(#id) }
  2429. }
  2430. });
  2431. }
  2432. }
  2433. impl ToTokens for SecurityConfig {
  2434. fn to_tokens(&self, tokens: &mut TokenStream) {
  2435. let csp = opt_lit(self.csp.as_ref());
  2436. let dev_csp = opt_lit(self.dev_csp.as_ref());
  2437. let freeze_prototype = self.freeze_prototype;
  2438. let dangerous_disable_asset_csp_modification = &self.dangerous_disable_asset_csp_modification;
  2439. let asset_protocol = &self.asset_protocol;
  2440. let pattern = &self.pattern;
  2441. let capabilities = vec_lit(&self.capabilities, identity);
  2442. literal_struct!(
  2443. tokens,
  2444. ::tauri::utils::config::SecurityConfig,
  2445. csp,
  2446. dev_csp,
  2447. freeze_prototype,
  2448. dangerous_disable_asset_csp_modification,
  2449. asset_protocol,
  2450. pattern,
  2451. capabilities
  2452. );
  2453. }
  2454. }
  2455. impl ToTokens for TrayIconConfig {
  2456. fn to_tokens(&self, tokens: &mut TokenStream) {
  2457. let id = opt_str_lit(self.id.as_ref());
  2458. let icon_as_template = self.icon_as_template;
  2459. let menu_on_left_click = self.menu_on_left_click;
  2460. let icon_path = path_buf_lit(&self.icon_path);
  2461. let title = opt_str_lit(self.title.as_ref());
  2462. let tooltip = opt_str_lit(self.tooltip.as_ref());
  2463. literal_struct!(
  2464. tokens,
  2465. ::tauri::utils::config::TrayIconConfig,
  2466. id,
  2467. icon_path,
  2468. icon_as_template,
  2469. menu_on_left_click,
  2470. title,
  2471. tooltip
  2472. );
  2473. }
  2474. }
  2475. impl ToTokens for FsScope {
  2476. fn to_tokens(&self, tokens: &mut TokenStream) {
  2477. let prefix = quote! { ::tauri::utils::config::FsScope };
  2478. tokens.append_all(match self {
  2479. Self::AllowedPaths(allow) => {
  2480. let allowed_paths = vec_lit(allow, path_buf_lit);
  2481. quote! { #prefix::AllowedPaths(#allowed_paths) }
  2482. }
  2483. Self::Scope { allow, deny , require_literal_leading_dot} => {
  2484. let allow = vec_lit(allow, path_buf_lit);
  2485. let deny = vec_lit(deny, path_buf_lit);
  2486. let require_literal_leading_dot = opt_lit(require_literal_leading_dot.as_ref());
  2487. quote! { #prefix::Scope { allow: #allow, deny: #deny, require_literal_leading_dot: #require_literal_leading_dot } }
  2488. }
  2489. });
  2490. }
  2491. }
  2492. impl ToTokens for AssetProtocolConfig {
  2493. fn to_tokens(&self, tokens: &mut TokenStream) {
  2494. let scope = &self.scope;
  2495. tokens.append_all(quote! { ::tauri::utils::config::AssetProtocolConfig { scope: #scope, ..Default::default() } })
  2496. }
  2497. }
  2498. impl ToTokens for AppConfig {
  2499. fn to_tokens(&self, tokens: &mut TokenStream) {
  2500. let windows = vec_lit(&self.windows, identity);
  2501. let security = &self.security;
  2502. let tray_icon = opt_lit(self.tray_icon.as_ref());
  2503. let macos_private_api = self.macos_private_api;
  2504. let with_global_tauri = self.with_global_tauri;
  2505. literal_struct!(
  2506. tokens,
  2507. ::tauri::utils::config::AppConfig,
  2508. windows,
  2509. security,
  2510. tray_icon,
  2511. macos_private_api,
  2512. with_global_tauri
  2513. );
  2514. }
  2515. }
  2516. impl ToTokens for PluginConfig {
  2517. fn to_tokens(&self, tokens: &mut TokenStream) {
  2518. let config = map_lit(
  2519. quote! { ::std::collections::HashMap },
  2520. &self.0,
  2521. str_lit,
  2522. json_value_lit,
  2523. );
  2524. tokens.append_all(quote! { ::tauri::utils::config::PluginConfig(#config) })
  2525. }
  2526. }
  2527. impl ToTokens for Config {
  2528. fn to_tokens(&self, tokens: &mut TokenStream) {
  2529. let schema = quote!(None);
  2530. let product_name = opt_str_lit(self.product_name.as_ref());
  2531. let version = opt_str_lit(self.version.as_ref());
  2532. let identifier = str_lit(&self.identifier);
  2533. let app = &self.app;
  2534. let build = &self.build;
  2535. let bundle = &self.bundle;
  2536. let plugins = &self.plugins;
  2537. literal_struct!(
  2538. tokens,
  2539. ::tauri::utils::config::Config,
  2540. schema,
  2541. product_name,
  2542. version,
  2543. identifier,
  2544. app,
  2545. build,
  2546. bundle,
  2547. plugins
  2548. );
  2549. }
  2550. }
  2551. }
  2552. #[cfg(test)]
  2553. mod test {
  2554. use super::*;
  2555. // TODO: create a test that compares a config to a json config
  2556. #[test]
  2557. // test all of the default functions
  2558. fn test_defaults() {
  2559. // get default app config
  2560. let a_config = AppConfig::default();
  2561. // get default build config
  2562. let b_config = BuildConfig::default();
  2563. // get default window
  2564. let d_windows: Vec<WindowConfig> = vec![];
  2565. // get default bundle
  2566. let d_bundle = BundleConfig::default();
  2567. // create a tauri config.
  2568. let app = AppConfig {
  2569. windows: vec![],
  2570. security: SecurityConfig {
  2571. csp: None,
  2572. dev_csp: None,
  2573. freeze_prototype: false,
  2574. dangerous_disable_asset_csp_modification: DisabledCspModificationKind::Flag(false),
  2575. asset_protocol: AssetProtocolConfig::default(),
  2576. pattern: Default::default(),
  2577. capabilities: Vec::new(),
  2578. },
  2579. tray_icon: None,
  2580. macos_private_api: false,
  2581. with_global_tauri: false,
  2582. };
  2583. // create a build config
  2584. let build = BuildConfig {
  2585. runner: None,
  2586. dev_url: None,
  2587. frontend_dist: None,
  2588. before_dev_command: None,
  2589. before_build_command: None,
  2590. before_bundle_command: None,
  2591. features: None,
  2592. };
  2593. // create a bundle config
  2594. let bundle = BundleConfig {
  2595. active: false,
  2596. targets: Default::default(),
  2597. publisher: None,
  2598. homepage: None,
  2599. icon: Vec::new(),
  2600. resources: None,
  2601. copyright: None,
  2602. category: None,
  2603. file_associations: None,
  2604. short_description: None,
  2605. long_description: None,
  2606. license: None,
  2607. license_file: None,
  2608. linux: Default::default(),
  2609. macos: Default::default(),
  2610. external_bin: None,
  2611. windows: Default::default(),
  2612. ios: Default::default(),
  2613. android: Default::default(),
  2614. };
  2615. // test the configs
  2616. assert_eq!(a_config, app);
  2617. assert_eq!(b_config, build);
  2618. assert_eq!(d_bundle, bundle);
  2619. assert_eq!(d_windows, app.windows);
  2620. }
  2621. }