config.rs 117 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587
  1. // Copyright 2019-2021 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. //! The Tauri configuration used at runtime.
  5. //!
  6. //! It is pulled from a `tauri.conf.json` file and the [`Config`] struct is generated at compile time.
  7. //!
  8. //! # Stability
  9. //! This is a core functionality that is not considered part of the stable API.
  10. //! If you use it, note that it may include breaking changes in the future.
  11. #[cfg(target_os = "linux")]
  12. use heck::ToKebabCase;
  13. #[cfg(feature = "schema")]
  14. use schemars::JsonSchema;
  15. use semver::Version;
  16. use serde::{
  17. de::{Deserializer, Error as DeError, Visitor},
  18. Deserialize, Serialize, Serializer,
  19. };
  20. use serde_json::Value as JsonValue;
  21. use serde_with::skip_serializing_none;
  22. use url::Url;
  23. use std::{
  24. collections::HashMap,
  25. fmt::{self, Display},
  26. fs::read_to_string,
  27. path::PathBuf,
  28. str::FromStr,
  29. };
  30. /// Items to help with parsing content into a [`Config`].
  31. pub mod parse;
  32. pub use self::parse::parse;
  33. /// An URL to open on a Tauri webview window.
  34. #[derive(PartialEq, Eq, Debug, Clone, Deserialize, Serialize)]
  35. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  36. #[serde(untagged)]
  37. #[non_exhaustive]
  38. pub enum WindowUrl {
  39. /// An external URL.
  40. External(Url),
  41. /// The path portion of an app URL.
  42. /// For instance, to load `tauri://localhost/users/john`,
  43. /// you can simply provide `users/john` in this configuration.
  44. App(PathBuf),
  45. }
  46. impl fmt::Display for WindowUrl {
  47. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  48. match self {
  49. Self::External(url) => write!(f, "{}", url),
  50. Self::App(path) => write!(f, "{}", path.display()),
  51. }
  52. }
  53. }
  54. impl Default for WindowUrl {
  55. fn default() -> Self {
  56. Self::App("index.html".into())
  57. }
  58. }
  59. /// A bundle referenced by tauri-bundler.
  60. #[derive(Debug, PartialEq, Eq, Clone)]
  61. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  62. #[cfg_attr(feature = "schema", schemars(rename_all = "lowercase"))]
  63. pub enum BundleType {
  64. /// The debian bundle (.deb).
  65. Deb,
  66. /// The AppImage bundle (.appimage).
  67. AppImage,
  68. /// The Microsoft Installer bundle (.msi).
  69. Msi,
  70. /// The macOS application bundle (.app).
  71. App,
  72. /// The Apple Disk Image bundle (.dmg).
  73. Dmg,
  74. /// The Tauri updater bundle.
  75. Updater,
  76. }
  77. impl Display for BundleType {
  78. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  79. write!(
  80. f,
  81. "{}",
  82. match self {
  83. Self::Deb => "deb",
  84. Self::AppImage => "appimage",
  85. Self::Msi => "msi",
  86. Self::App => "app",
  87. Self::Dmg => "dmg",
  88. Self::Updater => "updater",
  89. }
  90. )
  91. }
  92. }
  93. impl Serialize for BundleType {
  94. fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
  95. where
  96. S: Serializer,
  97. {
  98. serializer.serialize_str(self.to_string().as_ref())
  99. }
  100. }
  101. impl<'de> Deserialize<'de> for BundleType {
  102. fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
  103. where
  104. D: Deserializer<'de>,
  105. {
  106. let s = String::deserialize(deserializer)?;
  107. match s.to_lowercase().as_str() {
  108. "deb" => Ok(Self::Deb),
  109. "appimage" => Ok(Self::AppImage),
  110. "msi" => Ok(Self::Msi),
  111. "app" => Ok(Self::App),
  112. "dmg" => Ok(Self::Dmg),
  113. "updater" => Ok(Self::Updater),
  114. _ => Err(DeError::custom(format!("unknown bundle target '{}'", s))),
  115. }
  116. }
  117. }
  118. /// Targets to bundle. Each value is case insensitive.
  119. #[derive(Debug, PartialEq, Eq, Clone)]
  120. pub enum BundleTarget {
  121. /// Bundle all targets.
  122. All,
  123. /// A list of bundle targets.
  124. List(Vec<BundleType>),
  125. /// A single bundle target.
  126. One(BundleType),
  127. }
  128. #[cfg(feature = "schema")]
  129. impl schemars::JsonSchema for BundleTarget {
  130. fn schema_name() -> std::string::String {
  131. "BundleTarget".to_owned()
  132. }
  133. fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
  134. let any_of = vec![
  135. schemars::schema::SchemaObject {
  136. enum_values: Some(vec!["all".into()]),
  137. metadata: Some(Box::new(schemars::schema::Metadata {
  138. description: Some("Bundle all targets.".to_owned()),
  139. ..Default::default()
  140. })),
  141. ..Default::default()
  142. }
  143. .into(),
  144. schemars::_private::apply_metadata(
  145. gen.subschema_for::<Vec<BundleType>>(),
  146. schemars::schema::Metadata {
  147. description: Some("A list of bundle targets.".to_owned()),
  148. ..Default::default()
  149. },
  150. ),
  151. schemars::_private::apply_metadata(
  152. gen.subschema_for::<BundleType>(),
  153. schemars::schema::Metadata {
  154. description: Some("A single bundle target.".to_owned()),
  155. ..Default::default()
  156. },
  157. ),
  158. ];
  159. schemars::schema::SchemaObject {
  160. subschemas: Some(Box::new(schemars::schema::SubschemaValidation {
  161. any_of: Some(any_of),
  162. ..Default::default()
  163. })),
  164. metadata: Some(Box::new(schemars::schema::Metadata {
  165. description: Some("Targets to bundle. Each value is case insensitive.".to_owned()),
  166. ..Default::default()
  167. })),
  168. ..Default::default()
  169. }
  170. .into()
  171. }
  172. }
  173. impl Default for BundleTarget {
  174. fn default() -> Self {
  175. Self::All
  176. }
  177. }
  178. impl Serialize for BundleTarget {
  179. fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
  180. where
  181. S: Serializer,
  182. {
  183. match self {
  184. Self::All => serializer.serialize_str("all"),
  185. Self::List(l) => l.serialize(serializer),
  186. Self::One(t) => serializer.serialize_str(t.to_string().as_ref()),
  187. }
  188. }
  189. }
  190. impl<'de> Deserialize<'de> for BundleTarget {
  191. fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
  192. where
  193. D: Deserializer<'de>,
  194. {
  195. #[derive(Deserialize, Serialize)]
  196. #[serde(untagged)]
  197. pub enum BundleTargetInner {
  198. List(Vec<BundleType>),
  199. One(BundleType),
  200. All(String),
  201. }
  202. match BundleTargetInner::deserialize(deserializer)? {
  203. BundleTargetInner::All(s) if s.to_lowercase() == "all" => Ok(Self::All),
  204. BundleTargetInner::All(t) => Err(DeError::custom(format!("invalid bundle type {}", t))),
  205. BundleTargetInner::List(l) => Ok(Self::List(l)),
  206. BundleTargetInner::One(t) => Ok(Self::One(t)),
  207. }
  208. }
  209. }
  210. impl BundleTarget {
  211. /// Gets the bundle targets as a [`Vec`]. The vector is empty when set to [`BundleTarget::All`].
  212. #[allow(dead_code)]
  213. pub fn to_vec(&self) -> Vec<BundleType> {
  214. match self {
  215. Self::All => vec![],
  216. Self::List(list) => list.clone(),
  217. Self::One(i) => vec![i.clone()],
  218. }
  219. }
  220. }
  221. /// Configuration for AppImage bundles.
  222. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  223. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  224. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  225. pub struct AppImageConfig {
  226. /// Include additional gstreamer dependencies needed for audio and video playback.
  227. /// This increases the bundle size by ~15-35MB depending on your build system.
  228. #[serde(default, alias = "bundle-media-framework")]
  229. pub bundle_media_framework: bool,
  230. }
  231. /// Configuration for Debian (.deb) bundles.
  232. #[skip_serializing_none]
  233. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  234. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  235. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  236. pub struct DebConfig {
  237. /// The list of deb dependencies your application relies on.
  238. pub depends: Option<Vec<String>>,
  239. /// The files to include on the package.
  240. #[serde(default)]
  241. pub files: HashMap<PathBuf, PathBuf>,
  242. }
  243. fn de_minimum_system_version<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
  244. where
  245. D: Deserializer<'de>,
  246. {
  247. let version = Option::<String>::deserialize(deserializer)?;
  248. match version {
  249. Some(v) if v.is_empty() => Ok(minimum_system_version()),
  250. e => Ok(e),
  251. }
  252. }
  253. /// Configuration for the macOS bundles.
  254. #[skip_serializing_none]
  255. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  256. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  257. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  258. pub struct MacConfig {
  259. /// A list of strings indicating any macOS X frameworks that need to be bundled with the application.
  260. ///
  261. /// 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.
  262. pub frameworks: Option<Vec<String>>,
  263. /// A version string indicating the minimum macOS X version that the bundled application supports. Defaults to `10.13`.
  264. ///
  265. /// Setting it to `null` completely removes the `LSMinimumSystemVersion` field on the bundle's `Info.plist`
  266. /// and the `MACOSX_DEPLOYMENT_TARGET` environment variable.
  267. ///
  268. /// An empty string is considered an invalid value so the default value is used.
  269. #[serde(
  270. deserialize_with = "de_minimum_system_version",
  271. default = "minimum_system_version",
  272. alias = "minimum-system-version"
  273. )]
  274. pub minimum_system_version: Option<String>,
  275. /// Allows your application to communicate with the outside world.
  276. /// It should be a lowercase, without port and protocol domain name.
  277. #[serde(alias = "exception-domain")]
  278. pub exception_domain: Option<String>,
  279. /// The path to the license file to add to the DMG bundle.
  280. pub license: Option<String>,
  281. /// Identity to use for code signing.
  282. #[serde(alias = "signing-identity")]
  283. pub signing_identity: Option<String>,
  284. /// Provider short name for notarization.
  285. #[serde(alias = "provider-short-name")]
  286. pub provider_short_name: Option<String>,
  287. /// Path to the entitlements file.
  288. pub entitlements: Option<String>,
  289. }
  290. impl Default for MacConfig {
  291. fn default() -> Self {
  292. Self {
  293. frameworks: None,
  294. minimum_system_version: minimum_system_version(),
  295. exception_domain: None,
  296. license: None,
  297. signing_identity: None,
  298. provider_short_name: None,
  299. entitlements: None,
  300. }
  301. }
  302. }
  303. fn minimum_system_version() -> Option<String> {
  304. Some("10.13".into())
  305. }
  306. /// Configuration for a target language for the WiX build.
  307. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  308. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  309. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  310. pub struct WixLanguageConfig {
  311. /// The path to a locale (`.wxl`) file. See <https://wixtoolset.org/documentation/manual/v3/howtos/ui_and_localization/build_a_localized_version.html>.
  312. #[serde(alias = "locale-path")]
  313. pub locale_path: Option<String>,
  314. }
  315. /// The languages to build using WiX.
  316. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  317. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  318. #[serde(untagged)]
  319. pub enum WixLanguage {
  320. /// A single language to build, without configuration.
  321. One(String),
  322. /// A list of languages to build, without configuration.
  323. List(Vec<String>),
  324. /// A map of languages and its configuration.
  325. Localized(HashMap<String, WixLanguageConfig>),
  326. }
  327. impl Default for WixLanguage {
  328. fn default() -> Self {
  329. Self::One("en-US".into())
  330. }
  331. }
  332. /// Configuration for the MSI bundle using WiX.
  333. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  334. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  335. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  336. pub struct WixConfig {
  337. /// The installer languages to build. See <https://docs.microsoft.com/en-us/windows/win32/msi/localizing-the-error-and-actiontext-tables>.
  338. #[serde(default)]
  339. pub language: WixLanguage,
  340. /// A custom .wxs template to use.
  341. pub template: Option<PathBuf>,
  342. /// A list of paths to .wxs files with WiX fragments to use.
  343. #[serde(default, alias = "fragment-paths")]
  344. pub fragment_paths: Vec<PathBuf>,
  345. /// The ComponentGroup element ids you want to reference from the fragments.
  346. #[serde(default, alias = "component-group-refs")]
  347. pub component_group_refs: Vec<String>,
  348. /// The Component element ids you want to reference from the fragments.
  349. #[serde(default, alias = "component-refs")]
  350. pub component_refs: Vec<String>,
  351. /// The FeatureGroup element ids you want to reference from the fragments.
  352. #[serde(default, alias = "feature-group-refs")]
  353. pub feature_group_refs: Vec<String>,
  354. /// The Feature element ids you want to reference from the fragments.
  355. #[serde(default, alias = "feature-refs")]
  356. pub feature_refs: Vec<String>,
  357. /// The Merge element ids you want to reference from the fragments.
  358. #[serde(default, alias = "merge-refs")]
  359. pub merge_refs: Vec<String>,
  360. /// Disables the Webview2 runtime installation after app install.
  361. ///
  362. /// Will be removed in v2, prefer the [`WindowsConfig::webview_install_mode`] option.
  363. #[serde(default, alias = "skip-webview-install")]
  364. pub skip_webview_install: bool,
  365. /// The path to the license file to render on the installer.
  366. ///
  367. /// Must be an RTF file, so if a different extension is provided, we convert it to the RTF format.
  368. pub license: Option<PathBuf>,
  369. /// Create an elevated update task within Windows Task Scheduler.
  370. #[serde(default, alias = "enable-elevated-update-task")]
  371. pub enable_elevated_update_task: bool,
  372. /// Path to a bitmap file to use as the installation user interface banner.
  373. /// This bitmap will appear at the top of all but the first page of the installer.
  374. ///
  375. /// The required dimensions are 493px × 58px.
  376. #[serde(alias = "banner-path")]
  377. pub banner_path: Option<PathBuf>,
  378. /// Path to a bitmap file to use on the installation user interface dialogs.
  379. /// It is used on the welcome and completion dialogs.
  380. /// The required dimensions are 493px × 312px.
  381. #[serde(alias = "dialog-image-path")]
  382. pub dialog_image_path: Option<PathBuf>,
  383. }
  384. /// Install modes for the Webview2 runtime.
  385. /// Note that for the updater bundle [`Self::DownloadBootstrapper`] is used.
  386. ///
  387. /// For more information see <https://tauri.app/v1/guides/building/windows>.
  388. #[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
  389. #[serde(tag = "type", rename_all = "camelCase", deny_unknown_fields)]
  390. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  391. pub enum WebviewInstallMode {
  392. /// Do not install the Webview2 as part of the Windows Installer.
  393. Skip,
  394. /// Download the bootstrapper and run it.
  395. /// Requires internet connection.
  396. /// Results in a smaller installer size, but is not recommended on Windows 7.
  397. DownloadBootstrapper {
  398. /// Instructs the installer to run the bootstrapper in silent mode. Defaults to `true`.
  399. #[serde(default = "default_webview_install_silent")]
  400. silent: bool,
  401. },
  402. /// Embed the bootstrapper and run it.
  403. /// Requires internet connection.
  404. /// Increases the installer size by around 1.8MB, but offers better support on Windows 7.
  405. EmbedBootstrapper {
  406. /// Instructs the installer to run the bootstrapper in silent mode. Defaults to `true`.
  407. #[serde(default = "default_webview_install_silent")]
  408. silent: bool,
  409. },
  410. /// Embed the offline installer and run it.
  411. /// Does not require internet connection.
  412. /// Increases the installer size by around 127MB.
  413. OfflineInstaller {
  414. /// Instructs the installer to run the installer in silent mode. Defaults to `true`.
  415. #[serde(default = "default_webview_install_silent")]
  416. silent: bool,
  417. },
  418. /// Embed a fixed webview2 version and use it at runtime.
  419. /// Increases the installer size by around 180MB.
  420. FixedRuntime {
  421. /// The path to the fixed runtime to use.
  422. ///
  423. /// The fixed version can be downloaded [on the official website](https://developer.microsoft.com/en-us/microsoft-edge/webview2/#download-section).
  424. /// The `.cab` file must be extracted to a folder and this folder path must be defined on this field.
  425. path: PathBuf,
  426. },
  427. }
  428. fn default_webview_install_silent() -> bool {
  429. true
  430. }
  431. impl Default for WebviewInstallMode {
  432. fn default() -> Self {
  433. Self::DownloadBootstrapper {
  434. silent: default_webview_install_silent(),
  435. }
  436. }
  437. }
  438. /// Windows bundler configuration.
  439. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  440. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  441. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  442. pub struct WindowsConfig {
  443. /// Specifies the file digest algorithm to use for creating file signatures.
  444. /// Required for code signing. SHA-256 is recommended.
  445. #[serde(alias = "digest-algorithm")]
  446. pub digest_algorithm: Option<String>,
  447. /// Specifies the SHA1 hash of the signing certificate.
  448. #[serde(alias = "certificate-thumbprint")]
  449. pub certificate_thumbprint: Option<String>,
  450. /// Server to use during timestamping.
  451. #[serde(alias = "timestamp-url")]
  452. pub timestamp_url: Option<String>,
  453. /// Whether to use Time-Stamp Protocol (TSP, a.k.a. RFC 3161) for the timestamp server. Your code signing provider may
  454. /// use a TSP timestamp server, like e.g. SSL.com does. If so, enable TSP by setting to true.
  455. #[serde(default)]
  456. pub tsp: bool,
  457. /// The installation mode for the Webview2 runtime.
  458. #[serde(default, alias = "webview-install-mode")]
  459. pub webview_install_mode: WebviewInstallMode,
  460. /// Path to the webview fixed runtime to use. Overwrites [`Self::webview_install_mode`] if set.
  461. ///
  462. /// Will be removed in v2, prefer the [`Self::webview_install_mode`] option.
  463. ///
  464. /// The fixed version can be downloaded [on the official website](https://developer.microsoft.com/en-us/microsoft-edge/webview2/#download-section).
  465. /// The `.cab` file must be extracted to a folder and this folder path must be defined on this field.
  466. #[serde(alias = "webview-fixed-runtime-path")]
  467. pub webview_fixed_runtime_path: Option<PathBuf>,
  468. /// Validates a second app installation, blocking the user from installing an older version if set to `false`.
  469. ///
  470. /// 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`.
  471. ///
  472. /// The default value of this flag is `true`.
  473. #[serde(default = "default_allow_downgrades", alias = "allow-downgrades")]
  474. pub allow_downgrades: bool,
  475. /// Configuration for the MSI generated with WiX.
  476. pub wix: Option<WixConfig>,
  477. }
  478. impl Default for WindowsConfig {
  479. fn default() -> Self {
  480. Self {
  481. digest_algorithm: None,
  482. certificate_thumbprint: None,
  483. timestamp_url: None,
  484. tsp: false,
  485. webview_install_mode: Default::default(),
  486. webview_fixed_runtime_path: None,
  487. allow_downgrades: default_allow_downgrades(),
  488. wix: None,
  489. }
  490. }
  491. }
  492. fn default_allow_downgrades() -> bool {
  493. true
  494. }
  495. /// Configuration for tauri-bundler.
  496. #[skip_serializing_none]
  497. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  498. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  499. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  500. pub struct BundleConfig {
  501. /// Whether Tauri should bundle your application or just output the executable.
  502. #[serde(default)]
  503. pub active: bool,
  504. /// The bundle targets, currently supports ["deb", "appimage", "msi", "app", "dmg", "updater"] or "all".
  505. #[serde(default)]
  506. pub targets: BundleTarget,
  507. /// The application identifier in reverse domain name notation (e.g. `com.tauri.example`).
  508. /// This string must be unique across applications since it is used in system configurations like
  509. /// the bundle ID and path to the webview data directory.
  510. /// This string must contain only alphanumeric characters (A–Z, a–z, and 0–9), hyphens (-),
  511. /// and periods (.).
  512. pub identifier: String,
  513. /// The app's icons
  514. #[serde(default)]
  515. pub icon: Vec<String>,
  516. /// App resources to bundle.
  517. /// Each resource is a path to a file or directory.
  518. /// Glob patterns are supported.
  519. pub resources: Option<Vec<String>>,
  520. /// A copyright string associated with your application.
  521. pub copyright: Option<String>,
  522. /// The application kind.
  523. ///
  524. /// Should be one of the following:
  525. /// 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.
  526. pub category: Option<String>,
  527. /// A short description of your application.
  528. #[serde(alias = "short-description")]
  529. pub short_description: Option<String>,
  530. /// A longer, multi-line description of the application.
  531. #[serde(alias = "long-description")]
  532. pub long_description: Option<String>,
  533. /// Configuration for the AppImage bundle.
  534. #[serde(default)]
  535. pub appimage: AppImageConfig,
  536. /// Configuration for the Debian bundle.
  537. #[serde(default)]
  538. pub deb: DebConfig,
  539. /// Configuration for the macOS bundles.
  540. #[serde(rename = "macOS", default)]
  541. pub macos: MacConfig,
  542. /// A list of—either absolute or relative—paths to binaries to embed with your application.
  543. ///
  544. /// Note that Tauri will look for system-specific binaries following the pattern "binary-name{-target-triple}{.system-extension}".
  545. ///
  546. /// E.g. for the external binary "my-binary", Tauri looks for:
  547. ///
  548. /// - "my-binary-x86_64-pc-windows-msvc.exe" for Windows
  549. /// - "my-binary-x86_64-apple-darwin" for macOS
  550. /// - "my-binary-x86_64-unknown-linux-gnu" for Linux
  551. ///
  552. /// so don't forget to provide binaries for all targeted platforms.
  553. #[serde(alias = "external-bin")]
  554. pub external_bin: Option<Vec<String>>,
  555. /// Configuration for the Windows bundle.
  556. #[serde(default)]
  557. pub windows: WindowsConfig,
  558. }
  559. /// A CLI argument definition.
  560. #[skip_serializing_none]
  561. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  562. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  563. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  564. pub struct CliArg {
  565. /// The short version of the argument, without the preceding -.
  566. ///
  567. /// NOTE: Any leading `-` characters will be stripped, and only the first non-character will be used as the short version.
  568. pub short: Option<char>,
  569. /// The unique argument name
  570. pub name: String,
  571. /// The argument description which will be shown on the help information.
  572. /// Typically, this is a short (one line) description of the arg.
  573. pub description: Option<String>,
  574. /// The argument long description which will be shown on the help information.
  575. /// Typically this a more detailed (multi-line) message that describes the argument.
  576. #[serde(alias = "long-description")]
  577. pub long_description: Option<String>,
  578. /// Specifies that the argument takes a value at run time.
  579. ///
  580. /// NOTE: values for arguments may be specified in any of the following methods
  581. /// - Using a space such as -o value or --option value
  582. /// - Using an equals and no space such as -o=value or --option=value
  583. /// - Use a short and no space such as -ovalue
  584. #[serde(default, alias = "takes-value")]
  585. pub takes_value: bool,
  586. /// Specifies that the argument may have an unknown number of multiple values. Without any other settings, this argument may appear only once.
  587. ///
  588. /// For example, --opt val1 val2 is allowed, but --opt val1 val2 --opt val3 is not.
  589. ///
  590. /// NOTE: Setting this requires `takes_value` to be set to true.
  591. #[serde(default)]
  592. pub multiple: bool,
  593. /// Specifies that the argument may appear more than once.
  594. /// For flags, this results in the number of occurrences of the flag being recorded. For example -ddd or -d -d -d would count as three occurrences.
  595. /// For options or arguments that take a value, this does not affect how many values they can accept. (i.e. only one at a time is allowed)
  596. ///
  597. /// For example, --opt val1 --opt val2 is allowed, but --opt val1 val2 is not.
  598. #[serde(default, alias = "multiple-occurrences")]
  599. pub multiple_occurrences: bool,
  600. /// Specifies how many values are required to satisfy this argument. For example, if you had a
  601. /// `-f <file>` argument where you wanted exactly 3 'files' you would set
  602. /// `number_of_values = 3`, and this argument wouldn't be satisfied unless the user provided
  603. /// 3 and only 3 values.
  604. ///
  605. /// **NOTE:** Does *not* require `multiple_occurrences = true` to be set. Setting
  606. /// `multiple_occurrences = true` would allow `-f <file> <file> <file> -f <file> <file> <file>` where
  607. /// as *not* setting it would only allow one occurrence of this argument.
  608. ///
  609. /// **NOTE:** implicitly sets `takes_value = true` and `multiple_values = true`.
  610. #[serde(alias = "number-of-values")]
  611. pub number_of_values: Option<usize>,
  612. /// Specifies a list of possible values for this argument.
  613. /// At runtime, the CLI verifies that only one of the specified values was used, or fails with an error message.
  614. #[serde(alias = "possible-values")]
  615. pub possible_values: Option<Vec<String>>,
  616. /// Specifies the minimum number of values for this argument.
  617. /// For example, if you had a -f `<file>` argument where you wanted at least 2 'files',
  618. /// you would set `minValues: 2`, and this argument would be satisfied if the user provided, 2 or more values.
  619. #[serde(alias = "min-values")]
  620. pub min_values: Option<usize>,
  621. /// Specifies the maximum number of values are for this argument.
  622. /// For example, if you had a -f `<file>` argument where you wanted up to 3 'files',
  623. /// you would set .max_values(3), and this argument would be satisfied if the user provided, 1, 2, or 3 values.
  624. #[serde(alias = "max-values")]
  625. pub max_values: Option<usize>,
  626. /// Sets whether or not the argument is required by default.
  627. ///
  628. /// - Required by default means it is required, when no other conflicting rules have been evaluated
  629. /// - Conflicting rules take precedence over being required.
  630. #[serde(default)]
  631. pub required: bool,
  632. /// Sets an arg that override this arg's required setting
  633. /// i.e. this arg will be required unless this other argument is present.
  634. #[serde(alias = "requred-unless-present")]
  635. pub required_unless_present: Option<String>,
  636. /// Sets args that override this arg's required setting
  637. /// i.e. this arg will be required unless all these other arguments are present.
  638. #[serde(alias = "required-unless-present-all")]
  639. pub required_unless_present_all: Option<Vec<String>>,
  640. /// Sets args that override this arg's required setting
  641. /// i.e. this arg will be required unless at least one of these other arguments are present.
  642. #[serde(alias = "required-unless-present-any")]
  643. pub required_unless_present_any: Option<Vec<String>>,
  644. /// Sets a conflicting argument by name
  645. /// i.e. when using this argument, the following argument can't be present and vice versa.
  646. #[serde(alias = "conflicts-with")]
  647. pub conflicts_with: Option<String>,
  648. /// The same as conflictsWith but allows specifying multiple two-way conflicts per argument.
  649. #[serde(alias = "conflicts-with-all")]
  650. pub conflicts_with_all: Option<Vec<String>>,
  651. /// Tets an argument by name that is required when this one is present
  652. /// i.e. when using this argument, the following argument must be present.
  653. pub requires: Option<String>,
  654. /// Sts multiple arguments by names that are required when this one is present
  655. /// i.e. when using this argument, the following arguments must be present.
  656. #[serde(alias = "requires-all")]
  657. pub requires_all: Option<Vec<String>>,
  658. /// Allows a conditional requirement with the signature [arg, value]
  659. /// the requirement will only become valid if `arg`'s value equals `${value}`.
  660. #[serde(alias = "requires-if")]
  661. pub requires_if: Option<Vec<String>>,
  662. /// Allows specifying that an argument is required conditionally with the signature [arg, value]
  663. /// the requirement will only become valid if the `arg`'s value equals `${value}`.
  664. #[serde(alias = "requires-if-eq")]
  665. pub required_if_eq: Option<Vec<String>>,
  666. /// Requires that options use the --option=val syntax
  667. /// i.e. an equals between the option and associated value.
  668. #[serde(alias = "requires-equals")]
  669. pub require_equals: Option<bool>,
  670. /// The positional argument index, starting at 1.
  671. ///
  672. /// The index refers to position according to other positional argument.
  673. /// It does not define position in the argument list as a whole. When utilized with multiple=true,
  674. /// only the last positional argument may be defined as multiple (i.e. the one with the highest index).
  675. #[cfg_attr(feature = "schema", validate(range(min = 1)))]
  676. pub index: Option<usize>,
  677. }
  678. /// describes a CLI configuration
  679. #[skip_serializing_none]
  680. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  681. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  682. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  683. pub struct CliConfig {
  684. /// Command description which will be shown on the help information.
  685. pub description: Option<String>,
  686. /// Command long description which will be shown on the help information.
  687. #[serde(alias = "long-description")]
  688. pub long_description: Option<String>,
  689. /// Adds additional help information to be displayed in addition to auto-generated help.
  690. /// This information is displayed before the auto-generated help information.
  691. /// This is often used for header information.
  692. #[serde(alias = "before-help")]
  693. pub before_help: Option<String>,
  694. /// Adds additional help information to be displayed in addition to auto-generated help.
  695. /// This information is displayed after the auto-generated help information.
  696. /// This is often used to describe how to use the arguments, or caveats to be noted.
  697. #[serde(alias = "after-help")]
  698. pub after_help: Option<String>,
  699. /// List of arguments for the command
  700. pub args: Option<Vec<CliArg>>,
  701. /// List of subcommands of this command
  702. pub subcommands: Option<HashMap<String, CliConfig>>,
  703. }
  704. impl CliConfig {
  705. /// List of arguments for the command
  706. pub fn args(&self) -> Option<&Vec<CliArg>> {
  707. self.args.as_ref()
  708. }
  709. /// List of subcommands of this command
  710. pub fn subcommands(&self) -> Option<&HashMap<String, CliConfig>> {
  711. self.subcommands.as_ref()
  712. }
  713. /// Command description which will be shown on the help information.
  714. pub fn description(&self) -> Option<&String> {
  715. self.description.as_ref()
  716. }
  717. /// Command long description which will be shown on the help information.
  718. pub fn long_description(&self) -> Option<&String> {
  719. self.description.as_ref()
  720. }
  721. /// Adds additional help information to be displayed in addition to auto-generated help.
  722. /// This information is displayed before the auto-generated help information.
  723. /// This is often used for header information.
  724. pub fn before_help(&self) -> Option<&String> {
  725. self.before_help.as_ref()
  726. }
  727. /// Adds additional help information to be displayed in addition to auto-generated help.
  728. /// This information is displayed after the auto-generated help information.
  729. /// This is often used to describe how to use the arguments, or caveats to be noted.
  730. pub fn after_help(&self) -> Option<&String> {
  731. self.after_help.as_ref()
  732. }
  733. }
  734. /// The window configuration object.
  735. #[skip_serializing_none]
  736. #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
  737. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  738. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  739. pub struct WindowConfig {
  740. /// The window identifier. It must be alphanumeric.
  741. #[serde(default = "default_window_label")]
  742. pub label: String,
  743. /// The window webview URL.
  744. #[serde(default)]
  745. pub url: WindowUrl,
  746. /// Whether the file drop is enabled or not on the webview. By default it is enabled.
  747. ///
  748. /// Disabling it is required to use drag and drop on the frontend on Windows.
  749. #[serde(default = "default_file_drop_enabled", alias = "file-drop-enabled")]
  750. pub file_drop_enabled: bool,
  751. /// Whether or not the window starts centered or not.
  752. #[serde(default)]
  753. pub center: bool,
  754. /// The horizontal position of the window's top left corner
  755. pub x: Option<f64>,
  756. /// The vertical position of the window's top left corner
  757. pub y: Option<f64>,
  758. /// The window width.
  759. #[serde(default = "default_width")]
  760. pub width: f64,
  761. /// The window height.
  762. #[serde(default = "default_height")]
  763. pub height: f64,
  764. /// The min window width.
  765. #[serde(alias = "min-width")]
  766. pub min_width: Option<f64>,
  767. /// The min window height.
  768. #[serde(alias = "min-height")]
  769. pub min_height: Option<f64>,
  770. /// The max window width.
  771. #[serde(alias = "max-width")]
  772. pub max_width: Option<f64>,
  773. /// The max window height.
  774. #[serde(alias = "max-height")]
  775. pub max_height: Option<f64>,
  776. /// Whether the window is resizable or not.
  777. #[serde(default = "default_resizable")]
  778. pub resizable: bool,
  779. /// The window title.
  780. #[serde(default = "default_title")]
  781. pub title: String,
  782. /// Whether the window starts as fullscreen or not.
  783. #[serde(default)]
  784. pub fullscreen: bool,
  785. /// Whether the window will be initially hidden or focused.
  786. #[serde(default = "default_focus")]
  787. pub focus: bool,
  788. /// Whether the window is transparent or not.
  789. ///
  790. /// Note that on `macOS` this requires the `macos-private-api` feature flag, enabled under `tauri > macOSPrivateApi`.
  791. /// WARNING: Using private APIs on `macOS` prevents your application from being accepted to the `App Store`.
  792. #[serde(default)]
  793. pub transparent: bool,
  794. /// Whether the window is maximized or not.
  795. #[serde(default)]
  796. pub maximized: bool,
  797. /// Whether the window is visible or not.
  798. #[serde(default = "default_visible")]
  799. pub visible: bool,
  800. /// Whether the window should have borders and bars.
  801. #[serde(default = "default_decorations")]
  802. pub decorations: bool,
  803. /// Whether the window should always be on top of other windows.
  804. #[serde(default, alias = "always-on-top")]
  805. pub always_on_top: bool,
  806. /// Whether or not the window icon should be added to the taskbar.
  807. #[serde(default, alias = "skip-taskbar")]
  808. pub skip_taskbar: bool,
  809. /// The initial window theme. Defaults to the system theme. Only implemented on Windows and macOS 10.14+.
  810. pub theme: Option<crate::Theme>,
  811. }
  812. impl Default for WindowConfig {
  813. fn default() -> Self {
  814. Self {
  815. label: default_window_label(),
  816. url: WindowUrl::default(),
  817. file_drop_enabled: default_file_drop_enabled(),
  818. center: false,
  819. x: None,
  820. y: None,
  821. width: default_width(),
  822. height: default_height(),
  823. min_width: None,
  824. min_height: None,
  825. max_width: None,
  826. max_height: None,
  827. resizable: default_resizable(),
  828. title: default_title(),
  829. fullscreen: false,
  830. focus: false,
  831. transparent: false,
  832. maximized: false,
  833. visible: default_visible(),
  834. decorations: default_decorations(),
  835. always_on_top: false,
  836. skip_taskbar: false,
  837. theme: None,
  838. }
  839. }
  840. }
  841. fn default_window_label() -> String {
  842. "main".to_string()
  843. }
  844. fn default_width() -> f64 {
  845. 800f64
  846. }
  847. fn default_height() -> f64 {
  848. 600f64
  849. }
  850. fn default_resizable() -> bool {
  851. true
  852. }
  853. fn default_title() -> String {
  854. "Tauri App".to_string()
  855. }
  856. fn default_focus() -> bool {
  857. true
  858. }
  859. fn default_visible() -> bool {
  860. true
  861. }
  862. fn default_decorations() -> bool {
  863. true
  864. }
  865. fn default_file_drop_enabled() -> bool {
  866. true
  867. }
  868. /// A Content-Security-Policy directive source list.
  869. /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/Sources#sources>.
  870. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  871. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  872. #[serde(rename_all = "camelCase", untagged)]
  873. pub enum CspDirectiveSources {
  874. /// An inline list of CSP sources. Same as [`Self::List`], but concatenated with a space separator.
  875. Inline(String),
  876. /// A list of CSP sources. The collection will be concatenated with a space separator for the CSP string.
  877. List(Vec<String>),
  878. }
  879. impl Default for CspDirectiveSources {
  880. fn default() -> Self {
  881. Self::List(Vec::new())
  882. }
  883. }
  884. impl From<CspDirectiveSources> for Vec<String> {
  885. fn from(sources: CspDirectiveSources) -> Self {
  886. match sources {
  887. CspDirectiveSources::Inline(source) => source.split(' ').map(|s| s.to_string()).collect(),
  888. CspDirectiveSources::List(l) => l,
  889. }
  890. }
  891. }
  892. impl CspDirectiveSources {
  893. /// Whether the given source is configured on this directive or not.
  894. pub fn contains(&self, source: &str) -> bool {
  895. match self {
  896. Self::Inline(s) => s.contains(&format!("{} ", source)) || s.contains(&format!(" {}", source)),
  897. Self::List(l) => l.contains(&source.into()),
  898. }
  899. }
  900. /// Appends the given source to this directive.
  901. pub fn push<S: AsRef<str>>(&mut self, source: S) {
  902. match self {
  903. Self::Inline(s) => {
  904. s.push(' ');
  905. s.push_str(source.as_ref());
  906. }
  907. Self::List(l) => {
  908. l.push(source.as_ref().to_string());
  909. }
  910. }
  911. }
  912. /// Extends this CSP directive source list with the given array of sources.
  913. pub fn extend(&mut self, sources: Vec<String>) {
  914. for s in sources {
  915. self.push(s);
  916. }
  917. }
  918. }
  919. /// A Content-Security-Policy definition.
  920. /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP>.
  921. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  922. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  923. #[serde(rename_all = "camelCase", untagged)]
  924. pub enum Csp {
  925. /// The entire CSP policy in a single text string.
  926. Policy(String),
  927. /// An object mapping a directive with its sources values as a list of strings.
  928. DirectiveMap(HashMap<String, CspDirectiveSources>),
  929. }
  930. impl From<HashMap<String, CspDirectiveSources>> for Csp {
  931. fn from(map: HashMap<String, CspDirectiveSources>) -> Self {
  932. Self::DirectiveMap(map)
  933. }
  934. }
  935. impl From<Csp> for HashMap<String, CspDirectiveSources> {
  936. fn from(csp: Csp) -> Self {
  937. match csp {
  938. Csp::Policy(policy) => {
  939. let mut map = HashMap::new();
  940. for directive in policy.split(';') {
  941. let mut tokens = directive.trim().split(' ');
  942. if let Some(directive) = tokens.next() {
  943. let sources = tokens.map(|s| s.to_string()).collect::<Vec<String>>();
  944. map.insert(directive.to_string(), CspDirectiveSources::List(sources));
  945. }
  946. }
  947. map
  948. }
  949. Csp::DirectiveMap(m) => m,
  950. }
  951. }
  952. }
  953. impl Display for Csp {
  954. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  955. match self {
  956. Self::Policy(s) => write!(f, "{}", s),
  957. Self::DirectiveMap(m) => {
  958. let len = m.len();
  959. let mut i = 0;
  960. for (directive, sources) in m {
  961. let sources: Vec<String> = sources.clone().into();
  962. write!(f, "{} {}", directive, sources.join(" "))?;
  963. i += 1;
  964. if i != len {
  965. write!(f, "; ")?;
  966. }
  967. }
  968. Ok(())
  969. }
  970. }
  971. }
  972. }
  973. /// The possible values for the `dangerous_disable_asset_csp_modification` config option.
  974. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  975. #[serde(untagged)]
  976. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  977. pub enum DisabledCspModificationKind {
  978. /// If `true`, disables all CSP modification.
  979. /// `false` is the default value and it configures Tauri to control the CSP.
  980. Flag(bool),
  981. /// Disables the given list of CSP directives modifications.
  982. List(Vec<String>),
  983. }
  984. impl DisabledCspModificationKind {
  985. /// Determines whether the given CSP directive can be modified or not.
  986. pub fn can_modify(&self, directive: &str) -> bool {
  987. match self {
  988. Self::Flag(f) => !f,
  989. Self::List(l) => !l.contains(&directive.into()),
  990. }
  991. }
  992. }
  993. impl Default for DisabledCspModificationKind {
  994. fn default() -> Self {
  995. Self::Flag(false)
  996. }
  997. }
  998. /// Security configuration.
  999. #[skip_serializing_none]
  1000. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1001. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1002. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1003. pub struct SecurityConfig {
  1004. /// The Content Security Policy that will be injected on all HTML files on the built application.
  1005. /// If [`dev_csp`](#SecurityConfig.devCsp) is not specified, this value is also injected on dev.
  1006. ///
  1007. /// This is a really important part of the configuration since it helps you ensure your WebView is secured.
  1008. /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP>.
  1009. pub csp: Option<Csp>,
  1010. /// The Content Security Policy that will be injected on all HTML files on development.
  1011. ///
  1012. /// This is a really important part of the configuration since it helps you ensure your WebView is secured.
  1013. /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP>.
  1014. #[serde(alias = "dev-csp")]
  1015. pub dev_csp: Option<Csp>,
  1016. /// Freeze the `Object.prototype` when using the custom protocol.
  1017. #[serde(default, alias = "freeze-prototype")]
  1018. pub freeze_prototype: bool,
  1019. /// Disables the Tauri-injected CSP sources.
  1020. ///
  1021. /// At compile time, Tauri parses all the frontend assets and changes the Content-Security-Policy
  1022. /// to only allow loading of your own scripts and styles by injecting nonce and hash sources.
  1023. /// This stricts your CSP, which may introduce issues when using along with other flexing sources.
  1024. ///
  1025. /// This configuration option allows both a boolean and a list of strings as value.
  1026. /// A boolean instructs Tauri to disable the injection for all CSP injections,
  1027. /// and a list of strings indicates the CSP directives that Tauri cannot inject.
  1028. ///
  1029. /// **WARNING:** Only disable this if you know what you are doing and have properly configured the CSP.
  1030. /// Your application might be vulnerable to XSS attacks without this Tauri protection.
  1031. #[serde(default, alias = "dangerous-disable-asset-csp-modification")]
  1032. pub dangerous_disable_asset_csp_modification: DisabledCspModificationKind,
  1033. }
  1034. /// Defines an allowlist type.
  1035. pub trait Allowlist {
  1036. /// Returns all features associated with the allowlist struct.
  1037. fn all_features() -> Vec<&'static str>;
  1038. /// Returns the tauri features enabled on this allowlist.
  1039. fn to_features(&self) -> Vec<&'static str>;
  1040. }
  1041. macro_rules! check_feature {
  1042. ($self:ident, $features:ident, $flag:ident, $feature_name: expr) => {
  1043. if $self.$flag {
  1044. $features.push($feature_name)
  1045. }
  1046. };
  1047. }
  1048. /// Filesystem scope definition.
  1049. /// It is a list of glob patterns that restrict the API access from the webview.
  1050. ///
  1051. /// Each pattern can start with a variable that resolves to a system base directory.
  1052. /// The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`,
  1053. /// `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`,
  1054. /// `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$APP`, `$LOG`, `$TEMP`.
  1055. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1056. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1057. #[serde(untagged)]
  1058. pub enum FsAllowlistScope {
  1059. /// A list of paths that are allowed by this scope.
  1060. AllowedPaths(Vec<PathBuf>),
  1061. /// A complete scope configuration.
  1062. Scope {
  1063. /// A list of paths that are allowed by this scope.
  1064. #[serde(default)]
  1065. allow: Vec<PathBuf>,
  1066. /// A list of paths that are not allowed by this scope.
  1067. /// This gets precedence over the [`Self::Scope::allow`] list.
  1068. #[serde(default)]
  1069. deny: Vec<PathBuf>,
  1070. },
  1071. }
  1072. impl Default for FsAllowlistScope {
  1073. fn default() -> Self {
  1074. Self::AllowedPaths(Vec::new())
  1075. }
  1076. }
  1077. impl FsAllowlistScope {
  1078. /// The list of allowed paths.
  1079. pub fn allowed_paths(&self) -> &Vec<PathBuf> {
  1080. match self {
  1081. Self::AllowedPaths(p) => p,
  1082. Self::Scope { allow, .. } => allow,
  1083. }
  1084. }
  1085. /// The list of forbidden paths.
  1086. pub fn forbidden_paths(&self) -> Option<&Vec<PathBuf>> {
  1087. match self {
  1088. Self::AllowedPaths(_) => None,
  1089. Self::Scope { deny, .. } => Some(deny),
  1090. }
  1091. }
  1092. }
  1093. /// Allowlist for the file system APIs.
  1094. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1095. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1096. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1097. pub struct FsAllowlistConfig {
  1098. /// The access scope for the filesystem APIs.
  1099. #[serde(default)]
  1100. pub scope: FsAllowlistScope,
  1101. /// Use this flag to enable all file system API features.
  1102. #[serde(default)]
  1103. pub all: bool,
  1104. /// Read file from local filesystem.
  1105. #[serde(default, alias = "read-file")]
  1106. pub read_file: bool,
  1107. /// Write file to local filesystem.
  1108. #[serde(default, alias = "write-file")]
  1109. pub write_file: bool,
  1110. /// Read directory from local filesystem.
  1111. #[serde(default, alias = "read-dir")]
  1112. pub read_dir: bool,
  1113. /// Copy file from local filesystem.
  1114. #[serde(default, alias = "copy-file")]
  1115. pub copy_file: bool,
  1116. /// Create directory from local filesystem.
  1117. #[serde(default, alias = "create-dir")]
  1118. pub create_dir: bool,
  1119. /// Remove directory from local filesystem.
  1120. #[serde(default, alias = "remove-dir")]
  1121. pub remove_dir: bool,
  1122. /// Remove file from local filesystem.
  1123. #[serde(default, alias = "remove-file")]
  1124. pub remove_file: bool,
  1125. /// Rename file from local filesystem.
  1126. #[serde(default, alias = "rename-file")]
  1127. pub rename_file: bool,
  1128. }
  1129. impl Allowlist for FsAllowlistConfig {
  1130. fn all_features() -> Vec<&'static str> {
  1131. let allowlist = Self {
  1132. scope: Default::default(),
  1133. all: false,
  1134. read_file: true,
  1135. write_file: true,
  1136. read_dir: true,
  1137. copy_file: true,
  1138. create_dir: true,
  1139. remove_dir: true,
  1140. remove_file: true,
  1141. rename_file: true,
  1142. };
  1143. let mut features = allowlist.to_features();
  1144. features.push("fs-all");
  1145. features
  1146. }
  1147. fn to_features(&self) -> Vec<&'static str> {
  1148. if self.all {
  1149. vec!["fs-all"]
  1150. } else {
  1151. let mut features = Vec::new();
  1152. check_feature!(self, features, read_file, "fs-read-file");
  1153. check_feature!(self, features, write_file, "fs-write-file");
  1154. check_feature!(self, features, read_dir, "fs-read-dir");
  1155. check_feature!(self, features, copy_file, "fs-copy-file");
  1156. check_feature!(self, features, create_dir, "fs-create-dir");
  1157. check_feature!(self, features, remove_dir, "fs-remove-dir");
  1158. check_feature!(self, features, remove_file, "fs-remove-file");
  1159. check_feature!(self, features, rename_file, "fs-rename-file");
  1160. features
  1161. }
  1162. }
  1163. }
  1164. /// Allowlist for the window APIs.
  1165. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1166. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1167. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1168. pub struct WindowAllowlistConfig {
  1169. /// Use this flag to enable all window API features.
  1170. #[serde(default)]
  1171. pub all: bool,
  1172. /// Allows dynamic window creation.
  1173. #[serde(default)]
  1174. pub create: bool,
  1175. /// Allows centering the window.
  1176. #[serde(default)]
  1177. pub center: bool,
  1178. /// Allows requesting user attention on the window.
  1179. #[serde(default, alias = "request-user-attention")]
  1180. pub request_user_attention: bool,
  1181. /// Allows setting the resizable flag of the window.
  1182. #[serde(default, alias = "set-resizable")]
  1183. pub set_resizable: bool,
  1184. /// Allows changing the window title.
  1185. #[serde(default, alias = "set-title")]
  1186. pub set_title: bool,
  1187. /// Allows maximizing the window.
  1188. #[serde(default)]
  1189. pub maximize: bool,
  1190. /// Allows unmaximizing the window.
  1191. #[serde(default)]
  1192. pub unmaximize: bool,
  1193. /// Allows minimizing the window.
  1194. #[serde(default)]
  1195. pub minimize: bool,
  1196. /// Allows unminimizing the window.
  1197. #[serde(default)]
  1198. pub unminimize: bool,
  1199. /// Allows showing the window.
  1200. #[serde(default)]
  1201. pub show: bool,
  1202. /// Allows hiding the window.
  1203. #[serde(default)]
  1204. pub hide: bool,
  1205. /// Allows closing the window.
  1206. #[serde(default)]
  1207. pub close: bool,
  1208. /// Allows setting the decorations flag of the window.
  1209. #[serde(default, alias = "set-decorations")]
  1210. pub set_decorations: bool,
  1211. /// Allows setting the always_on_top flag of the window.
  1212. #[serde(default, alias = "set-always-on-top")]
  1213. pub set_always_on_top: bool,
  1214. /// Allows setting the window size.
  1215. #[serde(default, alias = "set-size")]
  1216. pub set_size: bool,
  1217. /// Allows setting the window minimum size.
  1218. #[serde(default, alias = "set-min-size")]
  1219. pub set_min_size: bool,
  1220. /// Allows setting the window maximum size.
  1221. #[serde(default, alias = "set-max-size")]
  1222. pub set_max_size: bool,
  1223. /// Allows changing the position of the window.
  1224. #[serde(default, alias = "set-position")]
  1225. pub set_position: bool,
  1226. /// Allows setting the fullscreen flag of the window.
  1227. #[serde(default, alias = "set-fullscreen")]
  1228. pub set_fullscreen: bool,
  1229. /// Allows focusing the window.
  1230. #[serde(default, alias = "set-focus")]
  1231. pub set_focus: bool,
  1232. /// Allows changing the window icon.
  1233. #[serde(default, alias = "set-icon")]
  1234. pub set_icon: bool,
  1235. /// Allows setting the skip_taskbar flag of the window.
  1236. #[serde(default, alias = "set-skip-taskbar")]
  1237. pub set_skip_taskbar: bool,
  1238. /// Allows start dragging on the window.
  1239. #[serde(default, alias = "start-dragging")]
  1240. pub start_dragging: bool,
  1241. /// Allows opening the system dialog to print the window content.
  1242. #[serde(default)]
  1243. pub print: bool,
  1244. }
  1245. impl Allowlist for WindowAllowlistConfig {
  1246. fn all_features() -> Vec<&'static str> {
  1247. let allowlist = Self {
  1248. all: false,
  1249. create: true,
  1250. center: true,
  1251. request_user_attention: true,
  1252. set_resizable: true,
  1253. set_title: true,
  1254. maximize: true,
  1255. unmaximize: true,
  1256. minimize: true,
  1257. unminimize: true,
  1258. show: true,
  1259. hide: true,
  1260. close: true,
  1261. set_decorations: true,
  1262. set_always_on_top: true,
  1263. set_size: true,
  1264. set_min_size: true,
  1265. set_max_size: true,
  1266. set_position: true,
  1267. set_fullscreen: true,
  1268. set_focus: true,
  1269. set_icon: true,
  1270. set_skip_taskbar: true,
  1271. start_dragging: true,
  1272. print: true,
  1273. };
  1274. let mut features = allowlist.to_features();
  1275. features.push("window-all");
  1276. features
  1277. }
  1278. fn to_features(&self) -> Vec<&'static str> {
  1279. if self.all {
  1280. vec!["window-all"]
  1281. } else {
  1282. let mut features = Vec::new();
  1283. check_feature!(self, features, create, "window-create");
  1284. check_feature!(self, features, center, "window-center");
  1285. check_feature!(
  1286. self,
  1287. features,
  1288. request_user_attention,
  1289. "window-request-user-attention"
  1290. );
  1291. check_feature!(self, features, set_resizable, "window-set-resizable");
  1292. check_feature!(self, features, set_title, "window-set-title");
  1293. check_feature!(self, features, maximize, "window-maximize");
  1294. check_feature!(self, features, unmaximize, "window-unmaximize");
  1295. check_feature!(self, features, minimize, "window-minimize");
  1296. check_feature!(self, features, unminimize, "window-unminimize");
  1297. check_feature!(self, features, show, "window-show");
  1298. check_feature!(self, features, hide, "window-hide");
  1299. check_feature!(self, features, close, "window-close");
  1300. check_feature!(self, features, set_decorations, "window-set-decorations");
  1301. check_feature!(
  1302. self,
  1303. features,
  1304. set_always_on_top,
  1305. "window-set-always-on-top"
  1306. );
  1307. check_feature!(self, features, set_size, "window-set-size");
  1308. check_feature!(self, features, set_min_size, "window-set-min-size");
  1309. check_feature!(self, features, set_max_size, "window-set-max-size");
  1310. check_feature!(self, features, set_position, "window-set-position");
  1311. check_feature!(self, features, set_fullscreen, "window-set-fullscreen");
  1312. check_feature!(self, features, set_focus, "window-set-focus");
  1313. check_feature!(self, features, set_icon, "window-set-icon");
  1314. check_feature!(self, features, set_skip_taskbar, "window-set-skip-taskbar");
  1315. check_feature!(self, features, start_dragging, "window-start-dragging");
  1316. check_feature!(self, features, print, "window-print");
  1317. features
  1318. }
  1319. }
  1320. }
  1321. /// A command allowed to be executed by the webview API.
  1322. #[derive(Debug, PartialEq, Eq, Clone, Serialize)]
  1323. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1324. pub struct ShellAllowedCommand {
  1325. /// The name for this allowed shell command configuration.
  1326. ///
  1327. /// This name will be used inside of the webview API to call this command along with
  1328. /// any specified arguments.
  1329. pub name: String,
  1330. /// The command name.
  1331. /// It can start with a variable that resolves to a system base directory.
  1332. /// The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`,
  1333. /// `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`,
  1334. /// `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$APP`, `$LOG`, `$TEMP`.
  1335. #[serde(rename = "cmd", default)] // use default just so the schema doesn't flag it as required
  1336. pub command: PathBuf,
  1337. /// The allowed arguments for the command execution.
  1338. #[serde(default)]
  1339. pub args: ShellAllowedArgs,
  1340. /// If this command is a sidecar command.
  1341. #[serde(default)]
  1342. pub sidecar: bool,
  1343. }
  1344. impl<'de> Deserialize<'de> for ShellAllowedCommand {
  1345. fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  1346. where
  1347. D: Deserializer<'de>,
  1348. {
  1349. #[derive(Deserialize)]
  1350. struct InnerShellAllowedCommand {
  1351. name: String,
  1352. #[serde(rename = "cmd")]
  1353. command: Option<PathBuf>,
  1354. #[serde(default)]
  1355. args: ShellAllowedArgs,
  1356. #[serde(default)]
  1357. sidecar: bool,
  1358. }
  1359. let config = InnerShellAllowedCommand::deserialize(deserializer)?;
  1360. if !config.sidecar && config.command.is_none() {
  1361. return Err(DeError::custom(
  1362. "The shell scope `command` value is required.",
  1363. ));
  1364. }
  1365. Ok(ShellAllowedCommand {
  1366. name: config.name,
  1367. command: config.command.unwrap_or_default(),
  1368. args: config.args,
  1369. sidecar: config.sidecar,
  1370. })
  1371. }
  1372. }
  1373. /// A set of command arguments allowed to be executed by the webview API.
  1374. ///
  1375. /// A value of `true` will allow any arguments to be passed to the command. `false` will disable all
  1376. /// arguments. A list of [`ShellAllowedArg`] will set those arguments as the only valid arguments to
  1377. /// be passed to the attached command configuration.
  1378. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1379. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1380. #[serde(untagged, deny_unknown_fields)]
  1381. #[non_exhaustive]
  1382. pub enum ShellAllowedArgs {
  1383. /// Use a simple boolean to allow all or disable all arguments to this command configuration.
  1384. Flag(bool),
  1385. /// A specific set of [`ShellAllowedArg`] that are valid to call for the command configuration.
  1386. List(Vec<ShellAllowedArg>),
  1387. }
  1388. impl Default for ShellAllowedArgs {
  1389. fn default() -> Self {
  1390. Self::Flag(false)
  1391. }
  1392. }
  1393. /// A command argument allowed to be executed by the webview API.
  1394. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1395. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1396. #[serde(untagged, deny_unknown_fields)]
  1397. #[non_exhaustive]
  1398. pub enum ShellAllowedArg {
  1399. /// A non-configurable argument that is passed to the command in the order it was specified.
  1400. Fixed(String),
  1401. /// A variable that is set while calling the command from the webview API.
  1402. ///
  1403. Var {
  1404. /// [regex] validator to require passed values to conform to an expected input.
  1405. ///
  1406. /// This will require the argument value passed to this variable to match the `validator` regex
  1407. /// before it will be executed.
  1408. ///
  1409. /// [regex]: https://docs.rs/regex/latest/regex/#syntax
  1410. validator: String,
  1411. },
  1412. }
  1413. /// Shell scope definition.
  1414. /// It is a list of command names and associated CLI arguments that restrict the API access from the webview.
  1415. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1416. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1417. pub struct ShellAllowlistScope(pub Vec<ShellAllowedCommand>);
  1418. /// Defines the `shell > open` api scope.
  1419. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1420. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1421. #[serde(untagged, deny_unknown_fields)]
  1422. #[non_exhaustive]
  1423. pub enum ShellAllowlistOpen {
  1424. /// If the shell open API should be enabled.
  1425. ///
  1426. /// If enabled, the default validation regex (`^https?://`) is used.
  1427. Flag(bool),
  1428. /// Enable the shell open API, with a custom regex that the opened path must match against.
  1429. ///
  1430. /// If using a custom regex to support a non-http(s) schema, care should be used to prevent values
  1431. /// that allow flag-like strings to pass validation. e.g. `--enable-debugging`, `-i`, `/R`.
  1432. Validate(String),
  1433. }
  1434. impl Default for ShellAllowlistOpen {
  1435. fn default() -> Self {
  1436. Self::Flag(false)
  1437. }
  1438. }
  1439. /// Allowlist for the shell APIs.
  1440. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1441. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1442. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1443. pub struct ShellAllowlistConfig {
  1444. /// Access scope for the binary execution APIs.
  1445. /// Sidecars are automatically enabled.
  1446. #[serde(default)]
  1447. pub scope: ShellAllowlistScope,
  1448. /// Use this flag to enable all shell API features.
  1449. #[serde(default)]
  1450. pub all: bool,
  1451. /// Enable binary execution.
  1452. #[serde(default)]
  1453. pub execute: bool,
  1454. /// Enable sidecar execution, allowing the JavaScript layer to spawn a sidecar command,
  1455. /// an executable that is shipped with the application.
  1456. /// For more information see <https://tauri.app/v1/guides/building/sidecar>.
  1457. #[serde(default)]
  1458. pub sidecar: bool,
  1459. /// Open URL with the user's default application.
  1460. #[serde(default)]
  1461. pub open: ShellAllowlistOpen,
  1462. }
  1463. impl Allowlist for ShellAllowlistConfig {
  1464. fn all_features() -> Vec<&'static str> {
  1465. let allowlist = Self {
  1466. scope: Default::default(),
  1467. all: false,
  1468. execute: true,
  1469. sidecar: true,
  1470. open: ShellAllowlistOpen::Flag(true),
  1471. };
  1472. let mut features = allowlist.to_features();
  1473. features.push("shell-all");
  1474. features
  1475. }
  1476. fn to_features(&self) -> Vec<&'static str> {
  1477. if self.all {
  1478. vec!["shell-all"]
  1479. } else {
  1480. let mut features = Vec::new();
  1481. check_feature!(self, features, execute, "shell-execute");
  1482. check_feature!(self, features, sidecar, "shell-sidecar");
  1483. if !matches!(self.open, ShellAllowlistOpen::Flag(false)) {
  1484. features.push("shell-open")
  1485. }
  1486. features
  1487. }
  1488. }
  1489. }
  1490. /// Allowlist for the dialog APIs.
  1491. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1492. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1493. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1494. pub struct DialogAllowlistConfig {
  1495. /// Use this flag to enable all dialog API features.
  1496. #[serde(default)]
  1497. pub all: bool,
  1498. /// Allows the API to open a dialog window to pick files.
  1499. #[serde(default)]
  1500. pub open: bool,
  1501. /// Allows the API to open a dialog window to pick where to save files.
  1502. #[serde(default)]
  1503. pub save: bool,
  1504. /// Allows the API to show a message dialog window.
  1505. #[serde(default)]
  1506. pub message: bool,
  1507. /// Allows the API to show a dialog window with Yes/No buttons.
  1508. #[serde(default)]
  1509. pub ask: bool,
  1510. /// Allows the API to show a dialog window with Ok/Cancel buttons.
  1511. #[serde(default)]
  1512. pub confirm: bool,
  1513. }
  1514. impl Allowlist for DialogAllowlistConfig {
  1515. fn all_features() -> Vec<&'static str> {
  1516. let allowlist = Self {
  1517. all: false,
  1518. open: true,
  1519. save: true,
  1520. message: true,
  1521. ask: true,
  1522. confirm: true,
  1523. };
  1524. let mut features = allowlist.to_features();
  1525. features.push("dialog-all");
  1526. features
  1527. }
  1528. fn to_features(&self) -> Vec<&'static str> {
  1529. if self.all {
  1530. vec!["dialog-all"]
  1531. } else {
  1532. let mut features = Vec::new();
  1533. check_feature!(self, features, open, "dialog-open");
  1534. check_feature!(self, features, save, "dialog-save");
  1535. check_feature!(self, features, message, "dialog-message");
  1536. check_feature!(self, features, ask, "dialog-ask");
  1537. check_feature!(self, features, confirm, "dialog-confirm");
  1538. features
  1539. }
  1540. }
  1541. }
  1542. /// HTTP API scope definition.
  1543. /// It is a list of URLs that can be accessed by the webview when using the HTTP APIs.
  1544. /// The scoped URL is matched against the request URL using a glob pattern.
  1545. ///
  1546. /// Examples:
  1547. /// - "https://**": allows all HTTPS urls
  1548. /// - "https://*.github.com/tauri-apps/tauri": allows any subdomain of "github.com" with the "tauri-apps/api" path
  1549. /// - "https://myapi.service.com/users/*": allows access to any URLs that begins with "https://myapi.service.com/users/"
  1550. #[allow(rustdoc::bare_urls)]
  1551. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1552. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1553. pub struct HttpAllowlistScope(pub Vec<Url>);
  1554. /// Allowlist for the HTTP APIs.
  1555. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1556. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1557. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1558. pub struct HttpAllowlistConfig {
  1559. /// The access scope for the HTTP APIs.
  1560. #[serde(default)]
  1561. pub scope: HttpAllowlistScope,
  1562. /// Use this flag to enable all HTTP API features.
  1563. #[serde(default)]
  1564. pub all: bool,
  1565. /// Allows making HTTP requests.
  1566. #[serde(default)]
  1567. pub request: bool,
  1568. }
  1569. impl Allowlist for HttpAllowlistConfig {
  1570. fn all_features() -> Vec<&'static str> {
  1571. let allowlist = Self {
  1572. scope: Default::default(),
  1573. all: false,
  1574. request: true,
  1575. };
  1576. let mut features = allowlist.to_features();
  1577. features.push("http-all");
  1578. features
  1579. }
  1580. fn to_features(&self) -> Vec<&'static str> {
  1581. if self.all {
  1582. vec!["http-all"]
  1583. } else {
  1584. let mut features = Vec::new();
  1585. check_feature!(self, features, request, "http-request");
  1586. features
  1587. }
  1588. }
  1589. }
  1590. /// Allowlist for the notification APIs.
  1591. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1592. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1593. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1594. pub struct NotificationAllowlistConfig {
  1595. /// Use this flag to enable all notification API features.
  1596. #[serde(default)]
  1597. pub all: bool,
  1598. }
  1599. impl Allowlist for NotificationAllowlistConfig {
  1600. fn all_features() -> Vec<&'static str> {
  1601. let allowlist = Self { all: false };
  1602. let mut features = allowlist.to_features();
  1603. features.push("notification-all");
  1604. features
  1605. }
  1606. fn to_features(&self) -> Vec<&'static str> {
  1607. if self.all {
  1608. vec!["notification-all"]
  1609. } else {
  1610. vec![]
  1611. }
  1612. }
  1613. }
  1614. /// Allowlist for the global shortcut APIs.
  1615. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1616. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1617. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1618. pub struct GlobalShortcutAllowlistConfig {
  1619. /// Use this flag to enable all global shortcut API features.
  1620. #[serde(default)]
  1621. pub all: bool,
  1622. }
  1623. impl Allowlist for GlobalShortcutAllowlistConfig {
  1624. fn all_features() -> Vec<&'static str> {
  1625. let allowlist = Self { all: false };
  1626. let mut features = allowlist.to_features();
  1627. features.push("global-shortcut-all");
  1628. features
  1629. }
  1630. fn to_features(&self) -> Vec<&'static str> {
  1631. if self.all {
  1632. vec!["global-shortcut-all"]
  1633. } else {
  1634. vec![]
  1635. }
  1636. }
  1637. }
  1638. /// Allowlist for the OS APIs.
  1639. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1640. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1641. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1642. pub struct OsAllowlistConfig {
  1643. /// Use this flag to enable all OS API features.
  1644. #[serde(default)]
  1645. pub all: bool,
  1646. }
  1647. impl Allowlist for OsAllowlistConfig {
  1648. fn all_features() -> Vec<&'static str> {
  1649. let allowlist = Self { all: false };
  1650. let mut features = allowlist.to_features();
  1651. features.push("os-all");
  1652. features
  1653. }
  1654. fn to_features(&self) -> Vec<&'static str> {
  1655. if self.all {
  1656. vec!["os-all"]
  1657. } else {
  1658. vec![]
  1659. }
  1660. }
  1661. }
  1662. /// Allowlist for the path APIs.
  1663. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1664. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1665. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1666. pub struct PathAllowlistConfig {
  1667. /// Use this flag to enable all path API features.
  1668. #[serde(default)]
  1669. pub all: bool,
  1670. }
  1671. impl Allowlist for PathAllowlistConfig {
  1672. fn all_features() -> Vec<&'static str> {
  1673. let allowlist = Self { all: false };
  1674. let mut features = allowlist.to_features();
  1675. features.push("path-all");
  1676. features
  1677. }
  1678. fn to_features(&self) -> Vec<&'static str> {
  1679. if self.all {
  1680. vec!["path-all"]
  1681. } else {
  1682. vec![]
  1683. }
  1684. }
  1685. }
  1686. /// Allowlist for the custom protocols.
  1687. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1688. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1689. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1690. pub struct ProtocolAllowlistConfig {
  1691. /// The access scope for the asset protocol.
  1692. #[serde(default, alias = "asset-scope")]
  1693. pub asset_scope: FsAllowlistScope,
  1694. /// Use this flag to enable all custom protocols.
  1695. #[serde(default)]
  1696. pub all: bool,
  1697. /// Enables the asset protocol.
  1698. #[serde(default)]
  1699. pub asset: bool,
  1700. }
  1701. impl Allowlist for ProtocolAllowlistConfig {
  1702. fn all_features() -> Vec<&'static str> {
  1703. let allowlist = Self {
  1704. asset_scope: Default::default(),
  1705. all: false,
  1706. asset: true,
  1707. };
  1708. let mut features = allowlist.to_features();
  1709. features.push("protocol-all");
  1710. features
  1711. }
  1712. fn to_features(&self) -> Vec<&'static str> {
  1713. if self.all {
  1714. vec!["protocol-all"]
  1715. } else {
  1716. let mut features = Vec::new();
  1717. check_feature!(self, features, asset, "protocol-asset");
  1718. features
  1719. }
  1720. }
  1721. }
  1722. /// Allowlist for the process APIs.
  1723. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1724. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1725. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1726. pub struct ProcessAllowlistConfig {
  1727. /// Use this flag to enable all process APIs.
  1728. #[serde(default)]
  1729. pub all: bool,
  1730. /// Enables the relaunch API.
  1731. #[serde(default)]
  1732. pub relaunch: bool,
  1733. /// Dangerous option that allows macOS to relaunch even if the binary contains a symlink.
  1734. ///
  1735. /// This is due to macOS having less symlink protection. Highly recommended to not set this flag
  1736. /// unless you have a very specific reason too, and understand the implications of it.
  1737. #[serde(
  1738. default,
  1739. alias = "relaunchDangerousAllowSymlinkMacOS",
  1740. alias = "relaunch-dangerous-allow-symlink-macos"
  1741. )]
  1742. pub relaunch_dangerous_allow_symlink_macos: bool,
  1743. /// Enables the exit API.
  1744. #[serde(default)]
  1745. pub exit: bool,
  1746. }
  1747. impl Allowlist for ProcessAllowlistConfig {
  1748. fn all_features() -> Vec<&'static str> {
  1749. let allowlist = Self {
  1750. all: false,
  1751. relaunch: true,
  1752. relaunch_dangerous_allow_symlink_macos: false,
  1753. exit: true,
  1754. };
  1755. let mut features = allowlist.to_features();
  1756. features.push("process-all");
  1757. features
  1758. }
  1759. fn to_features(&self) -> Vec<&'static str> {
  1760. if self.all {
  1761. vec!["process-all"]
  1762. } else {
  1763. let mut features = Vec::new();
  1764. check_feature!(self, features, relaunch, "process-relaunch");
  1765. check_feature!(
  1766. self,
  1767. features,
  1768. relaunch_dangerous_allow_symlink_macos,
  1769. "process-relaunch-dangerous-allow-symlink-macos"
  1770. );
  1771. check_feature!(self, features, exit, "process-exit");
  1772. features
  1773. }
  1774. }
  1775. }
  1776. /// Allowlist for the clipboard APIs.
  1777. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1778. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1779. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1780. pub struct ClipboardAllowlistConfig {
  1781. /// Use this flag to enable all clipboard APIs.
  1782. #[serde(default)]
  1783. pub all: bool,
  1784. /// Enables the clipboard's `writeText` API.
  1785. #[serde(default, alias = "writeText")]
  1786. pub write_text: bool,
  1787. /// Enables the clipboard's `readText` API.
  1788. #[serde(default, alias = "readText")]
  1789. pub read_text: bool,
  1790. }
  1791. impl Allowlist for ClipboardAllowlistConfig {
  1792. fn all_features() -> Vec<&'static str> {
  1793. let allowlist = Self {
  1794. all: false,
  1795. write_text: true,
  1796. read_text: true,
  1797. };
  1798. let mut features = allowlist.to_features();
  1799. features.push("clipboard-all");
  1800. features
  1801. }
  1802. fn to_features(&self) -> Vec<&'static str> {
  1803. if self.all {
  1804. vec!["clipboard-all"]
  1805. } else {
  1806. let mut features = Vec::new();
  1807. check_feature!(self, features, write_text, "clipboard-write-text");
  1808. check_feature!(self, features, read_text, "clipboard-read-text");
  1809. features
  1810. }
  1811. }
  1812. }
  1813. /// Allowlist configuration.
  1814. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1815. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1816. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1817. pub struct AllowlistConfig {
  1818. /// Use this flag to enable all API features.
  1819. #[serde(default)]
  1820. pub all: bool,
  1821. /// File system API allowlist.
  1822. #[serde(default)]
  1823. pub fs: FsAllowlistConfig,
  1824. /// Window API allowlist.
  1825. #[serde(default)]
  1826. pub window: WindowAllowlistConfig,
  1827. /// Shell API allowlist.
  1828. #[serde(default)]
  1829. pub shell: ShellAllowlistConfig,
  1830. /// Dialog API allowlist.
  1831. #[serde(default)]
  1832. pub dialog: DialogAllowlistConfig,
  1833. /// HTTP API allowlist.
  1834. #[serde(default)]
  1835. pub http: HttpAllowlistConfig,
  1836. /// Notification API allowlist.
  1837. #[serde(default)]
  1838. pub notification: NotificationAllowlistConfig,
  1839. /// Global shortcut API allowlist.
  1840. #[serde(default, alias = "global-shortcut")]
  1841. pub global_shortcut: GlobalShortcutAllowlistConfig,
  1842. /// OS allowlist.
  1843. #[serde(default)]
  1844. pub os: OsAllowlistConfig,
  1845. /// Path API allowlist.
  1846. #[serde(default)]
  1847. pub path: PathAllowlistConfig,
  1848. /// Custom protocol allowlist.
  1849. #[serde(default)]
  1850. pub protocol: ProtocolAllowlistConfig,
  1851. /// Process API allowlist.
  1852. #[serde(default)]
  1853. pub process: ProcessAllowlistConfig,
  1854. /// Clipboard APIs allowlist.
  1855. #[serde(default)]
  1856. pub clipboard: ClipboardAllowlistConfig,
  1857. }
  1858. impl Allowlist for AllowlistConfig {
  1859. fn all_features() -> Vec<&'static str> {
  1860. let mut features = vec!["api-all"];
  1861. features.extend(FsAllowlistConfig::all_features());
  1862. features.extend(WindowAllowlistConfig::all_features());
  1863. features.extend(ShellAllowlistConfig::all_features());
  1864. features.extend(DialogAllowlistConfig::all_features());
  1865. features.extend(HttpAllowlistConfig::all_features());
  1866. features.extend(NotificationAllowlistConfig::all_features());
  1867. features.extend(GlobalShortcutAllowlistConfig::all_features());
  1868. features.extend(OsAllowlistConfig::all_features());
  1869. features.extend(PathAllowlistConfig::all_features());
  1870. features.extend(ProtocolAllowlistConfig::all_features());
  1871. features.extend(ProcessAllowlistConfig::all_features());
  1872. features.extend(ClipboardAllowlistConfig::all_features());
  1873. features
  1874. }
  1875. fn to_features(&self) -> Vec<&'static str> {
  1876. if self.all {
  1877. vec!["api-all"]
  1878. } else {
  1879. let mut features = Vec::new();
  1880. features.extend(self.fs.to_features());
  1881. features.extend(self.window.to_features());
  1882. features.extend(self.shell.to_features());
  1883. features.extend(self.dialog.to_features());
  1884. features.extend(self.http.to_features());
  1885. features.extend(self.notification.to_features());
  1886. features.extend(self.global_shortcut.to_features());
  1887. features.extend(self.os.to_features());
  1888. features.extend(self.path.to_features());
  1889. features.extend(self.protocol.to_features());
  1890. features.extend(self.process.to_features());
  1891. features.extend(self.clipboard.to_features());
  1892. features
  1893. }
  1894. }
  1895. }
  1896. /// The application pattern.
  1897. #[skip_serializing_none]
  1898. #[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
  1899. #[serde(rename_all = "lowercase", tag = "use", content = "options")]
  1900. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1901. pub enum PatternKind {
  1902. /// Brownfield pattern.
  1903. Brownfield,
  1904. /// Isolation pattern. Recommended for security purposes.
  1905. #[cfg(feature = "isolation")]
  1906. Isolation {
  1907. /// The dir containing the index.html file that contains the secure isolation application.
  1908. dir: PathBuf,
  1909. },
  1910. }
  1911. impl Default for PatternKind {
  1912. fn default() -> Self {
  1913. Self::Brownfield
  1914. }
  1915. }
  1916. /// The Tauri configuration object.
  1917. #[skip_serializing_none]
  1918. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  1919. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1920. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1921. pub struct TauriConfig {
  1922. /// The pattern to use.
  1923. #[serde(default)]
  1924. pub pattern: PatternKind,
  1925. /// The windows configuration.
  1926. #[serde(default)]
  1927. pub windows: Vec<WindowConfig>,
  1928. /// The CLI configuration.
  1929. pub cli: Option<CliConfig>,
  1930. /// The bundler configuration.
  1931. #[serde(default)]
  1932. pub bundle: BundleConfig,
  1933. /// The allowlist configuration.
  1934. #[serde(default)]
  1935. pub allowlist: AllowlistConfig,
  1936. /// Security configuration.
  1937. #[serde(default)]
  1938. pub security: SecurityConfig,
  1939. /// The updater configuration.
  1940. #[serde(default)]
  1941. pub updater: UpdaterConfig,
  1942. /// Configuration for app system tray.
  1943. #[serde(alias = "system-tray")]
  1944. pub system_tray: Option<SystemTrayConfig>,
  1945. /// MacOS private API configuration. Enables the transparent background API and sets the `fullScreenEnabled` preference to `true`.
  1946. #[serde(rename = "macOSPrivateApi", alias = "macos-private-api", default)]
  1947. pub macos_private_api: bool,
  1948. }
  1949. impl TauriConfig {
  1950. /// Returns all Cargo features.
  1951. #[allow(dead_code)]
  1952. pub fn all_features() -> Vec<&'static str> {
  1953. let mut features = AllowlistConfig::all_features();
  1954. features.extend(vec![
  1955. "cli",
  1956. "updater",
  1957. "system-tray",
  1958. "macos-private-api",
  1959. "isolation",
  1960. ]);
  1961. features
  1962. }
  1963. /// Returns the enabled Cargo features.
  1964. #[allow(dead_code)]
  1965. pub fn features(&self) -> Vec<&str> {
  1966. let mut features = self.allowlist.to_features();
  1967. if self.cli.is_some() {
  1968. features.push("cli");
  1969. }
  1970. if self.updater.active {
  1971. features.push("updater");
  1972. }
  1973. if self.system_tray.is_some() {
  1974. features.push("system-tray");
  1975. }
  1976. if self.macos_private_api {
  1977. features.push("macos-private-api");
  1978. }
  1979. #[cfg(feature = "isolation")]
  1980. if let PatternKind::Isolation { .. } = self.pattern {
  1981. features.push("isolation");
  1982. }
  1983. features.sort_unstable();
  1984. features
  1985. }
  1986. }
  1987. /// A URL to an updater server.
  1988. ///
  1989. /// The URL must use the `https` scheme on production.
  1990. #[skip_serializing_none]
  1991. #[derive(Debug, PartialEq, Eq, Clone, Serialize)]
  1992. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1993. pub struct UpdaterEndpoint(pub Url);
  1994. impl std::fmt::Display for UpdaterEndpoint {
  1995. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  1996. write!(f, "{}", self.0)
  1997. }
  1998. }
  1999. impl<'de> Deserialize<'de> for UpdaterEndpoint {
  2000. fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  2001. where
  2002. D: Deserializer<'de>,
  2003. {
  2004. let url = Url::deserialize(deserializer)?;
  2005. #[cfg(all(not(debug_assertions), not(feature = "schema")))]
  2006. {
  2007. if url.scheme() != "https" {
  2008. return Err(serde::de::Error::custom(
  2009. "The configured updater endpoint must use the `https` protocol.",
  2010. ));
  2011. }
  2012. }
  2013. Ok(Self(url))
  2014. }
  2015. }
  2016. /// Install modes for the Windows update.
  2017. #[derive(Debug, PartialEq, Eq, Clone)]
  2018. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  2019. #[cfg_attr(feature = "schema", schemars(rename_all = "camelCase"))]
  2020. pub enum WindowsUpdateInstallMode {
  2021. /// Specifies there's a basic UI during the installation process, including a final dialog box at the end.
  2022. BasicUi,
  2023. /// The quiet mode means there's no user interaction required.
  2024. /// Requires admin privileges if the installer does.
  2025. Quiet,
  2026. /// Specifies unattended mode, which means the installation only shows a progress bar.
  2027. Passive,
  2028. // to add more modes, we need to check if the updater relaunch makes sense
  2029. // i.e. for a full UI mode, the user can also mark the installer to start the app
  2030. }
  2031. impl WindowsUpdateInstallMode {
  2032. /// Returns the associated `msiexec.exe` arguments.
  2033. pub fn msiexec_args(&self) -> &'static [&'static str] {
  2034. match self {
  2035. Self::BasicUi => &["/qb+"],
  2036. Self::Quiet => &["/quiet"],
  2037. Self::Passive => &["/passive"],
  2038. }
  2039. }
  2040. }
  2041. impl Display for WindowsUpdateInstallMode {
  2042. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  2043. write!(
  2044. f,
  2045. "{}",
  2046. match self {
  2047. Self::BasicUi => "basicUI",
  2048. Self::Quiet => "quiet",
  2049. Self::Passive => "passive",
  2050. }
  2051. )
  2052. }
  2053. }
  2054. impl Default for WindowsUpdateInstallMode {
  2055. fn default() -> Self {
  2056. Self::Passive
  2057. }
  2058. }
  2059. impl Serialize for WindowsUpdateInstallMode {
  2060. fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
  2061. where
  2062. S: Serializer,
  2063. {
  2064. serializer.serialize_str(self.to_string().as_ref())
  2065. }
  2066. }
  2067. impl<'de> Deserialize<'de> for WindowsUpdateInstallMode {
  2068. fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
  2069. where
  2070. D: Deserializer<'de>,
  2071. {
  2072. let s = String::deserialize(deserializer)?;
  2073. match s.to_lowercase().as_str() {
  2074. "basicui" => Ok(Self::BasicUi),
  2075. "quiet" => Ok(Self::Quiet),
  2076. "passive" => Ok(Self::Passive),
  2077. _ => Err(DeError::custom(format!(
  2078. "unknown update install mode '{}'",
  2079. s
  2080. ))),
  2081. }
  2082. }
  2083. }
  2084. /// The updater configuration for Windows.
  2085. #[skip_serializing_none]
  2086. #[derive(Debug, Default, PartialEq, Eq, Clone, Serialize, Deserialize)]
  2087. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  2088. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  2089. pub struct UpdaterWindowsConfig {
  2090. /// The installation mode for the update on Windows. Defaults to `passive`.
  2091. #[serde(default, alias = "install-mode")]
  2092. pub install_mode: WindowsUpdateInstallMode,
  2093. }
  2094. /// The Updater configuration object.
  2095. #[skip_serializing_none]
  2096. #[derive(Debug, PartialEq, Eq, Clone, Serialize)]
  2097. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  2098. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  2099. pub struct UpdaterConfig {
  2100. /// Whether the updater is active or not.
  2101. #[serde(default)]
  2102. pub active: bool,
  2103. /// Display built-in dialog or use event system if disabled.
  2104. #[serde(default = "default_dialog")]
  2105. pub dialog: bool,
  2106. /// The updater endpoints. TLS is enforced on production.
  2107. ///
  2108. /// The updater URL can contain the following variables:
  2109. /// - {{current_version}}: The version of the app that is requesting the update
  2110. /// - {{target}}: The operating system name (one of `linux`, `windows` or `darwin`).
  2111. /// - {{arch}}: The architecture of the machine (one of `x86_64`, `i686`, `aarch64` or `armv7`).
  2112. ///
  2113. /// # Examples
  2114. /// - "https://my.cdn.com/latest.json": a raw JSON endpoint that returns the latest version and download links for each platform.
  2115. /// - "https://updates.app.dev/{{target}}?version={{current_version}}&arch={{arch}}": a dedicated API with positional and query string arguments.
  2116. #[allow(rustdoc::bare_urls)]
  2117. pub endpoints: Option<Vec<UpdaterEndpoint>>,
  2118. /// Signature public key.
  2119. #[serde(default)] // use default just so the schema doesn't flag it as required
  2120. pub pubkey: String,
  2121. /// The Windows configuration for the updater.
  2122. #[serde(default)]
  2123. pub windows: UpdaterWindowsConfig,
  2124. }
  2125. impl<'de> Deserialize<'de> for UpdaterConfig {
  2126. fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  2127. where
  2128. D: Deserializer<'de>,
  2129. {
  2130. #[derive(Deserialize)]
  2131. struct InnerUpdaterConfig {
  2132. #[serde(default)]
  2133. active: bool,
  2134. #[serde(default = "default_dialog")]
  2135. dialog: bool,
  2136. endpoints: Option<Vec<UpdaterEndpoint>>,
  2137. pubkey: Option<String>,
  2138. #[serde(default)]
  2139. windows: UpdaterWindowsConfig,
  2140. }
  2141. let config = InnerUpdaterConfig::deserialize(deserializer)?;
  2142. if config.active && config.pubkey.is_none() {
  2143. return Err(DeError::custom(
  2144. "The updater `pubkey` configuration is required.",
  2145. ));
  2146. }
  2147. Ok(UpdaterConfig {
  2148. active: config.active,
  2149. dialog: config.dialog,
  2150. endpoints: config.endpoints,
  2151. pubkey: config.pubkey.unwrap_or_default(),
  2152. windows: config.windows,
  2153. })
  2154. }
  2155. }
  2156. impl Default for UpdaterConfig {
  2157. fn default() -> Self {
  2158. Self {
  2159. active: false,
  2160. dialog: default_dialog(),
  2161. endpoints: None,
  2162. pubkey: "".into(),
  2163. windows: Default::default(),
  2164. }
  2165. }
  2166. }
  2167. /// Configuration for application system tray icon.
  2168. #[skip_serializing_none]
  2169. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  2170. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  2171. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  2172. pub struct SystemTrayConfig {
  2173. /// Path to the icon to use on the system tray.
  2174. ///
  2175. /// It is forced to be a `.png` file on Linux and macOS, and a `.ico` file on Windows.
  2176. #[serde(alias = "icon-path")]
  2177. pub icon_path: PathBuf,
  2178. /// 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.
  2179. #[serde(default, alias = "icon-as-template")]
  2180. pub icon_as_template: bool,
  2181. /// A Boolean value that determines whether the menu should appear when the tray icon receives a left click on macOS.
  2182. #[serde(
  2183. default = "default_tray_menu_on_left_click",
  2184. alias = "menu-on-left-click"
  2185. )]
  2186. pub menu_on_left_click: bool,
  2187. }
  2188. fn default_tray_menu_on_left_click() -> bool {
  2189. true
  2190. }
  2191. // We enable the unnecessary_wraps because we need
  2192. // to use an Option for dialog otherwise the CLI schema will mark
  2193. // the dialog as a required field which is not as we default it to true.
  2194. fn default_dialog() -> bool {
  2195. true
  2196. }
  2197. /// Defines the URL or assets to embed in the application.
  2198. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  2199. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  2200. #[serde(untagged, deny_unknown_fields)]
  2201. #[non_exhaustive]
  2202. pub enum AppUrl {
  2203. /// The app's external URL, or the path to the directory containing the app assets.
  2204. Url(WindowUrl),
  2205. /// An array of files to embed on the app.
  2206. Files(Vec<PathBuf>),
  2207. }
  2208. impl std::fmt::Display for AppUrl {
  2209. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  2210. match self {
  2211. Self::Url(url) => write!(f, "{}", url),
  2212. Self::Files(files) => write!(f, "{}", serde_json::to_string(files).unwrap()),
  2213. }
  2214. }
  2215. }
  2216. /// Describes the shell command to run before `tauri dev`.
  2217. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  2218. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  2219. #[serde(rename_all = "camelCase", untagged)]
  2220. pub enum BeforeDevCommand {
  2221. /// Run the given script with the default options.
  2222. Script(String),
  2223. /// Run the given script with custom options.
  2224. ScriptWithOptions {
  2225. /// The script to execute.
  2226. script: String,
  2227. /// The current working directory.
  2228. cwd: Option<String>,
  2229. /// Whether `tauri dev` should wait for the command to finish or not. Defaults to `false`.
  2230. #[serde(default)]
  2231. wait: bool,
  2232. },
  2233. }
  2234. /// Describes a shell command to be executed when a CLI hook is triggered.
  2235. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  2236. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  2237. #[serde(rename_all = "camelCase", untagged)]
  2238. pub enum HookCommand {
  2239. /// Run the given script with the default options.
  2240. Script(String),
  2241. /// Run the given script with custom options.
  2242. ScriptWithOptions {
  2243. /// The script to execute.
  2244. script: String,
  2245. /// The current working directory.
  2246. cwd: Option<String>,
  2247. },
  2248. }
  2249. /// The Build configuration object.
  2250. #[skip_serializing_none]
  2251. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  2252. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  2253. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  2254. pub struct BuildConfig {
  2255. /// The binary used to build and run the application.
  2256. pub runner: Option<String>,
  2257. /// The path to the application assets or URL to load in development.
  2258. ///
  2259. /// This is usually an URL to a dev server, which serves your application assets
  2260. /// with live reloading. Most modern JavaScript bundlers provides a way to start a dev server by default.
  2261. ///
  2262. /// See [vite](https://vitejs.dev/guide/), [Webpack DevServer](https://webpack.js.org/configuration/dev-server/) and [sirv](https://github.com/lukeed/sirv)
  2263. /// for examples on how to set up a dev server.
  2264. #[serde(default = "default_dev_path", alias = "dev-path")]
  2265. pub dev_path: AppUrl,
  2266. /// The path to the application assets or URL to load in production.
  2267. ///
  2268. /// When a path relative to the configuration file is provided,
  2269. /// it is read recursively and all files are embedded in the application binary.
  2270. /// Tauri then looks for an `index.html` file unless you provide a custom window URL.
  2271. ///
  2272. /// You can also provide a list of paths to be embedded, which allows granular control over what files are added to the binary.
  2273. /// In this case, all files are added to the root and you must reference it that way in your HTML files.
  2274. ///
  2275. /// When an URL is provided, the application won't have bundled assets
  2276. /// and the application will load that URL by default.
  2277. #[serde(default = "default_dist_dir", alias = "dist-dir")]
  2278. pub dist_dir: AppUrl,
  2279. /// A shell command to run before `tauri dev` kicks in.
  2280. ///
  2281. /// The TAURI_PLATFORM, TAURI_ARCH, TAURI_FAMILY, TAURI_PLATFORM_VERSION, TAURI_PLATFORM_TYPE and TAURI_DEBUG environment variables are set if you perform conditional compilation.
  2282. #[serde(alias = "before-dev-command")]
  2283. pub before_dev_command: Option<BeforeDevCommand>,
  2284. /// A shell command to run before `tauri build` kicks in.
  2285. ///
  2286. /// The TAURI_PLATFORM, TAURI_ARCH, TAURI_FAMILY, TAURI_PLATFORM_VERSION, TAURI_PLATFORM_TYPE and TAURI_DEBUG environment variables are set if you perform conditional compilation.
  2287. #[serde(alias = "before-build-command")]
  2288. pub before_build_command: Option<HookCommand>,
  2289. /// A shell command to run before the bundling phase in `tauri build` kicks in.
  2290. ///
  2291. /// The TAURI_PLATFORM, TAURI_ARCH, TAURI_FAMILY, TAURI_PLATFORM_VERSION, TAURI_PLATFORM_TYPE and TAURI_DEBUG environment variables are set if you perform conditional compilation.
  2292. #[serde(alias = "before-build-command")]
  2293. pub before_bundle_command: Option<HookCommand>,
  2294. /// Features passed to `cargo` commands.
  2295. pub features: Option<Vec<String>>,
  2296. /// Whether we should inject the Tauri API on `window.__TAURI__` or not.
  2297. #[serde(default, alias = "with-global-tauri")]
  2298. pub with_global_tauri: bool,
  2299. }
  2300. impl Default for BuildConfig {
  2301. fn default() -> Self {
  2302. Self {
  2303. runner: None,
  2304. dev_path: default_dev_path(),
  2305. dist_dir: default_dist_dir(),
  2306. before_dev_command: None,
  2307. before_build_command: None,
  2308. before_bundle_command: None,
  2309. features: None,
  2310. with_global_tauri: false,
  2311. }
  2312. }
  2313. }
  2314. fn default_dev_path() -> AppUrl {
  2315. AppUrl::Url(WindowUrl::External(
  2316. Url::parse("http://localhost:8080").unwrap(),
  2317. ))
  2318. }
  2319. fn default_dist_dir() -> AppUrl {
  2320. AppUrl::Url(WindowUrl::App("../dist".into()))
  2321. }
  2322. #[derive(Debug, PartialEq, Eq)]
  2323. struct PackageVersion(String);
  2324. impl<'d> serde::Deserialize<'d> for PackageVersion {
  2325. fn deserialize<D: Deserializer<'d>>(deserializer: D) -> Result<PackageVersion, D::Error> {
  2326. struct PackageVersionVisitor;
  2327. impl<'d> Visitor<'d> for PackageVersionVisitor {
  2328. type Value = PackageVersion;
  2329. fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
  2330. write!(
  2331. formatter,
  2332. "a semver string or a path to a package.json file"
  2333. )
  2334. }
  2335. fn visit_str<E: DeError>(self, value: &str) -> Result<PackageVersion, E> {
  2336. let path = PathBuf::from(value);
  2337. if path.exists() {
  2338. let json_str = read_to_string(&path)
  2339. .map_err(|e| DeError::custom(format!("failed to read version JSON file: {}", e)))?;
  2340. let package_json: serde_json::Value = serde_json::from_str(&json_str)
  2341. .map_err(|e| DeError::custom(format!("failed to read version JSON file: {}", e)))?;
  2342. if let Some(obj) = package_json.as_object() {
  2343. let version = obj
  2344. .get("version")
  2345. .ok_or_else(|| DeError::custom("JSON must contain a `version` field"))?
  2346. .as_str()
  2347. .ok_or_else(|| {
  2348. DeError::custom(format!("`{} > version` must be a string", path.display()))
  2349. })?;
  2350. Ok(PackageVersion(
  2351. Version::from_str(version)
  2352. .map_err(|_| DeError::custom("`package > version` must be a semver string"))?
  2353. .to_string(),
  2354. ))
  2355. } else {
  2356. Err(DeError::custom(
  2357. "`package > version` value is not a path to a JSON object",
  2358. ))
  2359. }
  2360. } else {
  2361. Ok(PackageVersion(
  2362. Version::from_str(value)
  2363. .map_err(|_| DeError::custom("`package > version` must be a semver string"))?
  2364. .to_string(),
  2365. ))
  2366. }
  2367. }
  2368. }
  2369. deserializer.deserialize_string(PackageVersionVisitor {})
  2370. }
  2371. }
  2372. /// The package configuration.
  2373. #[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
  2374. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  2375. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  2376. pub struct PackageConfig {
  2377. /// App name.
  2378. #[serde(alias = "product-name")]
  2379. pub product_name: Option<String>,
  2380. /// App version. It is a semver version number or a path to a `package.json` file contaning the `version` field.
  2381. #[serde(deserialize_with = "version_deserializer", default)]
  2382. pub version: Option<String>,
  2383. }
  2384. fn version_deserializer<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
  2385. where
  2386. D: Deserializer<'de>,
  2387. {
  2388. Option::<PackageVersion>::deserialize(deserializer).map(|v| v.map(|v| v.0))
  2389. }
  2390. impl PackageConfig {
  2391. /// The binary name.
  2392. #[allow(dead_code)]
  2393. pub fn binary_name(&self) -> Option<String> {
  2394. #[cfg(target_os = "linux")]
  2395. {
  2396. self.product_name.as_ref().map(|n| n.to_kebab_case())
  2397. }
  2398. #[cfg(not(target_os = "linux"))]
  2399. {
  2400. self.product_name.clone()
  2401. }
  2402. }
  2403. }
  2404. /// The Tauri configuration object.
  2405. /// It is read from a file where you can define your frontend assets,
  2406. /// configure the bundler, enable the app updater, define a system tray,
  2407. /// enable APIs via the allowlist and more.
  2408. ///
  2409. /// The configuration file is generated by the
  2410. /// [`tauri init`](https://tauri.app/v1/api/cli#init) command that lives in
  2411. /// your Tauri application source directory (src-tauri).
  2412. ///
  2413. /// Once generated, you may modify it at will to customize your Tauri application.
  2414. ///
  2415. /// ## File Formats
  2416. ///
  2417. /// By default, the configuration is defined as a JSON file named `tauri.conf.json`.
  2418. ///
  2419. /// Tauri also supports JSON5 and TOML files via the `config-json5` and `config-toml` Cargo features, respectively.
  2420. /// The JSON5 file name must be either `tauri.conf.json` or `tauri.conf.json5`.
  2421. /// The TOML file name is `Tauri.toml`.
  2422. ///
  2423. /// ## Platform-Specific Configuration
  2424. ///
  2425. /// In addition to the default configuration file, Tauri can
  2426. /// read a platform-specific configuration from `tauri.linux.conf.json`,
  2427. /// `tauri.windows.conf.json`, and `tauri.macos.conf.json`
  2428. /// (or `Tauri.linux.toml`, `Tauri.windows.toml` and `Tauri.macos.toml` if the `Tauri.toml` format is used),
  2429. /// which gets merged with the main configuration object.
  2430. ///
  2431. /// ## Configuration Structure
  2432. ///
  2433. /// The configuration is composed of the following objects:
  2434. ///
  2435. /// - [`package`](#packageconfig): Package settings
  2436. /// - [`tauri`](#tauriconfig): The Tauri config
  2437. /// - [`build`](#buildconfig): The build configuration
  2438. /// - [`plugins`](#pluginconfig): The plugins config
  2439. ///
  2440. /// ```json title="Example tauri.config.json file"
  2441. /// {
  2442. /// "build": {
  2443. /// "beforeBuildCommand": "",
  2444. /// "beforeDevCommand": "",
  2445. /// "devPath": "../dist",
  2446. /// "distDir": "../dist"
  2447. /// },
  2448. /// "package": {
  2449. /// "productName": "tauri-app",
  2450. /// "version": "0.1.0"
  2451. /// },
  2452. /// "tauri": {
  2453. /// "allowlist": {
  2454. /// "all": true
  2455. /// },
  2456. /// "bundle": {},
  2457. /// "security": {
  2458. /// "csp": null
  2459. /// },
  2460. /// "updater": {
  2461. /// "active": false
  2462. /// },
  2463. /// "windows": [
  2464. /// {
  2465. /// "fullscreen": false,
  2466. /// "height": 600,
  2467. /// "resizable": true,
  2468. /// "title": "Tauri App",
  2469. /// "width": 800
  2470. /// }
  2471. /// ]
  2472. /// }
  2473. /// }
  2474. /// ```
  2475. #[skip_serializing_none]
  2476. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  2477. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  2478. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  2479. pub struct Config {
  2480. /// The JSON schema for the Tauri config.
  2481. #[serde(rename = "$schema")]
  2482. pub schema: Option<String>,
  2483. /// Package settings.
  2484. #[serde(default)]
  2485. pub package: PackageConfig,
  2486. /// The Tauri configuration.
  2487. #[serde(default)]
  2488. pub tauri: TauriConfig,
  2489. /// The build configuration.
  2490. #[serde(default = "default_build")]
  2491. pub build: BuildConfig,
  2492. /// The plugins config.
  2493. #[serde(default)]
  2494. pub plugins: PluginConfig,
  2495. }
  2496. /// The plugin configs holds a HashMap mapping a plugin name to its configuration object.
  2497. #[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
  2498. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  2499. pub struct PluginConfig(pub HashMap<String, JsonValue>);
  2500. fn default_build() -> BuildConfig {
  2501. BuildConfig {
  2502. runner: None,
  2503. dev_path: default_dev_path(),
  2504. dist_dir: default_dist_dir(),
  2505. before_dev_command: None,
  2506. before_build_command: None,
  2507. before_bundle_command: None,
  2508. features: None,
  2509. with_global_tauri: false,
  2510. }
  2511. }
  2512. /// Implement `ToTokens` for all config structs, allowing a literal `Config` to be built.
  2513. ///
  2514. /// This allows for a build script to output the values in a `Config` to a `TokenStream`, which can
  2515. /// then be consumed by another crate. Useful for passing a config to both the build script and the
  2516. /// application using tauri while only parsing it once (in the build script).
  2517. #[cfg(feature = "build")]
  2518. mod build {
  2519. use std::{convert::identity, path::Path};
  2520. use proc_macro2::TokenStream;
  2521. use quote::{quote, ToTokens, TokenStreamExt};
  2522. use super::*;
  2523. use serde_json::Value as JsonValue;
  2524. /// Create a `String` constructor `TokenStream`.
  2525. ///
  2526. /// e.g. `"Hello World" -> String::from("Hello World").
  2527. /// This takes a `&String` to reduce casting all the `&String` -> `&str` manually.
  2528. fn str_lit(s: impl AsRef<str>) -> TokenStream {
  2529. let s = s.as_ref();
  2530. quote! { #s.into() }
  2531. }
  2532. /// Create an `Option` constructor `TokenStream`.
  2533. fn opt_lit(item: Option<&impl ToTokens>) -> TokenStream {
  2534. match item {
  2535. None => quote! { ::core::option::Option::None },
  2536. Some(item) => quote! { ::core::option::Option::Some(#item) },
  2537. }
  2538. }
  2539. /// Helper function to combine an `opt_lit` with `str_lit`.
  2540. fn opt_str_lit(item: Option<impl AsRef<str>>) -> TokenStream {
  2541. opt_lit(item.map(str_lit).as_ref())
  2542. }
  2543. /// Helper function to combine an `opt_lit` with a list of `str_lit`
  2544. fn opt_vec_str_lit(item: Option<impl IntoIterator<Item = impl AsRef<str>>>) -> TokenStream {
  2545. opt_lit(item.map(|list| vec_lit(list, str_lit)).as_ref())
  2546. }
  2547. /// Create a `Vec` constructor, mapping items with a function that spits out `TokenStream`s.
  2548. fn vec_lit<Raw, Tokens>(
  2549. list: impl IntoIterator<Item = Raw>,
  2550. map: impl Fn(Raw) -> Tokens,
  2551. ) -> TokenStream
  2552. where
  2553. Tokens: ToTokens,
  2554. {
  2555. let items = list.into_iter().map(map);
  2556. quote! { vec![#(#items),*] }
  2557. }
  2558. /// Create a `PathBuf` constructor `TokenStream`.
  2559. ///
  2560. /// e.g. `"Hello World" -> String::from("Hello World").
  2561. fn path_buf_lit(s: impl AsRef<Path>) -> TokenStream {
  2562. let s = s.as_ref().to_string_lossy().into_owned();
  2563. quote! { ::std::path::PathBuf::from(#s) }
  2564. }
  2565. /// Creates a `Url` constructor `TokenStream`.
  2566. fn url_lit(url: &Url) -> TokenStream {
  2567. let url = url.as_str();
  2568. quote! { #url.parse().unwrap() }
  2569. }
  2570. /// Create a map constructor, mapping keys and values with other `TokenStream`s.
  2571. ///
  2572. /// This function is pretty generic because the types of keys AND values get transformed.
  2573. fn map_lit<Map, Key, Value, TokenStreamKey, TokenStreamValue, FuncKey, FuncValue>(
  2574. map_type: TokenStream,
  2575. map: Map,
  2576. map_key: FuncKey,
  2577. map_value: FuncValue,
  2578. ) -> TokenStream
  2579. where
  2580. <Map as IntoIterator>::IntoIter: ExactSizeIterator,
  2581. Map: IntoIterator<Item = (Key, Value)>,
  2582. TokenStreamKey: ToTokens,
  2583. TokenStreamValue: ToTokens,
  2584. FuncKey: Fn(Key) -> TokenStreamKey,
  2585. FuncValue: Fn(Value) -> TokenStreamValue,
  2586. {
  2587. let ident = quote::format_ident!("map");
  2588. let map = map.into_iter();
  2589. if map.len() > 0 {
  2590. let items = map.map(|(key, value)| {
  2591. let key = map_key(key);
  2592. let value = map_value(value);
  2593. quote! { #ident.insert(#key, #value); }
  2594. });
  2595. quote! {{
  2596. let mut #ident = #map_type::new();
  2597. #(#items)*
  2598. #ident
  2599. }}
  2600. } else {
  2601. quote! { #map_type::new() }
  2602. }
  2603. }
  2604. /// Create a `serde_json::Value` variant `TokenStream` for a number
  2605. fn json_value_number_lit(num: &serde_json::Number) -> TokenStream {
  2606. // See https://docs.rs/serde_json/1/serde_json/struct.Number.html for guarantees
  2607. let prefix = quote! { ::serde_json::Value };
  2608. if num.is_u64() {
  2609. // guaranteed u64
  2610. let num = num.as_u64().unwrap();
  2611. quote! { #prefix::Number(#num.into()) }
  2612. } else if num.is_i64() {
  2613. // guaranteed i64
  2614. let num = num.as_i64().unwrap();
  2615. quote! { #prefix::Number(#num.into()) }
  2616. } else if num.is_f64() {
  2617. // guaranteed f64
  2618. let num = num.as_f64().unwrap();
  2619. quote! { #prefix::Number(#num.into()) }
  2620. } else {
  2621. // invalid number
  2622. quote! { #prefix::Null }
  2623. }
  2624. }
  2625. /// Create a `serde_json::Value` constructor `TokenStream`
  2626. fn json_value_lit(jv: &JsonValue) -> TokenStream {
  2627. let prefix = quote! { ::serde_json::Value };
  2628. match jv {
  2629. JsonValue::Null => quote! { #prefix::Null },
  2630. JsonValue::Bool(bool) => quote! { #prefix::Bool(#bool) },
  2631. JsonValue::Number(number) => json_value_number_lit(number),
  2632. JsonValue::String(str) => {
  2633. let s = str_lit(str);
  2634. quote! { #prefix::String(#s) }
  2635. }
  2636. JsonValue::Array(vec) => {
  2637. let items = vec.iter().map(json_value_lit);
  2638. quote! { #prefix::Array(vec![#(#items),*]) }
  2639. }
  2640. JsonValue::Object(map) => {
  2641. let map = map_lit(quote! { ::serde_json::Map }, map, str_lit, json_value_lit);
  2642. quote! { #prefix::Object(#map) }
  2643. }
  2644. }
  2645. }
  2646. /// Write a `TokenStream` of the `$struct`'s fields to the `$tokens`.
  2647. ///
  2648. /// All fields must represent a binding of the same name that implements `ToTokens`.
  2649. macro_rules! literal_struct {
  2650. ($tokens:ident, $struct:ident, $($field:ident),+) => {
  2651. $tokens.append_all(quote! {
  2652. ::tauri::utils::config::$struct {
  2653. $($field: #$field),+
  2654. }
  2655. });
  2656. };
  2657. }
  2658. impl ToTokens for WindowUrl {
  2659. fn to_tokens(&self, tokens: &mut TokenStream) {
  2660. let prefix = quote! { ::tauri::utils::config::WindowUrl };
  2661. tokens.append_all(match self {
  2662. Self::App(path) => {
  2663. let path = path_buf_lit(&path);
  2664. quote! { #prefix::App(#path) }
  2665. }
  2666. Self::External(url) => {
  2667. let url = url_lit(url);
  2668. quote! { #prefix::External(#url) }
  2669. }
  2670. })
  2671. }
  2672. }
  2673. impl ToTokens for crate::Theme {
  2674. fn to_tokens(&self, tokens: &mut TokenStream) {
  2675. let prefix = quote! { ::tauri::utils::Theme };
  2676. tokens.append_all(match self {
  2677. Self::Light => quote! { #prefix::Light },
  2678. Self::Dark => quote! { #prefix::Dark },
  2679. })
  2680. }
  2681. }
  2682. impl ToTokens for WindowConfig {
  2683. fn to_tokens(&self, tokens: &mut TokenStream) {
  2684. let label = str_lit(&self.label);
  2685. let url = &self.url;
  2686. let file_drop_enabled = self.file_drop_enabled;
  2687. let center = self.center;
  2688. let x = opt_lit(self.x.as_ref());
  2689. let y = opt_lit(self.y.as_ref());
  2690. let width = self.width;
  2691. let height = self.height;
  2692. let min_width = opt_lit(self.min_width.as_ref());
  2693. let min_height = opt_lit(self.min_height.as_ref());
  2694. let max_width = opt_lit(self.max_width.as_ref());
  2695. let max_height = opt_lit(self.max_height.as_ref());
  2696. let resizable = self.resizable;
  2697. let title = str_lit(&self.title);
  2698. let fullscreen = self.fullscreen;
  2699. let focus = self.focus;
  2700. let transparent = self.transparent;
  2701. let maximized = self.maximized;
  2702. let visible = self.visible;
  2703. let decorations = self.decorations;
  2704. let always_on_top = self.always_on_top;
  2705. let skip_taskbar = self.skip_taskbar;
  2706. let theme = opt_lit(self.theme.as_ref());
  2707. literal_struct!(
  2708. tokens,
  2709. WindowConfig,
  2710. label,
  2711. url,
  2712. file_drop_enabled,
  2713. center,
  2714. x,
  2715. y,
  2716. width,
  2717. height,
  2718. min_width,
  2719. min_height,
  2720. max_width,
  2721. max_height,
  2722. resizable,
  2723. title,
  2724. fullscreen,
  2725. focus,
  2726. transparent,
  2727. maximized,
  2728. visible,
  2729. decorations,
  2730. always_on_top,
  2731. skip_taskbar,
  2732. theme
  2733. );
  2734. }
  2735. }
  2736. impl ToTokens for CliArg {
  2737. fn to_tokens(&self, tokens: &mut TokenStream) {
  2738. let short = opt_lit(self.short.as_ref());
  2739. let name = str_lit(&self.name);
  2740. let description = opt_str_lit(self.description.as_ref());
  2741. let long_description = opt_str_lit(self.long_description.as_ref());
  2742. let takes_value = self.takes_value;
  2743. let multiple = self.multiple;
  2744. let multiple_occurrences = self.multiple_occurrences;
  2745. let number_of_values = opt_lit(self.number_of_values.as_ref());
  2746. let possible_values = opt_vec_str_lit(self.possible_values.as_ref());
  2747. let min_values = opt_lit(self.min_values.as_ref());
  2748. let max_values = opt_lit(self.max_values.as_ref());
  2749. let required = self.required;
  2750. let required_unless_present = opt_str_lit(self.required_unless_present.as_ref());
  2751. let required_unless_present_all = opt_vec_str_lit(self.required_unless_present_all.as_ref());
  2752. let required_unless_present_any = opt_vec_str_lit(self.required_unless_present_any.as_ref());
  2753. let conflicts_with = opt_str_lit(self.conflicts_with.as_ref());
  2754. let conflicts_with_all = opt_vec_str_lit(self.conflicts_with_all.as_ref());
  2755. let requires = opt_str_lit(self.requires.as_ref());
  2756. let requires_all = opt_vec_str_lit(self.requires_all.as_ref());
  2757. let requires_if = opt_vec_str_lit(self.requires_if.as_ref());
  2758. let required_if_eq = opt_vec_str_lit(self.required_if_eq.as_ref());
  2759. let require_equals = opt_lit(self.require_equals.as_ref());
  2760. let index = opt_lit(self.index.as_ref());
  2761. literal_struct!(
  2762. tokens,
  2763. CliArg,
  2764. short,
  2765. name,
  2766. description,
  2767. long_description,
  2768. takes_value,
  2769. multiple,
  2770. multiple_occurrences,
  2771. number_of_values,
  2772. possible_values,
  2773. min_values,
  2774. max_values,
  2775. required,
  2776. required_unless_present,
  2777. required_unless_present_all,
  2778. required_unless_present_any,
  2779. conflicts_with,
  2780. conflicts_with_all,
  2781. requires,
  2782. requires_all,
  2783. requires_if,
  2784. required_if_eq,
  2785. require_equals,
  2786. index
  2787. );
  2788. }
  2789. }
  2790. impl ToTokens for CliConfig {
  2791. fn to_tokens(&self, tokens: &mut TokenStream) {
  2792. let description = opt_str_lit(self.description.as_ref());
  2793. let long_description = opt_str_lit(self.long_description.as_ref());
  2794. let before_help = opt_str_lit(self.before_help.as_ref());
  2795. let after_help = opt_str_lit(self.after_help.as_ref());
  2796. let args = {
  2797. let args = self.args.as_ref().map(|args| {
  2798. let arg = args.iter().map(|a| quote! { #a });
  2799. quote! { vec![#(#arg),*] }
  2800. });
  2801. opt_lit(args.as_ref())
  2802. };
  2803. let subcommands = opt_lit(
  2804. self
  2805. .subcommands
  2806. .as_ref()
  2807. .map(|map| {
  2808. map_lit(
  2809. quote! { ::std::collections::HashMap },
  2810. map,
  2811. str_lit,
  2812. identity,
  2813. )
  2814. })
  2815. .as_ref(),
  2816. );
  2817. literal_struct!(
  2818. tokens,
  2819. CliConfig,
  2820. description,
  2821. long_description,
  2822. before_help,
  2823. after_help,
  2824. args,
  2825. subcommands
  2826. );
  2827. }
  2828. }
  2829. impl ToTokens for PatternKind {
  2830. fn to_tokens(&self, tokens: &mut TokenStream) {
  2831. let prefix = quote! { ::tauri::utils::config::PatternKind };
  2832. tokens.append_all(match self {
  2833. Self::Brownfield => quote! { #prefix::Brownfield },
  2834. #[cfg(feature = "isolation")]
  2835. Self::Isolation { dir } => {
  2836. let dir = path_buf_lit(dir);
  2837. quote! { #prefix::Isolation { dir: #dir } }
  2838. }
  2839. })
  2840. }
  2841. }
  2842. impl ToTokens for WebviewInstallMode {
  2843. fn to_tokens(&self, tokens: &mut TokenStream) {
  2844. let prefix = quote! { ::tauri::utils::config::WebviewInstallMode };
  2845. tokens.append_all(match self {
  2846. Self::Skip => quote! { #prefix::Skip },
  2847. Self::DownloadBootstrapper { silent } => {
  2848. quote! { #prefix::DownloadBootstrapper { silent: #silent } }
  2849. }
  2850. Self::EmbedBootstrapper { silent } => {
  2851. quote! { #prefix::EmbedBootstrapper { silent: #silent } }
  2852. }
  2853. Self::OfflineInstaller { silent } => {
  2854. quote! { #prefix::OfflineInstaller { silent: #silent } }
  2855. }
  2856. Self::FixedRuntime { path } => {
  2857. let path = path_buf_lit(&path);
  2858. quote! { #prefix::FixedRuntime { path: #path } }
  2859. }
  2860. })
  2861. }
  2862. }
  2863. impl ToTokens for WindowsConfig {
  2864. fn to_tokens(&self, tokens: &mut TokenStream) {
  2865. let webview_install_mode = if let Some(fixed_runtime_path) = &self.webview_fixed_runtime_path
  2866. {
  2867. WebviewInstallMode::FixedRuntime {
  2868. path: fixed_runtime_path.clone(),
  2869. }
  2870. } else {
  2871. self.webview_install_mode.clone()
  2872. };
  2873. tokens.append_all(quote! { ::tauri::utils::config::WindowsConfig {
  2874. webview_install_mode: #webview_install_mode,
  2875. ..Default::default()
  2876. }})
  2877. }
  2878. }
  2879. impl ToTokens for BundleConfig {
  2880. fn to_tokens(&self, tokens: &mut TokenStream) {
  2881. let identifier = str_lit(&self.identifier);
  2882. let icon = vec_lit(&self.icon, str_lit);
  2883. let active = self.active;
  2884. let targets = quote!(Default::default());
  2885. let resources = quote!(None);
  2886. let copyright = quote!(None);
  2887. let category = quote!(None);
  2888. let short_description = quote!(None);
  2889. let long_description = quote!(None);
  2890. let appimage = quote!(Default::default());
  2891. let deb = quote!(Default::default());
  2892. let macos = quote!(Default::default());
  2893. let external_bin = opt_vec_str_lit(self.external_bin.as_ref());
  2894. let windows = &self.windows;
  2895. literal_struct!(
  2896. tokens,
  2897. BundleConfig,
  2898. active,
  2899. identifier,
  2900. icon,
  2901. targets,
  2902. resources,
  2903. copyright,
  2904. category,
  2905. short_description,
  2906. long_description,
  2907. appimage,
  2908. deb,
  2909. macos,
  2910. external_bin,
  2911. windows
  2912. );
  2913. }
  2914. }
  2915. impl ToTokens for AppUrl {
  2916. fn to_tokens(&self, tokens: &mut TokenStream) {
  2917. let prefix = quote! { ::tauri::utils::config::AppUrl };
  2918. tokens.append_all(match self {
  2919. Self::Url(url) => {
  2920. quote! { #prefix::Url(#url) }
  2921. }
  2922. Self::Files(files) => {
  2923. let files = vec_lit(files, path_buf_lit);
  2924. quote! { #prefix::Files(#files) }
  2925. }
  2926. })
  2927. }
  2928. }
  2929. impl ToTokens for BuildConfig {
  2930. fn to_tokens(&self, tokens: &mut TokenStream) {
  2931. let dev_path = &self.dev_path;
  2932. let dist_dir = &self.dist_dir;
  2933. let with_global_tauri = self.with_global_tauri;
  2934. let runner = quote!(None);
  2935. let before_dev_command = quote!(None);
  2936. let before_build_command = quote!(None);
  2937. let before_bundle_command = quote!(None);
  2938. let features = quote!(None);
  2939. literal_struct!(
  2940. tokens,
  2941. BuildConfig,
  2942. runner,
  2943. dev_path,
  2944. dist_dir,
  2945. with_global_tauri,
  2946. before_dev_command,
  2947. before_build_command,
  2948. before_bundle_command,
  2949. features
  2950. );
  2951. }
  2952. }
  2953. impl ToTokens for WindowsUpdateInstallMode {
  2954. fn to_tokens(&self, tokens: &mut TokenStream) {
  2955. let prefix = quote! { ::tauri::utils::config::WindowsUpdateInstallMode };
  2956. tokens.append_all(match self {
  2957. Self::BasicUi => quote! { #prefix::BasicUi },
  2958. Self::Quiet => quote! { #prefix::Quiet },
  2959. Self::Passive => quote! { #prefix::Passive },
  2960. })
  2961. }
  2962. }
  2963. impl ToTokens for UpdaterWindowsConfig {
  2964. fn to_tokens(&self, tokens: &mut TokenStream) {
  2965. let install_mode = &self.install_mode;
  2966. literal_struct!(tokens, UpdaterWindowsConfig, install_mode);
  2967. }
  2968. }
  2969. impl ToTokens for UpdaterConfig {
  2970. fn to_tokens(&self, tokens: &mut TokenStream) {
  2971. let active = self.active;
  2972. let dialog = self.dialog;
  2973. let pubkey = str_lit(&self.pubkey);
  2974. let endpoints = opt_lit(
  2975. self
  2976. .endpoints
  2977. .as_ref()
  2978. .map(|list| {
  2979. vec_lit(list, |url| {
  2980. let url = url.0.as_str();
  2981. quote! { ::tauri::utils::config::UpdaterEndpoint(#url.parse().unwrap()) }
  2982. })
  2983. })
  2984. .as_ref(),
  2985. );
  2986. let windows = &self.windows;
  2987. literal_struct!(
  2988. tokens,
  2989. UpdaterConfig,
  2990. active,
  2991. dialog,
  2992. pubkey,
  2993. endpoints,
  2994. windows
  2995. );
  2996. }
  2997. }
  2998. impl ToTokens for CspDirectiveSources {
  2999. fn to_tokens(&self, tokens: &mut TokenStream) {
  3000. let prefix = quote! { ::tauri::utils::config::CspDirectiveSources };
  3001. tokens.append_all(match self {
  3002. Self::Inline(sources) => {
  3003. let sources = sources.as_str();
  3004. quote!(#prefix::Inline(#sources.into()))
  3005. }
  3006. Self::List(list) => {
  3007. let list = vec_lit(list, str_lit);
  3008. quote!(#prefix::List(#list))
  3009. }
  3010. })
  3011. }
  3012. }
  3013. impl ToTokens for Csp {
  3014. fn to_tokens(&self, tokens: &mut TokenStream) {
  3015. let prefix = quote! { ::tauri::utils::config::Csp };
  3016. tokens.append_all(match self {
  3017. Self::Policy(policy) => {
  3018. let policy = policy.as_str();
  3019. quote!(#prefix::Policy(#policy.into()))
  3020. }
  3021. Self::DirectiveMap(list) => {
  3022. let map = map_lit(
  3023. quote! { ::std::collections::HashMap },
  3024. list,
  3025. str_lit,
  3026. identity,
  3027. );
  3028. quote!(#prefix::DirectiveMap(#map))
  3029. }
  3030. })
  3031. }
  3032. }
  3033. impl ToTokens for DisabledCspModificationKind {
  3034. fn to_tokens(&self, tokens: &mut TokenStream) {
  3035. let prefix = quote! { ::tauri::utils::config::DisabledCspModificationKind };
  3036. tokens.append_all(match self {
  3037. Self::Flag(flag) => {
  3038. quote! { #prefix::Flag(#flag) }
  3039. }
  3040. Self::List(directives) => {
  3041. let directives = vec_lit(directives, str_lit);
  3042. quote! { #prefix::List(#directives) }
  3043. }
  3044. });
  3045. }
  3046. }
  3047. impl ToTokens for SecurityConfig {
  3048. fn to_tokens(&self, tokens: &mut TokenStream) {
  3049. let csp = opt_lit(self.csp.as_ref());
  3050. let dev_csp = opt_lit(self.dev_csp.as_ref());
  3051. let freeze_prototype = self.freeze_prototype;
  3052. let dangerous_disable_asset_csp_modification = &self.dangerous_disable_asset_csp_modification;
  3053. literal_struct!(
  3054. tokens,
  3055. SecurityConfig,
  3056. csp,
  3057. dev_csp,
  3058. freeze_prototype,
  3059. dangerous_disable_asset_csp_modification
  3060. );
  3061. }
  3062. }
  3063. impl ToTokens for SystemTrayConfig {
  3064. fn to_tokens(&self, tokens: &mut TokenStream) {
  3065. let icon_as_template = self.icon_as_template;
  3066. let menu_on_left_click = self.menu_on_left_click;
  3067. let icon_path = path_buf_lit(&self.icon_path);
  3068. literal_struct!(
  3069. tokens,
  3070. SystemTrayConfig,
  3071. icon_path,
  3072. icon_as_template,
  3073. menu_on_left_click
  3074. );
  3075. }
  3076. }
  3077. impl ToTokens for FsAllowlistScope {
  3078. fn to_tokens(&self, tokens: &mut TokenStream) {
  3079. let prefix = quote! { ::tauri::utils::config::FsAllowlistScope };
  3080. tokens.append_all(match self {
  3081. Self::AllowedPaths(allow) => {
  3082. let allowed_paths = vec_lit(allow, path_buf_lit);
  3083. quote! { #prefix::AllowedPaths(#allowed_paths) }
  3084. }
  3085. Self::Scope { allow, deny } => {
  3086. let allow = vec_lit(allow, path_buf_lit);
  3087. let deny = vec_lit(deny, path_buf_lit);
  3088. quote! { #prefix::Scope { allow: #allow, deny: #deny } }
  3089. }
  3090. });
  3091. }
  3092. }
  3093. impl ToTokens for FsAllowlistConfig {
  3094. fn to_tokens(&self, tokens: &mut TokenStream) {
  3095. let scope = &self.scope;
  3096. tokens.append_all(quote! { ::tauri::utils::config::FsAllowlistConfig { scope: #scope, ..Default::default() } })
  3097. }
  3098. }
  3099. impl ToTokens for ProtocolAllowlistConfig {
  3100. fn to_tokens(&self, tokens: &mut TokenStream) {
  3101. let asset_scope = &self.asset_scope;
  3102. tokens.append_all(quote! { ::tauri::utils::config::ProtocolAllowlistConfig { asset_scope: #asset_scope, ..Default::default() } })
  3103. }
  3104. }
  3105. impl ToTokens for HttpAllowlistScope {
  3106. fn to_tokens(&self, tokens: &mut TokenStream) {
  3107. let allowed_urls = vec_lit(&self.0, url_lit);
  3108. tokens.append_all(quote! { ::tauri::utils::config::HttpAllowlistScope(#allowed_urls) })
  3109. }
  3110. }
  3111. impl ToTokens for HttpAllowlistConfig {
  3112. fn to_tokens(&self, tokens: &mut TokenStream) {
  3113. let scope = &self.scope;
  3114. tokens.append_all(quote! { ::tauri::utils::config::HttpAllowlistConfig { scope: #scope, ..Default::default() } })
  3115. }
  3116. }
  3117. impl ToTokens for ShellAllowedCommand {
  3118. fn to_tokens(&self, tokens: &mut TokenStream) {
  3119. let name = str_lit(&self.name);
  3120. let command = path_buf_lit(&self.command);
  3121. let args = &self.args;
  3122. let sidecar = &self.sidecar;
  3123. literal_struct!(tokens, ShellAllowedCommand, name, command, args, sidecar);
  3124. }
  3125. }
  3126. impl ToTokens for ShellAllowedArgs {
  3127. fn to_tokens(&self, tokens: &mut TokenStream) {
  3128. let prefix = quote! { ::tauri::utils::config::ShellAllowedArgs };
  3129. tokens.append_all(match self {
  3130. Self::Flag(flag) => quote!(#prefix::Flag(#flag)),
  3131. Self::List(list) => {
  3132. let list = vec_lit(list, identity);
  3133. quote!(#prefix::List(#list))
  3134. }
  3135. })
  3136. }
  3137. }
  3138. impl ToTokens for ShellAllowedArg {
  3139. fn to_tokens(&self, tokens: &mut TokenStream) {
  3140. let prefix = quote! { ::tauri::utils::config::ShellAllowedArg };
  3141. tokens.append_all(match self {
  3142. Self::Fixed(fixed) => {
  3143. let fixed = str_lit(fixed);
  3144. quote!(#prefix::Fixed(#fixed))
  3145. }
  3146. Self::Var { validator } => {
  3147. let validator = str_lit(validator);
  3148. quote!(#prefix::Var { validator: #validator })
  3149. }
  3150. })
  3151. }
  3152. }
  3153. impl ToTokens for ShellAllowlistOpen {
  3154. fn to_tokens(&self, tokens: &mut TokenStream) {
  3155. let prefix = quote! { ::tauri::utils::config::ShellAllowlistOpen };
  3156. tokens.append_all(match self {
  3157. Self::Flag(flag) => quote!(#prefix::Flag(#flag)),
  3158. Self::Validate(regex) => quote!(#prefix::Validate(#regex)),
  3159. })
  3160. }
  3161. }
  3162. impl ToTokens for ShellAllowlistScope {
  3163. fn to_tokens(&self, tokens: &mut TokenStream) {
  3164. let allowed_commands = vec_lit(&self.0, identity);
  3165. tokens.append_all(quote! { ::tauri::utils::config::ShellAllowlistScope(#allowed_commands) })
  3166. }
  3167. }
  3168. impl ToTokens for ShellAllowlistConfig {
  3169. fn to_tokens(&self, tokens: &mut TokenStream) {
  3170. let scope = &self.scope;
  3171. tokens.append_all(quote! { ::tauri::utils::config::ShellAllowlistConfig { scope: #scope, ..Default::default() } })
  3172. }
  3173. }
  3174. impl ToTokens for AllowlistConfig {
  3175. fn to_tokens(&self, tokens: &mut TokenStream) {
  3176. let fs = &self.fs;
  3177. let protocol = &self.protocol;
  3178. let http = &self.http;
  3179. let shell = &self.shell;
  3180. tokens.append_all(
  3181. quote! { ::tauri::utils::config::AllowlistConfig { fs: #fs, protocol: #protocol, http: #http, shell: #shell, ..Default::default() } },
  3182. )
  3183. }
  3184. }
  3185. impl ToTokens for TauriConfig {
  3186. fn to_tokens(&self, tokens: &mut TokenStream) {
  3187. let pattern = &self.pattern;
  3188. let windows = vec_lit(&self.windows, identity);
  3189. let cli = opt_lit(self.cli.as_ref());
  3190. let bundle = &self.bundle;
  3191. let updater = &self.updater;
  3192. let security = &self.security;
  3193. let system_tray = opt_lit(self.system_tray.as_ref());
  3194. let allowlist = &self.allowlist;
  3195. let macos_private_api = self.macos_private_api;
  3196. literal_struct!(
  3197. tokens,
  3198. TauriConfig,
  3199. pattern,
  3200. windows,
  3201. cli,
  3202. bundle,
  3203. updater,
  3204. security,
  3205. system_tray,
  3206. allowlist,
  3207. macos_private_api
  3208. );
  3209. }
  3210. }
  3211. impl ToTokens for PluginConfig {
  3212. fn to_tokens(&self, tokens: &mut TokenStream) {
  3213. let config = map_lit(
  3214. quote! { ::std::collections::HashMap },
  3215. &self.0,
  3216. str_lit,
  3217. json_value_lit,
  3218. );
  3219. tokens.append_all(quote! { ::tauri::utils::config::PluginConfig(#config) })
  3220. }
  3221. }
  3222. impl ToTokens for PackageConfig {
  3223. fn to_tokens(&self, tokens: &mut TokenStream) {
  3224. let product_name = opt_str_lit(self.product_name.as_ref());
  3225. let version = opt_str_lit(self.version.as_ref());
  3226. literal_struct!(tokens, PackageConfig, product_name, version);
  3227. }
  3228. }
  3229. impl ToTokens for Config {
  3230. fn to_tokens(&self, tokens: &mut TokenStream) {
  3231. let schema = quote!(None);
  3232. let package = &self.package;
  3233. let tauri = &self.tauri;
  3234. let build = &self.build;
  3235. let plugins = &self.plugins;
  3236. literal_struct!(tokens, Config, schema, package, tauri, build, plugins);
  3237. }
  3238. }
  3239. }
  3240. #[cfg(test)]
  3241. mod test {
  3242. use super::*;
  3243. // TODO: create a test that compares a config to a json config
  3244. #[test]
  3245. // test all of the default functions
  3246. fn test_defaults() {
  3247. // get default tauri config
  3248. let t_config = TauriConfig::default();
  3249. // get default build config
  3250. let b_config = BuildConfig::default();
  3251. // get default dev path
  3252. let d_path = default_dev_path();
  3253. // get default window
  3254. let d_windows: Vec<WindowConfig> = vec![];
  3255. // get default bundle
  3256. let d_bundle = BundleConfig::default();
  3257. // get default updater
  3258. let d_updater = UpdaterConfig::default();
  3259. // create a tauri config.
  3260. let tauri = TauriConfig {
  3261. pattern: Default::default(),
  3262. windows: vec![],
  3263. bundle: BundleConfig {
  3264. active: false,
  3265. targets: Default::default(),
  3266. identifier: String::from(""),
  3267. icon: Vec::new(),
  3268. resources: None,
  3269. copyright: None,
  3270. category: None,
  3271. short_description: None,
  3272. long_description: None,
  3273. appimage: Default::default(),
  3274. deb: Default::default(),
  3275. macos: Default::default(),
  3276. external_bin: None,
  3277. windows: Default::default(),
  3278. },
  3279. cli: None,
  3280. updater: UpdaterConfig {
  3281. active: false,
  3282. dialog: true,
  3283. pubkey: "".into(),
  3284. endpoints: None,
  3285. windows: Default::default(),
  3286. },
  3287. security: SecurityConfig {
  3288. csp: None,
  3289. dev_csp: None,
  3290. freeze_prototype: false,
  3291. dangerous_disable_asset_csp_modification: DisabledCspModificationKind::Flag(false),
  3292. },
  3293. allowlist: AllowlistConfig::default(),
  3294. system_tray: None,
  3295. macos_private_api: false,
  3296. };
  3297. // create a build config
  3298. let build = BuildConfig {
  3299. runner: None,
  3300. dev_path: AppUrl::Url(WindowUrl::External(
  3301. Url::parse("http://localhost:8080").unwrap(),
  3302. )),
  3303. dist_dir: AppUrl::Url(WindowUrl::App("../dist".into())),
  3304. before_dev_command: None,
  3305. before_build_command: None,
  3306. before_bundle_command: None,
  3307. features: None,
  3308. with_global_tauri: false,
  3309. };
  3310. // test the configs
  3311. assert_eq!(t_config, tauri);
  3312. assert_eq!(b_config, build);
  3313. assert_eq!(d_bundle, tauri.bundle);
  3314. assert_eq!(d_updater, tauri.updater);
  3315. assert_eq!(
  3316. d_path,
  3317. AppUrl::Url(WindowUrl::External(
  3318. Url::parse("http://localhost:8080").unwrap()
  3319. ))
  3320. );
  3321. assert_eq!(d_windows, tauri.windows);
  3322. }
  3323. }