config.rs 123 KB

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