config.rs 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276
  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 std::fmt::Display for WindowUrl {
  35. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::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, Default, 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. }
  526. /// Defines an allowlist type.
  527. pub trait Allowlist {
  528. /// Returns all features associated with the allowlist struct.
  529. fn all_features() -> Vec<&'static str>;
  530. /// Returns the tauri features enabled on this allowlist.
  531. fn to_features(&self) -> Vec<&'static str>;
  532. }
  533. macro_rules! check_feature {
  534. ($self:ident, $features:ident, $flag:ident, $feature_name: expr) => {
  535. if $self.$flag {
  536. $features.push($feature_name)
  537. }
  538. };
  539. }
  540. /// Filesystem scope definition.
  541. /// It is a list of glob patterns that restrict the API access from the webview.
  542. /// Each pattern can start with a variable that resolves to a system base directory.
  543. /// The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`,
  544. /// `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`,
  545. /// `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$APP`, `$CWD`.
  546. #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
  547. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  548. pub struct FsAllowlistScope(pub Vec<PathBuf>);
  549. impl Default for FsAllowlistScope {
  550. fn default() -> Self {
  551. Self(vec!["$APP/**".into()])
  552. }
  553. }
  554. /// Allowlist for the file system APIs.
  555. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  556. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  557. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  558. pub struct FsAllowlistConfig {
  559. /// The access scope for the filesystem APIs.
  560. #[serde(default)]
  561. pub scope: FsAllowlistScope,
  562. /// Use this flag to enable all file system API features.
  563. #[serde(default)]
  564. pub all: bool,
  565. /// Read file from local filesystem.
  566. #[serde(default)]
  567. pub read_file: bool,
  568. /// Write file to local filesystem.
  569. #[serde(default)]
  570. pub write_file: bool,
  571. /// Read directory from local filesystem.
  572. #[serde(default)]
  573. pub read_dir: bool,
  574. /// Copy file from local filesystem.
  575. #[serde(default)]
  576. pub copy_file: bool,
  577. /// Create directory from local filesystem.
  578. #[serde(default)]
  579. pub create_dir: bool,
  580. /// Remove directory from local filesystem.
  581. #[serde(default)]
  582. pub remove_dir: bool,
  583. /// Remove file from local filesystem.
  584. #[serde(default)]
  585. pub remove_file: bool,
  586. /// Rename file from local filesystem.
  587. #[serde(default)]
  588. pub rename_file: bool,
  589. }
  590. impl Allowlist for FsAllowlistConfig {
  591. fn all_features() -> Vec<&'static str> {
  592. let allowlist = Self {
  593. scope: Default::default(),
  594. all: false,
  595. read_file: true,
  596. write_file: true,
  597. read_dir: true,
  598. copy_file: true,
  599. create_dir: true,
  600. remove_dir: true,
  601. remove_file: true,
  602. rename_file: true,
  603. };
  604. let mut features = allowlist.to_features();
  605. features.push("fs-all");
  606. features
  607. }
  608. fn to_features(&self) -> Vec<&'static str> {
  609. if self.all {
  610. vec!["fs-all"]
  611. } else {
  612. let mut features = Vec::new();
  613. check_feature!(self, features, read_file, "fs-read-file");
  614. check_feature!(self, features, write_file, "fs-write-file");
  615. check_feature!(self, features, read_dir, "fs-read-dir");
  616. check_feature!(self, features, copy_file, "fs-copy-file");
  617. check_feature!(self, features, create_dir, "fs-create-dir");
  618. check_feature!(self, features, remove_dir, "fs-remove-dir");
  619. check_feature!(self, features, remove_file, "fs-remove-file");
  620. check_feature!(self, features, rename_file, "fs-rename-file");
  621. features
  622. }
  623. }
  624. }
  625. /// Allowlist for the window APIs.
  626. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  627. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  628. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  629. pub struct WindowAllowlistConfig {
  630. /// Use this flag to enable all window API features.
  631. #[serde(default)]
  632. pub all: bool,
  633. /// Allows dynamic window creation.
  634. #[serde(default)]
  635. pub create: bool,
  636. /// Allows centering the window.
  637. #[serde(default)]
  638. pub center: bool,
  639. /// Allows requesting user attention on the window.
  640. #[serde(default)]
  641. pub request_user_attention: bool,
  642. /// Allows setting the resizable flag of the window.
  643. #[serde(default)]
  644. pub set_resizable: bool,
  645. /// Allows changing the window title.
  646. #[serde(default)]
  647. pub set_title: bool,
  648. /// Allows maximizing the window.
  649. #[serde(default)]
  650. pub maximize: bool,
  651. /// Allows unmaximizing the window.
  652. #[serde(default)]
  653. pub unmaximize: bool,
  654. /// Allows minimizing the window.
  655. #[serde(default)]
  656. pub minimize: bool,
  657. /// Allows unminimizing the window.
  658. #[serde(default)]
  659. pub unminimize: bool,
  660. /// Allows showing the window.
  661. #[serde(default)]
  662. pub show: bool,
  663. /// Allows hiding the window.
  664. #[serde(default)]
  665. pub hide: bool,
  666. /// Allows closing the window.
  667. #[serde(default)]
  668. pub close: bool,
  669. /// Allows setting the decorations flag of the window.
  670. #[serde(default)]
  671. pub set_decorations: bool,
  672. /// Allows setting the always_on_top flag of the window.
  673. #[serde(default)]
  674. pub set_always_on_top: bool,
  675. /// Allows setting the window size.
  676. #[serde(default)]
  677. pub set_size: bool,
  678. /// Allows setting the window minimum size.
  679. #[serde(default)]
  680. pub set_min_size: bool,
  681. /// Allows setting the window maximum size.
  682. #[serde(default)]
  683. pub set_max_size: bool,
  684. /// Allows changing the position of the window.
  685. #[serde(default)]
  686. pub set_position: bool,
  687. /// Allows setting the fullscreen flag of the window.
  688. #[serde(default)]
  689. pub set_fullscreen: bool,
  690. /// Allows focusing the window.
  691. #[serde(default)]
  692. pub set_focus: bool,
  693. /// Allows changing the window icon.
  694. #[serde(default)]
  695. pub set_icon: bool,
  696. /// Allows setting the skip_taskbar flag of the window.
  697. #[serde(default)]
  698. pub set_skip_taskbar: bool,
  699. /// Allows start dragging on the window.
  700. #[serde(default)]
  701. pub start_dragging: bool,
  702. /// Allows opening the system dialog to print the window content.
  703. #[serde(default)]
  704. pub print: bool,
  705. }
  706. impl Allowlist for WindowAllowlistConfig {
  707. fn all_features() -> Vec<&'static str> {
  708. let allowlist = Self {
  709. all: false,
  710. create: true,
  711. center: true,
  712. request_user_attention: true,
  713. set_resizable: true,
  714. set_title: true,
  715. maximize: true,
  716. unmaximize: true,
  717. minimize: true,
  718. unminimize: true,
  719. show: true,
  720. hide: true,
  721. close: true,
  722. set_decorations: true,
  723. set_always_on_top: true,
  724. set_size: true,
  725. set_min_size: true,
  726. set_max_size: true,
  727. set_position: true,
  728. set_fullscreen: true,
  729. set_focus: true,
  730. set_icon: true,
  731. set_skip_taskbar: true,
  732. start_dragging: true,
  733. print: true,
  734. };
  735. let mut features = allowlist.to_features();
  736. features.push("window-all");
  737. features
  738. }
  739. fn to_features(&self) -> Vec<&'static str> {
  740. if self.all {
  741. vec!["window-all"]
  742. } else {
  743. let mut features = Vec::new();
  744. check_feature!(self, features, create, "window-create");
  745. check_feature!(self, features, center, "window-center");
  746. check_feature!(
  747. self,
  748. features,
  749. request_user_attention,
  750. "window-request-user-attention"
  751. );
  752. check_feature!(self, features, set_resizable, "window-set-resizable");
  753. check_feature!(self, features, set_title, "window-set-title");
  754. check_feature!(self, features, maximize, "window-maximize");
  755. check_feature!(self, features, unmaximize, "window-unmaximize");
  756. check_feature!(self, features, minimize, "window-minimize");
  757. check_feature!(self, features, unminimize, "window-unminimize");
  758. check_feature!(self, features, show, "window-show");
  759. check_feature!(self, features, hide, "window-hide");
  760. check_feature!(self, features, close, "window-close");
  761. check_feature!(self, features, set_decorations, "window-set-decorations");
  762. check_feature!(
  763. self,
  764. features,
  765. set_always_on_top,
  766. "window-set-always-on-top"
  767. );
  768. check_feature!(self, features, set_size, "window-set-size");
  769. check_feature!(self, features, set_min_size, "window-set-min-size");
  770. check_feature!(self, features, set_max_size, "window-set-max-size");
  771. check_feature!(self, features, set_position, "window-set-position");
  772. check_feature!(self, features, set_fullscreen, "window-set-fullscreen");
  773. check_feature!(self, features, set_focus, "window-set-focus");
  774. check_feature!(self, features, set_icon, "window-set-icon");
  775. check_feature!(self, features, set_skip_taskbar, "window-set-skip-taskbar");
  776. check_feature!(self, features, start_dragging, "window-start-dragging");
  777. check_feature!(self, features, print, "window-print");
  778. features
  779. }
  780. }
  781. }
  782. /// Allowlist for the shell APIs.
  783. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  784. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  785. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  786. pub struct ShellAllowlistConfig {
  787. /// Access scope for the binary execution APIs.
  788. /// Sidecars are automatically enabled.
  789. #[serde(default)]
  790. pub scope: FsAllowlistScope,
  791. /// Use this flag to enable all shell API features.
  792. #[serde(default)]
  793. pub all: bool,
  794. /// Enable binary execution.
  795. #[serde(default)]
  796. pub execute: bool,
  797. /// Enable sidecar execution, allowing the JavaScript layer to spawn a sidecar program,
  798. /// an executable that is shipped with the application.
  799. /// For more information see <https://tauri.studio/en/docs/usage/guides/bundler/sidecar>.
  800. #[serde(default)]
  801. pub sidecar: bool,
  802. /// Open URL with the user's default application.
  803. #[serde(default)]
  804. pub open: bool,
  805. }
  806. impl Allowlist for ShellAllowlistConfig {
  807. fn all_features() -> Vec<&'static str> {
  808. let allowlist = Self {
  809. scope: Default::default(),
  810. all: false,
  811. execute: true,
  812. sidecar: true,
  813. open: true,
  814. };
  815. let mut features = allowlist.to_features();
  816. features.push("shell-all");
  817. features
  818. }
  819. fn to_features(&self) -> Vec<&'static str> {
  820. if self.all {
  821. vec!["shell-all"]
  822. } else {
  823. let mut features = Vec::new();
  824. check_feature!(self, features, execute, "shell-execute");
  825. check_feature!(self, features, sidecar, "shell-sidecar");
  826. check_feature!(self, features, open, "shell-open");
  827. features
  828. }
  829. }
  830. }
  831. /// Allowlist for the dialog APIs.
  832. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  833. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  834. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  835. pub struct DialogAllowlistConfig {
  836. /// Use this flag to enable all dialog API features.
  837. #[serde(default)]
  838. pub all: bool,
  839. /// Allows the API to open a dialog window to pick files.
  840. #[serde(default)]
  841. pub open: bool,
  842. /// Allows the API to open a dialog window to pick where to save files.
  843. #[serde(default)]
  844. pub save: bool,
  845. /// Allows the API to show a message dialog window.
  846. #[serde(default)]
  847. pub message: bool,
  848. /// Allows the API to show a dialog window with Yes/No buttons.
  849. #[serde(default)]
  850. pub ask: bool,
  851. /// Allows the API to show a dialog window with Ok/Cancel buttons.
  852. #[serde(default)]
  853. pub confirm: bool,
  854. }
  855. impl Allowlist for DialogAllowlistConfig {
  856. fn all_features() -> Vec<&'static str> {
  857. let allowlist = Self {
  858. all: false,
  859. open: true,
  860. save: true,
  861. message: true,
  862. ask: true,
  863. confirm: true,
  864. };
  865. let mut features = allowlist.to_features();
  866. features.push("dialog-all");
  867. features
  868. }
  869. fn to_features(&self) -> Vec<&'static str> {
  870. if self.all {
  871. vec!["dialog-all"]
  872. } else {
  873. let mut features = Vec::new();
  874. check_feature!(self, features, open, "dialog-open");
  875. check_feature!(self, features, save, "dialog-save");
  876. check_feature!(self, features, message, "dialog-message");
  877. check_feature!(self, features, ask, "dialog-ask");
  878. check_feature!(self, features, confirm, "dialog-confirm");
  879. features
  880. }
  881. }
  882. }
  883. /// HTTP API scope definition.
  884. /// It is a list of URLs that can be accessed by the webview when using the HTTP APIs.
  885. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  886. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  887. pub struct HttpAllowlistScope(pub Vec<Url>);
  888. /// Allowlist for the HTTP APIs.
  889. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  890. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  891. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  892. pub struct HttpAllowlistConfig {
  893. /// The access scope for the HTTP APIs.
  894. #[serde(default)]
  895. pub scope: HttpAllowlistScope,
  896. /// Use this flag to enable all HTTP API features.
  897. #[serde(default)]
  898. pub all: bool,
  899. /// Allows making HTTP requests.
  900. #[serde(default)]
  901. pub request: bool,
  902. }
  903. impl Allowlist for HttpAllowlistConfig {
  904. fn all_features() -> Vec<&'static str> {
  905. let allowlist = Self {
  906. scope: Default::default(),
  907. all: false,
  908. request: true,
  909. };
  910. let mut features = allowlist.to_features();
  911. features.push("http-all");
  912. features
  913. }
  914. fn to_features(&self) -> Vec<&'static str> {
  915. if self.all {
  916. vec!["http-all"]
  917. } else {
  918. let mut features = Vec::new();
  919. check_feature!(self, features, request, "http-request");
  920. features
  921. }
  922. }
  923. }
  924. /// Allowlist for the notification APIs.
  925. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  926. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  927. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  928. pub struct NotificationAllowlistConfig {
  929. /// Use this flag to enable all notification API features.
  930. #[serde(default)]
  931. pub all: bool,
  932. }
  933. impl Allowlist for NotificationAllowlistConfig {
  934. fn all_features() -> Vec<&'static str> {
  935. let allowlist = Self { all: false };
  936. let mut features = allowlist.to_features();
  937. features.push("notification-all");
  938. features
  939. }
  940. fn to_features(&self) -> Vec<&'static str> {
  941. if self.all {
  942. vec!["notification-all"]
  943. } else {
  944. vec![]
  945. }
  946. }
  947. }
  948. /// Allowlist for the global shortcut APIs.
  949. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  950. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  951. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  952. pub struct GlobalShortcutAllowlistConfig {
  953. /// Use this flag to enable all global shortcut API features.
  954. #[serde(default)]
  955. pub all: bool,
  956. }
  957. impl Allowlist for GlobalShortcutAllowlistConfig {
  958. fn all_features() -> Vec<&'static str> {
  959. let allowlist = Self { all: false };
  960. let mut features = allowlist.to_features();
  961. features.push("global-shortcut-all");
  962. features
  963. }
  964. fn to_features(&self) -> Vec<&'static str> {
  965. if self.all {
  966. vec!["global-shortcut-all"]
  967. } else {
  968. vec![]
  969. }
  970. }
  971. }
  972. /// Allowlist for the OS APIs.
  973. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  974. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  975. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  976. pub struct OsAllowlistConfig {
  977. /// Use this flag to enable all OS API features.
  978. #[serde(default)]
  979. pub all: bool,
  980. }
  981. impl Allowlist for OsAllowlistConfig {
  982. fn all_features() -> Vec<&'static str> {
  983. let allowlist = Self { all: false };
  984. let mut features = allowlist.to_features();
  985. features.push("os-all");
  986. features
  987. }
  988. fn to_features(&self) -> Vec<&'static str> {
  989. if self.all {
  990. vec!["os-all"]
  991. } else {
  992. vec![]
  993. }
  994. }
  995. }
  996. /// Allowlist for the path APIs.
  997. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  998. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  999. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1000. pub struct PathAllowlistConfig {
  1001. /// Use this flag to enable all path API features.
  1002. #[serde(default)]
  1003. pub all: bool,
  1004. }
  1005. impl Allowlist for PathAllowlistConfig {
  1006. fn all_features() -> Vec<&'static str> {
  1007. let allowlist = Self { all: false };
  1008. let mut features = allowlist.to_features();
  1009. features.push("path-all");
  1010. features
  1011. }
  1012. fn to_features(&self) -> Vec<&'static str> {
  1013. if self.all {
  1014. vec!["path-all"]
  1015. } else {
  1016. vec![]
  1017. }
  1018. }
  1019. }
  1020. /// Allowlist for the custom protocols.
  1021. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  1022. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1023. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1024. pub struct ProtocolAllowlistConfig {
  1025. /// The access scope for the asset protocol.
  1026. #[serde(default)]
  1027. pub asset_scope: FsAllowlistScope,
  1028. /// Use this flag to enable all custom protocols.
  1029. #[serde(default)]
  1030. pub all: bool,
  1031. /// Enables the asset protocol.
  1032. #[serde(default)]
  1033. pub asset: bool,
  1034. }
  1035. impl Allowlist for ProtocolAllowlistConfig {
  1036. fn all_features() -> Vec<&'static str> {
  1037. let allowlist = Self {
  1038. asset_scope: Default::default(),
  1039. all: false,
  1040. asset: true,
  1041. };
  1042. let mut features = allowlist.to_features();
  1043. features.push("protocol-all");
  1044. features
  1045. }
  1046. fn to_features(&self) -> Vec<&'static str> {
  1047. if self.all {
  1048. vec!["protocol-all"]
  1049. } else {
  1050. let mut features = Vec::new();
  1051. check_feature!(self, features, asset, "protocol-asset");
  1052. features
  1053. }
  1054. }
  1055. }
  1056. /// Allowlist for the process APIs.
  1057. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  1058. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1059. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1060. pub struct ProcessAllowlistConfig {
  1061. /// Use this flag to enable all process APIs.
  1062. #[serde(default)]
  1063. pub all: bool,
  1064. /// Enables the relaunch API.
  1065. #[serde(default)]
  1066. pub relaunch: bool,
  1067. /// Enables the exit API.
  1068. #[serde(default)]
  1069. pub exit: bool,
  1070. }
  1071. impl Allowlist for ProcessAllowlistConfig {
  1072. fn all_features() -> Vec<&'static str> {
  1073. let allowlist = Self {
  1074. all: false,
  1075. relaunch: true,
  1076. exit: true,
  1077. };
  1078. let mut features = allowlist.to_features();
  1079. features.push("process-all");
  1080. features
  1081. }
  1082. fn to_features(&self) -> Vec<&'static str> {
  1083. if self.all {
  1084. vec!["process-all"]
  1085. } else {
  1086. let mut features = Vec::new();
  1087. check_feature!(self, features, relaunch, "process-relaunch");
  1088. check_feature!(self, features, exit, "process-exit");
  1089. features
  1090. }
  1091. }
  1092. }
  1093. /// Allowlist for the clipboard APIs.
  1094. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  1095. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1096. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1097. pub struct ClipboardAllowlistConfig {
  1098. /// Use this flag to enable all clipboard APIs.
  1099. #[serde(default)]
  1100. pub all: bool,
  1101. /// Enables the clipboard's `writeText` API.
  1102. #[serde(default)]
  1103. pub write_text: bool,
  1104. /// Enables the clipboard's `readText` API.
  1105. #[serde(default)]
  1106. pub read_text: bool,
  1107. }
  1108. impl Allowlist for ClipboardAllowlistConfig {
  1109. fn all_features() -> Vec<&'static str> {
  1110. let allowlist = Self {
  1111. all: false,
  1112. write_text: true,
  1113. read_text: true,
  1114. };
  1115. let mut features = allowlist.to_features();
  1116. features.push("clipboard-all");
  1117. features
  1118. }
  1119. fn to_features(&self) -> Vec<&'static str> {
  1120. if self.all {
  1121. vec!["clipboard-all"]
  1122. } else {
  1123. let mut features = Vec::new();
  1124. check_feature!(self, features, write_text, "clipboard-write-text");
  1125. check_feature!(self, features, read_text, "clipboard-read-text");
  1126. features
  1127. }
  1128. }
  1129. }
  1130. /// Allowlist configuration.
  1131. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  1132. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1133. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1134. pub struct AllowlistConfig {
  1135. /// Use this flag to enable all API features.
  1136. #[serde(default)]
  1137. pub all: bool,
  1138. /// File system API allowlist.
  1139. #[serde(default)]
  1140. pub fs: FsAllowlistConfig,
  1141. /// Window API allowlist.
  1142. #[serde(default)]
  1143. pub window: WindowAllowlistConfig,
  1144. /// Shell API allowlist.
  1145. #[serde(default)]
  1146. pub shell: ShellAllowlistConfig,
  1147. /// Dialog API allowlist.
  1148. #[serde(default)]
  1149. pub dialog: DialogAllowlistConfig,
  1150. /// HTTP API allowlist.
  1151. #[serde(default)]
  1152. pub http: HttpAllowlistConfig,
  1153. /// Notification API allowlist.
  1154. #[serde(default)]
  1155. pub notification: NotificationAllowlistConfig,
  1156. /// Global shortcut API allowlist.
  1157. #[serde(default)]
  1158. pub global_shortcut: GlobalShortcutAllowlistConfig,
  1159. /// OS allowlist.
  1160. #[serde(default)]
  1161. pub os: OsAllowlistConfig,
  1162. /// Path API allowlist.
  1163. #[serde(default)]
  1164. pub path: PathAllowlistConfig,
  1165. /// Custom protocol allowlist.
  1166. #[serde(default)]
  1167. pub protocol: ProtocolAllowlistConfig,
  1168. /// Process API allowlist.
  1169. #[serde(default)]
  1170. pub process: ProcessAllowlistConfig,
  1171. /// Clipboard APIs allowlist.
  1172. #[serde(default)]
  1173. pub clipboard: ClipboardAllowlistConfig,
  1174. }
  1175. impl Allowlist for AllowlistConfig {
  1176. fn all_features() -> Vec<&'static str> {
  1177. let mut features = Vec::new();
  1178. features.extend(FsAllowlistConfig::all_features());
  1179. features.extend(WindowAllowlistConfig::all_features());
  1180. features.extend(ShellAllowlistConfig::all_features());
  1181. features.extend(DialogAllowlistConfig::all_features());
  1182. features.extend(HttpAllowlistConfig::all_features());
  1183. features.extend(NotificationAllowlistConfig::all_features());
  1184. features.extend(GlobalShortcutAllowlistConfig::all_features());
  1185. features.extend(OsAllowlistConfig::all_features());
  1186. features.extend(PathAllowlistConfig::all_features());
  1187. features.extend(ProtocolAllowlistConfig::all_features());
  1188. features.extend(ProcessAllowlistConfig::all_features());
  1189. features.extend(ClipboardAllowlistConfig::all_features());
  1190. features
  1191. }
  1192. fn to_features(&self) -> Vec<&'static str> {
  1193. if self.all {
  1194. vec!["api-all"]
  1195. } else {
  1196. let mut features = Vec::new();
  1197. features.extend(self.fs.to_features());
  1198. features.extend(self.window.to_features());
  1199. features.extend(self.shell.to_features());
  1200. features.extend(self.dialog.to_features());
  1201. features.extend(self.http.to_features());
  1202. features.extend(self.notification.to_features());
  1203. features.extend(self.global_shortcut.to_features());
  1204. features.extend(self.os.to_features());
  1205. features.extend(self.path.to_features());
  1206. features.extend(self.protocol.to_features());
  1207. features
  1208. }
  1209. }
  1210. }
  1211. fn default_window_config() -> Vec<WindowConfig> {
  1212. vec![Default::default()]
  1213. }
  1214. /// The Tauri configuration object.
  1215. #[skip_serializing_none]
  1216. #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
  1217. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1218. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1219. pub struct TauriConfig {
  1220. /// The windows configuration.
  1221. #[serde(default = "default_window_config")]
  1222. pub windows: Vec<WindowConfig>,
  1223. /// The CLI configuration.
  1224. pub cli: Option<CliConfig>,
  1225. /// The bundler configuration.
  1226. #[serde(default)]
  1227. pub bundle: BundleConfig,
  1228. /// The allowlist configuration.
  1229. #[serde(default)]
  1230. pub allowlist: AllowlistConfig,
  1231. /// Security configuration.
  1232. #[serde(default)]
  1233. pub security: SecurityConfig,
  1234. /// The updater configuration.
  1235. #[serde(default)]
  1236. pub updater: UpdaterConfig,
  1237. /// Configuration for app system tray.
  1238. pub system_tray: Option<SystemTrayConfig>,
  1239. /// MacOS private API configuration. Enables the transparent background API and sets the `fullScreenEnabled` preference to `true`.
  1240. #[serde(rename = "macOSPrivateApi", default)]
  1241. pub macos_private_api: bool,
  1242. }
  1243. impl Default for TauriConfig {
  1244. fn default() -> Self {
  1245. Self {
  1246. windows: default_window_config(),
  1247. cli: None,
  1248. bundle: BundleConfig::default(),
  1249. allowlist: AllowlistConfig::default(),
  1250. security: SecurityConfig::default(),
  1251. updater: UpdaterConfig::default(),
  1252. system_tray: None,
  1253. macos_private_api: false,
  1254. }
  1255. }
  1256. }
  1257. impl TauriConfig {
  1258. /// Returns the enabled Cargo features.
  1259. #[allow(dead_code)]
  1260. pub fn features(&self) -> Vec<&str> {
  1261. let mut features = self.allowlist.to_features();
  1262. if self.cli.is_some() {
  1263. features.push("cli");
  1264. }
  1265. if self.updater.active {
  1266. features.push("updater");
  1267. }
  1268. if self.system_tray.is_some() {
  1269. features.push("system-tray");
  1270. }
  1271. if self.macos_private_api {
  1272. features.push("macos-private-api");
  1273. }
  1274. features.sort_unstable();
  1275. features
  1276. }
  1277. }
  1278. /// The Updater configuration object.
  1279. #[skip_serializing_none]
  1280. #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
  1281. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1282. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1283. pub struct UpdaterConfig {
  1284. /// Whether the updater is active or not.
  1285. #[serde(default)]
  1286. pub active: bool,
  1287. /// Display built-in dialog or use event system if disabled.
  1288. #[serde(default = "default_dialog")]
  1289. pub dialog: bool,
  1290. /// The updater endpoints.
  1291. pub endpoints: Option<Vec<String>>,
  1292. /// Signature public key.
  1293. pub pubkey: String,
  1294. }
  1295. impl Default for UpdaterConfig {
  1296. fn default() -> Self {
  1297. Self {
  1298. active: false,
  1299. dialog: default_dialog(),
  1300. endpoints: None,
  1301. pubkey: "".into(),
  1302. }
  1303. }
  1304. }
  1305. /// Configuration for application system tray icon.
  1306. #[skip_serializing_none]
  1307. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  1308. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1309. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1310. pub struct SystemTrayConfig {
  1311. /// Path to the icon to use on the system tray.
  1312. ///
  1313. /// It is forced to be a `.png` file on Linux and macOS, and a `.ico` file on Windows.
  1314. pub icon_path: PathBuf,
  1315. /// 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.
  1316. #[serde(default)]
  1317. pub icon_as_template: bool,
  1318. }
  1319. // We enable the unnecessary_wraps because we need
  1320. // to use an Option for dialog otherwise the CLI schema will mark
  1321. // the dialog as a required field which is not as we default it to true.
  1322. fn default_dialog() -> bool {
  1323. true
  1324. }
  1325. /// The `dev_path` and `dist_dir` options.
  1326. #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
  1327. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1328. #[serde(untagged, deny_unknown_fields)]
  1329. #[non_exhaustive]
  1330. pub enum AppUrl {
  1331. /// The app's external URL, or the path to the directory containing the app assets.
  1332. Url(WindowUrl),
  1333. /// An array of files to embed on the app.
  1334. Files(Vec<PathBuf>),
  1335. }
  1336. impl std::fmt::Display for AppUrl {
  1337. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  1338. match self {
  1339. Self::Url(url) => write!(f, "{}", url),
  1340. Self::Files(files) => write!(f, "{}", serde_json::to_string(files).unwrap()),
  1341. }
  1342. }
  1343. }
  1344. /// The Build configuration object.
  1345. #[skip_serializing_none]
  1346. #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
  1347. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1348. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1349. pub struct BuildConfig {
  1350. /// The binary used to build and run the application.
  1351. pub runner: Option<String>,
  1352. /// The path or URL to use on development.
  1353. #[serde(default = "default_dev_path")]
  1354. pub dev_path: AppUrl,
  1355. /// The path to the app's dist dir. This path must contain your index.html file.
  1356. #[serde(default = "default_dist_dir")]
  1357. pub dist_dir: AppUrl,
  1358. /// A shell command to run before `tauri dev` kicks in.
  1359. ///
  1360. /// The PLATFORM, ARCH, FAMILY, PLATFORM_TYPE and TAURI_DEBUG environment variables are set if you perform conditional compilation.
  1361. pub before_dev_command: Option<String>,
  1362. /// A shell command to run before `tauri build` kicks in.
  1363. ///
  1364. /// The PLATFORM, ARCH, FAMILY, PLATFORM_TYPE and TAURI_DEBUG environment variables are set if you perform conditional compilation.
  1365. pub before_build_command: Option<String>,
  1366. /// Features passed to `cargo` commands.
  1367. pub features: Option<Vec<String>>,
  1368. /// Whether we should inject the Tauri API on `window.__TAURI__` or not.
  1369. #[serde(default)]
  1370. pub with_global_tauri: bool,
  1371. }
  1372. impl Default for BuildConfig {
  1373. fn default() -> Self {
  1374. Self {
  1375. runner: None,
  1376. dev_path: default_dev_path(),
  1377. dist_dir: default_dist_dir(),
  1378. before_dev_command: None,
  1379. before_build_command: None,
  1380. features: None,
  1381. with_global_tauri: false,
  1382. }
  1383. }
  1384. }
  1385. fn default_dev_path() -> AppUrl {
  1386. AppUrl::Url(WindowUrl::External(
  1387. Url::parse("http://localhost:8080").unwrap(),
  1388. ))
  1389. }
  1390. fn default_dist_dir() -> AppUrl {
  1391. AppUrl::Url(WindowUrl::App("../dist".into()))
  1392. }
  1393. #[derive(Debug, PartialEq)]
  1394. struct PackageVersion(String);
  1395. impl<'d> serde::Deserialize<'d> for PackageVersion {
  1396. fn deserialize<D: Deserializer<'d>>(deserializer: D) -> Result<PackageVersion, D::Error> {
  1397. struct PackageVersionVisitor;
  1398. impl<'d> Visitor<'d> for PackageVersionVisitor {
  1399. type Value = PackageVersion;
  1400. fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
  1401. write!(
  1402. formatter,
  1403. "a semver string or a path to a package.json file"
  1404. )
  1405. }
  1406. fn visit_str<E: DeError>(self, value: &str) -> Result<PackageVersion, E> {
  1407. let path = PathBuf::from(value);
  1408. if path.exists() {
  1409. let json_str = read_to_string(&path)
  1410. .map_err(|e| DeError::custom(format!("failed to read version JSON file: {}", e)))?;
  1411. let package_json: serde_json::Value = serde_json::from_str(&json_str)
  1412. .map_err(|e| DeError::custom(format!("failed to read version JSON file: {}", e)))?;
  1413. if let Some(obj) = package_json.as_object() {
  1414. let version = obj
  1415. .get("version")
  1416. .ok_or_else(|| DeError::custom("JSON must contain a `version` field"))?
  1417. .as_str()
  1418. .ok_or_else(|| DeError::custom("`version` must be a string"))?;
  1419. Ok(PackageVersion(version.into()))
  1420. } else {
  1421. Err(DeError::custom("value is not a path to a JSON object"))
  1422. }
  1423. } else {
  1424. Ok(PackageVersion(value.into()))
  1425. }
  1426. }
  1427. }
  1428. deserializer.deserialize_string(PackageVersionVisitor {})
  1429. }
  1430. }
  1431. /// The package configuration.
  1432. #[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
  1433. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1434. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1435. pub struct PackageConfig {
  1436. /// App name.
  1437. pub product_name: Option<String>,
  1438. /// App version. It is a semver version number or a path to a `package.json` file contaning the `version` field.
  1439. #[serde(deserialize_with = "version_deserializer", default)]
  1440. pub version: Option<String>,
  1441. }
  1442. fn version_deserializer<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
  1443. where
  1444. D: Deserializer<'de>,
  1445. {
  1446. Option::<PackageVersion>::deserialize(deserializer).map(|v| v.map(|v| v.0))
  1447. }
  1448. impl PackageConfig {
  1449. /// The binary name.
  1450. #[allow(dead_code)]
  1451. pub fn binary_name(&self) -> Option<String> {
  1452. #[cfg(target_os = "linux")]
  1453. {
  1454. self.product_name.as_ref().map(|n| n.to_kebab_case())
  1455. }
  1456. #[cfg(not(target_os = "linux"))]
  1457. {
  1458. self.product_name.clone()
  1459. }
  1460. }
  1461. }
  1462. /// The config type mapped to `tauri.conf.json`.
  1463. #[skip_serializing_none]
  1464. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  1465. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1466. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1467. pub struct Config {
  1468. /// Package settings.
  1469. #[serde(default)]
  1470. pub package: PackageConfig,
  1471. /// The Tauri configuration.
  1472. #[serde(default)]
  1473. pub tauri: TauriConfig,
  1474. /// The build configuration.
  1475. #[serde(default = "default_build")]
  1476. pub build: BuildConfig,
  1477. /// The plugins config.
  1478. #[serde(default)]
  1479. pub plugins: PluginConfig,
  1480. }
  1481. /// The plugin configs holds a HashMap mapping a plugin name to its configuration object.
  1482. #[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
  1483. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1484. pub struct PluginConfig(pub HashMap<String, JsonValue>);
  1485. fn default_build() -> BuildConfig {
  1486. BuildConfig {
  1487. runner: None,
  1488. dev_path: default_dev_path(),
  1489. dist_dir: default_dist_dir(),
  1490. before_dev_command: None,
  1491. before_build_command: None,
  1492. features: None,
  1493. with_global_tauri: false,
  1494. }
  1495. }
  1496. /// Implement `ToTokens` for all config structs, allowing a literal `Config` to be built.
  1497. ///
  1498. /// This allows for a build script to output the values in a `Config` to a `TokenStream`, which can
  1499. /// then be consumed by another crate. Useful for passing a config to both the build script and the
  1500. /// application using tauri while only parsing it once (in the build script).
  1501. #[cfg(feature = "build")]
  1502. mod build {
  1503. use std::{convert::identity, path::Path};
  1504. use proc_macro2::TokenStream;
  1505. use quote::{quote, ToTokens, TokenStreamExt};
  1506. use super::*;
  1507. use serde_json::Value as JsonValue;
  1508. /// Create a `String` constructor `TokenStream`.
  1509. ///
  1510. /// e.g. `"Hello World" -> String::from("Hello World").
  1511. /// This takes a `&String` to reduce casting all the `&String` -> `&str` manually.
  1512. fn str_lit(s: impl AsRef<str>) -> TokenStream {
  1513. let s = s.as_ref();
  1514. quote! { #s.into() }
  1515. }
  1516. /// Create an `Option` constructor `TokenStream`.
  1517. fn opt_lit(item: Option<&impl ToTokens>) -> TokenStream {
  1518. match item {
  1519. None => quote! { ::core::option::Option::None },
  1520. Some(item) => quote! { ::core::option::Option::Some(#item) },
  1521. }
  1522. }
  1523. /// Helper function to combine an `opt_lit` with `str_lit`.
  1524. fn opt_str_lit(item: Option<impl AsRef<str>>) -> TokenStream {
  1525. opt_lit(item.map(str_lit).as_ref())
  1526. }
  1527. /// Helper function to combine an `opt_lit` with a list of `str_lit`
  1528. fn opt_vec_str_lit(item: Option<impl IntoIterator<Item = impl AsRef<str>>>) -> TokenStream {
  1529. opt_lit(item.map(|list| vec_lit(list, str_lit)).as_ref())
  1530. }
  1531. /// Create a `Vec` constructor, mapping items with a function that spits out `TokenStream`s.
  1532. fn vec_lit<Raw, Tokens>(
  1533. list: impl IntoIterator<Item = Raw>,
  1534. map: impl Fn(Raw) -> Tokens,
  1535. ) -> TokenStream
  1536. where
  1537. Tokens: ToTokens,
  1538. {
  1539. let items = list.into_iter().map(map);
  1540. quote! { vec![#(#items),*] }
  1541. }
  1542. /// Create a `PathBuf` constructor `TokenStream`.
  1543. ///
  1544. /// e.g. `"Hello World" -> String::from("Hello World").
  1545. /// This takes a `&String` to reduce casting all the `&String` -> `&str` manually.
  1546. fn path_buf_lit(s: impl AsRef<Path>) -> TokenStream {
  1547. let s = s.as_ref().to_string_lossy().into_owned();
  1548. quote! { ::std::path::PathBuf::from(#s) }
  1549. }
  1550. /// Creates a `Url` constructor `TokenStream`.
  1551. fn url_lit(url: &Url) -> TokenStream {
  1552. let url = url.as_str();
  1553. quote! { #url.parse().unwrap() }
  1554. }
  1555. /// Create a map constructor, mapping keys and values with other `TokenStream`s.
  1556. ///
  1557. /// This function is pretty generic because the types of keys AND values get transformed.
  1558. fn map_lit<Map, Key, Value, TokenStreamKey, TokenStreamValue, FuncKey, FuncValue>(
  1559. map_type: TokenStream,
  1560. map: Map,
  1561. map_key: FuncKey,
  1562. map_value: FuncValue,
  1563. ) -> TokenStream
  1564. where
  1565. <Map as IntoIterator>::IntoIter: ExactSizeIterator,
  1566. Map: IntoIterator<Item = (Key, Value)>,
  1567. TokenStreamKey: ToTokens,
  1568. TokenStreamValue: ToTokens,
  1569. FuncKey: Fn(Key) -> TokenStreamKey,
  1570. FuncValue: Fn(Value) -> TokenStreamValue,
  1571. {
  1572. let ident = quote::format_ident!("map");
  1573. let map = map.into_iter();
  1574. if map.len() > 0 {
  1575. let items = map.map(|(key, value)| {
  1576. let key = map_key(key);
  1577. let value = map_value(value);
  1578. quote! { #ident.insert(#key, #value); }
  1579. });
  1580. quote! {{
  1581. let mut #ident = #map_type::new();
  1582. #(#items)*
  1583. #ident
  1584. }}
  1585. } else {
  1586. quote! { #map_type::new() }
  1587. }
  1588. }
  1589. /// Create a `serde_json::Value` variant `TokenStream` for a number
  1590. fn json_value_number_lit(num: &serde_json::Number) -> TokenStream {
  1591. // See https://docs.rs/serde_json/1/serde_json/struct.Number.html for guarantees
  1592. let prefix = quote! { ::serde_json::Value };
  1593. if num.is_u64() {
  1594. // guaranteed u64
  1595. let num = num.as_u64().unwrap();
  1596. quote! { #prefix::Number(#num.into()) }
  1597. } else if num.is_i64() {
  1598. // guaranteed i64
  1599. let num = num.as_i64().unwrap();
  1600. quote! { #prefix::Number(#num.into()) }
  1601. } else if num.is_f64() {
  1602. // guaranteed f64
  1603. let num = num.as_f64().unwrap();
  1604. quote! { #prefix::Number(#num.into()) }
  1605. } else {
  1606. // invalid number
  1607. quote! { #prefix::Null }
  1608. }
  1609. }
  1610. /// Create a `serde_json::Value` constructor `TokenStream`
  1611. fn json_value_lit(jv: &JsonValue) -> TokenStream {
  1612. let prefix = quote! { ::serde_json::Value };
  1613. match jv {
  1614. JsonValue::Null => quote! { #prefix::Null },
  1615. JsonValue::Bool(bool) => quote! { #prefix::Bool(#bool) },
  1616. JsonValue::Number(number) => json_value_number_lit(number),
  1617. JsonValue::String(str) => {
  1618. let s = str_lit(str);
  1619. quote! { #prefix::String(#s) }
  1620. }
  1621. JsonValue::Array(vec) => {
  1622. let items = vec.iter().map(json_value_lit);
  1623. quote! { #prefix::Array(vec![#(#items),*]) }
  1624. }
  1625. JsonValue::Object(map) => {
  1626. let map = map_lit(quote! { ::serde_json::Map }, map, str_lit, json_value_lit);
  1627. quote! { #prefix::Object(#map) }
  1628. }
  1629. }
  1630. }
  1631. /// Write a `TokenStream` of the `$struct`'s fields to the `$tokens`.
  1632. ///
  1633. /// All fields must represent a binding of the same name that implements `ToTokens`.
  1634. macro_rules! literal_struct {
  1635. ($tokens:ident, $struct:ident, $($field:ident),+) => {
  1636. $tokens.append_all(quote! {
  1637. ::tauri::utils::config::$struct {
  1638. $($field: #$field),+
  1639. }
  1640. });
  1641. };
  1642. }
  1643. impl ToTokens for WindowUrl {
  1644. fn to_tokens(&self, tokens: &mut TokenStream) {
  1645. let prefix = quote! { ::tauri::utils::config::WindowUrl };
  1646. tokens.append_all(match self {
  1647. Self::App(path) => {
  1648. let path = path_buf_lit(&path);
  1649. quote! { #prefix::App(#path) }
  1650. }
  1651. Self::External(url) => {
  1652. let url = url_lit(url);
  1653. quote! { #prefix::External(#url) }
  1654. }
  1655. })
  1656. }
  1657. }
  1658. impl ToTokens for WindowConfig {
  1659. fn to_tokens(&self, tokens: &mut TokenStream) {
  1660. let label = str_lit(&self.label);
  1661. let url = &self.url;
  1662. let file_drop_enabled = self.file_drop_enabled;
  1663. let center = self.center;
  1664. let x = opt_lit(self.x.as_ref());
  1665. let y = opt_lit(self.y.as_ref());
  1666. let width = self.width;
  1667. let height = self.height;
  1668. let min_width = opt_lit(self.min_width.as_ref());
  1669. let min_height = opt_lit(self.min_height.as_ref());
  1670. let max_width = opt_lit(self.max_width.as_ref());
  1671. let max_height = opt_lit(self.max_height.as_ref());
  1672. let resizable = self.resizable;
  1673. let title = str_lit(&self.title);
  1674. let fullscreen = self.fullscreen;
  1675. let focus = self.focus;
  1676. let transparent = self.transparent;
  1677. let maximized = self.maximized;
  1678. let visible = self.visible;
  1679. let decorations = self.decorations;
  1680. let always_on_top = self.always_on_top;
  1681. let skip_taskbar = self.skip_taskbar;
  1682. literal_struct!(
  1683. tokens,
  1684. WindowConfig,
  1685. label,
  1686. url,
  1687. file_drop_enabled,
  1688. center,
  1689. x,
  1690. y,
  1691. width,
  1692. height,
  1693. min_width,
  1694. min_height,
  1695. max_width,
  1696. max_height,
  1697. resizable,
  1698. title,
  1699. fullscreen,
  1700. focus,
  1701. transparent,
  1702. maximized,
  1703. visible,
  1704. decorations,
  1705. always_on_top,
  1706. skip_taskbar
  1707. );
  1708. }
  1709. }
  1710. impl ToTokens for CliArg {
  1711. fn to_tokens(&self, tokens: &mut TokenStream) {
  1712. let short = opt_lit(self.short.as_ref());
  1713. let name = str_lit(&self.name);
  1714. let description = opt_str_lit(self.description.as_ref());
  1715. let long_description = opt_str_lit(self.long_description.as_ref());
  1716. let takes_value = opt_lit(self.takes_value.as_ref());
  1717. let multiple = opt_lit(self.multiple.as_ref());
  1718. let multiple_occurrences = opt_lit(self.multiple_occurrences.as_ref());
  1719. let number_of_values = opt_lit(self.number_of_values.as_ref());
  1720. let possible_values = opt_vec_str_lit(self.possible_values.as_ref());
  1721. let min_values = opt_lit(self.min_values.as_ref());
  1722. let max_values = opt_lit(self.max_values.as_ref());
  1723. let required = opt_lit(self.required.as_ref());
  1724. let required_unless_present = opt_str_lit(self.required_unless_present.as_ref());
  1725. let required_unless_present_all = opt_vec_str_lit(self.required_unless_present_all.as_ref());
  1726. let required_unless_present_any = opt_vec_str_lit(self.required_unless_present_any.as_ref());
  1727. let conflicts_with = opt_str_lit(self.conflicts_with.as_ref());
  1728. let conflicts_with_all = opt_vec_str_lit(self.conflicts_with_all.as_ref());
  1729. let requires = opt_str_lit(self.requires.as_ref());
  1730. let requires_all = opt_vec_str_lit(self.requires_all.as_ref());
  1731. let requires_if = opt_vec_str_lit(self.requires_if.as_ref());
  1732. let required_if_eq = opt_vec_str_lit(self.required_if_eq.as_ref());
  1733. let require_equals = opt_lit(self.require_equals.as_ref());
  1734. let index = opt_lit(self.index.as_ref());
  1735. literal_struct!(
  1736. tokens,
  1737. CliArg,
  1738. short,
  1739. name,
  1740. description,
  1741. long_description,
  1742. takes_value,
  1743. multiple,
  1744. multiple_occurrences,
  1745. number_of_values,
  1746. possible_values,
  1747. min_values,
  1748. max_values,
  1749. required,
  1750. required_unless_present,
  1751. required_unless_present_all,
  1752. required_unless_present_any,
  1753. conflicts_with,
  1754. conflicts_with_all,
  1755. requires,
  1756. requires_all,
  1757. requires_if,
  1758. required_if_eq,
  1759. require_equals,
  1760. index
  1761. );
  1762. }
  1763. }
  1764. impl ToTokens for CliConfig {
  1765. fn to_tokens(&self, tokens: &mut TokenStream) {
  1766. let description = opt_str_lit(self.description.as_ref());
  1767. let long_description = opt_str_lit(self.long_description.as_ref());
  1768. let before_help = opt_str_lit(self.before_help.as_ref());
  1769. let after_help = opt_str_lit(self.after_help.as_ref());
  1770. let args = {
  1771. let args = self.args.as_ref().map(|args| {
  1772. let arg = args.iter().map(|a| quote! { #a });
  1773. quote! { vec![#(#arg),*] }
  1774. });
  1775. opt_lit(args.as_ref())
  1776. };
  1777. let subcommands = opt_lit(
  1778. self
  1779. .subcommands
  1780. .as_ref()
  1781. .map(|map| {
  1782. map_lit(
  1783. quote! { ::std::collections::HashMap },
  1784. map,
  1785. str_lit,
  1786. identity,
  1787. )
  1788. })
  1789. .as_ref(),
  1790. );
  1791. literal_struct!(
  1792. tokens,
  1793. CliConfig,
  1794. description,
  1795. long_description,
  1796. before_help,
  1797. after_help,
  1798. args,
  1799. subcommands
  1800. );
  1801. }
  1802. }
  1803. impl ToTokens for WindowsConfig {
  1804. fn to_tokens(&self, tokens: &mut TokenStream) {
  1805. let webview_fixed_runtime_path = opt_lit(
  1806. self
  1807. .webview_fixed_runtime_path
  1808. .as_ref()
  1809. .map(path_buf_lit)
  1810. .as_ref(),
  1811. );
  1812. tokens.append_all(quote! { ::tauri::utils::config::WindowsConfig {
  1813. webview_fixed_runtime_path: #webview_fixed_runtime_path,
  1814. ..Default::default()
  1815. }})
  1816. }
  1817. }
  1818. impl ToTokens for BundleConfig {
  1819. fn to_tokens(&self, tokens: &mut TokenStream) {
  1820. let identifier = str_lit(&self.identifier);
  1821. let icon = vec_lit(&self.icon, str_lit);
  1822. let active = self.active;
  1823. let targets = quote!(None);
  1824. let resources = quote!(None);
  1825. let copyright = quote!(None);
  1826. let category = quote!(None);
  1827. let short_description = quote!(None);
  1828. let long_description = quote!(None);
  1829. let deb = quote!(Default::default());
  1830. let macos = quote!(Default::default());
  1831. let external_bin = opt_vec_str_lit(self.external_bin.as_ref());
  1832. let windows = &self.windows;
  1833. literal_struct!(
  1834. tokens,
  1835. BundleConfig,
  1836. active,
  1837. identifier,
  1838. icon,
  1839. targets,
  1840. resources,
  1841. copyright,
  1842. category,
  1843. short_description,
  1844. long_description,
  1845. deb,
  1846. macos,
  1847. external_bin,
  1848. windows
  1849. );
  1850. }
  1851. }
  1852. impl ToTokens for AppUrl {
  1853. fn to_tokens(&self, tokens: &mut TokenStream) {
  1854. let prefix = quote! { ::tauri::utils::config::AppUrl };
  1855. tokens.append_all(match self {
  1856. Self::Url(url) => {
  1857. quote! { #prefix::Url(#url) }
  1858. }
  1859. Self::Files(files) => {
  1860. let files = vec_lit(files, path_buf_lit);
  1861. quote! { #prefix::Files(#files) }
  1862. }
  1863. })
  1864. }
  1865. }
  1866. impl ToTokens for BuildConfig {
  1867. fn to_tokens(&self, tokens: &mut TokenStream) {
  1868. let dev_path = &self.dev_path;
  1869. let dist_dir = &self.dist_dir;
  1870. let with_global_tauri = self.with_global_tauri;
  1871. let runner = quote!(None);
  1872. let before_dev_command = quote!(None);
  1873. let before_build_command = quote!(None);
  1874. let features = quote!(None);
  1875. literal_struct!(
  1876. tokens,
  1877. BuildConfig,
  1878. runner,
  1879. dev_path,
  1880. dist_dir,
  1881. with_global_tauri,
  1882. before_dev_command,
  1883. before_build_command,
  1884. features
  1885. );
  1886. }
  1887. }
  1888. impl ToTokens for UpdaterConfig {
  1889. fn to_tokens(&self, tokens: &mut TokenStream) {
  1890. let active = self.active;
  1891. let dialog = self.dialog;
  1892. let pubkey = str_lit(&self.pubkey);
  1893. let endpoints = opt_vec_str_lit(self.endpoints.as_ref());
  1894. literal_struct!(tokens, UpdaterConfig, active, dialog, pubkey, endpoints);
  1895. }
  1896. }
  1897. impl ToTokens for SecurityConfig {
  1898. fn to_tokens(&self, tokens: &mut TokenStream) {
  1899. let csp = opt_str_lit(self.csp.as_ref());
  1900. let dev_csp = opt_str_lit(self.dev_csp.as_ref());
  1901. literal_struct!(tokens, SecurityConfig, csp, dev_csp);
  1902. }
  1903. }
  1904. impl ToTokens for SystemTrayConfig {
  1905. fn to_tokens(&self, tokens: &mut TokenStream) {
  1906. let icon_as_template = self.icon_as_template;
  1907. let icon_path = path_buf_lit(&self.icon_path);
  1908. literal_struct!(tokens, SystemTrayConfig, icon_path, icon_as_template);
  1909. }
  1910. }
  1911. impl ToTokens for FsAllowlistScope {
  1912. fn to_tokens(&self, tokens: &mut TokenStream) {
  1913. let allowed_paths = vec_lit(&self.0, path_buf_lit);
  1914. tokens.append_all(quote! { ::tauri::utils::config::FsAllowlistScope(#allowed_paths) })
  1915. }
  1916. }
  1917. impl ToTokens for FsAllowlistConfig {
  1918. fn to_tokens(&self, tokens: &mut TokenStream) {
  1919. let scope = &self.scope;
  1920. tokens.append_all(quote! { ::tauri::utils::config::FsAllowlistConfig { scope: #scope, ..Default::default() } })
  1921. }
  1922. }
  1923. impl ToTokens for ProtocolAllowlistConfig {
  1924. fn to_tokens(&self, tokens: &mut TokenStream) {
  1925. let asset_scope = &self.asset_scope;
  1926. tokens.append_all(quote! { ::tauri::utils::config::ProtocolAllowlistConfig { asset_scope: #asset_scope, ..Default::default() } })
  1927. }
  1928. }
  1929. impl ToTokens for HttpAllowlistScope {
  1930. fn to_tokens(&self, tokens: &mut TokenStream) {
  1931. let allowed_urls = vec_lit(&self.0, url_lit);
  1932. tokens.append_all(quote! { ::tauri::utils::config::HttpAllowlistScope(#allowed_urls) })
  1933. }
  1934. }
  1935. impl ToTokens for HttpAllowlistConfig {
  1936. fn to_tokens(&self, tokens: &mut TokenStream) {
  1937. let scope = &self.scope;
  1938. tokens.append_all(quote! { ::tauri::utils::config::HttpAllowlistConfig { scope: #scope, ..Default::default() } })
  1939. }
  1940. }
  1941. impl ToTokens for ShellAllowlistConfig {
  1942. fn to_tokens(&self, tokens: &mut TokenStream) {
  1943. let scope = &self.scope;
  1944. tokens.append_all(quote! { ::tauri::utils::config::ShellAllowlistConfig { scope: #scope, ..Default::default() } })
  1945. }
  1946. }
  1947. impl ToTokens for AllowlistConfig {
  1948. fn to_tokens(&self, tokens: &mut TokenStream) {
  1949. let fs = &self.fs;
  1950. let protocol = &self.protocol;
  1951. let http = &self.http;
  1952. let shell = &self.shell;
  1953. tokens.append_all(
  1954. quote! { ::tauri::utils::config::AllowlistConfig { fs: #fs, protocol: #protocol, http: #http, shell: #shell, ..Default::default() } },
  1955. )
  1956. }
  1957. }
  1958. impl ToTokens for TauriConfig {
  1959. fn to_tokens(&self, tokens: &mut TokenStream) {
  1960. let windows = vec_lit(&self.windows, identity);
  1961. let cli = opt_lit(self.cli.as_ref());
  1962. let bundle = &self.bundle;
  1963. let updater = &self.updater;
  1964. let security = &self.security;
  1965. let system_tray = opt_lit(self.system_tray.as_ref());
  1966. let allowlist = &self.allowlist;
  1967. let macos_private_api = self.macos_private_api;
  1968. literal_struct!(
  1969. tokens,
  1970. TauriConfig,
  1971. windows,
  1972. cli,
  1973. bundle,
  1974. updater,
  1975. security,
  1976. system_tray,
  1977. allowlist,
  1978. macos_private_api
  1979. );
  1980. }
  1981. }
  1982. impl ToTokens for PluginConfig {
  1983. fn to_tokens(&self, tokens: &mut TokenStream) {
  1984. let config = map_lit(
  1985. quote! { ::std::collections::HashMap },
  1986. &self.0,
  1987. str_lit,
  1988. json_value_lit,
  1989. );
  1990. tokens.append_all(quote! { ::tauri::utils::config::PluginConfig(#config) })
  1991. }
  1992. }
  1993. impl ToTokens for PackageConfig {
  1994. fn to_tokens(&self, tokens: &mut TokenStream) {
  1995. let product_name = opt_str_lit(self.product_name.as_ref());
  1996. let version = opt_str_lit(self.version.as_ref());
  1997. literal_struct!(tokens, PackageConfig, product_name, version);
  1998. }
  1999. }
  2000. impl ToTokens for Config {
  2001. fn to_tokens(&self, tokens: &mut TokenStream) {
  2002. let package = &self.package;
  2003. let tauri = &self.tauri;
  2004. let build = &self.build;
  2005. let plugins = &self.plugins;
  2006. literal_struct!(tokens, Config, package, tauri, build, plugins);
  2007. }
  2008. }
  2009. }
  2010. #[cfg(test)]
  2011. mod test {
  2012. use super::*;
  2013. // TODO: create a test that compares a config to a json config
  2014. #[test]
  2015. // test all of the default functions
  2016. fn test_defaults() {
  2017. // get default tauri config
  2018. let t_config = TauriConfig::default();
  2019. // get default build config
  2020. let b_config = BuildConfig::default();
  2021. // get default dev path
  2022. let d_path = default_dev_path();
  2023. // get default window
  2024. let d_windows = default_window_config();
  2025. // get default title
  2026. let d_title = default_title();
  2027. // get default bundle
  2028. let d_bundle = BundleConfig::default();
  2029. // get default updater
  2030. let d_updater = UpdaterConfig::default();
  2031. // create a tauri config.
  2032. let tauri = TauriConfig {
  2033. windows: vec![WindowConfig {
  2034. label: "main".to_string(),
  2035. url: WindowUrl::default(),
  2036. file_drop_enabled: true,
  2037. center: false,
  2038. x: None,
  2039. y: None,
  2040. width: 800f64,
  2041. height: 600f64,
  2042. min_width: None,
  2043. min_height: None,
  2044. max_width: None,
  2045. max_height: None,
  2046. resizable: true,
  2047. title: String::from("Tauri App"),
  2048. fullscreen: false,
  2049. focus: false,
  2050. transparent: false,
  2051. maximized: false,
  2052. visible: true,
  2053. decorations: true,
  2054. always_on_top: false,
  2055. skip_taskbar: false,
  2056. }],
  2057. bundle: BundleConfig {
  2058. active: false,
  2059. targets: None,
  2060. identifier: String::from(""),
  2061. icon: Vec::new(),
  2062. resources: None,
  2063. copyright: None,
  2064. category: None,
  2065. short_description: None,
  2066. long_description: None,
  2067. deb: Default::default(),
  2068. macos: Default::default(),
  2069. external_bin: None,
  2070. windows: Default::default(),
  2071. },
  2072. cli: None,
  2073. updater: UpdaterConfig {
  2074. active: false,
  2075. dialog: true,
  2076. pubkey: "".into(),
  2077. endpoints: None,
  2078. },
  2079. security: SecurityConfig {
  2080. csp: None,
  2081. dev_csp: None,
  2082. },
  2083. allowlist: AllowlistConfig::default(),
  2084. system_tray: None,
  2085. macos_private_api: false,
  2086. };
  2087. // create a build config
  2088. let build = BuildConfig {
  2089. runner: None,
  2090. dev_path: AppUrl::Url(WindowUrl::External(
  2091. Url::parse("http://localhost:8080").unwrap(),
  2092. )),
  2093. dist_dir: AppUrl::Url(WindowUrl::App("../dist".into())),
  2094. before_dev_command: None,
  2095. before_build_command: None,
  2096. features: None,
  2097. with_global_tauri: false,
  2098. };
  2099. // test the configs
  2100. assert_eq!(t_config, tauri);
  2101. assert_eq!(b_config, build);
  2102. assert_eq!(d_bundle, tauri.bundle);
  2103. assert_eq!(d_updater, tauri.updater);
  2104. assert_eq!(
  2105. d_path,
  2106. AppUrl::Url(WindowUrl::External(
  2107. Url::parse("http://localhost:8080").unwrap()
  2108. ))
  2109. );
  2110. assert_eq!(d_title, tauri.windows[0].title);
  2111. assert_eq!(d_windows, tauri.windows);
  2112. }
  2113. }