config.rs 123 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735
  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_true")]
  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_true")]
  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_true")]
  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. impl Default for WebviewInstallMode {
  430. fn default() -> Self {
  431. Self::DownloadBootstrapper {
  432. silent: default_true(),
  433. }
  434. }
  435. }
  436. /// Windows bundler configuration.
  437. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  438. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  439. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  440. pub struct WindowsConfig {
  441. /// Specifies the file digest algorithm to use for creating file signatures.
  442. /// Required for code signing. SHA-256 is recommended.
  443. #[serde(alias = "digest-algorithm")]
  444. pub digest_algorithm: Option<String>,
  445. /// Specifies the SHA1 hash of the signing certificate.
  446. #[serde(alias = "certificate-thumbprint")]
  447. pub certificate_thumbprint: Option<String>,
  448. /// Server to use during timestamping.
  449. #[serde(alias = "timestamp-url")]
  450. pub timestamp_url: Option<String>,
  451. /// Whether to use Time-Stamp Protocol (TSP, a.k.a. RFC 3161) for the timestamp server. Your code signing provider may
  452. /// use a TSP timestamp server, like e.g. SSL.com does. If so, enable TSP by setting to true.
  453. #[serde(default)]
  454. pub tsp: bool,
  455. /// The installation mode for the Webview2 runtime.
  456. #[serde(default, alias = "webview-install-mode")]
  457. pub webview_install_mode: WebviewInstallMode,
  458. /// Path to the webview fixed runtime to use. Overwrites [`Self::webview_install_mode`] if set.
  459. ///
  460. /// Will be removed in v2, prefer the [`Self::webview_install_mode`] option.
  461. ///
  462. /// The fixed version can be downloaded [on the official website](https://developer.microsoft.com/en-us/microsoft-edge/webview2/#download-section).
  463. /// The `.cab` file must be extracted to a folder and this folder path must be defined on this field.
  464. #[serde(alias = "webview-fixed-runtime-path")]
  465. pub webview_fixed_runtime_path: Option<PathBuf>,
  466. /// Validates a second app installation, blocking the user from installing an older version if set to `false`.
  467. ///
  468. /// 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`.
  469. ///
  470. /// The default value of this flag is `true`.
  471. #[serde(default = "default_true", alias = "allow-downgrades")]
  472. pub allow_downgrades: bool,
  473. /// Configuration for the MSI generated with WiX.
  474. pub wix: Option<WixConfig>,
  475. }
  476. impl Default for WindowsConfig {
  477. fn default() -> Self {
  478. Self {
  479. digest_algorithm: None,
  480. certificate_thumbprint: None,
  481. timestamp_url: None,
  482. tsp: false,
  483. webview_install_mode: Default::default(),
  484. webview_fixed_runtime_path: None,
  485. allow_downgrades: default_true(),
  486. wix: None,
  487. }
  488. }
  489. }
  490. /// Configuration for tauri-bundler.
  491. #[skip_serializing_none]
  492. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  493. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  494. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  495. pub struct BundleConfig {
  496. /// Whether Tauri should bundle your application or just output the executable.
  497. #[serde(default)]
  498. pub active: bool,
  499. /// The bundle targets, currently supports ["deb", "appimage", "msi", "app", "dmg", "updater"] or "all".
  500. #[serde(default)]
  501. pub targets: BundleTarget,
  502. /// The application identifier in reverse domain name notation (e.g. `com.tauri.example`).
  503. /// This string must be unique across applications since it is used in system configurations like
  504. /// the bundle ID and path to the webview data directory.
  505. /// This string must contain only alphanumeric characters (A–Z, a–z, and 0–9), hyphens (-),
  506. /// and periods (.).
  507. pub identifier: String,
  508. /// The application's publisher. Defaults to the second element in the identifier string.
  509. /// Currently maps to the Manufacturer property of the Windows Installer.
  510. pub publisher: Option<String>,
  511. /// The app's icons
  512. #[serde(default)]
  513. pub icon: Vec<String>,
  514. /// App resources to bundle.
  515. /// Each resource is a path to a file or directory.
  516. /// Glob patterns are supported.
  517. pub resources: Option<Vec<String>>,
  518. /// A copyright string associated with your application.
  519. pub copyright: Option<String>,
  520. /// The application kind.
  521. ///
  522. /// Should be one of the following:
  523. /// 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.
  524. pub category: Option<String>,
  525. /// A short description of your application.
  526. #[serde(alias = "short-description")]
  527. pub short_description: Option<String>,
  528. /// A longer, multi-line description of the application.
  529. #[serde(alias = "long-description")]
  530. pub long_description: Option<String>,
  531. /// Configuration for the AppImage bundle.
  532. #[serde(default)]
  533. pub appimage: AppImageConfig,
  534. /// Configuration for the Debian bundle.
  535. #[serde(default)]
  536. pub deb: DebConfig,
  537. /// Configuration for the macOS bundles.
  538. #[serde(rename = "macOS", default)]
  539. pub macos: MacConfig,
  540. /// A list of—either absolute or relative—paths to binaries to embed with your application.
  541. ///
  542. /// Note that Tauri will look for system-specific binaries following the pattern "binary-name{-target-triple}{.system-extension}".
  543. ///
  544. /// E.g. for the external binary "my-binary", Tauri looks for:
  545. ///
  546. /// - "my-binary-x86_64-pc-windows-msvc.exe" for Windows
  547. /// - "my-binary-x86_64-apple-darwin" for macOS
  548. /// - "my-binary-x86_64-unknown-linux-gnu" for Linux
  549. ///
  550. /// so don't forget to provide binaries for all targeted platforms.
  551. #[serde(alias = "external-bin")]
  552. pub external_bin: Option<Vec<String>>,
  553. /// Configuration for the Windows bundle.
  554. #[serde(default)]
  555. pub windows: WindowsConfig,
  556. /// iOS configuration.
  557. #[serde(rename = "iOS", default)]
  558. pub ios: IosConfig,
  559. }
  560. /// A CLI argument definition.
  561. #[skip_serializing_none]
  562. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  563. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  564. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  565. pub struct CliArg {
  566. /// The short version of the argument, without the preceding -.
  567. ///
  568. /// NOTE: Any leading `-` characters will be stripped, and only the first non-character will be used as the short version.
  569. pub short: Option<char>,
  570. /// The unique argument name
  571. pub name: String,
  572. /// The argument description which will be shown on the help information.
  573. /// Typically, this is a short (one line) description of the arg.
  574. pub description: Option<String>,
  575. /// The argument long description which will be shown on the help information.
  576. /// Typically this a more detailed (multi-line) message that describes the argument.
  577. #[serde(alias = "long-description")]
  578. pub long_description: Option<String>,
  579. /// Specifies that the argument takes a value at run time.
  580. ///
  581. /// NOTE: values for arguments may be specified in any of the following methods
  582. /// - Using a space such as -o value or --option value
  583. /// - Using an equals and no space such as -o=value or --option=value
  584. /// - Use a short and no space such as -ovalue
  585. #[serde(default, alias = "takes-value")]
  586. pub takes_value: bool,
  587. /// Specifies that the argument may have an unknown number of multiple values. Without any other settings, this argument may appear only once.
  588. ///
  589. /// For example, --opt val1 val2 is allowed, but --opt val1 val2 --opt val3 is not.
  590. ///
  591. /// NOTE: Setting this requires `takes_value` to be set to true.
  592. #[serde(default)]
  593. pub multiple: bool,
  594. /// Specifies that the argument may appear more than once.
  595. /// 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.
  596. /// 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)
  597. ///
  598. /// For example, --opt val1 --opt val2 is allowed, but --opt val1 val2 is not.
  599. #[serde(default, alias = "multiple-occurrences")]
  600. pub multiple_occurrences: bool,
  601. /// Specifies how many values are required to satisfy this argument. For example, if you had a
  602. /// `-f <file>` argument where you wanted exactly 3 'files' you would set
  603. /// `number_of_values = 3`, and this argument wouldn't be satisfied unless the user provided
  604. /// 3 and only 3 values.
  605. ///
  606. /// **NOTE:** Does *not* require `multiple_occurrences = true` to be set. Setting
  607. /// `multiple_occurrences = true` would allow `-f <file> <file> <file> -f <file> <file> <file>` where
  608. /// as *not* setting it would only allow one occurrence of this argument.
  609. ///
  610. /// **NOTE:** implicitly sets `takes_value = true` and `multiple_values = true`.
  611. #[serde(alias = "number-of-values")]
  612. pub number_of_values: Option<usize>,
  613. /// Specifies a list of possible values for this argument.
  614. /// At runtime, the CLI verifies that only one of the specified values was used, or fails with an error message.
  615. #[serde(alias = "possible-values")]
  616. pub possible_values: Option<Vec<String>>,
  617. /// Specifies the minimum number of values for this argument.
  618. /// For example, if you had a -f `<file>` argument where you wanted at least 2 'files',
  619. /// you would set `minValues: 2`, and this argument would be satisfied if the user provided, 2 or more values.
  620. #[serde(alias = "min-values")]
  621. pub min_values: Option<usize>,
  622. /// Specifies the maximum number of values are for this argument.
  623. /// For example, if you had a -f `<file>` argument where you wanted up to 3 'files',
  624. /// you would set .max_values(3), and this argument would be satisfied if the user provided, 1, 2, or 3 values.
  625. #[serde(alias = "max-values")]
  626. pub max_values: Option<usize>,
  627. /// Sets whether or not the argument is required by default.
  628. ///
  629. /// - Required by default means it is required, when no other conflicting rules have been evaluated
  630. /// - Conflicting rules take precedence over being required.
  631. #[serde(default)]
  632. pub required: bool,
  633. /// Sets an arg that override this arg's required setting
  634. /// i.e. this arg will be required unless this other argument is present.
  635. #[serde(alias = "required-unless-present")]
  636. pub required_unless_present: Option<String>,
  637. /// Sets args that override this arg's required setting
  638. /// i.e. this arg will be required unless all these other arguments are present.
  639. #[serde(alias = "required-unless-present-all")]
  640. pub required_unless_present_all: Option<Vec<String>>,
  641. /// Sets args that override this arg's required setting
  642. /// i.e. this arg will be required unless at least one of these other arguments are present.
  643. #[serde(alias = "required-unless-present-any")]
  644. pub required_unless_present_any: Option<Vec<String>>,
  645. /// Sets a conflicting argument by name
  646. /// i.e. when using this argument, the following argument can't be present and vice versa.
  647. #[serde(alias = "conflicts-with")]
  648. pub conflicts_with: Option<String>,
  649. /// The same as conflictsWith but allows specifying multiple two-way conflicts per argument.
  650. #[serde(alias = "conflicts-with-all")]
  651. pub conflicts_with_all: Option<Vec<String>>,
  652. /// Tets an argument by name that is required when this one is present
  653. /// i.e. when using this argument, the following argument must be present.
  654. pub requires: Option<String>,
  655. /// Sts multiple arguments by names that are required when this one is present
  656. /// i.e. when using this argument, the following arguments must be present.
  657. #[serde(alias = "requires-all")]
  658. pub requires_all: Option<Vec<String>>,
  659. /// Allows a conditional requirement with the signature [arg, value]
  660. /// the requirement will only become valid if `arg`'s value equals `${value}`.
  661. #[serde(alias = "requires-if")]
  662. pub requires_if: Option<Vec<String>>,
  663. /// Allows specifying that an argument is required conditionally with the signature [arg, value]
  664. /// the requirement will only become valid if the `arg`'s value equals `${value}`.
  665. #[serde(alias = "requires-if-eq")]
  666. pub required_if_eq: Option<Vec<String>>,
  667. /// Requires that options use the --option=val syntax
  668. /// i.e. an equals between the option and associated value.
  669. #[serde(alias = "requires-equals")]
  670. pub require_equals: Option<bool>,
  671. /// The positional argument index, starting at 1.
  672. ///
  673. /// The index refers to position according to other positional argument.
  674. /// It does not define position in the argument list as a whole. When utilized with multiple=true,
  675. /// only the last positional argument may be defined as multiple (i.e. the one with the highest index).
  676. #[cfg_attr(feature = "schema", validate(range(min = 1)))]
  677. pub index: Option<usize>,
  678. }
  679. /// describes a CLI configuration
  680. #[skip_serializing_none]
  681. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  682. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  683. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  684. pub struct CliConfig {
  685. /// Command description which will be shown on the help information.
  686. pub description: Option<String>,
  687. /// Command long description which will be shown on the help information.
  688. #[serde(alias = "long-description")]
  689. pub long_description: Option<String>,
  690. /// Adds additional help information to be displayed in addition to auto-generated help.
  691. /// This information is displayed before the auto-generated help information.
  692. /// This is often used for header information.
  693. #[serde(alias = "before-help")]
  694. pub before_help: Option<String>,
  695. /// Adds additional help information to be displayed in addition to auto-generated help.
  696. /// This information is displayed after the auto-generated help information.
  697. /// This is often used to describe how to use the arguments, or caveats to be noted.
  698. #[serde(alias = "after-help")]
  699. pub after_help: Option<String>,
  700. /// List of arguments for the command
  701. pub args: Option<Vec<CliArg>>,
  702. /// List of subcommands of this command
  703. pub subcommands: Option<HashMap<String, CliConfig>>,
  704. }
  705. impl CliConfig {
  706. /// List of arguments for the command
  707. pub fn args(&self) -> Option<&Vec<CliArg>> {
  708. self.args.as_ref()
  709. }
  710. /// List of subcommands of this command
  711. pub fn subcommands(&self) -> Option<&HashMap<String, CliConfig>> {
  712. self.subcommands.as_ref()
  713. }
  714. /// Command description which will be shown on the help information.
  715. pub fn description(&self) -> Option<&String> {
  716. self.description.as_ref()
  717. }
  718. /// Command long description which will be shown on the help information.
  719. pub fn long_description(&self) -> Option<&String> {
  720. self.description.as_ref()
  721. }
  722. /// Adds additional help information to be displayed in addition to auto-generated help.
  723. /// This information is displayed before the auto-generated help information.
  724. /// This is often used for header information.
  725. pub fn before_help(&self) -> Option<&String> {
  726. self.before_help.as_ref()
  727. }
  728. /// Adds additional help information to be displayed in addition to auto-generated help.
  729. /// This information is displayed after the auto-generated help information.
  730. /// This is often used to describe how to use the arguments, or caveats to be noted.
  731. pub fn after_help(&self) -> Option<&String> {
  732. self.after_help.as_ref()
  733. }
  734. }
  735. /// The window configuration object.
  736. #[skip_serializing_none]
  737. #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
  738. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  739. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  740. pub struct WindowConfig {
  741. /// The window identifier. It must be alphanumeric.
  742. #[serde(default = "default_window_label")]
  743. pub label: String,
  744. /// The window webview URL.
  745. #[serde(default)]
  746. pub url: WindowUrl,
  747. /// The user agent for the webview
  748. #[serde(alias = "user-agent")]
  749. pub user_agent: Option<String>,
  750. /// Whether the file drop is enabled or not on the webview. By default it is enabled.
  751. ///
  752. /// Disabling it is required to use drag and drop on the frontend on Windows.
  753. #[serde(default = "default_true", alias = "file-drop-enabled")]
  754. pub file_drop_enabled: bool,
  755. /// Whether or not the window starts centered or not.
  756. #[serde(default)]
  757. pub center: bool,
  758. /// The horizontal position of the window's top left corner
  759. pub x: Option<f64>,
  760. /// The vertical position of the window's top left corner
  761. pub y: Option<f64>,
  762. /// The window width.
  763. #[serde(default = "default_width")]
  764. pub width: f64,
  765. /// The window height.
  766. #[serde(default = "default_height")]
  767. pub height: f64,
  768. /// The min window width.
  769. #[serde(alias = "min-width")]
  770. pub min_width: Option<f64>,
  771. /// The min window height.
  772. #[serde(alias = "min-height")]
  773. pub min_height: Option<f64>,
  774. /// The max window width.
  775. #[serde(alias = "max-width")]
  776. pub max_width: Option<f64>,
  777. /// The max window height.
  778. #[serde(alias = "max-height")]
  779. pub max_height: Option<f64>,
  780. /// Whether the window is resizable or not.
  781. #[serde(default = "default_true")]
  782. pub resizable: bool,
  783. /// The window title.
  784. #[serde(default = "default_title")]
  785. pub title: String,
  786. /// Whether the window starts as fullscreen or not.
  787. #[serde(default)]
  788. pub fullscreen: bool,
  789. /// Whether the window will be initially focused or not.
  790. #[serde(default = "default_true")]
  791. pub focus: bool,
  792. /// Whether the window is transparent or not.
  793. ///
  794. /// Note that on `macOS` this requires the `macos-private-api` feature flag, enabled under `tauri > macOSPrivateApi`.
  795. /// WARNING: Using private APIs on `macOS` prevents your application from being accepted to the `App Store`.
  796. #[serde(default)]
  797. pub transparent: bool,
  798. /// Whether the window is maximized or not.
  799. #[serde(default)]
  800. pub maximized: bool,
  801. /// Whether the window is visible or not.
  802. #[serde(default = "default_true")]
  803. pub visible: bool,
  804. /// Whether the window should have borders and bars.
  805. #[serde(default = "default_true")]
  806. pub decorations: bool,
  807. /// Whether the window should always be on top of other windows.
  808. #[serde(default, alias = "always-on-top")]
  809. pub always_on_top: bool,
  810. /// If `true`, hides the window icon from the taskbar on Windows and Linux.
  811. #[serde(default, alias = "skip-taskbar")]
  812. pub skip_taskbar: bool,
  813. /// The initial window theme. Defaults to the system theme. Only implemented on Windows and macOS 10.14+.
  814. pub theme: Option<crate::Theme>,
  815. /// The style of the macOS title bar.
  816. #[serde(default, alias = "title-bar-style")]
  817. pub title_bar_style: TitleBarStyle,
  818. /// If `true`, sets the window title to be hidden on macOS.
  819. #[serde(default, alias = "hidden-title")]
  820. pub hidden_title: bool,
  821. /// Whether clicking an inactive window also clicks through to the webview on macOS.
  822. #[serde(default, alias = "accept-first-mouse")]
  823. pub accept_first_mouse: bool,
  824. /// Defines the window [tabbing identifier] for macOS.
  825. ///
  826. /// Windows with matching tabbing identifiers will be grouped together.
  827. /// If the tabbing identifier is not set, automatic tabbing will be disabled.
  828. ///
  829. /// [tabbing identifier]: <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier>
  830. #[serde(default, alias = "tabbing-identifier")]
  831. pub tabbing_identifier: Option<String>,
  832. /// Whether or not the window has shadow.
  833. ///
  834. /// ## Platform-specific
  835. ///
  836. /// - **Windows:**
  837. /// - `false` has no effect on decorated window, shadow are always ON.
  838. /// - `true` will make ndecorated window have a 1px white border,
  839. /// and on Windows 11, it will have a rounded corners.
  840. /// - **Linux:** Unsupported.
  841. #[serde(default)]
  842. pub shadow: bool,
  843. }
  844. impl Default for WindowConfig {
  845. fn default() -> Self {
  846. Self {
  847. label: default_window_label(),
  848. url: WindowUrl::default(),
  849. user_agent: None,
  850. file_drop_enabled: default_true(),
  851. center: false,
  852. x: None,
  853. y: None,
  854. width: default_width(),
  855. height: default_height(),
  856. min_width: None,
  857. min_height: None,
  858. max_width: None,
  859. max_height: None,
  860. resizable: default_true(),
  861. title: default_title(),
  862. fullscreen: false,
  863. focus: false,
  864. transparent: false,
  865. maximized: false,
  866. visible: default_true(),
  867. decorations: default_true(),
  868. always_on_top: false,
  869. skip_taskbar: false,
  870. theme: None,
  871. title_bar_style: Default::default(),
  872. hidden_title: false,
  873. accept_first_mouse: false,
  874. tabbing_identifier: None,
  875. shadow: false,
  876. }
  877. }
  878. }
  879. fn default_window_label() -> String {
  880. "main".to_string()
  881. }
  882. fn default_width() -> f64 {
  883. 800f64
  884. }
  885. fn default_height() -> f64 {
  886. 600f64
  887. }
  888. fn default_true() -> bool {
  889. true
  890. }
  891. fn default_title() -> String {
  892. "Tauri App".to_string()
  893. }
  894. /// A Content-Security-Policy directive source list.
  895. /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/Sources#sources>.
  896. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  897. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  898. #[serde(rename_all = "camelCase", untagged)]
  899. pub enum CspDirectiveSources {
  900. /// An inline list of CSP sources. Same as [`Self::List`], but concatenated with a space separator.
  901. Inline(String),
  902. /// A list of CSP sources. The collection will be concatenated with a space separator for the CSP string.
  903. List(Vec<String>),
  904. }
  905. impl Default for CspDirectiveSources {
  906. fn default() -> Self {
  907. Self::List(Vec::new())
  908. }
  909. }
  910. impl From<CspDirectiveSources> for Vec<String> {
  911. fn from(sources: CspDirectiveSources) -> Self {
  912. match sources {
  913. CspDirectiveSources::Inline(source) => source.split(' ').map(|s| s.to_string()).collect(),
  914. CspDirectiveSources::List(l) => l,
  915. }
  916. }
  917. }
  918. impl CspDirectiveSources {
  919. /// Whether the given source is configured on this directive or not.
  920. pub fn contains(&self, source: &str) -> bool {
  921. match self {
  922. Self::Inline(s) => s.contains(&format!("{source} ")) || s.contains(&format!(" {source}")),
  923. Self::List(l) => l.contains(&source.into()),
  924. }
  925. }
  926. /// Appends the given source to this directive.
  927. pub fn push<S: AsRef<str>>(&mut self, source: S) {
  928. match self {
  929. Self::Inline(s) => {
  930. s.push(' ');
  931. s.push_str(source.as_ref());
  932. }
  933. Self::List(l) => {
  934. l.push(source.as_ref().to_string());
  935. }
  936. }
  937. }
  938. /// Extends this CSP directive source list with the given array of sources.
  939. pub fn extend(&mut self, sources: Vec<String>) {
  940. for s in sources {
  941. self.push(s);
  942. }
  943. }
  944. }
  945. /// A Content-Security-Policy definition.
  946. /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP>.
  947. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  948. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  949. #[serde(rename_all = "camelCase", untagged)]
  950. pub enum Csp {
  951. /// The entire CSP policy in a single text string.
  952. Policy(String),
  953. /// An object mapping a directive with its sources values as a list of strings.
  954. DirectiveMap(HashMap<String, CspDirectiveSources>),
  955. }
  956. impl From<HashMap<String, CspDirectiveSources>> for Csp {
  957. fn from(map: HashMap<String, CspDirectiveSources>) -> Self {
  958. Self::DirectiveMap(map)
  959. }
  960. }
  961. impl From<Csp> for HashMap<String, CspDirectiveSources> {
  962. fn from(csp: Csp) -> Self {
  963. match csp {
  964. Csp::Policy(policy) => {
  965. let mut map = HashMap::new();
  966. for directive in policy.split(';') {
  967. let mut tokens = directive.trim().split(' ');
  968. if let Some(directive) = tokens.next() {
  969. let sources = tokens.map(|s| s.to_string()).collect::<Vec<String>>();
  970. map.insert(directive.to_string(), CspDirectiveSources::List(sources));
  971. }
  972. }
  973. map
  974. }
  975. Csp::DirectiveMap(m) => m,
  976. }
  977. }
  978. }
  979. impl Display for Csp {
  980. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  981. match self {
  982. Self::Policy(s) => write!(f, "{s}"),
  983. Self::DirectiveMap(m) => {
  984. let len = m.len();
  985. let mut i = 0;
  986. for (directive, sources) in m {
  987. let sources: Vec<String> = sources.clone().into();
  988. write!(f, "{} {}", directive, sources.join(" "))?;
  989. i += 1;
  990. if i != len {
  991. write!(f, "; ")?;
  992. }
  993. }
  994. Ok(())
  995. }
  996. }
  997. }
  998. }
  999. /// The possible values for the `dangerous_disable_asset_csp_modification` config option.
  1000. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1001. #[serde(untagged)]
  1002. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1003. pub enum DisabledCspModificationKind {
  1004. /// If `true`, disables all CSP modification.
  1005. /// `false` is the default value and it configures Tauri to control the CSP.
  1006. Flag(bool),
  1007. /// Disables the given list of CSP directives modifications.
  1008. List(Vec<String>),
  1009. }
  1010. impl DisabledCspModificationKind {
  1011. /// Determines whether the given CSP directive can be modified or not.
  1012. pub fn can_modify(&self, directive: &str) -> bool {
  1013. match self {
  1014. Self::Flag(f) => !f,
  1015. Self::List(l) => !l.contains(&directive.into()),
  1016. }
  1017. }
  1018. }
  1019. impl Default for DisabledCspModificationKind {
  1020. fn default() -> Self {
  1021. Self::Flag(false)
  1022. }
  1023. }
  1024. /// Security configuration.
  1025. #[skip_serializing_none]
  1026. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1027. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1028. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1029. pub struct SecurityConfig {
  1030. /// The Content Security Policy that will be injected on all HTML files on the built application.
  1031. /// If [`dev_csp`](#SecurityConfig.devCsp) is not specified, this value is also injected on dev.
  1032. ///
  1033. /// This is a really important part of the configuration since it helps you ensure your WebView is secured.
  1034. /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP>.
  1035. pub csp: Option<Csp>,
  1036. /// The Content Security Policy that will be injected on all HTML files on development.
  1037. ///
  1038. /// This is a really important part of the configuration since it helps you ensure your WebView is secured.
  1039. /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP>.
  1040. #[serde(alias = "dev-csp")]
  1041. pub dev_csp: Option<Csp>,
  1042. /// Freeze the `Object.prototype` when using the custom protocol.
  1043. #[serde(default, alias = "freeze-prototype")]
  1044. pub freeze_prototype: bool,
  1045. /// Disables the Tauri-injected CSP sources.
  1046. ///
  1047. /// At compile time, Tauri parses all the frontend assets and changes the Content-Security-Policy
  1048. /// to only allow loading of your own scripts and styles by injecting nonce and hash sources.
  1049. /// This stricts your CSP, which may introduce issues when using along with other flexing sources.
  1050. ///
  1051. /// This configuration option allows both a boolean and a list of strings as value.
  1052. /// A boolean instructs Tauri to disable the injection for all CSP injections,
  1053. /// and a list of strings indicates the CSP directives that Tauri cannot inject.
  1054. ///
  1055. /// **WARNING:** Only disable this if you know what you are doing and have properly configured the CSP.
  1056. /// Your application might be vulnerable to XSS attacks without this Tauri protection.
  1057. #[serde(default, alias = "dangerous-disable-asset-csp-modification")]
  1058. pub dangerous_disable_asset_csp_modification: DisabledCspModificationKind,
  1059. }
  1060. /// Defines an allowlist type.
  1061. pub trait Allowlist {
  1062. /// Returns all features associated with the allowlist struct.
  1063. fn all_features() -> Vec<&'static str>;
  1064. /// Returns the tauri features enabled on this allowlist.
  1065. fn to_features(&self) -> Vec<&'static str>;
  1066. }
  1067. macro_rules! check_feature {
  1068. ($self:ident, $features:ident, $flag:ident, $feature_name: expr) => {
  1069. if $self.$flag {
  1070. $features.push($feature_name)
  1071. }
  1072. };
  1073. }
  1074. /// Filesystem scope definition.
  1075. /// It is a list of glob patterns that restrict the API access from the webview.
  1076. ///
  1077. /// Each pattern can start with a variable that resolves to a system base directory.
  1078. /// The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`,
  1079. /// `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`,
  1080. /// `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$APP`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`,
  1081. /// `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.
  1082. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1083. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1084. #[serde(untagged)]
  1085. pub enum FsAllowlistScope {
  1086. /// A list of paths that are allowed by this scope.
  1087. AllowedPaths(Vec<PathBuf>),
  1088. /// A complete scope configuration.
  1089. Scope {
  1090. /// A list of paths that are allowed by this scope.
  1091. #[serde(default)]
  1092. allow: Vec<PathBuf>,
  1093. /// A list of paths that are not allowed by this scope.
  1094. /// This gets precedence over the [`Self::Scope::allow`] list.
  1095. #[serde(default)]
  1096. deny: Vec<PathBuf>,
  1097. },
  1098. }
  1099. impl Default for FsAllowlistScope {
  1100. fn default() -> Self {
  1101. Self::AllowedPaths(Vec::new())
  1102. }
  1103. }
  1104. impl FsAllowlistScope {
  1105. /// The list of allowed paths.
  1106. pub fn allowed_paths(&self) -> &Vec<PathBuf> {
  1107. match self {
  1108. Self::AllowedPaths(p) => p,
  1109. Self::Scope { allow, .. } => allow,
  1110. }
  1111. }
  1112. /// The list of forbidden paths.
  1113. pub fn forbidden_paths(&self) -> Option<&Vec<PathBuf>> {
  1114. match self {
  1115. Self::AllowedPaths(_) => None,
  1116. Self::Scope { deny, .. } => Some(deny),
  1117. }
  1118. }
  1119. }
  1120. /// Allowlist for the file system APIs.
  1121. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1122. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1123. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1124. pub struct FsAllowlistConfig {
  1125. /// The access scope for the filesystem APIs.
  1126. #[serde(default)]
  1127. pub scope: FsAllowlistScope,
  1128. /// Use this flag to enable all file system API features.
  1129. #[serde(default)]
  1130. pub all: bool,
  1131. /// Read file from local filesystem.
  1132. #[serde(default, alias = "read-file")]
  1133. pub read_file: bool,
  1134. /// Write file to local filesystem.
  1135. #[serde(default, alias = "write-file")]
  1136. pub write_file: bool,
  1137. /// Read directory from local filesystem.
  1138. #[serde(default, alias = "read-dir")]
  1139. pub read_dir: bool,
  1140. /// Copy file from local filesystem.
  1141. #[serde(default, alias = "copy-file")]
  1142. pub copy_file: bool,
  1143. /// Create directory from local filesystem.
  1144. #[serde(default, alias = "create-dir")]
  1145. pub create_dir: bool,
  1146. /// Remove directory from local filesystem.
  1147. #[serde(default, alias = "remove-dir")]
  1148. pub remove_dir: bool,
  1149. /// Remove file from local filesystem.
  1150. #[serde(default, alias = "remove-file")]
  1151. pub remove_file: bool,
  1152. /// Rename file from local filesystem.
  1153. #[serde(default, alias = "rename-file")]
  1154. pub rename_file: bool,
  1155. /// Check if path exists on the local filesystem.
  1156. #[serde(default)]
  1157. pub exists: bool,
  1158. }
  1159. impl Allowlist for FsAllowlistConfig {
  1160. fn all_features() -> Vec<&'static str> {
  1161. let allowlist = Self {
  1162. scope: Default::default(),
  1163. all: false,
  1164. read_file: true,
  1165. write_file: true,
  1166. read_dir: true,
  1167. copy_file: true,
  1168. create_dir: true,
  1169. remove_dir: true,
  1170. remove_file: true,
  1171. rename_file: true,
  1172. exists: true,
  1173. };
  1174. let mut features = allowlist.to_features();
  1175. features.push("fs-all");
  1176. features
  1177. }
  1178. fn to_features(&self) -> Vec<&'static str> {
  1179. if self.all {
  1180. vec!["fs-all"]
  1181. } else {
  1182. let mut features = Vec::new();
  1183. check_feature!(self, features, read_file, "fs-read-file");
  1184. check_feature!(self, features, write_file, "fs-write-file");
  1185. check_feature!(self, features, read_dir, "fs-read-dir");
  1186. check_feature!(self, features, copy_file, "fs-copy-file");
  1187. check_feature!(self, features, create_dir, "fs-create-dir");
  1188. check_feature!(self, features, remove_dir, "fs-remove-dir");
  1189. check_feature!(self, features, remove_file, "fs-remove-file");
  1190. check_feature!(self, features, rename_file, "fs-rename-file");
  1191. check_feature!(self, features, exists, "fs-exists");
  1192. features
  1193. }
  1194. }
  1195. }
  1196. /// Allowlist for the window APIs.
  1197. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1198. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1199. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1200. pub struct WindowAllowlistConfig {
  1201. /// Use this flag to enable all window API features.
  1202. #[serde(default)]
  1203. pub all: bool,
  1204. /// Allows dynamic window creation.
  1205. #[serde(default)]
  1206. pub create: bool,
  1207. /// Allows centering the window.
  1208. #[serde(default)]
  1209. pub center: bool,
  1210. /// Allows requesting user attention on the window.
  1211. #[serde(default, alias = "request-user-attention")]
  1212. pub request_user_attention: bool,
  1213. /// Allows setting the resizable flag of the window.
  1214. #[serde(default, alias = "set-resizable")]
  1215. pub set_resizable: bool,
  1216. /// Allows changing the window title.
  1217. #[serde(default, alias = "set-title")]
  1218. pub set_title: bool,
  1219. /// Allows maximizing the window.
  1220. #[serde(default)]
  1221. pub maximize: bool,
  1222. /// Allows unmaximizing the window.
  1223. #[serde(default)]
  1224. pub unmaximize: bool,
  1225. /// Allows minimizing the window.
  1226. #[serde(default)]
  1227. pub minimize: bool,
  1228. /// Allows unminimizing the window.
  1229. #[serde(default)]
  1230. pub unminimize: bool,
  1231. /// Allows showing the window.
  1232. #[serde(default)]
  1233. pub show: bool,
  1234. /// Allows hiding the window.
  1235. #[serde(default)]
  1236. pub hide: bool,
  1237. /// Allows closing the window.
  1238. #[serde(default)]
  1239. pub close: bool,
  1240. /// Allows setting the decorations flag of the window.
  1241. #[serde(default, alias = "set-decorations")]
  1242. pub set_decorations: bool,
  1243. /// Allows setting the shadow flag of the window.
  1244. #[serde(default, alias = "set-shadow")]
  1245. pub set_shadow: 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. set_shadow: true,
  1327. start_dragging: true,
  1328. print: true,
  1329. };
  1330. let mut features = allowlist.to_features();
  1331. features.push("window-all");
  1332. features
  1333. }
  1334. fn to_features(&self) -> Vec<&'static str> {
  1335. if self.all {
  1336. vec!["window-all"]
  1337. } else {
  1338. let mut features = Vec::new();
  1339. check_feature!(self, features, create, "window-create");
  1340. check_feature!(self, features, center, "window-center");
  1341. check_feature!(
  1342. self,
  1343. features,
  1344. request_user_attention,
  1345. "window-request-user-attention"
  1346. );
  1347. check_feature!(self, features, set_resizable, "window-set-resizable");
  1348. check_feature!(self, features, set_title, "window-set-title");
  1349. check_feature!(self, features, maximize, "window-maximize");
  1350. check_feature!(self, features, unmaximize, "window-unmaximize");
  1351. check_feature!(self, features, minimize, "window-minimize");
  1352. check_feature!(self, features, unminimize, "window-unminimize");
  1353. check_feature!(self, features, show, "window-show");
  1354. check_feature!(self, features, hide, "window-hide");
  1355. check_feature!(self, features, close, "window-close");
  1356. check_feature!(self, features, set_decorations, "window-set-decorations");
  1357. check_feature!(self, features, set_shadow, "window-set-shadow");
  1358. check_feature!(
  1359. self,
  1360. features,
  1361. set_always_on_top,
  1362. "window-set-always-on-top"
  1363. );
  1364. check_feature!(self, features, set_size, "window-set-size");
  1365. check_feature!(self, features, set_min_size, "window-set-min-size");
  1366. check_feature!(self, features, set_max_size, "window-set-max-size");
  1367. check_feature!(self, features, set_position, "window-set-position");
  1368. check_feature!(self, features, set_fullscreen, "window-set-fullscreen");
  1369. check_feature!(self, features, set_focus, "window-set-focus");
  1370. check_feature!(self, features, set_icon, "window-set-icon");
  1371. check_feature!(self, features, set_skip_taskbar, "window-set-skip-taskbar");
  1372. check_feature!(self, features, set_cursor_grab, "window-set-cursor-grab");
  1373. check_feature!(
  1374. self,
  1375. features,
  1376. set_cursor_visible,
  1377. "window-set-cursor-visible"
  1378. );
  1379. check_feature!(self, features, set_cursor_icon, "window-set-cursor-icon");
  1380. check_feature!(
  1381. self,
  1382. features,
  1383. set_cursor_position,
  1384. "window-set-cursor-position"
  1385. );
  1386. check_feature!(
  1387. self,
  1388. features,
  1389. set_ignore_cursor_events,
  1390. "window-set-ignore-cursor-events"
  1391. );
  1392. check_feature!(self, features, start_dragging, "window-start-dragging");
  1393. check_feature!(self, features, print, "window-print");
  1394. features
  1395. }
  1396. }
  1397. }
  1398. /// A command allowed to be executed by the webview API.
  1399. #[derive(Debug, PartialEq, Eq, Clone, Serialize)]
  1400. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1401. pub struct ShellAllowedCommand {
  1402. /// The name for this allowed shell command configuration.
  1403. ///
  1404. /// This name will be used inside of the webview API to call this command along with
  1405. /// any specified arguments.
  1406. pub name: String,
  1407. /// The command name.
  1408. /// It can start with a variable that resolves to a system base directory.
  1409. /// The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`,
  1410. /// `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`,
  1411. /// `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$APP`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`,
  1412. /// `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.
  1413. #[serde(rename = "cmd", default)] // use default just so the schema doesn't flag it as required
  1414. pub command: PathBuf,
  1415. /// The allowed arguments for the command execution.
  1416. #[serde(default)]
  1417. pub args: ShellAllowedArgs,
  1418. /// If this command is a sidecar command.
  1419. #[serde(default)]
  1420. pub sidecar: bool,
  1421. }
  1422. impl<'de> Deserialize<'de> for ShellAllowedCommand {
  1423. fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  1424. where
  1425. D: Deserializer<'de>,
  1426. {
  1427. #[derive(Deserialize)]
  1428. struct InnerShellAllowedCommand {
  1429. name: String,
  1430. #[serde(rename = "cmd")]
  1431. command: Option<PathBuf>,
  1432. #[serde(default)]
  1433. args: ShellAllowedArgs,
  1434. #[serde(default)]
  1435. sidecar: bool,
  1436. }
  1437. let config = InnerShellAllowedCommand::deserialize(deserializer)?;
  1438. if !config.sidecar && config.command.is_none() {
  1439. return Err(DeError::custom(
  1440. "The shell scope `command` value is required.",
  1441. ));
  1442. }
  1443. Ok(ShellAllowedCommand {
  1444. name: config.name,
  1445. command: config.command.unwrap_or_default(),
  1446. args: config.args,
  1447. sidecar: config.sidecar,
  1448. })
  1449. }
  1450. }
  1451. /// A set of command arguments allowed to be executed by the webview API.
  1452. ///
  1453. /// A value of `true` will allow any arguments to be passed to the command. `false` will disable all
  1454. /// arguments. A list of [`ShellAllowedArg`] will set those arguments as the only valid arguments to
  1455. /// be passed to the attached command configuration.
  1456. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1457. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1458. #[serde(untagged, deny_unknown_fields)]
  1459. #[non_exhaustive]
  1460. pub enum ShellAllowedArgs {
  1461. /// Use a simple boolean to allow all or disable all arguments to this command configuration.
  1462. Flag(bool),
  1463. /// A specific set of [`ShellAllowedArg`] that are valid to call for the command configuration.
  1464. List(Vec<ShellAllowedArg>),
  1465. }
  1466. impl Default for ShellAllowedArgs {
  1467. fn default() -> Self {
  1468. Self::Flag(false)
  1469. }
  1470. }
  1471. /// A command argument allowed to be executed by the webview API.
  1472. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1473. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1474. #[serde(untagged, deny_unknown_fields)]
  1475. #[non_exhaustive]
  1476. pub enum ShellAllowedArg {
  1477. /// A non-configurable argument that is passed to the command in the order it was specified.
  1478. Fixed(String),
  1479. /// A variable that is set while calling the command from the webview API.
  1480. ///
  1481. Var {
  1482. /// [regex] validator to require passed values to conform to an expected input.
  1483. ///
  1484. /// This will require the argument value passed to this variable to match the `validator` regex
  1485. /// before it will be executed.
  1486. ///
  1487. /// [regex]: https://docs.rs/regex/latest/regex/#syntax
  1488. validator: String,
  1489. },
  1490. }
  1491. /// Shell scope definition.
  1492. /// It is a list of command names and associated CLI arguments that restrict the API access from the webview.
  1493. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1494. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1495. pub struct ShellAllowlistScope(pub Vec<ShellAllowedCommand>);
  1496. /// Defines the `shell > open` api scope.
  1497. #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1498. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1499. #[serde(untagged, deny_unknown_fields)]
  1500. #[non_exhaustive]
  1501. pub enum ShellAllowlistOpen {
  1502. /// If the shell open API should be enabled.
  1503. ///
  1504. /// If enabled, the default validation regex (`^https?://`) is used.
  1505. Flag(bool),
  1506. /// Enable the shell open API, with a custom regex that the opened path must match against.
  1507. ///
  1508. /// If using a custom regex to support a non-http(s) schema, care should be used to prevent values
  1509. /// that allow flag-like strings to pass validation. e.g. `--enable-debugging`, `-i`, `/R`.
  1510. Validate(String),
  1511. }
  1512. impl Default for ShellAllowlistOpen {
  1513. fn default() -> Self {
  1514. Self::Flag(false)
  1515. }
  1516. }
  1517. /// Allowlist for the shell APIs.
  1518. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1519. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1520. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1521. pub struct ShellAllowlistConfig {
  1522. /// Access scope for the binary execution APIs.
  1523. /// Sidecars are automatically enabled.
  1524. #[serde(default)]
  1525. pub scope: ShellAllowlistScope,
  1526. /// Use this flag to enable all shell API features.
  1527. #[serde(default)]
  1528. pub all: bool,
  1529. /// Enable binary execution.
  1530. #[serde(default)]
  1531. pub execute: bool,
  1532. /// Enable sidecar execution, allowing the JavaScript layer to spawn a sidecar command,
  1533. /// an executable that is shipped with the application.
  1534. /// For more information see <https://tauri.app/v1/guides/building/sidecar>.
  1535. #[serde(default)]
  1536. pub sidecar: bool,
  1537. /// Open URL with the user's default application.
  1538. #[serde(default)]
  1539. pub open: ShellAllowlistOpen,
  1540. }
  1541. impl Allowlist for ShellAllowlistConfig {
  1542. fn all_features() -> Vec<&'static str> {
  1543. let allowlist = Self {
  1544. scope: Default::default(),
  1545. all: false,
  1546. execute: true,
  1547. sidecar: true,
  1548. open: ShellAllowlistOpen::Flag(true),
  1549. };
  1550. let mut features = allowlist.to_features();
  1551. features.push("shell-all");
  1552. features
  1553. }
  1554. fn to_features(&self) -> Vec<&'static str> {
  1555. if self.all {
  1556. vec!["shell-all"]
  1557. } else {
  1558. let mut features = Vec::new();
  1559. check_feature!(self, features, execute, "shell-execute");
  1560. check_feature!(self, features, sidecar, "shell-sidecar");
  1561. if !matches!(self.open, ShellAllowlistOpen::Flag(false)) {
  1562. features.push("shell-open")
  1563. }
  1564. features
  1565. }
  1566. }
  1567. }
  1568. /// Allowlist for the dialog APIs.
  1569. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1570. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1571. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1572. pub struct DialogAllowlistConfig {
  1573. /// Use this flag to enable all dialog API features.
  1574. #[serde(default)]
  1575. pub all: bool,
  1576. /// Allows the API to open a dialog window to pick files.
  1577. #[serde(default)]
  1578. pub open: bool,
  1579. /// Allows the API to open a dialog window to pick where to save files.
  1580. #[serde(default)]
  1581. pub save: bool,
  1582. /// Allows the API to show a message dialog window.
  1583. #[serde(default)]
  1584. pub message: bool,
  1585. /// Allows the API to show a dialog window with Yes/No buttons.
  1586. #[serde(default)]
  1587. pub ask: bool,
  1588. /// Allows the API to show a dialog window with Ok/Cancel buttons.
  1589. #[serde(default)]
  1590. pub confirm: bool,
  1591. }
  1592. impl Allowlist for DialogAllowlistConfig {
  1593. fn all_features() -> Vec<&'static str> {
  1594. let allowlist = Self {
  1595. all: false,
  1596. open: true,
  1597. save: true,
  1598. message: true,
  1599. ask: true,
  1600. confirm: true,
  1601. };
  1602. let mut features = allowlist.to_features();
  1603. features.push("dialog-all");
  1604. features
  1605. }
  1606. fn to_features(&self) -> Vec<&'static str> {
  1607. if self.all {
  1608. vec!["dialog-all"]
  1609. } else {
  1610. let mut features = Vec::new();
  1611. check_feature!(self, features, open, "dialog-open");
  1612. check_feature!(self, features, save, "dialog-save");
  1613. check_feature!(self, features, message, "dialog-message");
  1614. check_feature!(self, features, ask, "dialog-ask");
  1615. check_feature!(self, features, confirm, "dialog-confirm");
  1616. features
  1617. }
  1618. }
  1619. }
  1620. /// HTTP API scope definition.
  1621. /// It is a list of URLs that can be accessed by the webview when using the HTTP APIs.
  1622. /// The scoped URL is matched against the request URL using a glob pattern.
  1623. ///
  1624. /// Examples:
  1625. /// - "https://**": allows all HTTPS urls
  1626. /// - "https://*.github.com/tauri-apps/tauri": allows any subdomain of "github.com" with the "tauri-apps/api" path
  1627. /// - "https://myapi.service.com/users/*": allows access to any URLs that begins with "https://myapi.service.com/users/"
  1628. #[allow(rustdoc::bare_urls)]
  1629. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1630. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1631. pub struct HttpAllowlistScope(pub Vec<Url>);
  1632. /// Allowlist for the HTTP APIs.
  1633. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1634. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1635. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1636. pub struct HttpAllowlistConfig {
  1637. /// The access scope for the HTTP APIs.
  1638. #[serde(default)]
  1639. pub scope: HttpAllowlistScope,
  1640. /// Use this flag to enable all HTTP API features.
  1641. #[serde(default)]
  1642. pub all: bool,
  1643. /// Allows making HTTP requests.
  1644. #[serde(default)]
  1645. pub request: bool,
  1646. }
  1647. impl Allowlist for HttpAllowlistConfig {
  1648. fn all_features() -> Vec<&'static str> {
  1649. let allowlist = Self {
  1650. scope: Default::default(),
  1651. all: false,
  1652. request: true,
  1653. };
  1654. let mut features = allowlist.to_features();
  1655. features.push("http-all");
  1656. features
  1657. }
  1658. fn to_features(&self) -> Vec<&'static str> {
  1659. if self.all {
  1660. vec!["http-all"]
  1661. } else {
  1662. let mut features = Vec::new();
  1663. check_feature!(self, features, request, "http-request");
  1664. features
  1665. }
  1666. }
  1667. }
  1668. /// Allowlist for the notification APIs.
  1669. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1670. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1671. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1672. pub struct NotificationAllowlistConfig {
  1673. /// Use this flag to enable all notification API features.
  1674. #[serde(default)]
  1675. pub all: bool,
  1676. }
  1677. impl Allowlist for NotificationAllowlistConfig {
  1678. fn all_features() -> Vec<&'static str> {
  1679. let allowlist = Self { all: false };
  1680. let mut features = allowlist.to_features();
  1681. features.push("notification-all");
  1682. features
  1683. }
  1684. fn to_features(&self) -> Vec<&'static str> {
  1685. if self.all {
  1686. vec!["notification-all"]
  1687. } else {
  1688. vec![]
  1689. }
  1690. }
  1691. }
  1692. /// Allowlist for the global shortcut APIs.
  1693. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1694. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1695. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1696. pub struct GlobalShortcutAllowlistConfig {
  1697. /// Use this flag to enable all global shortcut API features.
  1698. #[serde(default)]
  1699. pub all: bool,
  1700. }
  1701. impl Allowlist for GlobalShortcutAllowlistConfig {
  1702. fn all_features() -> Vec<&'static str> {
  1703. let allowlist = Self { all: false };
  1704. let mut features = allowlist.to_features();
  1705. features.push("global-shortcut-all");
  1706. features
  1707. }
  1708. fn to_features(&self) -> Vec<&'static str> {
  1709. if self.all {
  1710. vec!["global-shortcut-all"]
  1711. } else {
  1712. vec![]
  1713. }
  1714. }
  1715. }
  1716. /// Allowlist for the OS APIs.
  1717. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1718. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1719. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1720. pub struct OsAllowlistConfig {
  1721. /// Use this flag to enable all OS API features.
  1722. #[serde(default)]
  1723. pub all: bool,
  1724. }
  1725. impl Allowlist for OsAllowlistConfig {
  1726. fn all_features() -> Vec<&'static str> {
  1727. let allowlist = Self { all: false };
  1728. let mut features = allowlist.to_features();
  1729. features.push("os-all");
  1730. features
  1731. }
  1732. fn to_features(&self) -> Vec<&'static str> {
  1733. if self.all {
  1734. vec!["os-all"]
  1735. } else {
  1736. vec![]
  1737. }
  1738. }
  1739. }
  1740. /// Allowlist for the path APIs.
  1741. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1742. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1743. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1744. pub struct PathAllowlistConfig {
  1745. /// Use this flag to enable all path API features.
  1746. #[serde(default)]
  1747. pub all: bool,
  1748. }
  1749. impl Allowlist for PathAllowlistConfig {
  1750. fn all_features() -> Vec<&'static str> {
  1751. let allowlist = Self { all: false };
  1752. let mut features = allowlist.to_features();
  1753. features.push("path-all");
  1754. features
  1755. }
  1756. fn to_features(&self) -> Vec<&'static str> {
  1757. if self.all {
  1758. vec!["path-all"]
  1759. } else {
  1760. vec![]
  1761. }
  1762. }
  1763. }
  1764. /// Allowlist for the custom protocols.
  1765. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1766. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1767. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1768. pub struct ProtocolAllowlistConfig {
  1769. /// The access scope for the asset protocol.
  1770. #[serde(default, alias = "asset-scope")]
  1771. pub asset_scope: FsAllowlistScope,
  1772. /// Use this flag to enable all custom protocols.
  1773. #[serde(default)]
  1774. pub all: bool,
  1775. /// Enables the asset protocol.
  1776. #[serde(default)]
  1777. pub asset: bool,
  1778. }
  1779. impl Allowlist for ProtocolAllowlistConfig {
  1780. fn all_features() -> Vec<&'static str> {
  1781. let allowlist = Self {
  1782. asset_scope: Default::default(),
  1783. all: false,
  1784. asset: true,
  1785. };
  1786. let mut features = allowlist.to_features();
  1787. features.push("protocol-all");
  1788. features
  1789. }
  1790. fn to_features(&self) -> Vec<&'static str> {
  1791. if self.all {
  1792. vec!["protocol-all"]
  1793. } else {
  1794. let mut features = Vec::new();
  1795. check_feature!(self, features, asset, "protocol-asset");
  1796. features
  1797. }
  1798. }
  1799. }
  1800. /// Allowlist for the process APIs.
  1801. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1802. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1803. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1804. pub struct ProcessAllowlistConfig {
  1805. /// Use this flag to enable all process APIs.
  1806. #[serde(default)]
  1807. pub all: bool,
  1808. /// Enables the relaunch API.
  1809. #[serde(default)]
  1810. pub relaunch: bool,
  1811. /// Dangerous option that allows macOS to relaunch even if the binary contains a symlink.
  1812. ///
  1813. /// This is due to macOS having less symlink protection. Highly recommended to not set this flag
  1814. /// unless you have a very specific reason too, and understand the implications of it.
  1815. #[serde(
  1816. default,
  1817. alias = "relaunchDangerousAllowSymlinkMacOS",
  1818. alias = "relaunch-dangerous-allow-symlink-macos"
  1819. )]
  1820. pub relaunch_dangerous_allow_symlink_macos: bool,
  1821. /// Enables the exit API.
  1822. #[serde(default)]
  1823. pub exit: bool,
  1824. }
  1825. impl Allowlist for ProcessAllowlistConfig {
  1826. fn all_features() -> Vec<&'static str> {
  1827. let allowlist = Self {
  1828. all: false,
  1829. relaunch: true,
  1830. relaunch_dangerous_allow_symlink_macos: false,
  1831. exit: true,
  1832. };
  1833. let mut features = allowlist.to_features();
  1834. features.push("process-all");
  1835. features
  1836. }
  1837. fn to_features(&self) -> Vec<&'static str> {
  1838. if self.all {
  1839. vec!["process-all"]
  1840. } else {
  1841. let mut features = Vec::new();
  1842. check_feature!(self, features, relaunch, "process-relaunch");
  1843. check_feature!(
  1844. self,
  1845. features,
  1846. relaunch_dangerous_allow_symlink_macos,
  1847. "process-relaunch-dangerous-allow-symlink-macos"
  1848. );
  1849. check_feature!(self, features, exit, "process-exit");
  1850. features
  1851. }
  1852. }
  1853. }
  1854. /// Allowlist for the clipboard APIs.
  1855. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1856. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1857. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1858. pub struct ClipboardAllowlistConfig {
  1859. /// Use this flag to enable all clipboard APIs.
  1860. #[serde(default)]
  1861. pub all: bool,
  1862. /// Enables the clipboard's `writeText` API.
  1863. #[serde(default, alias = "writeText")]
  1864. pub write_text: bool,
  1865. /// Enables the clipboard's `readText` API.
  1866. #[serde(default, alias = "readText")]
  1867. pub read_text: bool,
  1868. }
  1869. impl Allowlist for ClipboardAllowlistConfig {
  1870. fn all_features() -> Vec<&'static str> {
  1871. let allowlist = Self {
  1872. all: false,
  1873. write_text: true,
  1874. read_text: true,
  1875. };
  1876. let mut features = allowlist.to_features();
  1877. features.push("clipboard-all");
  1878. features
  1879. }
  1880. fn to_features(&self) -> Vec<&'static str> {
  1881. if self.all {
  1882. vec!["clipboard-all"]
  1883. } else {
  1884. let mut features = Vec::new();
  1885. check_feature!(self, features, write_text, "clipboard-write-text");
  1886. check_feature!(self, features, read_text, "clipboard-read-text");
  1887. features
  1888. }
  1889. }
  1890. }
  1891. /// Allowlist for the app APIs.
  1892. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1893. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1894. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1895. pub struct AppAllowlistConfig {
  1896. /// Use this flag to enable all app APIs.
  1897. #[serde(default)]
  1898. pub all: bool,
  1899. /// Enables the app's `show` API.
  1900. #[serde(default)]
  1901. pub show: bool,
  1902. /// Enables the app's `hide` API.
  1903. #[serde(default)]
  1904. pub hide: bool,
  1905. }
  1906. impl Allowlist for AppAllowlistConfig {
  1907. fn all_features() -> Vec<&'static str> {
  1908. let allowlist = Self {
  1909. all: false,
  1910. show: true,
  1911. hide: true,
  1912. };
  1913. let mut features = allowlist.to_features();
  1914. features.push("app-all");
  1915. features
  1916. }
  1917. fn to_features(&self) -> Vec<&'static str> {
  1918. if self.all {
  1919. vec!["app-all"]
  1920. } else {
  1921. let mut features = Vec::new();
  1922. check_feature!(self, features, show, "app-show");
  1923. check_feature!(self, features, hide, "app-hide");
  1924. features
  1925. }
  1926. }
  1927. }
  1928. /// Allowlist configuration.
  1929. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  1930. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1931. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1932. pub struct AllowlistConfig {
  1933. /// Use this flag to enable all API features.
  1934. #[serde(default)]
  1935. pub all: bool,
  1936. /// File system API allowlist.
  1937. #[serde(default)]
  1938. pub fs: FsAllowlistConfig,
  1939. /// Window API allowlist.
  1940. #[serde(default)]
  1941. pub window: WindowAllowlistConfig,
  1942. /// Shell API allowlist.
  1943. #[serde(default)]
  1944. pub shell: ShellAllowlistConfig,
  1945. /// Dialog API allowlist.
  1946. #[serde(default)]
  1947. pub dialog: DialogAllowlistConfig,
  1948. /// HTTP API allowlist.
  1949. #[serde(default)]
  1950. pub http: HttpAllowlistConfig,
  1951. /// Notification API allowlist.
  1952. #[serde(default)]
  1953. pub notification: NotificationAllowlistConfig,
  1954. /// Global shortcut API allowlist.
  1955. #[serde(default, alias = "global-shortcut")]
  1956. pub global_shortcut: GlobalShortcutAllowlistConfig,
  1957. /// OS allowlist.
  1958. #[serde(default)]
  1959. pub os: OsAllowlistConfig,
  1960. /// Path API allowlist.
  1961. #[serde(default)]
  1962. pub path: PathAllowlistConfig,
  1963. /// Custom protocol allowlist.
  1964. #[serde(default)]
  1965. pub protocol: ProtocolAllowlistConfig,
  1966. /// Process API allowlist.
  1967. #[serde(default)]
  1968. pub process: ProcessAllowlistConfig,
  1969. /// Clipboard APIs allowlist.
  1970. #[serde(default)]
  1971. pub clipboard: ClipboardAllowlistConfig,
  1972. /// App APIs allowlist.
  1973. #[serde(default)]
  1974. pub app: AppAllowlistConfig,
  1975. }
  1976. impl Allowlist for AllowlistConfig {
  1977. fn all_features() -> Vec<&'static str> {
  1978. let mut features = vec!["api-all"];
  1979. features.extend(FsAllowlistConfig::all_features());
  1980. features.extend(WindowAllowlistConfig::all_features());
  1981. features.extend(ShellAllowlistConfig::all_features());
  1982. features.extend(DialogAllowlistConfig::all_features());
  1983. features.extend(HttpAllowlistConfig::all_features());
  1984. features.extend(NotificationAllowlistConfig::all_features());
  1985. features.extend(GlobalShortcutAllowlistConfig::all_features());
  1986. features.extend(OsAllowlistConfig::all_features());
  1987. features.extend(PathAllowlistConfig::all_features());
  1988. features.extend(ProtocolAllowlistConfig::all_features());
  1989. features.extend(ProcessAllowlistConfig::all_features());
  1990. features.extend(ClipboardAllowlistConfig::all_features());
  1991. features.extend(AppAllowlistConfig::all_features());
  1992. features
  1993. }
  1994. fn to_features(&self) -> Vec<&'static str> {
  1995. if self.all {
  1996. vec!["api-all"]
  1997. } else {
  1998. let mut features = Vec::new();
  1999. features.extend(self.fs.to_features());
  2000. features.extend(self.window.to_features());
  2001. features.extend(self.shell.to_features());
  2002. features.extend(self.dialog.to_features());
  2003. features.extend(self.http.to_features());
  2004. features.extend(self.notification.to_features());
  2005. features.extend(self.global_shortcut.to_features());
  2006. features.extend(self.os.to_features());
  2007. features.extend(self.path.to_features());
  2008. features.extend(self.protocol.to_features());
  2009. features.extend(self.process.to_features());
  2010. features.extend(self.clipboard.to_features());
  2011. features.extend(self.app.to_features());
  2012. features
  2013. }
  2014. }
  2015. }
  2016. /// The application pattern.
  2017. #[skip_serializing_none]
  2018. #[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
  2019. #[serde(rename_all = "lowercase", tag = "use", content = "options")]
  2020. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  2021. pub enum PatternKind {
  2022. /// Brownfield pattern.
  2023. Brownfield,
  2024. /// Isolation pattern. Recommended for security purposes.
  2025. Isolation {
  2026. /// The dir containing the index.html file that contains the secure isolation application.
  2027. dir: PathBuf,
  2028. },
  2029. }
  2030. impl Default for PatternKind {
  2031. fn default() -> Self {
  2032. Self::Brownfield
  2033. }
  2034. }
  2035. /// The Tauri configuration object.
  2036. #[skip_serializing_none]
  2037. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  2038. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  2039. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  2040. pub struct TauriConfig {
  2041. /// The pattern to use.
  2042. #[serde(default)]
  2043. pub pattern: PatternKind,
  2044. /// The windows configuration.
  2045. #[serde(default)]
  2046. pub windows: Vec<WindowConfig>,
  2047. /// The CLI configuration.
  2048. pub cli: Option<CliConfig>,
  2049. /// The bundler configuration.
  2050. #[serde(default)]
  2051. pub bundle: BundleConfig,
  2052. /// The allowlist configuration.
  2053. #[serde(default)]
  2054. pub allowlist: AllowlistConfig,
  2055. /// Security configuration.
  2056. #[serde(default)]
  2057. pub security: SecurityConfig,
  2058. /// The updater configuration.
  2059. #[serde(default)]
  2060. pub updater: UpdaterConfig,
  2061. /// Configuration for app system tray.
  2062. #[serde(alias = "system-tray")]
  2063. pub system_tray: Option<SystemTrayConfig>,
  2064. /// MacOS private API configuration. Enables the transparent background API and sets the `fullScreenEnabled` preference to `true`.
  2065. #[serde(rename = "macOSPrivateApi", alias = "macos-private-api", default)]
  2066. pub macos_private_api: bool,
  2067. }
  2068. impl TauriConfig {
  2069. /// Returns all Cargo features.
  2070. #[allow(dead_code)]
  2071. pub fn all_features() -> Vec<&'static str> {
  2072. let mut features = AllowlistConfig::all_features();
  2073. features.extend(vec![
  2074. "cli",
  2075. "updater",
  2076. "system-tray",
  2077. "macos-private-api",
  2078. "isolation",
  2079. ]);
  2080. features
  2081. }
  2082. /// Returns the enabled Cargo features.
  2083. #[allow(dead_code)]
  2084. pub fn features(&self) -> Vec<&str> {
  2085. let mut features = self.allowlist.to_features();
  2086. if self.cli.is_some() {
  2087. features.push("cli");
  2088. }
  2089. if self.updater.active {
  2090. features.push("updater");
  2091. }
  2092. if self.system_tray.is_some() {
  2093. features.push("system-tray");
  2094. }
  2095. if self.macos_private_api {
  2096. features.push("macos-private-api");
  2097. }
  2098. if let PatternKind::Isolation { .. } = self.pattern {
  2099. features.push("isolation");
  2100. }
  2101. features.sort_unstable();
  2102. features
  2103. }
  2104. }
  2105. /// A URL to an updater server.
  2106. ///
  2107. /// The URL must use the `https` scheme on production.
  2108. #[skip_serializing_none]
  2109. #[derive(Debug, PartialEq, Eq, Clone, Serialize)]
  2110. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  2111. pub struct UpdaterEndpoint(pub Url);
  2112. impl std::fmt::Display for UpdaterEndpoint {
  2113. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  2114. write!(f, "{}", self.0)
  2115. }
  2116. }
  2117. impl<'de> Deserialize<'de> for UpdaterEndpoint {
  2118. fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  2119. where
  2120. D: Deserializer<'de>,
  2121. {
  2122. let url = Url::deserialize(deserializer)?;
  2123. #[cfg(all(not(debug_assertions), not(feature = "schema")))]
  2124. {
  2125. if url.scheme() != "https" {
  2126. return Err(serde::de::Error::custom(
  2127. "The configured updater endpoint must use the `https` protocol.",
  2128. ));
  2129. }
  2130. }
  2131. Ok(Self(url))
  2132. }
  2133. }
  2134. /// Install modes for the Windows update.
  2135. #[derive(Debug, PartialEq, Eq, Clone)]
  2136. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  2137. #[cfg_attr(feature = "schema", schemars(rename_all = "camelCase"))]
  2138. pub enum WindowsUpdateInstallMode {
  2139. /// Specifies there's a basic UI during the installation process, including a final dialog box at the end.
  2140. BasicUi,
  2141. /// The quiet mode means there's no user interaction required.
  2142. /// Requires admin privileges if the installer does.
  2143. Quiet,
  2144. /// Specifies unattended mode, which means the installation only shows a progress bar.
  2145. Passive,
  2146. // to add more modes, we need to check if the updater relaunch makes sense
  2147. // i.e. for a full UI mode, the user can also mark the installer to start the app
  2148. }
  2149. impl WindowsUpdateInstallMode {
  2150. /// Returns the associated `msiexec.exe` arguments.
  2151. pub fn msiexec_args(&self) -> &'static [&'static str] {
  2152. match self {
  2153. Self::BasicUi => &["/qb+"],
  2154. Self::Quiet => &["/quiet"],
  2155. Self::Passive => &["/passive"],
  2156. }
  2157. }
  2158. }
  2159. impl Display for WindowsUpdateInstallMode {
  2160. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  2161. write!(
  2162. f,
  2163. "{}",
  2164. match self {
  2165. Self::BasicUi => "basicUI",
  2166. Self::Quiet => "quiet",
  2167. Self::Passive => "passive",
  2168. }
  2169. )
  2170. }
  2171. }
  2172. impl Default for WindowsUpdateInstallMode {
  2173. fn default() -> Self {
  2174. Self::Passive
  2175. }
  2176. }
  2177. impl Serialize for WindowsUpdateInstallMode {
  2178. fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
  2179. where
  2180. S: Serializer,
  2181. {
  2182. serializer.serialize_str(self.to_string().as_ref())
  2183. }
  2184. }
  2185. impl<'de> Deserialize<'de> for WindowsUpdateInstallMode {
  2186. fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
  2187. where
  2188. D: Deserializer<'de>,
  2189. {
  2190. let s = String::deserialize(deserializer)?;
  2191. match s.to_lowercase().as_str() {
  2192. "basicui" => Ok(Self::BasicUi),
  2193. "quiet" => Ok(Self::Quiet),
  2194. "passive" => Ok(Self::Passive),
  2195. _ => Err(DeError::custom(format!(
  2196. "unknown update install mode '{s}'"
  2197. ))),
  2198. }
  2199. }
  2200. }
  2201. /// The updater configuration for Windows.
  2202. #[skip_serializing_none]
  2203. #[derive(Debug, Default, PartialEq, Eq, Clone, Serialize, Deserialize)]
  2204. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  2205. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  2206. pub struct UpdaterWindowsConfig {
  2207. /// The installation mode for the update on Windows. Defaults to `passive`.
  2208. #[serde(default, alias = "install-mode")]
  2209. pub install_mode: WindowsUpdateInstallMode,
  2210. }
  2211. /// The Updater configuration object.
  2212. #[skip_serializing_none]
  2213. #[derive(Debug, PartialEq, Eq, Clone, Serialize)]
  2214. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  2215. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  2216. pub struct UpdaterConfig {
  2217. /// Whether the updater is active or not.
  2218. #[serde(default)]
  2219. pub active: bool,
  2220. /// Display built-in dialog or use event system if disabled.
  2221. #[serde(default = "default_true")]
  2222. pub dialog: bool,
  2223. /// The updater endpoints. TLS is enforced on production.
  2224. ///
  2225. /// The updater URL can contain the following variables:
  2226. /// - {{current_version}}: The version of the app that is requesting the update
  2227. /// - {{target}}: The operating system name (one of `linux`, `windows` or `darwin`).
  2228. /// - {{arch}}: The architecture of the machine (one of `x86_64`, `i686`, `aarch64` or `armv7`).
  2229. ///
  2230. /// # Examples
  2231. /// - "https://my.cdn.com/latest.json": a raw JSON endpoint that returns the latest version and download links for each platform.
  2232. /// - "https://updates.app.dev/{{target}}?version={{current_version}}&arch={{arch}}": a dedicated API with positional and query string arguments.
  2233. #[allow(rustdoc::bare_urls)]
  2234. pub endpoints: Option<Vec<UpdaterEndpoint>>,
  2235. /// Signature public key.
  2236. #[serde(default)] // use default just so the schema doesn't flag it as required
  2237. pub pubkey: String,
  2238. /// The Windows configuration for the updater.
  2239. #[serde(default)]
  2240. pub windows: UpdaterWindowsConfig,
  2241. }
  2242. impl<'de> Deserialize<'de> for UpdaterConfig {
  2243. fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  2244. where
  2245. D: Deserializer<'de>,
  2246. {
  2247. #[derive(Deserialize)]
  2248. struct InnerUpdaterConfig {
  2249. #[serde(default)]
  2250. active: bool,
  2251. #[serde(default = "default_true")]
  2252. dialog: bool,
  2253. endpoints: Option<Vec<UpdaterEndpoint>>,
  2254. pubkey: Option<String>,
  2255. #[serde(default)]
  2256. windows: UpdaterWindowsConfig,
  2257. }
  2258. let config = InnerUpdaterConfig::deserialize(deserializer)?;
  2259. if config.active && config.pubkey.is_none() {
  2260. return Err(DeError::custom(
  2261. "The updater `pubkey` configuration is required.",
  2262. ));
  2263. }
  2264. Ok(UpdaterConfig {
  2265. active: config.active,
  2266. dialog: config.dialog,
  2267. endpoints: config.endpoints,
  2268. pubkey: config.pubkey.unwrap_or_default(),
  2269. windows: config.windows,
  2270. })
  2271. }
  2272. }
  2273. impl Default for UpdaterConfig {
  2274. fn default() -> Self {
  2275. Self {
  2276. active: false,
  2277. dialog: default_true(),
  2278. endpoints: None,
  2279. pubkey: "".into(),
  2280. windows: Default::default(),
  2281. }
  2282. }
  2283. }
  2284. /// Configuration for application system tray icon.
  2285. #[skip_serializing_none]
  2286. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  2287. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  2288. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  2289. pub struct SystemTrayConfig {
  2290. /// Path to the default icon to use on the system tray.
  2291. #[serde(alias = "icon-path")]
  2292. pub icon_path: PathBuf,
  2293. /// 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.
  2294. #[serde(default, alias = "icon-as-template")]
  2295. pub icon_as_template: bool,
  2296. /// A Boolean value that determines whether the menu should appear when the tray icon receives a left click on macOS.
  2297. #[serde(default = "default_true", alias = "menu-on-left-click")]
  2298. pub menu_on_left_click: bool,
  2299. /// Title for MacOS tray
  2300. pub title: Option<String>,
  2301. }
  2302. /// General configuration for the iOS target.
  2303. #[skip_serializing_none]
  2304. #[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
  2305. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  2306. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  2307. pub struct IosConfig {
  2308. /// The development team. This value is required for iOS development because code signing is enforced.
  2309. /// The `TAURI_APPLE_DEVELOPMENT_TEAM` environment variable can be set to overwrite it.
  2310. #[serde(alias = "development-team")]
  2311. pub development_team: Option<String>,
  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`, `tauri.macos.conf.json`, `tauri.android.conf.json` and `tauri.ios.conf.json`
  2545. /// (or `Tauri.linux.toml`, `Tauri.windows.toml`, `Tauri.macos.toml`, `Tauri.android.toml` and `Tauri.ios.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. let shadow = self.shadow;
  2840. literal_struct!(
  2841. tokens,
  2842. WindowConfig,
  2843. label,
  2844. url,
  2845. user_agent,
  2846. file_drop_enabled,
  2847. center,
  2848. x,
  2849. y,
  2850. width,
  2851. height,
  2852. min_width,
  2853. min_height,
  2854. max_width,
  2855. max_height,
  2856. resizable,
  2857. title,
  2858. fullscreen,
  2859. focus,
  2860. transparent,
  2861. maximized,
  2862. visible,
  2863. decorations,
  2864. always_on_top,
  2865. skip_taskbar,
  2866. theme,
  2867. title_bar_style,
  2868. hidden_title,
  2869. accept_first_mouse,
  2870. tabbing_identifier,
  2871. shadow
  2872. );
  2873. }
  2874. }
  2875. impl ToTokens for CliArg {
  2876. fn to_tokens(&self, tokens: &mut TokenStream) {
  2877. let short = opt_lit(self.short.as_ref());
  2878. let name = str_lit(&self.name);
  2879. let description = opt_str_lit(self.description.as_ref());
  2880. let long_description = opt_str_lit(self.long_description.as_ref());
  2881. let takes_value = self.takes_value;
  2882. let multiple = self.multiple;
  2883. let multiple_occurrences = self.multiple_occurrences;
  2884. let number_of_values = opt_lit(self.number_of_values.as_ref());
  2885. let possible_values = opt_vec_str_lit(self.possible_values.as_ref());
  2886. let min_values = opt_lit(self.min_values.as_ref());
  2887. let max_values = opt_lit(self.max_values.as_ref());
  2888. let required = self.required;
  2889. let required_unless_present = opt_str_lit(self.required_unless_present.as_ref());
  2890. let required_unless_present_all = opt_vec_str_lit(self.required_unless_present_all.as_ref());
  2891. let required_unless_present_any = opt_vec_str_lit(self.required_unless_present_any.as_ref());
  2892. let conflicts_with = opt_str_lit(self.conflicts_with.as_ref());
  2893. let conflicts_with_all = opt_vec_str_lit(self.conflicts_with_all.as_ref());
  2894. let requires = opt_str_lit(self.requires.as_ref());
  2895. let requires_all = opt_vec_str_lit(self.requires_all.as_ref());
  2896. let requires_if = opt_vec_str_lit(self.requires_if.as_ref());
  2897. let required_if_eq = opt_vec_str_lit(self.required_if_eq.as_ref());
  2898. let require_equals = opt_lit(self.require_equals.as_ref());
  2899. let index = opt_lit(self.index.as_ref());
  2900. literal_struct!(
  2901. tokens,
  2902. CliArg,
  2903. short,
  2904. name,
  2905. description,
  2906. long_description,
  2907. takes_value,
  2908. multiple,
  2909. multiple_occurrences,
  2910. number_of_values,
  2911. possible_values,
  2912. min_values,
  2913. max_values,
  2914. required,
  2915. required_unless_present,
  2916. required_unless_present_all,
  2917. required_unless_present_any,
  2918. conflicts_with,
  2919. conflicts_with_all,
  2920. requires,
  2921. requires_all,
  2922. requires_if,
  2923. required_if_eq,
  2924. require_equals,
  2925. index
  2926. );
  2927. }
  2928. }
  2929. impl ToTokens for CliConfig {
  2930. fn to_tokens(&self, tokens: &mut TokenStream) {
  2931. let description = opt_str_lit(self.description.as_ref());
  2932. let long_description = opt_str_lit(self.long_description.as_ref());
  2933. let before_help = opt_str_lit(self.before_help.as_ref());
  2934. let after_help = opt_str_lit(self.after_help.as_ref());
  2935. let args = {
  2936. let args = self.args.as_ref().map(|args| {
  2937. let arg = args.iter().map(|a| quote! { #a });
  2938. quote! { vec![#(#arg),*] }
  2939. });
  2940. opt_lit(args.as_ref())
  2941. };
  2942. let subcommands = opt_lit(
  2943. self
  2944. .subcommands
  2945. .as_ref()
  2946. .map(|map| {
  2947. map_lit(
  2948. quote! { ::std::collections::HashMap },
  2949. map,
  2950. str_lit,
  2951. identity,
  2952. )
  2953. })
  2954. .as_ref(),
  2955. );
  2956. literal_struct!(
  2957. tokens,
  2958. CliConfig,
  2959. description,
  2960. long_description,
  2961. before_help,
  2962. after_help,
  2963. args,
  2964. subcommands
  2965. );
  2966. }
  2967. }
  2968. impl ToTokens for PatternKind {
  2969. fn to_tokens(&self, tokens: &mut TokenStream) {
  2970. let prefix = quote! { ::tauri::utils::config::PatternKind };
  2971. tokens.append_all(match self {
  2972. Self::Brownfield => quote! { #prefix::Brownfield },
  2973. #[cfg(not(feature = "isolation"))]
  2974. Self::Isolation { dir: _ } => quote! { #prefix::Brownfield },
  2975. #[cfg(feature = "isolation")]
  2976. Self::Isolation { dir } => {
  2977. let dir = path_buf_lit(dir);
  2978. quote! { #prefix::Isolation { dir: #dir } }
  2979. }
  2980. })
  2981. }
  2982. }
  2983. impl ToTokens for WebviewInstallMode {
  2984. fn to_tokens(&self, tokens: &mut TokenStream) {
  2985. let prefix = quote! { ::tauri::utils::config::WebviewInstallMode };
  2986. tokens.append_all(match self {
  2987. Self::Skip => quote! { #prefix::Skip },
  2988. Self::DownloadBootstrapper { silent } => {
  2989. quote! { #prefix::DownloadBootstrapper { silent: #silent } }
  2990. }
  2991. Self::EmbedBootstrapper { silent } => {
  2992. quote! { #prefix::EmbedBootstrapper { silent: #silent } }
  2993. }
  2994. Self::OfflineInstaller { silent } => {
  2995. quote! { #prefix::OfflineInstaller { silent: #silent } }
  2996. }
  2997. Self::FixedRuntime { path } => {
  2998. let path = path_buf_lit(path);
  2999. quote! { #prefix::FixedRuntime { path: #path } }
  3000. }
  3001. })
  3002. }
  3003. }
  3004. impl ToTokens for WindowsConfig {
  3005. fn to_tokens(&self, tokens: &mut TokenStream) {
  3006. let webview_install_mode = if let Some(fixed_runtime_path) = &self.webview_fixed_runtime_path
  3007. {
  3008. WebviewInstallMode::FixedRuntime {
  3009. path: fixed_runtime_path.clone(),
  3010. }
  3011. } else {
  3012. self.webview_install_mode.clone()
  3013. };
  3014. tokens.append_all(quote! { ::tauri::utils::config::WindowsConfig {
  3015. webview_install_mode: #webview_install_mode,
  3016. ..Default::default()
  3017. }})
  3018. }
  3019. }
  3020. impl ToTokens for BundleConfig {
  3021. fn to_tokens(&self, tokens: &mut TokenStream) {
  3022. let identifier = str_lit(&self.identifier);
  3023. let publisher = quote!(None);
  3024. let icon = vec_lit(&self.icon, str_lit);
  3025. let active = self.active;
  3026. let targets = quote!(Default::default());
  3027. let resources = quote!(None);
  3028. let copyright = quote!(None);
  3029. let category = quote!(None);
  3030. let short_description = quote!(None);
  3031. let long_description = quote!(None);
  3032. let appimage = quote!(Default::default());
  3033. let deb = quote!(Default::default());
  3034. let macos = quote!(Default::default());
  3035. let external_bin = opt_vec_str_lit(self.external_bin.as_ref());
  3036. let windows = &self.windows;
  3037. let ios = quote!(Default::default());
  3038. literal_struct!(
  3039. tokens,
  3040. BundleConfig,
  3041. active,
  3042. identifier,
  3043. publisher,
  3044. icon,
  3045. targets,
  3046. resources,
  3047. copyright,
  3048. category,
  3049. short_description,
  3050. long_description,
  3051. appimage,
  3052. deb,
  3053. macos,
  3054. external_bin,
  3055. windows,
  3056. ios
  3057. );
  3058. }
  3059. }
  3060. impl ToTokens for AppUrl {
  3061. fn to_tokens(&self, tokens: &mut TokenStream) {
  3062. let prefix = quote! { ::tauri::utils::config::AppUrl };
  3063. tokens.append_all(match self {
  3064. Self::Url(url) => {
  3065. quote! { #prefix::Url(#url) }
  3066. }
  3067. Self::Files(files) => {
  3068. let files = vec_lit(files, path_buf_lit);
  3069. quote! { #prefix::Files(#files) }
  3070. }
  3071. })
  3072. }
  3073. }
  3074. impl ToTokens for BuildConfig {
  3075. fn to_tokens(&self, tokens: &mut TokenStream) {
  3076. let dev_path = &self.dev_path;
  3077. let dist_dir = &self.dist_dir;
  3078. let with_global_tauri = self.with_global_tauri;
  3079. let runner = quote!(None);
  3080. let before_dev_command = quote!(None);
  3081. let before_build_command = quote!(None);
  3082. let before_bundle_command = quote!(None);
  3083. let features = quote!(None);
  3084. literal_struct!(
  3085. tokens,
  3086. BuildConfig,
  3087. runner,
  3088. dev_path,
  3089. dist_dir,
  3090. with_global_tauri,
  3091. before_dev_command,
  3092. before_build_command,
  3093. before_bundle_command,
  3094. features
  3095. );
  3096. }
  3097. }
  3098. impl ToTokens for WindowsUpdateInstallMode {
  3099. fn to_tokens(&self, tokens: &mut TokenStream) {
  3100. let prefix = quote! { ::tauri::utils::config::WindowsUpdateInstallMode };
  3101. tokens.append_all(match self {
  3102. Self::BasicUi => quote! { #prefix::BasicUi },
  3103. Self::Quiet => quote! { #prefix::Quiet },
  3104. Self::Passive => quote! { #prefix::Passive },
  3105. })
  3106. }
  3107. }
  3108. impl ToTokens for UpdaterWindowsConfig {
  3109. fn to_tokens(&self, tokens: &mut TokenStream) {
  3110. let install_mode = &self.install_mode;
  3111. literal_struct!(tokens, UpdaterWindowsConfig, install_mode);
  3112. }
  3113. }
  3114. impl ToTokens for UpdaterConfig {
  3115. fn to_tokens(&self, tokens: &mut TokenStream) {
  3116. let active = self.active;
  3117. let dialog = self.dialog;
  3118. let pubkey = str_lit(&self.pubkey);
  3119. let endpoints = opt_lit(
  3120. self
  3121. .endpoints
  3122. .as_ref()
  3123. .map(|list| {
  3124. vec_lit(list, |url| {
  3125. let url = url.0.as_str();
  3126. quote! { ::tauri::utils::config::UpdaterEndpoint(#url.parse().unwrap()) }
  3127. })
  3128. })
  3129. .as_ref(),
  3130. );
  3131. let windows = &self.windows;
  3132. literal_struct!(
  3133. tokens,
  3134. UpdaterConfig,
  3135. active,
  3136. dialog,
  3137. pubkey,
  3138. endpoints,
  3139. windows
  3140. );
  3141. }
  3142. }
  3143. impl ToTokens for CspDirectiveSources {
  3144. fn to_tokens(&self, tokens: &mut TokenStream) {
  3145. let prefix = quote! { ::tauri::utils::config::CspDirectiveSources };
  3146. tokens.append_all(match self {
  3147. Self::Inline(sources) => {
  3148. let sources = sources.as_str();
  3149. quote!(#prefix::Inline(#sources.into()))
  3150. }
  3151. Self::List(list) => {
  3152. let list = vec_lit(list, str_lit);
  3153. quote!(#prefix::List(#list))
  3154. }
  3155. })
  3156. }
  3157. }
  3158. impl ToTokens for Csp {
  3159. fn to_tokens(&self, tokens: &mut TokenStream) {
  3160. let prefix = quote! { ::tauri::utils::config::Csp };
  3161. tokens.append_all(match self {
  3162. Self::Policy(policy) => {
  3163. let policy = policy.as_str();
  3164. quote!(#prefix::Policy(#policy.into()))
  3165. }
  3166. Self::DirectiveMap(list) => {
  3167. let map = map_lit(
  3168. quote! { ::std::collections::HashMap },
  3169. list,
  3170. str_lit,
  3171. identity,
  3172. );
  3173. quote!(#prefix::DirectiveMap(#map))
  3174. }
  3175. })
  3176. }
  3177. }
  3178. impl ToTokens for DisabledCspModificationKind {
  3179. fn to_tokens(&self, tokens: &mut TokenStream) {
  3180. let prefix = quote! { ::tauri::utils::config::DisabledCspModificationKind };
  3181. tokens.append_all(match self {
  3182. Self::Flag(flag) => {
  3183. quote! { #prefix::Flag(#flag) }
  3184. }
  3185. Self::List(directives) => {
  3186. let directives = vec_lit(directives, str_lit);
  3187. quote! { #prefix::List(#directives) }
  3188. }
  3189. });
  3190. }
  3191. }
  3192. impl ToTokens for SecurityConfig {
  3193. fn to_tokens(&self, tokens: &mut TokenStream) {
  3194. let csp = opt_lit(self.csp.as_ref());
  3195. let dev_csp = opt_lit(self.dev_csp.as_ref());
  3196. let freeze_prototype = self.freeze_prototype;
  3197. let dangerous_disable_asset_csp_modification = &self.dangerous_disable_asset_csp_modification;
  3198. literal_struct!(
  3199. tokens,
  3200. SecurityConfig,
  3201. csp,
  3202. dev_csp,
  3203. freeze_prototype,
  3204. dangerous_disable_asset_csp_modification
  3205. );
  3206. }
  3207. }
  3208. impl ToTokens for SystemTrayConfig {
  3209. fn to_tokens(&self, tokens: &mut TokenStream) {
  3210. let icon_as_template = self.icon_as_template;
  3211. let menu_on_left_click = self.menu_on_left_click;
  3212. let icon_path = path_buf_lit(&self.icon_path);
  3213. let title = opt_str_lit(self.title.as_ref());
  3214. literal_struct!(
  3215. tokens,
  3216. SystemTrayConfig,
  3217. icon_path,
  3218. icon_as_template,
  3219. menu_on_left_click,
  3220. title
  3221. );
  3222. }
  3223. }
  3224. impl ToTokens for FsAllowlistScope {
  3225. fn to_tokens(&self, tokens: &mut TokenStream) {
  3226. let prefix = quote! { ::tauri::utils::config::FsAllowlistScope };
  3227. tokens.append_all(match self {
  3228. Self::AllowedPaths(allow) => {
  3229. let allowed_paths = vec_lit(allow, path_buf_lit);
  3230. quote! { #prefix::AllowedPaths(#allowed_paths) }
  3231. }
  3232. Self::Scope { allow, deny } => {
  3233. let allow = vec_lit(allow, path_buf_lit);
  3234. let deny = vec_lit(deny, path_buf_lit);
  3235. quote! { #prefix::Scope { allow: #allow, deny: #deny } }
  3236. }
  3237. });
  3238. }
  3239. }
  3240. impl ToTokens for FsAllowlistConfig {
  3241. fn to_tokens(&self, tokens: &mut TokenStream) {
  3242. let scope = &self.scope;
  3243. tokens.append_all(quote! { ::tauri::utils::config::FsAllowlistConfig { scope: #scope, ..Default::default() } })
  3244. }
  3245. }
  3246. impl ToTokens for ProtocolAllowlistConfig {
  3247. fn to_tokens(&self, tokens: &mut TokenStream) {
  3248. let asset_scope = &self.asset_scope;
  3249. tokens.append_all(quote! { ::tauri::utils::config::ProtocolAllowlistConfig { asset_scope: #asset_scope, ..Default::default() } })
  3250. }
  3251. }
  3252. impl ToTokens for HttpAllowlistScope {
  3253. fn to_tokens(&self, tokens: &mut TokenStream) {
  3254. let allowed_urls = vec_lit(&self.0, url_lit);
  3255. tokens.append_all(quote! { ::tauri::utils::config::HttpAllowlistScope(#allowed_urls) })
  3256. }
  3257. }
  3258. impl ToTokens for HttpAllowlistConfig {
  3259. fn to_tokens(&self, tokens: &mut TokenStream) {
  3260. let scope = &self.scope;
  3261. tokens.append_all(quote! { ::tauri::utils::config::HttpAllowlistConfig { scope: #scope, ..Default::default() } })
  3262. }
  3263. }
  3264. impl ToTokens for ShellAllowedCommand {
  3265. fn to_tokens(&self, tokens: &mut TokenStream) {
  3266. let name = str_lit(&self.name);
  3267. let command = path_buf_lit(&self.command);
  3268. let args = &self.args;
  3269. let sidecar = &self.sidecar;
  3270. literal_struct!(tokens, ShellAllowedCommand, name, command, args, sidecar);
  3271. }
  3272. }
  3273. impl ToTokens for ShellAllowedArgs {
  3274. fn to_tokens(&self, tokens: &mut TokenStream) {
  3275. let prefix = quote! { ::tauri::utils::config::ShellAllowedArgs };
  3276. tokens.append_all(match self {
  3277. Self::Flag(flag) => quote!(#prefix::Flag(#flag)),
  3278. Self::List(list) => {
  3279. let list = vec_lit(list, identity);
  3280. quote!(#prefix::List(#list))
  3281. }
  3282. })
  3283. }
  3284. }
  3285. impl ToTokens for ShellAllowedArg {
  3286. fn to_tokens(&self, tokens: &mut TokenStream) {
  3287. let prefix = quote! { ::tauri::utils::config::ShellAllowedArg };
  3288. tokens.append_all(match self {
  3289. Self::Fixed(fixed) => {
  3290. let fixed = str_lit(fixed);
  3291. quote!(#prefix::Fixed(#fixed))
  3292. }
  3293. Self::Var { validator } => {
  3294. let validator = str_lit(validator);
  3295. quote!(#prefix::Var { validator: #validator })
  3296. }
  3297. })
  3298. }
  3299. }
  3300. impl ToTokens for ShellAllowlistOpen {
  3301. fn to_tokens(&self, tokens: &mut TokenStream) {
  3302. let prefix = quote! { ::tauri::utils::config::ShellAllowlistOpen };
  3303. tokens.append_all(match self {
  3304. Self::Flag(flag) => quote!(#prefix::Flag(#flag)),
  3305. Self::Validate(regex) => quote!(#prefix::Validate(#regex)),
  3306. })
  3307. }
  3308. }
  3309. impl ToTokens for ShellAllowlistScope {
  3310. fn to_tokens(&self, tokens: &mut TokenStream) {
  3311. let allowed_commands = vec_lit(&self.0, identity);
  3312. tokens.append_all(quote! { ::tauri::utils::config::ShellAllowlistScope(#allowed_commands) })
  3313. }
  3314. }
  3315. impl ToTokens for ShellAllowlistConfig {
  3316. fn to_tokens(&self, tokens: &mut TokenStream) {
  3317. let scope = &self.scope;
  3318. tokens.append_all(quote! { ::tauri::utils::config::ShellAllowlistConfig { scope: #scope, ..Default::default() } })
  3319. }
  3320. }
  3321. impl ToTokens for AllowlistConfig {
  3322. fn to_tokens(&self, tokens: &mut TokenStream) {
  3323. let fs = &self.fs;
  3324. let protocol = &self.protocol;
  3325. let http = &self.http;
  3326. let shell = &self.shell;
  3327. tokens.append_all(
  3328. quote! { ::tauri::utils::config::AllowlistConfig { fs: #fs, protocol: #protocol, http: #http, shell: #shell, ..Default::default() } },
  3329. )
  3330. }
  3331. }
  3332. impl ToTokens for TauriConfig {
  3333. fn to_tokens(&self, tokens: &mut TokenStream) {
  3334. let pattern = &self.pattern;
  3335. let windows = vec_lit(&self.windows, identity);
  3336. let cli = opt_lit(self.cli.as_ref());
  3337. let bundle = &self.bundle;
  3338. let updater = &self.updater;
  3339. let security = &self.security;
  3340. let system_tray = opt_lit(self.system_tray.as_ref());
  3341. let allowlist = &self.allowlist;
  3342. let macos_private_api = self.macos_private_api;
  3343. literal_struct!(
  3344. tokens,
  3345. TauriConfig,
  3346. pattern,
  3347. windows,
  3348. cli,
  3349. bundle,
  3350. updater,
  3351. security,
  3352. system_tray,
  3353. allowlist,
  3354. macos_private_api
  3355. );
  3356. }
  3357. }
  3358. impl ToTokens for PluginConfig {
  3359. fn to_tokens(&self, tokens: &mut TokenStream) {
  3360. let config = map_lit(
  3361. quote! { ::std::collections::HashMap },
  3362. &self.0,
  3363. str_lit,
  3364. json_value_lit,
  3365. );
  3366. tokens.append_all(quote! { ::tauri::utils::config::PluginConfig(#config) })
  3367. }
  3368. }
  3369. impl ToTokens for PackageConfig {
  3370. fn to_tokens(&self, tokens: &mut TokenStream) {
  3371. let product_name = opt_str_lit(self.product_name.as_ref());
  3372. let version = opt_str_lit(self.version.as_ref());
  3373. literal_struct!(tokens, PackageConfig, product_name, version);
  3374. }
  3375. }
  3376. impl ToTokens for Config {
  3377. fn to_tokens(&self, tokens: &mut TokenStream) {
  3378. let schema = quote!(None);
  3379. let package = &self.package;
  3380. let tauri = &self.tauri;
  3381. let build = &self.build;
  3382. let plugins = &self.plugins;
  3383. literal_struct!(tokens, Config, schema, package, tauri, build, plugins);
  3384. }
  3385. }
  3386. }
  3387. #[cfg(test)]
  3388. mod test {
  3389. use super::*;
  3390. // TODO: create a test that compares a config to a json config
  3391. #[test]
  3392. // test all of the default functions
  3393. fn test_defaults() {
  3394. // get default tauri config
  3395. let t_config = TauriConfig::default();
  3396. // get default build config
  3397. let b_config = BuildConfig::default();
  3398. // get default dev path
  3399. let d_path = default_dev_path();
  3400. // get default window
  3401. let d_windows: Vec<WindowConfig> = vec![];
  3402. // get default bundle
  3403. let d_bundle = BundleConfig::default();
  3404. // get default updater
  3405. let d_updater = UpdaterConfig::default();
  3406. // create a tauri config.
  3407. let tauri = TauriConfig {
  3408. pattern: Default::default(),
  3409. windows: vec![],
  3410. bundle: BundleConfig {
  3411. active: false,
  3412. targets: Default::default(),
  3413. identifier: String::from(""),
  3414. publisher: None,
  3415. icon: Vec::new(),
  3416. resources: None,
  3417. copyright: None,
  3418. category: None,
  3419. short_description: None,
  3420. long_description: None,
  3421. appimage: Default::default(),
  3422. deb: Default::default(),
  3423. macos: Default::default(),
  3424. external_bin: None,
  3425. windows: Default::default(),
  3426. ios: Default::default(),
  3427. },
  3428. cli: None,
  3429. updater: UpdaterConfig {
  3430. active: false,
  3431. dialog: true,
  3432. pubkey: "".into(),
  3433. endpoints: None,
  3434. windows: Default::default(),
  3435. },
  3436. security: SecurityConfig {
  3437. csp: None,
  3438. dev_csp: None,
  3439. freeze_prototype: false,
  3440. dangerous_disable_asset_csp_modification: DisabledCspModificationKind::Flag(false),
  3441. },
  3442. allowlist: AllowlistConfig::default(),
  3443. system_tray: None,
  3444. macos_private_api: false,
  3445. };
  3446. // create a build config
  3447. let build = BuildConfig {
  3448. runner: None,
  3449. dev_path: AppUrl::Url(WindowUrl::External(
  3450. Url::parse("http://localhost:8080").unwrap(),
  3451. )),
  3452. dist_dir: AppUrl::Url(WindowUrl::App("../dist".into())),
  3453. before_dev_command: None,
  3454. before_build_command: None,
  3455. before_bundle_command: None,
  3456. features: None,
  3457. with_global_tauri: false,
  3458. };
  3459. // test the configs
  3460. assert_eq!(t_config, tauri);
  3461. assert_eq!(b_config, build);
  3462. assert_eq!(d_bundle, tauri.bundle);
  3463. assert_eq!(d_updater, tauri.updater);
  3464. assert_eq!(
  3465. d_path,
  3466. AppUrl::Url(WindowUrl::External(
  3467. Url::parse("http://localhost:8080").unwrap()
  3468. ))
  3469. );
  3470. assert_eq!(d_windows, tauri.windows);
  3471. }
  3472. }