config.rs 112 KB

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