config.rs 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606
  1. // Copyright 2019-2021 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. //! The Tauri configuration used at runtime.
  5. //!
  6. //! It is pulled from a `tauri.conf.json` file and the [`Config`] struct is generated at compile time.
  7. //!
  8. //! # Stability
  9. //! This is a core functionality that is not considered part of the stable API.
  10. //! If you use it, note that it may include breaking changes in the future.
  11. #[cfg(target_os = "linux")]
  12. use heck::ToKebabCase;
  13. #[cfg(feature = "schema")]
  14. use schemars::JsonSchema;
  15. use serde::{
  16. de::{Deserializer, Error as DeError, Visitor},
  17. Deserialize, Serialize,
  18. };
  19. use serde_json::Value as JsonValue;
  20. use serde_with::skip_serializing_none;
  21. use url::Url;
  22. use std::{collections::HashMap, fmt, fs::read_to_string, path::PathBuf};
  23. /// The window webview URL options.
  24. #[derive(PartialEq, Debug, Clone, Deserialize, Serialize)]
  25. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  26. #[serde(untagged)]
  27. #[non_exhaustive]
  28. pub enum WindowUrl {
  29. /// An external URL.
  30. External(Url),
  31. /// An app URL.
  32. App(PathBuf),
  33. }
  34. impl fmt::Display for WindowUrl {
  35. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  36. match self {
  37. Self::External(url) => write!(f, "{}", url),
  38. Self::App(path) => write!(f, "{}", path.display()),
  39. }
  40. }
  41. }
  42. impl Default for WindowUrl {
  43. fn default() -> Self {
  44. Self::App("index.html".into())
  45. }
  46. }
  47. /// Targets to bundle.
  48. #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
  49. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  50. #[serde(untagged)]
  51. pub enum BundleTarget {
  52. /// A list of bundle targets.
  53. All(Vec<String>),
  54. /// A single bundle target.
  55. One(String),
  56. }
  57. impl BundleTarget {
  58. /// Gets the bundle targets as a [`Vec`].
  59. #[allow(dead_code)]
  60. pub fn to_vec(&self) -> Vec<String> {
  61. match self {
  62. Self::All(list) => list.clone(),
  63. Self::One(i) => vec![i.clone()],
  64. }
  65. }
  66. }
  67. /// Configuration for Debian (.deb) bundles.
  68. #[skip_serializing_none]
  69. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  70. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  71. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  72. pub struct DebConfig {
  73. /// The list of deb dependencies your application relies on.
  74. pub depends: Option<Vec<String>>,
  75. /// Enable the boostrapper script.
  76. #[serde(default)]
  77. pub use_bootstrapper: bool,
  78. /// The files to include on the package.
  79. #[serde(default)]
  80. pub files: HashMap<PathBuf, PathBuf>,
  81. }
  82. /// Configuration for the macOS bundles.
  83. #[skip_serializing_none]
  84. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  85. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  86. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  87. pub struct MacConfig {
  88. /// A list of strings indicating any macOS X frameworks that need to be bundled with the application.
  89. ///
  90. /// 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.
  91. pub frameworks: Option<Vec<String>>,
  92. /// A version string indicating the minimum macOS X version that the bundled application supports.
  93. pub minimum_system_version: Option<String>,
  94. /// Allows your application to communicate with the outside world.
  95. /// It should be a lowercase, without port and protocol domain name.
  96. pub exception_domain: Option<String>,
  97. /// The path to the license file to add to the DMG bundle.
  98. pub license: Option<String>,
  99. /// Enable the boostrapper script.
  100. #[serde(default)]
  101. pub use_bootstrapper: bool,
  102. /// Identity to use for code signing.
  103. pub signing_identity: Option<String>,
  104. /// Path to the entitlements file.
  105. pub entitlements: Option<String>,
  106. }
  107. fn default_language() -> String {
  108. "en-US".into()
  109. }
  110. /// Configuration for the MSI bundle using WiX.
  111. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  112. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  113. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  114. pub struct WixConfig {
  115. /// The installer language. See <https://docs.microsoft.com/en-us/windows/win32/msi/localizing-the-error-and-actiontext-tables>.
  116. #[serde(default = "default_language")]
  117. pub language: String,
  118. /// A custom .wxs template to use.
  119. pub template: Option<PathBuf>,
  120. /// A list of paths to .wxs files with WiX fragments to use.
  121. #[serde(default)]
  122. pub fragment_paths: Vec<PathBuf>,
  123. /// The ComponentGroup element ids you want to reference from the fragments.
  124. #[serde(default)]
  125. pub component_group_refs: Vec<String>,
  126. /// The Component element ids you want to reference from the fragments.
  127. #[serde(default)]
  128. pub component_refs: Vec<String>,
  129. /// The FeatureGroup element ids you want to reference from the fragments.
  130. #[serde(default)]
  131. pub feature_group_refs: Vec<String>,
  132. /// The Feature element ids you want to reference from the fragments.
  133. #[serde(default)]
  134. pub feature_refs: Vec<String>,
  135. /// The Merge element ids you want to reference from the fragments.
  136. #[serde(default)]
  137. pub merge_refs: Vec<String>,
  138. /// Disables the Webview2 runtime installation after app install.
  139. #[serde(default)]
  140. pub skip_webview_install: bool,
  141. /// The path to the license file to render on the installer.
  142. ///
  143. /// Must be an RTF file, so if a different extension is provided, we convert it to the RTF format.
  144. pub license: Option<PathBuf>,
  145. /// Create an elevated update task within Windows Task Scheduler.
  146. #[serde(default)]
  147. pub enable_elevated_update_task: bool,
  148. /// Path to a bitmap file to use as the installation user interface banner.
  149. /// This bitmap will appear at the top of all but the first page of the installer.
  150. ///
  151. /// The required dimensions are 493px × 58px.
  152. pub banner_path: Option<PathBuf>,
  153. /// Path to a bitmap file to use on the installation user interface dialogs.
  154. /// It is used on the welcome and completion dialogs.
  155. /// The required dimensions are 493px × 312px.
  156. pub dialog_image_path: Option<PathBuf>,
  157. }
  158. /// Windows bundler configuration.
  159. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  160. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  161. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  162. pub struct WindowsConfig {
  163. /// Specifies the file digest algorithm to use for creating file signatures.
  164. /// Required for code signing. SHA-256 is recommended.
  165. pub digest_algorithm: Option<String>,
  166. /// Specifies the SHA1 hash of the signing certificate.
  167. pub certificate_thumbprint: Option<String>,
  168. /// Server to use during timestamping.
  169. pub timestamp_url: Option<String>,
  170. /// Path to the webview fixed runtime to use.
  171. ///
  172. /// The fixed version can be downloaded [on the official website](https://developer.microsoft.com/en-us/microsoft-edge/webview2/#download-section).
  173. /// The `.cab` file must be extracted to a folder and this folder path must be defined on this field.
  174. pub webview_fixed_runtime_path: Option<PathBuf>,
  175. /// Configuration for the MSI generated with WiX.
  176. pub wix: Option<WixConfig>,
  177. }
  178. /// Configuration for tauri-bundler.
  179. #[skip_serializing_none]
  180. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  181. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  182. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  183. pub struct BundleConfig {
  184. /// Whether we should build your app with tauri-bundler or plain `cargo build`
  185. #[serde(default)]
  186. pub active: bool,
  187. /// The bundle targets, currently supports ["deb", "app", "msi", "appimage", "dmg"] or "all"
  188. pub targets: Option<BundleTarget>,
  189. /// The app's identifier
  190. pub identifier: String,
  191. /// The app's icons
  192. #[serde(default)]
  193. pub icon: Vec<String>,
  194. /// App resources to bundle.
  195. /// Each resource is a path to a file or directory.
  196. /// Glob patterns are supported.
  197. pub resources: Option<Vec<String>>,
  198. /// A copyright string associated with your application.
  199. pub copyright: Option<String>,
  200. /// The application kind.
  201. pub category: Option<String>,
  202. /// A short description of your application.
  203. pub short_description: Option<String>,
  204. /// A longer, multi-line description of the application.
  205. pub long_description: Option<String>,
  206. /// Configuration for the Debian bundle.
  207. #[serde(default)]
  208. pub deb: DebConfig,
  209. /// Configuration for the macOS bundles.
  210. #[serde(rename = "macOS", default)]
  211. pub macos: MacConfig,
  212. /// A list of—either absolute or relative—paths to binaries to embed with your application.
  213. ///
  214. /// Note that Tauri will look for system-specific binaries following the pattern "binary-name{-target-triple}{.system-extension}".
  215. ///
  216. /// E.g. for the external binary "my-binary", Tauri looks for:
  217. ///
  218. /// - "my-binary-x86_64-pc-windows-msvc.exe" for Windows
  219. /// - "my-binary-x86_64-apple-darwin" for macOS
  220. /// - "my-binary-x86_64-unknown-linux-gnu" for Linux
  221. ///
  222. /// so don't forget to provide binaries for all targeted platforms.
  223. pub external_bin: Option<Vec<String>>,
  224. /// Configuration for the Windows bundle.
  225. #[serde(default)]
  226. pub windows: WindowsConfig,
  227. }
  228. /// A CLI argument definition.
  229. #[skip_serializing_none]
  230. #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
  231. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  232. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  233. pub struct CliArg {
  234. /// The short version of the argument, without the preceding -.
  235. ///
  236. /// NOTE: Any leading - characters will be stripped, and only the first non - character will be used as the short version.
  237. pub short: Option<char>,
  238. /// The unique argument name
  239. pub name: String,
  240. /// The argument description which will be shown on the help information.
  241. /// Typically, this is a short (one line) description of the arg.
  242. pub description: Option<String>,
  243. /// The argument long description which will be shown on the help information.
  244. /// Typically this a more detailed (multi-line) message that describes the argument.
  245. pub long_description: Option<String>,
  246. /// Specifies that the argument takes a value at run time.
  247. ///
  248. /// NOTE: values for arguments may be specified in any of the following methods
  249. /// - Using a space such as -o value or --option value
  250. /// - Using an equals and no space such as -o=value or --option=value
  251. /// - Use a short and no space such as -ovalue
  252. pub takes_value: Option<bool>,
  253. /// Specifies that the argument may have an unknown number of multiple values. Without any other settings, this argument may appear only once.
  254. ///
  255. /// For example, --opt val1 val2 is allowed, but --opt val1 val2 --opt val3 is not.
  256. ///
  257. /// NOTE: Setting this requires `takes_value` to be set to true.
  258. pub multiple: Option<bool>,
  259. /// Specifies that the argument may appear more than once.
  260. /// 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.
  261. /// 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)
  262. ///
  263. /// For example, --opt val1 --opt val2 is allowed, but --opt val1 val2 is not.
  264. pub multiple_occurrences: Option<bool>,
  265. /// Specifies how many values are required to satisfy this argument. For example, if you had a
  266. /// `-f <file>` argument where you wanted exactly 3 'files' you would set
  267. /// `number_of_values = 3`, and this argument wouldn't be satisfied unless the user provided
  268. /// 3 and only 3 values.
  269. ///
  270. /// **NOTE:** Does *not* require `multiple_occurrences = true` to be set. Setting
  271. /// `multiple_occurrences = true` would allow `-f <file> <file> <file> -f <file> <file> <file>` where
  272. /// as *not* setting it would only allow one occurrence of this argument.
  273. ///
  274. /// **NOTE:** implicitly sets `takes_value = true` and `multiple_values = true`.
  275. pub number_of_values: Option<usize>,
  276. /// Specifies a list of possible values for this argument.
  277. /// At runtime, the CLI verifies that only one of the specified values was used, or fails with an error message.
  278. pub possible_values: Option<Vec<String>>,
  279. /// Specifies the minimum number of values for this argument.
  280. /// For example, if you had a -f <file> argument where you wanted at least 2 'files',
  281. /// you would set `minValues: 2`, and this argument would be satisfied if the user provided, 2 or more values.
  282. pub min_values: Option<usize>,
  283. /// Specifies the maximum number of values are for this argument.
  284. /// For example, if you had a -f <file> argument where you wanted up to 3 'files',
  285. /// you would set .max_values(3), and this argument would be satisfied if the user provided, 1, 2, or 3 values.
  286. pub max_values: Option<usize>,
  287. /// Sets whether or not the argument is required by default.
  288. ///
  289. /// - Required by default means it is required, when no other conflicting rules have been evaluated
  290. /// - Conflicting rules take precedence over being required.
  291. pub required: Option<bool>,
  292. /// Sets an arg that override this arg's required setting
  293. /// i.e. this arg will be required unless this other argument is present.
  294. pub required_unless_present: Option<String>,
  295. /// Sets args that override this arg's required setting
  296. /// i.e. this arg will be required unless all these other arguments are present.
  297. pub required_unless_present_all: Option<Vec<String>>,
  298. /// Sets args that override this arg's required setting
  299. /// i.e. this arg will be required unless at least one of these other arguments are present.
  300. pub required_unless_present_any: Option<Vec<String>>,
  301. /// Sets a conflicting argument by name
  302. /// i.e. when using this argument, the following argument can't be present and vice versa.
  303. pub conflicts_with: Option<String>,
  304. /// The same as conflictsWith but allows specifying multiple two-way conflicts per argument.
  305. pub conflicts_with_all: Option<Vec<String>>,
  306. /// Tets an argument by name that is required when this one is present
  307. /// i.e. when using this argument, the following argument must be present.
  308. pub requires: Option<String>,
  309. /// Sts multiple arguments by names that are required when this one is present
  310. /// i.e. when using this argument, the following arguments must be present.
  311. pub requires_all: Option<Vec<String>>,
  312. /// Allows a conditional requirement with the signature [arg, value]
  313. /// the requirement will only become valid if `arg`'s value equals `${value}`.
  314. pub requires_if: Option<Vec<String>>,
  315. /// Allows specifying that an argument is required conditionally with the signature [arg, value]
  316. /// the requirement will only become valid if the `arg`'s value equals `${value}`.
  317. pub required_if_eq: Option<Vec<String>>,
  318. /// Requires that options use the --option=val syntax
  319. /// i.e. an equals between the option and associated value.
  320. pub require_equals: Option<bool>,
  321. /// The positional argument index, starting at 1.
  322. ///
  323. /// The index refers to position according to other positional argument.
  324. /// It does not define position in the argument list as a whole. When utilized with multiple=true,
  325. /// only the last positional argument may be defined as multiple (i.e. the one with the highest index).
  326. pub index: Option<usize>,
  327. }
  328. /// describes a CLI configuration
  329. #[skip_serializing_none]
  330. #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
  331. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  332. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  333. pub struct CliConfig {
  334. /// Command description which will be shown on the help information.
  335. pub description: Option<String>,
  336. /// Command long description which will be shown on the help information.
  337. pub long_description: Option<String>,
  338. /// Adds additional help information to be displayed in addition to auto-generated help.
  339. /// This information is displayed before the auto-generated help information.
  340. /// This is often used for header information.
  341. pub before_help: Option<String>,
  342. /// Adds additional help information to be displayed in addition to auto-generated help.
  343. /// This information is displayed after the auto-generated help information.
  344. /// This is often used to describe how to use the arguments, or caveats to be noted.
  345. pub after_help: Option<String>,
  346. /// List of arguments for the command
  347. pub args: Option<Vec<CliArg>>,
  348. /// List of subcommands of this command
  349. pub subcommands: Option<HashMap<String, CliConfig>>,
  350. }
  351. impl CliConfig {
  352. /// List of arguments for the command
  353. pub fn args(&self) -> Option<&Vec<CliArg>> {
  354. self.args.as_ref()
  355. }
  356. /// List of subcommands of this command
  357. pub fn subcommands(&self) -> Option<&HashMap<String, CliConfig>> {
  358. self.subcommands.as_ref()
  359. }
  360. /// Command description which will be shown on the help information.
  361. pub fn description(&self) -> Option<&String> {
  362. self.description.as_ref()
  363. }
  364. /// Command long description which will be shown on the help information.
  365. pub fn long_description(&self) -> Option<&String> {
  366. self.description.as_ref()
  367. }
  368. /// Adds additional help information to be displayed in addition to auto-generated help.
  369. /// This information is displayed before the auto-generated help information.
  370. /// This is often used for header information.
  371. pub fn before_help(&self) -> Option<&String> {
  372. self.before_help.as_ref()
  373. }
  374. /// Adds additional help information to be displayed in addition to auto-generated help.
  375. /// This information is displayed after the auto-generated help information.
  376. /// This is often used to describe how to use the arguments, or caveats to be noted.
  377. pub fn after_help(&self) -> Option<&String> {
  378. self.after_help.as_ref()
  379. }
  380. }
  381. /// The window configuration object.
  382. #[skip_serializing_none]
  383. #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
  384. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  385. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  386. pub struct WindowConfig {
  387. /// The window identifier. It must be alphanumeric.
  388. #[serde(default = "default_window_label")]
  389. pub label: String,
  390. /// The window webview URL.
  391. #[serde(default)]
  392. pub url: WindowUrl,
  393. /// Whether the file drop is enabled or not on the webview. By default it is enabled.
  394. ///
  395. /// Disabling it is required to use drag and drop on the frontend on Windows.
  396. #[serde(default = "default_file_drop_enabled")]
  397. pub file_drop_enabled: bool,
  398. /// Whether or not the window starts centered or not.
  399. #[serde(default)]
  400. pub center: bool,
  401. /// The horizontal position of the window's top left corner
  402. pub x: Option<f64>,
  403. /// The vertical position of the window's top left corner
  404. pub y: Option<f64>,
  405. /// The window width.
  406. #[serde(default = "default_width")]
  407. pub width: f64,
  408. /// The window height.
  409. #[serde(default = "default_height")]
  410. pub height: f64,
  411. /// The min window width.
  412. pub min_width: Option<f64>,
  413. /// The min window height.
  414. pub min_height: Option<f64>,
  415. /// The max window width.
  416. pub max_width: Option<f64>,
  417. /// The max window height.
  418. pub max_height: Option<f64>,
  419. /// Whether the window is resizable or not.
  420. #[serde(default = "default_resizable")]
  421. pub resizable: bool,
  422. /// The window title.
  423. #[serde(default = "default_title")]
  424. pub title: String,
  425. /// Whether the window starts as fullscreen or not.
  426. #[serde(default)]
  427. pub fullscreen: bool,
  428. /// Whether the window will be initially hidden or focused.
  429. #[serde(default = "default_focus")]
  430. pub focus: bool,
  431. /// Whether the window is transparent or not.
  432. ///
  433. /// Note that on `macOS` this requires the `macos-private-api` feature flag, enabled under `tauri.conf.json > tauri > macosPrivateApi`.
  434. /// WARNING: Using private APIs on `macOS` prevents your application from being accepted for the `App Store`.
  435. #[serde(default)]
  436. pub transparent: bool,
  437. /// Whether the window is maximized or not.
  438. #[serde(default)]
  439. pub maximized: bool,
  440. /// Whether the window is visible or not.
  441. #[serde(default = "default_visible")]
  442. pub visible: bool,
  443. /// Whether the window should have borders and bars.
  444. #[serde(default = "default_decorations")]
  445. pub decorations: bool,
  446. /// Whether the window should always be on top of other windows.
  447. #[serde(default)]
  448. pub always_on_top: bool,
  449. /// Whether or not the window icon should be added to the taskbar.
  450. #[serde(default)]
  451. pub skip_taskbar: bool,
  452. }
  453. impl Default for WindowConfig {
  454. fn default() -> Self {
  455. Self {
  456. label: default_window_label(),
  457. url: WindowUrl::default(),
  458. file_drop_enabled: default_file_drop_enabled(),
  459. center: false,
  460. x: None,
  461. y: None,
  462. width: default_width(),
  463. height: default_height(),
  464. min_width: None,
  465. min_height: None,
  466. max_width: None,
  467. max_height: None,
  468. resizable: default_resizable(),
  469. title: default_title(),
  470. fullscreen: false,
  471. focus: false,
  472. transparent: false,
  473. maximized: false,
  474. visible: default_visible(),
  475. decorations: default_decorations(),
  476. always_on_top: false,
  477. skip_taskbar: false,
  478. }
  479. }
  480. }
  481. fn default_window_label() -> String {
  482. "main".to_string()
  483. }
  484. fn default_width() -> f64 {
  485. 800f64
  486. }
  487. fn default_height() -> f64 {
  488. 600f64
  489. }
  490. fn default_resizable() -> bool {
  491. true
  492. }
  493. fn default_title() -> String {
  494. "Tauri App".to_string()
  495. }
  496. fn default_focus() -> bool {
  497. true
  498. }
  499. fn default_visible() -> bool {
  500. true
  501. }
  502. fn default_decorations() -> bool {
  503. true
  504. }
  505. fn default_file_drop_enabled() -> bool {
  506. true
  507. }
  508. /// Security configuration.
  509. #[skip_serializing_none]
  510. #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
  511. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  512. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  513. pub struct SecurityConfig {
  514. /// The Content Security Policy that will be injected on all HTML files on the built application.
  515. /// If [`dev_csp`](SecurityConfig.dev_csp) is not specified, this value is also injected on dev.
  516. ///
  517. /// This is a really important part of the configuration since it helps you ensure your WebView is secured.
  518. /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP>.
  519. pub csp: Option<String>,
  520. /// The Content Security Policy that will be injected on all HTML files on development.
  521. ///
  522. /// This is a really important part of the configuration since it helps you ensure your WebView is secured.
  523. /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP>.
  524. pub dev_csp: Option<String>,
  525. /// Freeze the `Object.prototype` when using the custom protocol.
  526. #[serde(default = "default_freeze_prototype")]
  527. pub freeze_prototype: bool,
  528. }
  529. impl Default for SecurityConfig {
  530. fn default() -> Self {
  531. Self {
  532. csp: None,
  533. dev_csp: None,
  534. freeze_prototype: default_freeze_prototype(),
  535. }
  536. }
  537. }
  538. fn default_freeze_prototype() -> bool {
  539. true
  540. }
  541. /// Defines an allowlist type.
  542. pub trait Allowlist {
  543. /// Returns all features associated with the allowlist struct.
  544. fn all_features() -> Vec<&'static str>;
  545. /// Returns the tauri features enabled on this allowlist.
  546. fn to_features(&self) -> Vec<&'static str>;
  547. }
  548. macro_rules! check_feature {
  549. ($self:ident, $features:ident, $flag:ident, $feature_name: expr) => {
  550. if $self.$flag {
  551. $features.push($feature_name)
  552. }
  553. };
  554. }
  555. /// Filesystem scope definition.
  556. /// It is a list of glob patterns that restrict the API access from the webview.
  557. ///
  558. /// Each pattern can start with a variable that resolves to a system base directory.
  559. /// The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`,
  560. /// `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`,
  561. /// `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$APP`, `$CWD`.
  562. #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
  563. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  564. pub struct FsAllowlistScope(pub Vec<PathBuf>);
  565. impl Default for FsAllowlistScope {
  566. fn default() -> Self {
  567. Self(vec!["$APP/**".into()])
  568. }
  569. }
  570. /// Allowlist for the file system APIs.
  571. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  572. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  573. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  574. pub struct FsAllowlistConfig {
  575. /// The access scope for the filesystem APIs.
  576. #[serde(default)]
  577. pub scope: FsAllowlistScope,
  578. /// Use this flag to enable all file system API features.
  579. #[serde(default)]
  580. pub all: bool,
  581. /// Read file from local filesystem.
  582. #[serde(default)]
  583. pub read_file: bool,
  584. /// Write file to local filesystem.
  585. #[serde(default)]
  586. pub write_file: bool,
  587. /// Read directory from local filesystem.
  588. #[serde(default)]
  589. pub read_dir: bool,
  590. /// Copy file from local filesystem.
  591. #[serde(default)]
  592. pub copy_file: bool,
  593. /// Create directory from local filesystem.
  594. #[serde(default)]
  595. pub create_dir: bool,
  596. /// Remove directory from local filesystem.
  597. #[serde(default)]
  598. pub remove_dir: bool,
  599. /// Remove file from local filesystem.
  600. #[serde(default)]
  601. pub remove_file: bool,
  602. /// Rename file from local filesystem.
  603. #[serde(default)]
  604. pub rename_file: bool,
  605. }
  606. impl Allowlist for FsAllowlistConfig {
  607. fn all_features() -> Vec<&'static str> {
  608. let allowlist = Self {
  609. scope: Default::default(),
  610. all: false,
  611. read_file: true,
  612. write_file: true,
  613. read_dir: true,
  614. copy_file: true,
  615. create_dir: true,
  616. remove_dir: true,
  617. remove_file: true,
  618. rename_file: true,
  619. };
  620. let mut features = allowlist.to_features();
  621. features.push("fs-all");
  622. features
  623. }
  624. fn to_features(&self) -> Vec<&'static str> {
  625. if self.all {
  626. vec!["fs-all"]
  627. } else {
  628. let mut features = Vec::new();
  629. check_feature!(self, features, read_file, "fs-read-file");
  630. check_feature!(self, features, write_file, "fs-write-file");
  631. check_feature!(self, features, read_dir, "fs-read-dir");
  632. check_feature!(self, features, copy_file, "fs-copy-file");
  633. check_feature!(self, features, create_dir, "fs-create-dir");
  634. check_feature!(self, features, remove_dir, "fs-remove-dir");
  635. check_feature!(self, features, remove_file, "fs-remove-file");
  636. check_feature!(self, features, rename_file, "fs-rename-file");
  637. features
  638. }
  639. }
  640. }
  641. /// Allowlist for the window APIs.
  642. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  643. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  644. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  645. pub struct WindowAllowlistConfig {
  646. /// Use this flag to enable all window API features.
  647. #[serde(default)]
  648. pub all: bool,
  649. /// Allows dynamic window creation.
  650. #[serde(default)]
  651. pub create: bool,
  652. /// Allows centering the window.
  653. #[serde(default)]
  654. pub center: bool,
  655. /// Allows requesting user attention on the window.
  656. #[serde(default)]
  657. pub request_user_attention: bool,
  658. /// Allows setting the resizable flag of the window.
  659. #[serde(default)]
  660. pub set_resizable: bool,
  661. /// Allows changing the window title.
  662. #[serde(default)]
  663. pub set_title: bool,
  664. /// Allows maximizing the window.
  665. #[serde(default)]
  666. pub maximize: bool,
  667. /// Allows unmaximizing the window.
  668. #[serde(default)]
  669. pub unmaximize: bool,
  670. /// Allows minimizing the window.
  671. #[serde(default)]
  672. pub minimize: bool,
  673. /// Allows unminimizing the window.
  674. #[serde(default)]
  675. pub unminimize: bool,
  676. /// Allows showing the window.
  677. #[serde(default)]
  678. pub show: bool,
  679. /// Allows hiding the window.
  680. #[serde(default)]
  681. pub hide: bool,
  682. /// Allows closing the window.
  683. #[serde(default)]
  684. pub close: bool,
  685. /// Allows setting the decorations flag of the window.
  686. #[serde(default)]
  687. pub set_decorations: bool,
  688. /// Allows setting the always_on_top flag of the window.
  689. #[serde(default)]
  690. pub set_always_on_top: bool,
  691. /// Allows setting the window size.
  692. #[serde(default)]
  693. pub set_size: bool,
  694. /// Allows setting the window minimum size.
  695. #[serde(default)]
  696. pub set_min_size: bool,
  697. /// Allows setting the window maximum size.
  698. #[serde(default)]
  699. pub set_max_size: bool,
  700. /// Allows changing the position of the window.
  701. #[serde(default)]
  702. pub set_position: bool,
  703. /// Allows setting the fullscreen flag of the window.
  704. #[serde(default)]
  705. pub set_fullscreen: bool,
  706. /// Allows focusing the window.
  707. #[serde(default)]
  708. pub set_focus: bool,
  709. /// Allows changing the window icon.
  710. #[serde(default)]
  711. pub set_icon: bool,
  712. /// Allows setting the skip_taskbar flag of the window.
  713. #[serde(default)]
  714. pub set_skip_taskbar: bool,
  715. /// Allows start dragging on the window.
  716. #[serde(default)]
  717. pub start_dragging: bool,
  718. /// Allows opening the system dialog to print the window content.
  719. #[serde(default)]
  720. pub print: bool,
  721. }
  722. impl Allowlist for WindowAllowlistConfig {
  723. fn all_features() -> Vec<&'static str> {
  724. let allowlist = Self {
  725. all: false,
  726. create: true,
  727. center: true,
  728. request_user_attention: true,
  729. set_resizable: true,
  730. set_title: true,
  731. maximize: true,
  732. unmaximize: true,
  733. minimize: true,
  734. unminimize: true,
  735. show: true,
  736. hide: true,
  737. close: true,
  738. set_decorations: true,
  739. set_always_on_top: true,
  740. set_size: true,
  741. set_min_size: true,
  742. set_max_size: true,
  743. set_position: true,
  744. set_fullscreen: true,
  745. set_focus: true,
  746. set_icon: true,
  747. set_skip_taskbar: true,
  748. start_dragging: true,
  749. print: true,
  750. };
  751. let mut features = allowlist.to_features();
  752. features.push("window-all");
  753. features
  754. }
  755. fn to_features(&self) -> Vec<&'static str> {
  756. if self.all {
  757. vec!["window-all"]
  758. } else {
  759. let mut features = Vec::new();
  760. check_feature!(self, features, create, "window-create");
  761. check_feature!(self, features, center, "window-center");
  762. check_feature!(
  763. self,
  764. features,
  765. request_user_attention,
  766. "window-request-user-attention"
  767. );
  768. check_feature!(self, features, set_resizable, "window-set-resizable");
  769. check_feature!(self, features, set_title, "window-set-title");
  770. check_feature!(self, features, maximize, "window-maximize");
  771. check_feature!(self, features, unmaximize, "window-unmaximize");
  772. check_feature!(self, features, minimize, "window-minimize");
  773. check_feature!(self, features, unminimize, "window-unminimize");
  774. check_feature!(self, features, show, "window-show");
  775. check_feature!(self, features, hide, "window-hide");
  776. check_feature!(self, features, close, "window-close");
  777. check_feature!(self, features, set_decorations, "window-set-decorations");
  778. check_feature!(
  779. self,
  780. features,
  781. set_always_on_top,
  782. "window-set-always-on-top"
  783. );
  784. check_feature!(self, features, set_size, "window-set-size");
  785. check_feature!(self, features, set_min_size, "window-set-min-size");
  786. check_feature!(self, features, set_max_size, "window-set-max-size");
  787. check_feature!(self, features, set_position, "window-set-position");
  788. check_feature!(self, features, set_fullscreen, "window-set-fullscreen");
  789. check_feature!(self, features, set_focus, "window-set-focus");
  790. check_feature!(self, features, set_icon, "window-set-icon");
  791. check_feature!(self, features, set_skip_taskbar, "window-set-skip-taskbar");
  792. check_feature!(self, features, start_dragging, "window-start-dragging");
  793. check_feature!(self, features, print, "window-print");
  794. features
  795. }
  796. }
  797. }
  798. /// A command allowed to be executed by the webview API.
  799. #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
  800. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  801. pub struct ShellAllowedCommand {
  802. /// The name for this allowed shell command configuration.
  803. ///
  804. /// This name will be used inside of the webview API to call this command along with
  805. /// any specified arguments.
  806. pub name: String,
  807. /// The command name.
  808. /// It can start with a variable that resolves to a system base directory.
  809. /// The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`,
  810. /// `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`,
  811. /// `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$APP`, `$CWD`.
  812. #[serde(rename = "cmd")]
  813. pub command: PathBuf,
  814. /// The allowed arguments for the command execution.
  815. #[serde(default)]
  816. pub args: ShellAllowedArgs,
  817. /// If this command is a sidecar command.
  818. #[serde(default)]
  819. pub sidecar: bool,
  820. }
  821. /// A set of command arguments allowed to be executed by the webview API.
  822. ///
  823. /// A value of `true` will allow any arguments to be passed to the command. `false` will disable all
  824. /// arguments. A list of [`ShellAllowedArg`] will set those arguments as the only valid arguments to
  825. /// be passed to the attached command configuration.
  826. #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
  827. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  828. #[serde(untagged, deny_unknown_fields)]
  829. #[non_exhaustive]
  830. pub enum ShellAllowedArgs {
  831. /// Use a simple boolean to allow all or disable all arguments to this command configuration.
  832. Flag(bool),
  833. /// A specific set of [`ShellAllowedArg`] that are valid to call for the command configuration.
  834. List(Vec<ShellAllowedArg>),
  835. }
  836. impl Default for ShellAllowedArgs {
  837. fn default() -> Self {
  838. Self::Flag(false)
  839. }
  840. }
  841. /// A command argument allowed to be executed by the webview API.
  842. #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
  843. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  844. #[serde(untagged, deny_unknown_fields)]
  845. #[non_exhaustive]
  846. pub enum ShellAllowedArg {
  847. /// A non-configurable argument that is passed to the command in the order it was specified.
  848. Fixed(String),
  849. /// A variable that is set while calling the command from the webview API.
  850. ///
  851. Var {
  852. /// The name of the variable to be passed in.
  853. ///
  854. /// This will try to match the key of the passed arguments object from the webview API.
  855. name: String,
  856. /// Optional [regex] validator to require passed values to conform to an expected input.
  857. ///
  858. /// This will require the argument value passed to this variable to match the `validate` regex
  859. /// before it will be executed.
  860. ///
  861. /// [regex]: https://docs.rs/regex/latest/regex/#syntax
  862. #[serde(default)]
  863. validate: Option<String>,
  864. },
  865. }
  866. /// Shell scope definition.
  867. /// It is a list of command names and associated CLI arguments that restrict the API access from the webview.
  868. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  869. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  870. pub struct ShellAllowlistScope(pub Vec<ShellAllowedCommand>);
  871. /// Defines the `shell > open` api scope.
  872. #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
  873. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  874. #[serde(untagged, deny_unknown_fields)]
  875. #[non_exhaustive]
  876. pub enum ShellAllowlistOpen {
  877. /// If the shell open API should be enabled.
  878. ///
  879. /// If enabled, the default validation regex (`^https?://`) is used.
  880. Flag(bool),
  881. /// Enable the shell open API, with a custom regex that the opened path must match against.
  882. ///
  883. /// If using a custom regex to support a non-http(s) schema, care should be used to prevent values
  884. /// that allow flag-like strings to pass validation. e.g. `--enable-debugging`, `-i`, `/R`.
  885. Validate(String),
  886. }
  887. impl Default for ShellAllowlistOpen {
  888. fn default() -> Self {
  889. Self::Flag(false)
  890. }
  891. }
  892. /// Allowlist for the shell APIs.
  893. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  894. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  895. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  896. pub struct ShellAllowlistConfig {
  897. /// Access scope for the binary execution APIs.
  898. /// Sidecars are automatically enabled.
  899. #[serde(default)]
  900. pub scope: ShellAllowlistScope,
  901. /// Use this flag to enable all shell API features.
  902. #[serde(default)]
  903. pub all: bool,
  904. /// Enable binary execution.
  905. #[serde(default)]
  906. pub execute: bool,
  907. /// Enable sidecar execution, allowing the JavaScript layer to spawn a sidecar command,
  908. /// an executable that is shipped with the application.
  909. /// For more information see <https://tauri.studio/en/docs/usage/guides/bundler/sidecar>.
  910. #[serde(default)]
  911. pub sidecar: bool,
  912. /// Open URL with the user's default application.
  913. #[serde(default)]
  914. pub open: ShellAllowlistOpen,
  915. }
  916. impl Allowlist for ShellAllowlistConfig {
  917. fn all_features() -> Vec<&'static str> {
  918. let allowlist = Self {
  919. scope: Default::default(),
  920. all: false,
  921. execute: true,
  922. sidecar: true,
  923. open: ShellAllowlistOpen::Flag(true),
  924. };
  925. let mut features = allowlist.to_features();
  926. features.push("shell-all");
  927. features
  928. }
  929. fn to_features(&self) -> Vec<&'static str> {
  930. if self.all {
  931. vec!["shell-all"]
  932. } else {
  933. let mut features = Vec::new();
  934. check_feature!(self, features, execute, "shell-execute");
  935. check_feature!(self, features, sidecar, "shell-sidecar");
  936. if !matches!(self.open, ShellAllowlistOpen::Flag(false)) {
  937. features.push("shell-open")
  938. }
  939. features
  940. }
  941. }
  942. }
  943. /// Allowlist for the dialog APIs.
  944. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  945. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  946. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  947. pub struct DialogAllowlistConfig {
  948. /// Use this flag to enable all dialog API features.
  949. #[serde(default)]
  950. pub all: bool,
  951. /// Allows the API to open a dialog window to pick files.
  952. #[serde(default)]
  953. pub open: bool,
  954. /// Allows the API to open a dialog window to pick where to save files.
  955. #[serde(default)]
  956. pub save: bool,
  957. /// Allows the API to show a message dialog window.
  958. #[serde(default)]
  959. pub message: bool,
  960. /// Allows the API to show a dialog window with Yes/No buttons.
  961. #[serde(default)]
  962. pub ask: bool,
  963. /// Allows the API to show a dialog window with Ok/Cancel buttons.
  964. #[serde(default)]
  965. pub confirm: bool,
  966. }
  967. impl Allowlist for DialogAllowlistConfig {
  968. fn all_features() -> Vec<&'static str> {
  969. let allowlist = Self {
  970. all: false,
  971. open: true,
  972. save: true,
  973. message: true,
  974. ask: true,
  975. confirm: true,
  976. };
  977. let mut features = allowlist.to_features();
  978. features.push("dialog-all");
  979. features
  980. }
  981. fn to_features(&self) -> Vec<&'static str> {
  982. if self.all {
  983. vec!["dialog-all"]
  984. } else {
  985. let mut features = Vec::new();
  986. check_feature!(self, features, open, "dialog-open");
  987. check_feature!(self, features, save, "dialog-save");
  988. check_feature!(self, features, message, "dialog-message");
  989. check_feature!(self, features, ask, "dialog-ask");
  990. check_feature!(self, features, confirm, "dialog-confirm");
  991. features
  992. }
  993. }
  994. }
  995. /// HTTP API scope definition.
  996. /// It is a list of URLs that can be accessed by the webview when using the HTTP APIs.
  997. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  998. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  999. pub struct HttpAllowlistScope(pub Vec<Url>);
  1000. /// Allowlist for the HTTP APIs.
  1001. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  1002. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1003. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1004. pub struct HttpAllowlistConfig {
  1005. /// The access scope for the HTTP APIs.
  1006. #[serde(default)]
  1007. pub scope: HttpAllowlistScope,
  1008. /// Use this flag to enable all HTTP API features.
  1009. #[serde(default)]
  1010. pub all: bool,
  1011. /// Allows making HTTP requests.
  1012. #[serde(default)]
  1013. pub request: bool,
  1014. }
  1015. impl Allowlist for HttpAllowlistConfig {
  1016. fn all_features() -> Vec<&'static str> {
  1017. let allowlist = Self {
  1018. scope: Default::default(),
  1019. all: false,
  1020. request: true,
  1021. };
  1022. let mut features = allowlist.to_features();
  1023. features.push("http-all");
  1024. features
  1025. }
  1026. fn to_features(&self) -> Vec<&'static str> {
  1027. if self.all {
  1028. vec!["http-all"]
  1029. } else {
  1030. let mut features = Vec::new();
  1031. check_feature!(self, features, request, "http-request");
  1032. features
  1033. }
  1034. }
  1035. }
  1036. /// Allowlist for the notification APIs.
  1037. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  1038. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1039. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1040. pub struct NotificationAllowlistConfig {
  1041. /// Use this flag to enable all notification API features.
  1042. #[serde(default)]
  1043. pub all: bool,
  1044. }
  1045. impl Allowlist for NotificationAllowlistConfig {
  1046. fn all_features() -> Vec<&'static str> {
  1047. let allowlist = Self { all: false };
  1048. let mut features = allowlist.to_features();
  1049. features.push("notification-all");
  1050. features
  1051. }
  1052. fn to_features(&self) -> Vec<&'static str> {
  1053. if self.all {
  1054. vec!["notification-all"]
  1055. } else {
  1056. vec![]
  1057. }
  1058. }
  1059. }
  1060. /// Allowlist for the global shortcut APIs.
  1061. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  1062. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1063. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1064. pub struct GlobalShortcutAllowlistConfig {
  1065. /// Use this flag to enable all global shortcut API features.
  1066. #[serde(default)]
  1067. pub all: bool,
  1068. }
  1069. impl Allowlist for GlobalShortcutAllowlistConfig {
  1070. fn all_features() -> Vec<&'static str> {
  1071. let allowlist = Self { all: false };
  1072. let mut features = allowlist.to_features();
  1073. features.push("global-shortcut-all");
  1074. features
  1075. }
  1076. fn to_features(&self) -> Vec<&'static str> {
  1077. if self.all {
  1078. vec!["global-shortcut-all"]
  1079. } else {
  1080. vec![]
  1081. }
  1082. }
  1083. }
  1084. /// Allowlist for the OS APIs.
  1085. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  1086. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1087. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1088. pub struct OsAllowlistConfig {
  1089. /// Use this flag to enable all OS API features.
  1090. #[serde(default)]
  1091. pub all: bool,
  1092. }
  1093. impl Allowlist for OsAllowlistConfig {
  1094. fn all_features() -> Vec<&'static str> {
  1095. let allowlist = Self { all: false };
  1096. let mut features = allowlist.to_features();
  1097. features.push("os-all");
  1098. features
  1099. }
  1100. fn to_features(&self) -> Vec<&'static str> {
  1101. if self.all {
  1102. vec!["os-all"]
  1103. } else {
  1104. vec![]
  1105. }
  1106. }
  1107. }
  1108. /// Allowlist for the path APIs.
  1109. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  1110. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1111. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1112. pub struct PathAllowlistConfig {
  1113. /// Use this flag to enable all path API features.
  1114. #[serde(default)]
  1115. pub all: bool,
  1116. }
  1117. impl Allowlist for PathAllowlistConfig {
  1118. fn all_features() -> Vec<&'static str> {
  1119. let allowlist = Self { all: false };
  1120. let mut features = allowlist.to_features();
  1121. features.push("path-all");
  1122. features
  1123. }
  1124. fn to_features(&self) -> Vec<&'static str> {
  1125. if self.all {
  1126. vec!["path-all"]
  1127. } else {
  1128. vec![]
  1129. }
  1130. }
  1131. }
  1132. /// Allowlist for the custom protocols.
  1133. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  1134. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1135. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1136. pub struct ProtocolAllowlistConfig {
  1137. /// The access scope for the asset protocol.
  1138. #[serde(default)]
  1139. pub asset_scope: FsAllowlistScope,
  1140. /// Use this flag to enable all custom protocols.
  1141. #[serde(default)]
  1142. pub all: bool,
  1143. /// Enables the asset protocol.
  1144. #[serde(default)]
  1145. pub asset: bool,
  1146. }
  1147. impl Allowlist for ProtocolAllowlistConfig {
  1148. fn all_features() -> Vec<&'static str> {
  1149. let allowlist = Self {
  1150. asset_scope: Default::default(),
  1151. all: false,
  1152. asset: true,
  1153. };
  1154. let mut features = allowlist.to_features();
  1155. features.push("protocol-all");
  1156. features
  1157. }
  1158. fn to_features(&self) -> Vec<&'static str> {
  1159. if self.all {
  1160. vec!["protocol-all"]
  1161. } else {
  1162. let mut features = Vec::new();
  1163. check_feature!(self, features, asset, "protocol-asset");
  1164. features
  1165. }
  1166. }
  1167. }
  1168. /// Allowlist for the process APIs.
  1169. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  1170. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1171. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1172. pub struct ProcessAllowlistConfig {
  1173. /// Use this flag to enable all process APIs.
  1174. #[serde(default)]
  1175. pub all: bool,
  1176. /// Enables the relaunch API.
  1177. #[serde(default)]
  1178. pub relaunch: bool,
  1179. /// Enables the exit API.
  1180. #[serde(default)]
  1181. pub exit: bool,
  1182. }
  1183. impl Allowlist for ProcessAllowlistConfig {
  1184. fn all_features() -> Vec<&'static str> {
  1185. let allowlist = Self {
  1186. all: false,
  1187. relaunch: true,
  1188. exit: true,
  1189. };
  1190. let mut features = allowlist.to_features();
  1191. features.push("process-all");
  1192. features
  1193. }
  1194. fn to_features(&self) -> Vec<&'static str> {
  1195. if self.all {
  1196. vec!["process-all"]
  1197. } else {
  1198. let mut features = Vec::new();
  1199. check_feature!(self, features, relaunch, "process-relaunch");
  1200. check_feature!(self, features, exit, "process-exit");
  1201. features
  1202. }
  1203. }
  1204. }
  1205. /// Allowlist for the clipboard APIs.
  1206. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  1207. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1208. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1209. pub struct ClipboardAllowlistConfig {
  1210. /// Use this flag to enable all clipboard APIs.
  1211. #[serde(default)]
  1212. pub all: bool,
  1213. /// Enables the clipboard's `writeText` API.
  1214. #[serde(default)]
  1215. pub write_text: bool,
  1216. /// Enables the clipboard's `readText` API.
  1217. #[serde(default)]
  1218. pub read_text: bool,
  1219. }
  1220. impl Allowlist for ClipboardAllowlistConfig {
  1221. fn all_features() -> Vec<&'static str> {
  1222. let allowlist = Self {
  1223. all: false,
  1224. write_text: true,
  1225. read_text: true,
  1226. };
  1227. let mut features = allowlist.to_features();
  1228. features.push("clipboard-all");
  1229. features
  1230. }
  1231. fn to_features(&self) -> Vec<&'static str> {
  1232. if self.all {
  1233. vec!["clipboard-all"]
  1234. } else {
  1235. let mut features = Vec::new();
  1236. check_feature!(self, features, write_text, "clipboard-write-text");
  1237. check_feature!(self, features, read_text, "clipboard-read-text");
  1238. features
  1239. }
  1240. }
  1241. }
  1242. /// Allowlist configuration.
  1243. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  1244. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1245. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1246. pub struct AllowlistConfig {
  1247. /// Use this flag to enable all API features.
  1248. #[serde(default)]
  1249. pub all: bool,
  1250. /// File system API allowlist.
  1251. #[serde(default)]
  1252. pub fs: FsAllowlistConfig,
  1253. /// Window API allowlist.
  1254. #[serde(default)]
  1255. pub window: WindowAllowlistConfig,
  1256. /// Shell API allowlist.
  1257. #[serde(default)]
  1258. pub shell: ShellAllowlistConfig,
  1259. /// Dialog API allowlist.
  1260. #[serde(default)]
  1261. pub dialog: DialogAllowlistConfig,
  1262. /// HTTP API allowlist.
  1263. #[serde(default)]
  1264. pub http: HttpAllowlistConfig,
  1265. /// Notification API allowlist.
  1266. #[serde(default)]
  1267. pub notification: NotificationAllowlistConfig,
  1268. /// Global shortcut API allowlist.
  1269. #[serde(default)]
  1270. pub global_shortcut: GlobalShortcutAllowlistConfig,
  1271. /// OS allowlist.
  1272. #[serde(default)]
  1273. pub os: OsAllowlistConfig,
  1274. /// Path API allowlist.
  1275. #[serde(default)]
  1276. pub path: PathAllowlistConfig,
  1277. /// Custom protocol allowlist.
  1278. #[serde(default)]
  1279. pub protocol: ProtocolAllowlistConfig,
  1280. /// Process API allowlist.
  1281. #[serde(default)]
  1282. pub process: ProcessAllowlistConfig,
  1283. /// Clipboard APIs allowlist.
  1284. #[serde(default)]
  1285. pub clipboard: ClipboardAllowlistConfig,
  1286. }
  1287. impl Allowlist for AllowlistConfig {
  1288. fn all_features() -> Vec<&'static str> {
  1289. let mut features = Vec::new();
  1290. features.extend(FsAllowlistConfig::all_features());
  1291. features.extend(WindowAllowlistConfig::all_features());
  1292. features.extend(ShellAllowlistConfig::all_features());
  1293. features.extend(DialogAllowlistConfig::all_features());
  1294. features.extend(HttpAllowlistConfig::all_features());
  1295. features.extend(NotificationAllowlistConfig::all_features());
  1296. features.extend(GlobalShortcutAllowlistConfig::all_features());
  1297. features.extend(OsAllowlistConfig::all_features());
  1298. features.extend(PathAllowlistConfig::all_features());
  1299. features.extend(ProtocolAllowlistConfig::all_features());
  1300. features.extend(ProcessAllowlistConfig::all_features());
  1301. features.extend(ClipboardAllowlistConfig::all_features());
  1302. features
  1303. }
  1304. fn to_features(&self) -> Vec<&'static str> {
  1305. if self.all {
  1306. vec!["api-all"]
  1307. } else {
  1308. let mut features = Vec::new();
  1309. features.extend(self.fs.to_features());
  1310. features.extend(self.window.to_features());
  1311. features.extend(self.shell.to_features());
  1312. features.extend(self.dialog.to_features());
  1313. features.extend(self.http.to_features());
  1314. features.extend(self.notification.to_features());
  1315. features.extend(self.global_shortcut.to_features());
  1316. features.extend(self.os.to_features());
  1317. features.extend(self.path.to_features());
  1318. features.extend(self.protocol.to_features());
  1319. features
  1320. }
  1321. }
  1322. }
  1323. fn default_window_config() -> Vec<WindowConfig> {
  1324. vec![Default::default()]
  1325. }
  1326. /// The application pattern.
  1327. #[skip_serializing_none]
  1328. #[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
  1329. #[serde(rename_all = "lowercase", tag = "use", content = "options")]
  1330. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1331. pub enum PatternKind {
  1332. /// Brownfield pattern.
  1333. Brownfield,
  1334. /// Isolation pattern. Recommended for security purposes.
  1335. #[cfg(feature = "isolation")]
  1336. Isolation {
  1337. /// The dir containing the index.html file that contains the secure isolation application.
  1338. dir: PathBuf,
  1339. },
  1340. }
  1341. impl Default for PatternKind {
  1342. fn default() -> Self {
  1343. Self::Brownfield
  1344. }
  1345. }
  1346. /// The Tauri configuration object.
  1347. #[skip_serializing_none]
  1348. #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
  1349. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1350. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1351. pub struct TauriConfig {
  1352. /// The pattern to use.
  1353. #[serde(default)]
  1354. pub pattern: PatternKind,
  1355. /// The windows configuration.
  1356. #[serde(default = "default_window_config")]
  1357. pub windows: Vec<WindowConfig>,
  1358. /// The CLI configuration.
  1359. pub cli: Option<CliConfig>,
  1360. /// The bundler configuration.
  1361. #[serde(default)]
  1362. pub bundle: BundleConfig,
  1363. /// The allowlist configuration.
  1364. #[serde(default)]
  1365. pub allowlist: AllowlistConfig,
  1366. /// Security configuration.
  1367. #[serde(default)]
  1368. pub security: SecurityConfig,
  1369. /// The updater configuration.
  1370. #[serde(default)]
  1371. pub updater: UpdaterConfig,
  1372. /// Configuration for app system tray.
  1373. pub system_tray: Option<SystemTrayConfig>,
  1374. /// MacOS private API configuration. Enables the transparent background API and sets the `fullScreenEnabled` preference to `true`.
  1375. #[serde(rename = "macOSPrivateApi", default)]
  1376. pub macos_private_api: bool,
  1377. }
  1378. impl Default for TauriConfig {
  1379. fn default() -> Self {
  1380. Self {
  1381. pattern: Default::default(),
  1382. windows: default_window_config(),
  1383. cli: None,
  1384. bundle: BundleConfig::default(),
  1385. allowlist: AllowlistConfig::default(),
  1386. security: SecurityConfig::default(),
  1387. updater: UpdaterConfig::default(),
  1388. system_tray: None,
  1389. macos_private_api: false,
  1390. }
  1391. }
  1392. }
  1393. impl TauriConfig {
  1394. /// Returns all Cargo features.
  1395. #[allow(dead_code)]
  1396. pub fn all_features() -> Vec<&'static str> {
  1397. let mut features = AllowlistConfig::all_features();
  1398. features.extend(vec![
  1399. "cli",
  1400. "updater",
  1401. "system-tray",
  1402. "macos-private-api",
  1403. "isolation",
  1404. ]);
  1405. features
  1406. }
  1407. /// Returns the enabled Cargo features.
  1408. #[allow(dead_code)]
  1409. pub fn features(&self) -> Vec<&str> {
  1410. let mut features = self.allowlist.to_features();
  1411. if self.cli.is_some() {
  1412. features.push("cli");
  1413. }
  1414. if self.updater.active {
  1415. features.push("updater");
  1416. }
  1417. if self.system_tray.is_some() {
  1418. features.push("system-tray");
  1419. }
  1420. if self.macos_private_api {
  1421. features.push("macos-private-api");
  1422. }
  1423. #[cfg(feature = "isolation")]
  1424. if let PatternKind::Isolation { .. } = self.pattern {
  1425. features.push("isolation");
  1426. }
  1427. features.sort_unstable();
  1428. features
  1429. }
  1430. }
  1431. /// A URL to an updater server.
  1432. ///
  1433. /// The URL must use the `https` scheme on production.
  1434. #[skip_serializing_none]
  1435. #[derive(Debug, PartialEq, Clone, Serialize)]
  1436. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1437. pub struct UpdaterEndpoint(pub Url);
  1438. impl std::fmt::Display for UpdaterEndpoint {
  1439. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  1440. write!(f, "{}", self.0)
  1441. }
  1442. }
  1443. impl<'de> Deserialize<'de> for UpdaterEndpoint {
  1444. fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  1445. where
  1446. D: Deserializer<'de>,
  1447. {
  1448. let url = Url::deserialize(deserializer)?;
  1449. #[cfg(all(not(debug_assertions), not(feature = "schema")))]
  1450. {
  1451. if url.scheme() != "https" {
  1452. return Err(serde::de::Error::custom(
  1453. "The configured updater endpoint must use the `https` protocol.",
  1454. ));
  1455. }
  1456. }
  1457. Ok(Self(url))
  1458. }
  1459. }
  1460. /// The Updater configuration object.
  1461. #[skip_serializing_none]
  1462. #[derive(Debug, PartialEq, Clone, Serialize)]
  1463. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1464. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1465. pub struct UpdaterConfig {
  1466. /// Whether the updater is active or not.
  1467. #[serde(default)]
  1468. pub active: bool,
  1469. /// Display built-in dialog or use event system if disabled.
  1470. #[serde(default = "default_dialog")]
  1471. pub dialog: bool,
  1472. /// The updater endpoints. TLS is enforced on production.
  1473. pub endpoints: Option<Vec<UpdaterEndpoint>>,
  1474. /// Signature public key.
  1475. #[serde(default)] // use default just so the schema doesn't flag it as required
  1476. pub pubkey: String,
  1477. }
  1478. impl<'de> Deserialize<'de> for UpdaterConfig {
  1479. fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  1480. where
  1481. D: Deserializer<'de>,
  1482. {
  1483. #[derive(Deserialize)]
  1484. struct InnerUpdaterConfig {
  1485. #[serde(default)]
  1486. active: bool,
  1487. #[serde(default = "default_dialog")]
  1488. dialog: bool,
  1489. endpoints: Option<Vec<UpdaterEndpoint>>,
  1490. pubkey: Option<String>,
  1491. }
  1492. let config = InnerUpdaterConfig::deserialize(deserializer)?;
  1493. if config.active && config.pubkey.is_none() {
  1494. return Err(DeError::custom(
  1495. "The updater `pubkey` configuration is required.",
  1496. ));
  1497. }
  1498. Ok(UpdaterConfig {
  1499. active: config.active,
  1500. dialog: config.dialog,
  1501. endpoints: config.endpoints,
  1502. pubkey: config.pubkey.unwrap_or_default(),
  1503. })
  1504. }
  1505. }
  1506. impl Default for UpdaterConfig {
  1507. fn default() -> Self {
  1508. Self {
  1509. active: false,
  1510. dialog: default_dialog(),
  1511. endpoints: None,
  1512. pubkey: "".into(),
  1513. }
  1514. }
  1515. }
  1516. /// Configuration for application system tray icon.
  1517. #[skip_serializing_none]
  1518. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  1519. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1520. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1521. pub struct SystemTrayConfig {
  1522. /// Path to the icon to use on the system tray.
  1523. ///
  1524. /// It is forced to be a `.png` file on Linux and macOS, and a `.ico` file on Windows.
  1525. pub icon_path: PathBuf,
  1526. /// 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.
  1527. #[serde(default)]
  1528. pub icon_as_template: bool,
  1529. }
  1530. // We enable the unnecessary_wraps because we need
  1531. // to use an Option for dialog otherwise the CLI schema will mark
  1532. // the dialog as a required field which is not as we default it to true.
  1533. fn default_dialog() -> bool {
  1534. true
  1535. }
  1536. /// The `dev_path` and `dist_dir` options.
  1537. #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
  1538. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1539. #[serde(untagged, deny_unknown_fields)]
  1540. #[non_exhaustive]
  1541. pub enum AppUrl {
  1542. /// The app's external URL, or the path to the directory containing the app assets.
  1543. Url(WindowUrl),
  1544. /// An array of files to embed on the app.
  1545. Files(Vec<PathBuf>),
  1546. }
  1547. impl std::fmt::Display for AppUrl {
  1548. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  1549. match self {
  1550. Self::Url(url) => write!(f, "{}", url),
  1551. Self::Files(files) => write!(f, "{}", serde_json::to_string(files).unwrap()),
  1552. }
  1553. }
  1554. }
  1555. /// The Build configuration object.
  1556. #[skip_serializing_none]
  1557. #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
  1558. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1559. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1560. pub struct BuildConfig {
  1561. /// The binary used to build and run the application.
  1562. pub runner: Option<String>,
  1563. /// The path or URL to use on development.
  1564. #[serde(default = "default_dev_path")]
  1565. pub dev_path: AppUrl,
  1566. /// The path to the app's dist dir. This path must contain your index.html file.
  1567. #[serde(default = "default_dist_dir")]
  1568. pub dist_dir: AppUrl,
  1569. /// A shell command to run before `tauri dev` kicks in.
  1570. ///
  1571. /// The PLATFORM, ARCH, FAMILY, PLATFORM_TYPE and TAURI_DEBUG environment variables are set if you perform conditional compilation.
  1572. pub before_dev_command: Option<String>,
  1573. /// A shell command to run before `tauri build` kicks in.
  1574. ///
  1575. /// The PLATFORM, ARCH, FAMILY, PLATFORM_TYPE and TAURI_DEBUG environment variables are set if you perform conditional compilation.
  1576. pub before_build_command: Option<String>,
  1577. /// Features passed to `cargo` commands.
  1578. pub features: Option<Vec<String>>,
  1579. /// Whether we should inject the Tauri API on `window.__TAURI__` or not.
  1580. #[serde(default)]
  1581. pub with_global_tauri: bool,
  1582. }
  1583. impl Default for BuildConfig {
  1584. fn default() -> Self {
  1585. Self {
  1586. runner: None,
  1587. dev_path: default_dev_path(),
  1588. dist_dir: default_dist_dir(),
  1589. before_dev_command: None,
  1590. before_build_command: None,
  1591. features: None,
  1592. with_global_tauri: false,
  1593. }
  1594. }
  1595. }
  1596. fn default_dev_path() -> AppUrl {
  1597. AppUrl::Url(WindowUrl::External(
  1598. Url::parse("http://localhost:8080").unwrap(),
  1599. ))
  1600. }
  1601. fn default_dist_dir() -> AppUrl {
  1602. AppUrl::Url(WindowUrl::App("../dist".into()))
  1603. }
  1604. #[derive(Debug, PartialEq)]
  1605. struct PackageVersion(String);
  1606. impl<'d> serde::Deserialize<'d> for PackageVersion {
  1607. fn deserialize<D: Deserializer<'d>>(deserializer: D) -> Result<PackageVersion, D::Error> {
  1608. struct PackageVersionVisitor;
  1609. impl<'d> Visitor<'d> for PackageVersionVisitor {
  1610. type Value = PackageVersion;
  1611. fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
  1612. write!(
  1613. formatter,
  1614. "a semver string or a path to a package.json file"
  1615. )
  1616. }
  1617. fn visit_str<E: DeError>(self, value: &str) -> Result<PackageVersion, E> {
  1618. let path = PathBuf::from(value);
  1619. if path.exists() {
  1620. let json_str = read_to_string(&path)
  1621. .map_err(|e| DeError::custom(format!("failed to read version JSON file: {}", e)))?;
  1622. let package_json: serde_json::Value = serde_json::from_str(&json_str)
  1623. .map_err(|e| DeError::custom(format!("failed to read version JSON file: {}", e)))?;
  1624. if let Some(obj) = package_json.as_object() {
  1625. let version = obj
  1626. .get("version")
  1627. .ok_or_else(|| DeError::custom("JSON must contain a `version` field"))?
  1628. .as_str()
  1629. .ok_or_else(|| DeError::custom("`version` must be a string"))?;
  1630. Ok(PackageVersion(version.into()))
  1631. } else {
  1632. Err(DeError::custom("value is not a path to a JSON object"))
  1633. }
  1634. } else {
  1635. Ok(PackageVersion(value.into()))
  1636. }
  1637. }
  1638. }
  1639. deserializer.deserialize_string(PackageVersionVisitor {})
  1640. }
  1641. }
  1642. /// The package configuration.
  1643. #[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
  1644. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1645. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1646. pub struct PackageConfig {
  1647. /// App name.
  1648. pub product_name: Option<String>,
  1649. /// App version. It is a semver version number or a path to a `package.json` file contaning the `version` field.
  1650. #[serde(deserialize_with = "version_deserializer", default)]
  1651. pub version: Option<String>,
  1652. }
  1653. fn version_deserializer<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
  1654. where
  1655. D: Deserializer<'de>,
  1656. {
  1657. Option::<PackageVersion>::deserialize(deserializer).map(|v| v.map(|v| v.0))
  1658. }
  1659. impl PackageConfig {
  1660. /// The binary name.
  1661. #[allow(dead_code)]
  1662. pub fn binary_name(&self) -> Option<String> {
  1663. #[cfg(target_os = "linux")]
  1664. {
  1665. self.product_name.as_ref().map(|n| n.to_kebab_case())
  1666. }
  1667. #[cfg(not(target_os = "linux"))]
  1668. {
  1669. self.product_name.clone()
  1670. }
  1671. }
  1672. }
  1673. /// The config type mapped to `tauri.conf.json`.
  1674. #[skip_serializing_none]
  1675. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  1676. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1677. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1678. pub struct Config {
  1679. /// Package settings.
  1680. #[serde(default)]
  1681. pub package: PackageConfig,
  1682. /// The Tauri configuration.
  1683. #[serde(default)]
  1684. pub tauri: TauriConfig,
  1685. /// The build configuration.
  1686. #[serde(default = "default_build")]
  1687. pub build: BuildConfig,
  1688. /// The plugins config.
  1689. #[serde(default)]
  1690. pub plugins: PluginConfig,
  1691. }
  1692. /// The plugin configs holds a HashMap mapping a plugin name to its configuration object.
  1693. #[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
  1694. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1695. pub struct PluginConfig(pub HashMap<String, JsonValue>);
  1696. fn default_build() -> BuildConfig {
  1697. BuildConfig {
  1698. runner: None,
  1699. dev_path: default_dev_path(),
  1700. dist_dir: default_dist_dir(),
  1701. before_dev_command: None,
  1702. before_build_command: None,
  1703. features: None,
  1704. with_global_tauri: false,
  1705. }
  1706. }
  1707. /// Implement `ToTokens` for all config structs, allowing a literal `Config` to be built.
  1708. ///
  1709. /// This allows for a build script to output the values in a `Config` to a `TokenStream`, which can
  1710. /// then be consumed by another crate. Useful for passing a config to both the build script and the
  1711. /// application using tauri while only parsing it once (in the build script).
  1712. #[cfg(feature = "build")]
  1713. mod build {
  1714. use std::{convert::identity, path::Path};
  1715. use proc_macro2::TokenStream;
  1716. use quote::{quote, ToTokens, TokenStreamExt};
  1717. use super::*;
  1718. use serde_json::Value as JsonValue;
  1719. /// Create a `String` constructor `TokenStream`.
  1720. ///
  1721. /// e.g. `"Hello World" -> String::from("Hello World").
  1722. /// This takes a `&String` to reduce casting all the `&String` -> `&str` manually.
  1723. fn str_lit(s: impl AsRef<str>) -> TokenStream {
  1724. let s = s.as_ref();
  1725. quote! { #s.into() }
  1726. }
  1727. /// Create an `Option` constructor `TokenStream`.
  1728. fn opt_lit(item: Option<&impl ToTokens>) -> TokenStream {
  1729. match item {
  1730. None => quote! { ::core::option::Option::None },
  1731. Some(item) => quote! { ::core::option::Option::Some(#item) },
  1732. }
  1733. }
  1734. /// Helper function to combine an `opt_lit` with `str_lit`.
  1735. fn opt_str_lit(item: Option<impl AsRef<str>>) -> TokenStream {
  1736. opt_lit(item.map(str_lit).as_ref())
  1737. }
  1738. /// Helper function to combine an `opt_lit` with a list of `str_lit`
  1739. fn opt_vec_str_lit(item: Option<impl IntoIterator<Item = impl AsRef<str>>>) -> TokenStream {
  1740. opt_lit(item.map(|list| vec_lit(list, str_lit)).as_ref())
  1741. }
  1742. /// Create a `Vec` constructor, mapping items with a function that spits out `TokenStream`s.
  1743. fn vec_lit<Raw, Tokens>(
  1744. list: impl IntoIterator<Item = Raw>,
  1745. map: impl Fn(Raw) -> Tokens,
  1746. ) -> TokenStream
  1747. where
  1748. Tokens: ToTokens,
  1749. {
  1750. let items = list.into_iter().map(map);
  1751. quote! { vec![#(#items),*] }
  1752. }
  1753. /// Create a `PathBuf` constructor `TokenStream`.
  1754. ///
  1755. /// e.g. `"Hello World" -> String::from("Hello World").
  1756. fn path_buf_lit(s: impl AsRef<Path>) -> TokenStream {
  1757. let s = s.as_ref().to_string_lossy().into_owned();
  1758. quote! { ::std::path::PathBuf::from(#s) }
  1759. }
  1760. /// Creates a `Url` constructor `TokenStream`.
  1761. fn url_lit(url: &Url) -> TokenStream {
  1762. let url = url.as_str();
  1763. quote! { #url.parse().unwrap() }
  1764. }
  1765. /// Create a map constructor, mapping keys and values with other `TokenStream`s.
  1766. ///
  1767. /// This function is pretty generic because the types of keys AND values get transformed.
  1768. fn map_lit<Map, Key, Value, TokenStreamKey, TokenStreamValue, FuncKey, FuncValue>(
  1769. map_type: TokenStream,
  1770. map: Map,
  1771. map_key: FuncKey,
  1772. map_value: FuncValue,
  1773. ) -> TokenStream
  1774. where
  1775. <Map as IntoIterator>::IntoIter: ExactSizeIterator,
  1776. Map: IntoIterator<Item = (Key, Value)>,
  1777. TokenStreamKey: ToTokens,
  1778. TokenStreamValue: ToTokens,
  1779. FuncKey: Fn(Key) -> TokenStreamKey,
  1780. FuncValue: Fn(Value) -> TokenStreamValue,
  1781. {
  1782. let ident = quote::format_ident!("map");
  1783. let map = map.into_iter();
  1784. if map.len() > 0 {
  1785. let items = map.map(|(key, value)| {
  1786. let key = map_key(key);
  1787. let value = map_value(value);
  1788. quote! { #ident.insert(#key, #value); }
  1789. });
  1790. quote! {{
  1791. let mut #ident = #map_type::new();
  1792. #(#items)*
  1793. #ident
  1794. }}
  1795. } else {
  1796. quote! { #map_type::new() }
  1797. }
  1798. }
  1799. /// Create a `serde_json::Value` variant `TokenStream` for a number
  1800. fn json_value_number_lit(num: &serde_json::Number) -> TokenStream {
  1801. // See https://docs.rs/serde_json/1/serde_json/struct.Number.html for guarantees
  1802. let prefix = quote! { ::serde_json::Value };
  1803. if num.is_u64() {
  1804. // guaranteed u64
  1805. let num = num.as_u64().unwrap();
  1806. quote! { #prefix::Number(#num.into()) }
  1807. } else if num.is_i64() {
  1808. // guaranteed i64
  1809. let num = num.as_i64().unwrap();
  1810. quote! { #prefix::Number(#num.into()) }
  1811. } else if num.is_f64() {
  1812. // guaranteed f64
  1813. let num = num.as_f64().unwrap();
  1814. quote! { #prefix::Number(#num.into()) }
  1815. } else {
  1816. // invalid number
  1817. quote! { #prefix::Null }
  1818. }
  1819. }
  1820. /// Create a `serde_json::Value` constructor `TokenStream`
  1821. fn json_value_lit(jv: &JsonValue) -> TokenStream {
  1822. let prefix = quote! { ::serde_json::Value };
  1823. match jv {
  1824. JsonValue::Null => quote! { #prefix::Null },
  1825. JsonValue::Bool(bool) => quote! { #prefix::Bool(#bool) },
  1826. JsonValue::Number(number) => json_value_number_lit(number),
  1827. JsonValue::String(str) => {
  1828. let s = str_lit(str);
  1829. quote! { #prefix::String(#s) }
  1830. }
  1831. JsonValue::Array(vec) => {
  1832. let items = vec.iter().map(json_value_lit);
  1833. quote! { #prefix::Array(vec![#(#items),*]) }
  1834. }
  1835. JsonValue::Object(map) => {
  1836. let map = map_lit(quote! { ::serde_json::Map }, map, str_lit, json_value_lit);
  1837. quote! { #prefix::Object(#map) }
  1838. }
  1839. }
  1840. }
  1841. /// Write a `TokenStream` of the `$struct`'s fields to the `$tokens`.
  1842. ///
  1843. /// All fields must represent a binding of the same name that implements `ToTokens`.
  1844. macro_rules! literal_struct {
  1845. ($tokens:ident, $struct:ident, $($field:ident),+) => {
  1846. $tokens.append_all(quote! {
  1847. ::tauri::utils::config::$struct {
  1848. $($field: #$field),+
  1849. }
  1850. });
  1851. };
  1852. }
  1853. impl ToTokens for WindowUrl {
  1854. fn to_tokens(&self, tokens: &mut TokenStream) {
  1855. let prefix = quote! { ::tauri::utils::config::WindowUrl };
  1856. tokens.append_all(match self {
  1857. Self::App(path) => {
  1858. let path = path_buf_lit(&path);
  1859. quote! { #prefix::App(#path) }
  1860. }
  1861. Self::External(url) => {
  1862. let url = url_lit(url);
  1863. quote! { #prefix::External(#url) }
  1864. }
  1865. })
  1866. }
  1867. }
  1868. impl ToTokens for WindowConfig {
  1869. fn to_tokens(&self, tokens: &mut TokenStream) {
  1870. let label = str_lit(&self.label);
  1871. let url = &self.url;
  1872. let file_drop_enabled = self.file_drop_enabled;
  1873. let center = self.center;
  1874. let x = opt_lit(self.x.as_ref());
  1875. let y = opt_lit(self.y.as_ref());
  1876. let width = self.width;
  1877. let height = self.height;
  1878. let min_width = opt_lit(self.min_width.as_ref());
  1879. let min_height = opt_lit(self.min_height.as_ref());
  1880. let max_width = opt_lit(self.max_width.as_ref());
  1881. let max_height = opt_lit(self.max_height.as_ref());
  1882. let resizable = self.resizable;
  1883. let title = str_lit(&self.title);
  1884. let fullscreen = self.fullscreen;
  1885. let focus = self.focus;
  1886. let transparent = self.transparent;
  1887. let maximized = self.maximized;
  1888. let visible = self.visible;
  1889. let decorations = self.decorations;
  1890. let always_on_top = self.always_on_top;
  1891. let skip_taskbar = self.skip_taskbar;
  1892. literal_struct!(
  1893. tokens,
  1894. WindowConfig,
  1895. label,
  1896. url,
  1897. file_drop_enabled,
  1898. center,
  1899. x,
  1900. y,
  1901. width,
  1902. height,
  1903. min_width,
  1904. min_height,
  1905. max_width,
  1906. max_height,
  1907. resizable,
  1908. title,
  1909. fullscreen,
  1910. focus,
  1911. transparent,
  1912. maximized,
  1913. visible,
  1914. decorations,
  1915. always_on_top,
  1916. skip_taskbar
  1917. );
  1918. }
  1919. }
  1920. impl ToTokens for CliArg {
  1921. fn to_tokens(&self, tokens: &mut TokenStream) {
  1922. let short = opt_lit(self.short.as_ref());
  1923. let name = str_lit(&self.name);
  1924. let description = opt_str_lit(self.description.as_ref());
  1925. let long_description = opt_str_lit(self.long_description.as_ref());
  1926. let takes_value = opt_lit(self.takes_value.as_ref());
  1927. let multiple = opt_lit(self.multiple.as_ref());
  1928. let multiple_occurrences = opt_lit(self.multiple_occurrences.as_ref());
  1929. let number_of_values = opt_lit(self.number_of_values.as_ref());
  1930. let possible_values = opt_vec_str_lit(self.possible_values.as_ref());
  1931. let min_values = opt_lit(self.min_values.as_ref());
  1932. let max_values = opt_lit(self.max_values.as_ref());
  1933. let required = opt_lit(self.required.as_ref());
  1934. let required_unless_present = opt_str_lit(self.required_unless_present.as_ref());
  1935. let required_unless_present_all = opt_vec_str_lit(self.required_unless_present_all.as_ref());
  1936. let required_unless_present_any = opt_vec_str_lit(self.required_unless_present_any.as_ref());
  1937. let conflicts_with = opt_str_lit(self.conflicts_with.as_ref());
  1938. let conflicts_with_all = opt_vec_str_lit(self.conflicts_with_all.as_ref());
  1939. let requires = opt_str_lit(self.requires.as_ref());
  1940. let requires_all = opt_vec_str_lit(self.requires_all.as_ref());
  1941. let requires_if = opt_vec_str_lit(self.requires_if.as_ref());
  1942. let required_if_eq = opt_vec_str_lit(self.required_if_eq.as_ref());
  1943. let require_equals = opt_lit(self.require_equals.as_ref());
  1944. let index = opt_lit(self.index.as_ref());
  1945. literal_struct!(
  1946. tokens,
  1947. CliArg,
  1948. short,
  1949. name,
  1950. description,
  1951. long_description,
  1952. takes_value,
  1953. multiple,
  1954. multiple_occurrences,
  1955. number_of_values,
  1956. possible_values,
  1957. min_values,
  1958. max_values,
  1959. required,
  1960. required_unless_present,
  1961. required_unless_present_all,
  1962. required_unless_present_any,
  1963. conflicts_with,
  1964. conflicts_with_all,
  1965. requires,
  1966. requires_all,
  1967. requires_if,
  1968. required_if_eq,
  1969. require_equals,
  1970. index
  1971. );
  1972. }
  1973. }
  1974. impl ToTokens for CliConfig {
  1975. fn to_tokens(&self, tokens: &mut TokenStream) {
  1976. let description = opt_str_lit(self.description.as_ref());
  1977. let long_description = opt_str_lit(self.long_description.as_ref());
  1978. let before_help = opt_str_lit(self.before_help.as_ref());
  1979. let after_help = opt_str_lit(self.after_help.as_ref());
  1980. let args = {
  1981. let args = self.args.as_ref().map(|args| {
  1982. let arg = args.iter().map(|a| quote! { #a });
  1983. quote! { vec![#(#arg),*] }
  1984. });
  1985. opt_lit(args.as_ref())
  1986. };
  1987. let subcommands = opt_lit(
  1988. self
  1989. .subcommands
  1990. .as_ref()
  1991. .map(|map| {
  1992. map_lit(
  1993. quote! { ::std::collections::HashMap },
  1994. map,
  1995. str_lit,
  1996. identity,
  1997. )
  1998. })
  1999. .as_ref(),
  2000. );
  2001. literal_struct!(
  2002. tokens,
  2003. CliConfig,
  2004. description,
  2005. long_description,
  2006. before_help,
  2007. after_help,
  2008. args,
  2009. subcommands
  2010. );
  2011. }
  2012. }
  2013. impl ToTokens for PatternKind {
  2014. fn to_tokens(&self, tokens: &mut TokenStream) {
  2015. let prefix = quote! { ::tauri::utils::config::PatternKind };
  2016. tokens.append_all(match self {
  2017. Self::Brownfield => quote! { #prefix::Brownfield },
  2018. #[cfg(feature = "isolation")]
  2019. Self::Isolation { dir } => {
  2020. let dir = path_buf_lit(dir);
  2021. quote! { #prefix::Isolation { dir: #dir } }
  2022. }
  2023. })
  2024. }
  2025. }
  2026. impl ToTokens for WindowsConfig {
  2027. fn to_tokens(&self, tokens: &mut TokenStream) {
  2028. let webview_fixed_runtime_path = opt_lit(
  2029. self
  2030. .webview_fixed_runtime_path
  2031. .as_ref()
  2032. .map(path_buf_lit)
  2033. .as_ref(),
  2034. );
  2035. tokens.append_all(quote! { ::tauri::utils::config::WindowsConfig {
  2036. webview_fixed_runtime_path: #webview_fixed_runtime_path,
  2037. ..Default::default()
  2038. }})
  2039. }
  2040. }
  2041. impl ToTokens for BundleConfig {
  2042. fn to_tokens(&self, tokens: &mut TokenStream) {
  2043. let identifier = str_lit(&self.identifier);
  2044. let icon = vec_lit(&self.icon, str_lit);
  2045. let active = self.active;
  2046. let targets = quote!(None);
  2047. let resources = quote!(None);
  2048. let copyright = quote!(None);
  2049. let category = quote!(None);
  2050. let short_description = quote!(None);
  2051. let long_description = quote!(None);
  2052. let deb = quote!(Default::default());
  2053. let macos = quote!(Default::default());
  2054. let external_bin = opt_vec_str_lit(self.external_bin.as_ref());
  2055. let windows = &self.windows;
  2056. literal_struct!(
  2057. tokens,
  2058. BundleConfig,
  2059. active,
  2060. identifier,
  2061. icon,
  2062. targets,
  2063. resources,
  2064. copyright,
  2065. category,
  2066. short_description,
  2067. long_description,
  2068. deb,
  2069. macos,
  2070. external_bin,
  2071. windows
  2072. );
  2073. }
  2074. }
  2075. impl ToTokens for AppUrl {
  2076. fn to_tokens(&self, tokens: &mut TokenStream) {
  2077. let prefix = quote! { ::tauri::utils::config::AppUrl };
  2078. tokens.append_all(match self {
  2079. Self::Url(url) => {
  2080. quote! { #prefix::Url(#url) }
  2081. }
  2082. Self::Files(files) => {
  2083. let files = vec_lit(files, path_buf_lit);
  2084. quote! { #prefix::Files(#files) }
  2085. }
  2086. })
  2087. }
  2088. }
  2089. impl ToTokens for BuildConfig {
  2090. fn to_tokens(&self, tokens: &mut TokenStream) {
  2091. let dev_path = &self.dev_path;
  2092. let dist_dir = &self.dist_dir;
  2093. let with_global_tauri = self.with_global_tauri;
  2094. let runner = quote!(None);
  2095. let before_dev_command = quote!(None);
  2096. let before_build_command = quote!(None);
  2097. let features = quote!(None);
  2098. literal_struct!(
  2099. tokens,
  2100. BuildConfig,
  2101. runner,
  2102. dev_path,
  2103. dist_dir,
  2104. with_global_tauri,
  2105. before_dev_command,
  2106. before_build_command,
  2107. features
  2108. );
  2109. }
  2110. }
  2111. impl ToTokens for UpdaterConfig {
  2112. fn to_tokens(&self, tokens: &mut TokenStream) {
  2113. let active = self.active;
  2114. let dialog = self.dialog;
  2115. let pubkey = str_lit(&self.pubkey);
  2116. let endpoints = opt_lit(
  2117. self
  2118. .endpoints
  2119. .as_ref()
  2120. .map(|list| {
  2121. vec_lit(list, |url| {
  2122. let url = url.0.as_str();
  2123. quote! { ::tauri::utils::config::UpdaterEndpoint(#url.parse().unwrap()) }
  2124. })
  2125. })
  2126. .as_ref(),
  2127. );
  2128. literal_struct!(tokens, UpdaterConfig, active, dialog, pubkey, endpoints);
  2129. }
  2130. }
  2131. impl ToTokens for SecurityConfig {
  2132. fn to_tokens(&self, tokens: &mut TokenStream) {
  2133. let csp = opt_str_lit(self.csp.as_ref());
  2134. let dev_csp = opt_str_lit(self.dev_csp.as_ref());
  2135. let freeze_prototype = self.freeze_prototype;
  2136. literal_struct!(tokens, SecurityConfig, csp, dev_csp, freeze_prototype);
  2137. }
  2138. }
  2139. impl ToTokens for SystemTrayConfig {
  2140. fn to_tokens(&self, tokens: &mut TokenStream) {
  2141. let icon_as_template = self.icon_as_template;
  2142. let icon_path = path_buf_lit(&self.icon_path);
  2143. literal_struct!(tokens, SystemTrayConfig, icon_path, icon_as_template);
  2144. }
  2145. }
  2146. impl ToTokens for FsAllowlistScope {
  2147. fn to_tokens(&self, tokens: &mut TokenStream) {
  2148. let allowed_paths = vec_lit(&self.0, path_buf_lit);
  2149. tokens.append_all(quote! { ::tauri::utils::config::FsAllowlistScope(#allowed_paths) })
  2150. }
  2151. }
  2152. impl ToTokens for FsAllowlistConfig {
  2153. fn to_tokens(&self, tokens: &mut TokenStream) {
  2154. let scope = &self.scope;
  2155. tokens.append_all(quote! { ::tauri::utils::config::FsAllowlistConfig { scope: #scope, ..Default::default() } })
  2156. }
  2157. }
  2158. impl ToTokens for ProtocolAllowlistConfig {
  2159. fn to_tokens(&self, tokens: &mut TokenStream) {
  2160. let asset_scope = &self.asset_scope;
  2161. tokens.append_all(quote! { ::tauri::utils::config::ProtocolAllowlistConfig { asset_scope: #asset_scope, ..Default::default() } })
  2162. }
  2163. }
  2164. impl ToTokens for HttpAllowlistScope {
  2165. fn to_tokens(&self, tokens: &mut TokenStream) {
  2166. let allowed_urls = vec_lit(&self.0, url_lit);
  2167. tokens.append_all(quote! { ::tauri::utils::config::HttpAllowlistScope(#allowed_urls) })
  2168. }
  2169. }
  2170. impl ToTokens for HttpAllowlistConfig {
  2171. fn to_tokens(&self, tokens: &mut TokenStream) {
  2172. let scope = &self.scope;
  2173. tokens.append_all(quote! { ::tauri::utils::config::HttpAllowlistConfig { scope: #scope, ..Default::default() } })
  2174. }
  2175. }
  2176. impl ToTokens for ShellAllowedCommand {
  2177. fn to_tokens(&self, tokens: &mut TokenStream) {
  2178. let name = str_lit(&self.name);
  2179. let command = path_buf_lit(&self.command);
  2180. let args = &self.args;
  2181. let sidecar = &self.sidecar;
  2182. literal_struct!(tokens, ShellAllowedCommand, name, command, args, sidecar);
  2183. }
  2184. }
  2185. impl ToTokens for ShellAllowedArgs {
  2186. fn to_tokens(&self, tokens: &mut TokenStream) {
  2187. let prefix = quote! { ::tauri::utils::config::ShellAllowedArgs };
  2188. tokens.append_all(match self {
  2189. Self::Flag(flag) => quote!(#prefix::Flag(#flag)),
  2190. Self::List(list) => {
  2191. let list = vec_lit(list, identity);
  2192. quote!(#prefix::List(#list))
  2193. }
  2194. })
  2195. }
  2196. }
  2197. impl ToTokens for ShellAllowedArg {
  2198. fn to_tokens(&self, tokens: &mut TokenStream) {
  2199. let prefix = quote! { ::tauri::utils::config::ShellAllowedArg };
  2200. tokens.append_all(match self {
  2201. Self::Fixed(fixed) => {
  2202. let fixed = str_lit(fixed);
  2203. quote!(#prefix::Fixed(#fixed))
  2204. }
  2205. Self::Var { name, validate } => {
  2206. let name = str_lit(name);
  2207. let validate = opt_str_lit(validate.as_ref());
  2208. quote!(#prefix::Var { name: #name, validate: #validate })
  2209. }
  2210. })
  2211. }
  2212. }
  2213. impl ToTokens for ShellAllowlistOpen {
  2214. fn to_tokens(&self, tokens: &mut TokenStream) {
  2215. let prefix = quote! { ::tauri::utils::config::ShellAllowlistOpen };
  2216. tokens.append_all(match self {
  2217. Self::Flag(flag) => quote!(#prefix::Flag(#flag)),
  2218. Self::Validate(regex) => quote!(#prefix::Validate(#regex)),
  2219. })
  2220. }
  2221. }
  2222. impl ToTokens for ShellAllowlistScope {
  2223. fn to_tokens(&self, tokens: &mut TokenStream) {
  2224. let allowed_commands = vec_lit(&self.0, identity);
  2225. tokens.append_all(quote! { ::tauri::utils::config::ShellAllowlistScope(#allowed_commands) })
  2226. }
  2227. }
  2228. impl ToTokens for ShellAllowlistConfig {
  2229. fn to_tokens(&self, tokens: &mut TokenStream) {
  2230. let scope = &self.scope;
  2231. tokens.append_all(quote! { ::tauri::utils::config::ShellAllowlistConfig { scope: #scope, ..Default::default() } })
  2232. }
  2233. }
  2234. impl ToTokens for AllowlistConfig {
  2235. fn to_tokens(&self, tokens: &mut TokenStream) {
  2236. let fs = &self.fs;
  2237. let protocol = &self.protocol;
  2238. let http = &self.http;
  2239. let shell = &self.shell;
  2240. tokens.append_all(
  2241. quote! { ::tauri::utils::config::AllowlistConfig { fs: #fs, protocol: #protocol, http: #http, shell: #shell, ..Default::default() } },
  2242. )
  2243. }
  2244. }
  2245. impl ToTokens for TauriConfig {
  2246. fn to_tokens(&self, tokens: &mut TokenStream) {
  2247. let pattern = &self.pattern;
  2248. let windows = vec_lit(&self.windows, identity);
  2249. let cli = opt_lit(self.cli.as_ref());
  2250. let bundle = &self.bundle;
  2251. let updater = &self.updater;
  2252. let security = &self.security;
  2253. let system_tray = opt_lit(self.system_tray.as_ref());
  2254. let allowlist = &self.allowlist;
  2255. let macos_private_api = self.macos_private_api;
  2256. literal_struct!(
  2257. tokens,
  2258. TauriConfig,
  2259. pattern,
  2260. windows,
  2261. cli,
  2262. bundle,
  2263. updater,
  2264. security,
  2265. system_tray,
  2266. allowlist,
  2267. macos_private_api
  2268. );
  2269. }
  2270. }
  2271. impl ToTokens for PluginConfig {
  2272. fn to_tokens(&self, tokens: &mut TokenStream) {
  2273. let config = map_lit(
  2274. quote! { ::std::collections::HashMap },
  2275. &self.0,
  2276. str_lit,
  2277. json_value_lit,
  2278. );
  2279. tokens.append_all(quote! { ::tauri::utils::config::PluginConfig(#config) })
  2280. }
  2281. }
  2282. impl ToTokens for PackageConfig {
  2283. fn to_tokens(&self, tokens: &mut TokenStream) {
  2284. let product_name = opt_str_lit(self.product_name.as_ref());
  2285. let version = opt_str_lit(self.version.as_ref());
  2286. literal_struct!(tokens, PackageConfig, product_name, version);
  2287. }
  2288. }
  2289. impl ToTokens for Config {
  2290. fn to_tokens(&self, tokens: &mut TokenStream) {
  2291. let package = &self.package;
  2292. let tauri = &self.tauri;
  2293. let build = &self.build;
  2294. let plugins = &self.plugins;
  2295. literal_struct!(tokens, Config, package, tauri, build, plugins);
  2296. }
  2297. }
  2298. }
  2299. #[cfg(test)]
  2300. mod test {
  2301. use super::*;
  2302. // TODO: create a test that compares a config to a json config
  2303. #[test]
  2304. // test all of the default functions
  2305. fn test_defaults() {
  2306. // get default tauri config
  2307. let t_config = TauriConfig::default();
  2308. // get default build config
  2309. let b_config = BuildConfig::default();
  2310. // get default dev path
  2311. let d_path = default_dev_path();
  2312. // get default window
  2313. let d_windows = default_window_config();
  2314. // get default title
  2315. let d_title = default_title();
  2316. // get default bundle
  2317. let d_bundle = BundleConfig::default();
  2318. // get default updater
  2319. let d_updater = UpdaterConfig::default();
  2320. // create a tauri config.
  2321. let tauri = TauriConfig {
  2322. pattern: Default::default(),
  2323. windows: vec![WindowConfig {
  2324. label: "main".to_string(),
  2325. url: WindowUrl::default(),
  2326. file_drop_enabled: true,
  2327. center: false,
  2328. x: None,
  2329. y: None,
  2330. width: 800f64,
  2331. height: 600f64,
  2332. min_width: None,
  2333. min_height: None,
  2334. max_width: None,
  2335. max_height: None,
  2336. resizable: true,
  2337. title: String::from("Tauri App"),
  2338. fullscreen: false,
  2339. focus: false,
  2340. transparent: false,
  2341. maximized: false,
  2342. visible: true,
  2343. decorations: true,
  2344. always_on_top: false,
  2345. skip_taskbar: false,
  2346. }],
  2347. bundle: BundleConfig {
  2348. active: false,
  2349. targets: None,
  2350. identifier: String::from(""),
  2351. icon: Vec::new(),
  2352. resources: None,
  2353. copyright: None,
  2354. category: None,
  2355. short_description: None,
  2356. long_description: None,
  2357. deb: Default::default(),
  2358. macos: Default::default(),
  2359. external_bin: None,
  2360. windows: Default::default(),
  2361. },
  2362. cli: None,
  2363. updater: UpdaterConfig {
  2364. active: false,
  2365. dialog: true,
  2366. pubkey: "".into(),
  2367. endpoints: None,
  2368. },
  2369. security: SecurityConfig {
  2370. csp: None,
  2371. dev_csp: None,
  2372. freeze_prototype: true,
  2373. },
  2374. allowlist: AllowlistConfig::default(),
  2375. system_tray: None,
  2376. macos_private_api: false,
  2377. };
  2378. // create a build config
  2379. let build = BuildConfig {
  2380. runner: None,
  2381. dev_path: AppUrl::Url(WindowUrl::External(
  2382. Url::parse("http://localhost:8080").unwrap(),
  2383. )),
  2384. dist_dir: AppUrl::Url(WindowUrl::App("../dist".into())),
  2385. before_dev_command: None,
  2386. before_build_command: None,
  2387. features: None,
  2388. with_global_tauri: false,
  2389. };
  2390. // test the configs
  2391. assert_eq!(t_config, tauri);
  2392. assert_eq!(b_config, build);
  2393. assert_eq!(d_bundle, tauri.bundle);
  2394. assert_eq!(d_updater, tauri.updater);
  2395. assert_eq!(
  2396. d_path,
  2397. AppUrl::Url(WindowUrl::External(
  2398. Url::parse("http://localhost:8080").unwrap()
  2399. ))
  2400. );
  2401. assert_eq!(d_title, tauri.windows[0].title);
  2402. assert_eq!(d_windows, tauri.windows);
  2403. }
  2404. }