config.rs 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319
  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. /// A URL to an updater server.
  1279. ///
  1280. /// The URL must use the `https` scheme on production.
  1281. #[skip_serializing_none]
  1282. #[derive(Debug, PartialEq, Clone, Serialize)]
  1283. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1284. pub struct UpdaterEndpoint(pub Url);
  1285. impl std::fmt::Display for UpdaterEndpoint {
  1286. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  1287. write!(f, "{}", self.0)
  1288. }
  1289. }
  1290. impl<'de> Deserialize<'de> for UpdaterEndpoint {
  1291. fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  1292. where
  1293. D: Deserializer<'de>,
  1294. {
  1295. let url = Url::deserialize(deserializer)?;
  1296. #[cfg(all(not(debug_assertions), not(feature = "schema")))]
  1297. {
  1298. if url.scheme() != "https" {
  1299. return Err(serde::de::Error::custom(
  1300. "The configured updater endpoint must use the `https` protocol.",
  1301. ));
  1302. }
  1303. }
  1304. Ok(Self(url))
  1305. }
  1306. }
  1307. /// The Updater configuration object.
  1308. #[skip_serializing_none]
  1309. #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
  1310. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1311. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1312. pub struct UpdaterConfig {
  1313. /// Whether the updater is active or not.
  1314. #[serde(default)]
  1315. pub active: bool,
  1316. /// Display built-in dialog or use event system if disabled.
  1317. #[serde(default = "default_dialog")]
  1318. pub dialog: bool,
  1319. /// The updater endpoints. TLS is enforced on production.
  1320. pub endpoints: Option<Vec<UpdaterEndpoint>>,
  1321. /// Signature public key.
  1322. pub pubkey: String,
  1323. }
  1324. impl Default for UpdaterConfig {
  1325. fn default() -> Self {
  1326. Self {
  1327. active: false,
  1328. dialog: default_dialog(),
  1329. endpoints: None,
  1330. pubkey: "".into(),
  1331. }
  1332. }
  1333. }
  1334. /// Configuration for application system tray icon.
  1335. #[skip_serializing_none]
  1336. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  1337. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1338. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1339. pub struct SystemTrayConfig {
  1340. /// Path to the icon to use on the system tray.
  1341. ///
  1342. /// It is forced to be a `.png` file on Linux and macOS, and a `.ico` file on Windows.
  1343. pub icon_path: PathBuf,
  1344. /// 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.
  1345. #[serde(default)]
  1346. pub icon_as_template: bool,
  1347. }
  1348. // We enable the unnecessary_wraps because we need
  1349. // to use an Option for dialog otherwise the CLI schema will mark
  1350. // the dialog as a required field which is not as we default it to true.
  1351. fn default_dialog() -> bool {
  1352. true
  1353. }
  1354. /// The `dev_path` and `dist_dir` options.
  1355. #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
  1356. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1357. #[serde(untagged, deny_unknown_fields)]
  1358. #[non_exhaustive]
  1359. pub enum AppUrl {
  1360. /// The app's external URL, or the path to the directory containing the app assets.
  1361. Url(WindowUrl),
  1362. /// An array of files to embed on the app.
  1363. Files(Vec<PathBuf>),
  1364. }
  1365. impl std::fmt::Display for AppUrl {
  1366. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  1367. match self {
  1368. Self::Url(url) => write!(f, "{}", url),
  1369. Self::Files(files) => write!(f, "{}", serde_json::to_string(files).unwrap()),
  1370. }
  1371. }
  1372. }
  1373. /// The Build configuration object.
  1374. #[skip_serializing_none]
  1375. #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
  1376. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1377. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1378. pub struct BuildConfig {
  1379. /// The binary used to build and run the application.
  1380. pub runner: Option<String>,
  1381. /// The path or URL to use on development.
  1382. #[serde(default = "default_dev_path")]
  1383. pub dev_path: AppUrl,
  1384. /// The path to the app's dist dir. This path must contain your index.html file.
  1385. #[serde(default = "default_dist_dir")]
  1386. pub dist_dir: AppUrl,
  1387. /// A shell command to run before `tauri dev` kicks in.
  1388. ///
  1389. /// The PLATFORM, ARCH, FAMILY, PLATFORM_TYPE and TAURI_DEBUG environment variables are set if you perform conditional compilation.
  1390. pub before_dev_command: Option<String>,
  1391. /// A shell command to run before `tauri build` kicks in.
  1392. ///
  1393. /// The PLATFORM, ARCH, FAMILY, PLATFORM_TYPE and TAURI_DEBUG environment variables are set if you perform conditional compilation.
  1394. pub before_build_command: Option<String>,
  1395. /// Features passed to `cargo` commands.
  1396. pub features: Option<Vec<String>>,
  1397. /// Whether we should inject the Tauri API on `window.__TAURI__` or not.
  1398. #[serde(default)]
  1399. pub with_global_tauri: bool,
  1400. }
  1401. impl Default for BuildConfig {
  1402. fn default() -> Self {
  1403. Self {
  1404. runner: None,
  1405. dev_path: default_dev_path(),
  1406. dist_dir: default_dist_dir(),
  1407. before_dev_command: None,
  1408. before_build_command: None,
  1409. features: None,
  1410. with_global_tauri: false,
  1411. }
  1412. }
  1413. }
  1414. fn default_dev_path() -> AppUrl {
  1415. AppUrl::Url(WindowUrl::External(
  1416. Url::parse("http://localhost:8080").unwrap(),
  1417. ))
  1418. }
  1419. fn default_dist_dir() -> AppUrl {
  1420. AppUrl::Url(WindowUrl::App("../dist".into()))
  1421. }
  1422. #[derive(Debug, PartialEq)]
  1423. struct PackageVersion(String);
  1424. impl<'d> serde::Deserialize<'d> for PackageVersion {
  1425. fn deserialize<D: Deserializer<'d>>(deserializer: D) -> Result<PackageVersion, D::Error> {
  1426. struct PackageVersionVisitor;
  1427. impl<'d> Visitor<'d> for PackageVersionVisitor {
  1428. type Value = PackageVersion;
  1429. fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
  1430. write!(
  1431. formatter,
  1432. "a semver string or a path to a package.json file"
  1433. )
  1434. }
  1435. fn visit_str<E: DeError>(self, value: &str) -> Result<PackageVersion, E> {
  1436. let path = PathBuf::from(value);
  1437. if path.exists() {
  1438. let json_str = read_to_string(&path)
  1439. .map_err(|e| DeError::custom(format!("failed to read version JSON file: {}", e)))?;
  1440. let package_json: serde_json::Value = serde_json::from_str(&json_str)
  1441. .map_err(|e| DeError::custom(format!("failed to read version JSON file: {}", e)))?;
  1442. if let Some(obj) = package_json.as_object() {
  1443. let version = obj
  1444. .get("version")
  1445. .ok_or_else(|| DeError::custom("JSON must contain a `version` field"))?
  1446. .as_str()
  1447. .ok_or_else(|| DeError::custom("`version` must be a string"))?;
  1448. Ok(PackageVersion(version.into()))
  1449. } else {
  1450. Err(DeError::custom("value is not a path to a JSON object"))
  1451. }
  1452. } else {
  1453. Ok(PackageVersion(value.into()))
  1454. }
  1455. }
  1456. }
  1457. deserializer.deserialize_string(PackageVersionVisitor {})
  1458. }
  1459. }
  1460. /// The package configuration.
  1461. #[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
  1462. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1463. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1464. pub struct PackageConfig {
  1465. /// App name.
  1466. pub product_name: Option<String>,
  1467. /// App version. It is a semver version number or a path to a `package.json` file contaning the `version` field.
  1468. #[serde(deserialize_with = "version_deserializer", default)]
  1469. pub version: Option<String>,
  1470. }
  1471. fn version_deserializer<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
  1472. where
  1473. D: Deserializer<'de>,
  1474. {
  1475. Option::<PackageVersion>::deserialize(deserializer).map(|v| v.map(|v| v.0))
  1476. }
  1477. impl PackageConfig {
  1478. /// The binary name.
  1479. #[allow(dead_code)]
  1480. pub fn binary_name(&self) -> Option<String> {
  1481. #[cfg(target_os = "linux")]
  1482. {
  1483. self.product_name.as_ref().map(|n| n.to_kebab_case())
  1484. }
  1485. #[cfg(not(target_os = "linux"))]
  1486. {
  1487. self.product_name.clone()
  1488. }
  1489. }
  1490. }
  1491. /// The config type mapped to `tauri.conf.json`.
  1492. #[skip_serializing_none]
  1493. #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
  1494. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1495. #[serde(rename_all = "camelCase", deny_unknown_fields)]
  1496. pub struct Config {
  1497. /// Package settings.
  1498. #[serde(default)]
  1499. pub package: PackageConfig,
  1500. /// The Tauri configuration.
  1501. #[serde(default)]
  1502. pub tauri: TauriConfig,
  1503. /// The build configuration.
  1504. #[serde(default = "default_build")]
  1505. pub build: BuildConfig,
  1506. /// The plugins config.
  1507. #[serde(default)]
  1508. pub plugins: PluginConfig,
  1509. }
  1510. /// The plugin configs holds a HashMap mapping a plugin name to its configuration object.
  1511. #[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
  1512. #[cfg_attr(feature = "schema", derive(JsonSchema))]
  1513. pub struct PluginConfig(pub HashMap<String, JsonValue>);
  1514. fn default_build() -> BuildConfig {
  1515. BuildConfig {
  1516. runner: None,
  1517. dev_path: default_dev_path(),
  1518. dist_dir: default_dist_dir(),
  1519. before_dev_command: None,
  1520. before_build_command: None,
  1521. features: None,
  1522. with_global_tauri: false,
  1523. }
  1524. }
  1525. /// Implement `ToTokens` for all config structs, allowing a literal `Config` to be built.
  1526. ///
  1527. /// This allows for a build script to output the values in a `Config` to a `TokenStream`, which can
  1528. /// then be consumed by another crate. Useful for passing a config to both the build script and the
  1529. /// application using tauri while only parsing it once (in the build script).
  1530. #[cfg(feature = "build")]
  1531. mod build {
  1532. use std::{convert::identity, path::Path};
  1533. use proc_macro2::TokenStream;
  1534. use quote::{quote, ToTokens, TokenStreamExt};
  1535. use super::*;
  1536. use serde_json::Value as JsonValue;
  1537. /// Create a `String` constructor `TokenStream`.
  1538. ///
  1539. /// e.g. `"Hello World" -> String::from("Hello World").
  1540. /// This takes a `&String` to reduce casting all the `&String` -> `&str` manually.
  1541. fn str_lit(s: impl AsRef<str>) -> TokenStream {
  1542. let s = s.as_ref();
  1543. quote! { #s.into() }
  1544. }
  1545. /// Create an `Option` constructor `TokenStream`.
  1546. fn opt_lit(item: Option<&impl ToTokens>) -> TokenStream {
  1547. match item {
  1548. None => quote! { ::core::option::Option::None },
  1549. Some(item) => quote! { ::core::option::Option::Some(#item) },
  1550. }
  1551. }
  1552. /// Helper function to combine an `opt_lit` with `str_lit`.
  1553. fn opt_str_lit(item: Option<impl AsRef<str>>) -> TokenStream {
  1554. opt_lit(item.map(str_lit).as_ref())
  1555. }
  1556. /// Helper function to combine an `opt_lit` with a list of `str_lit`
  1557. fn opt_vec_str_lit(item: Option<impl IntoIterator<Item = impl AsRef<str>>>) -> TokenStream {
  1558. opt_lit(item.map(|list| vec_lit(list, str_lit)).as_ref())
  1559. }
  1560. /// Create a `Vec` constructor, mapping items with a function that spits out `TokenStream`s.
  1561. fn vec_lit<Raw, Tokens>(
  1562. list: impl IntoIterator<Item = Raw>,
  1563. map: impl Fn(Raw) -> Tokens,
  1564. ) -> TokenStream
  1565. where
  1566. Tokens: ToTokens,
  1567. {
  1568. let items = list.into_iter().map(map);
  1569. quote! { vec![#(#items),*] }
  1570. }
  1571. /// Create a `PathBuf` constructor `TokenStream`.
  1572. ///
  1573. /// e.g. `"Hello World" -> String::from("Hello World").
  1574. /// This takes a `&String` to reduce casting all the `&String` -> `&str` manually.
  1575. fn path_buf_lit(s: impl AsRef<Path>) -> TokenStream {
  1576. let s = s.as_ref().to_string_lossy().into_owned();
  1577. quote! { ::std::path::PathBuf::from(#s) }
  1578. }
  1579. /// Creates a `Url` constructor `TokenStream`.
  1580. fn url_lit(url: &Url) -> TokenStream {
  1581. let url = url.as_str();
  1582. quote! { #url.parse().unwrap() }
  1583. }
  1584. /// Create a map constructor, mapping keys and values with other `TokenStream`s.
  1585. ///
  1586. /// This function is pretty generic because the types of keys AND values get transformed.
  1587. fn map_lit<Map, Key, Value, TokenStreamKey, TokenStreamValue, FuncKey, FuncValue>(
  1588. map_type: TokenStream,
  1589. map: Map,
  1590. map_key: FuncKey,
  1591. map_value: FuncValue,
  1592. ) -> TokenStream
  1593. where
  1594. <Map as IntoIterator>::IntoIter: ExactSizeIterator,
  1595. Map: IntoIterator<Item = (Key, Value)>,
  1596. TokenStreamKey: ToTokens,
  1597. TokenStreamValue: ToTokens,
  1598. FuncKey: Fn(Key) -> TokenStreamKey,
  1599. FuncValue: Fn(Value) -> TokenStreamValue,
  1600. {
  1601. let ident = quote::format_ident!("map");
  1602. let map = map.into_iter();
  1603. if map.len() > 0 {
  1604. let items = map.map(|(key, value)| {
  1605. let key = map_key(key);
  1606. let value = map_value(value);
  1607. quote! { #ident.insert(#key, #value); }
  1608. });
  1609. quote! {{
  1610. let mut #ident = #map_type::new();
  1611. #(#items)*
  1612. #ident
  1613. }}
  1614. } else {
  1615. quote! { #map_type::new() }
  1616. }
  1617. }
  1618. /// Create a `serde_json::Value` variant `TokenStream` for a number
  1619. fn json_value_number_lit(num: &serde_json::Number) -> TokenStream {
  1620. // See https://docs.rs/serde_json/1/serde_json/struct.Number.html for guarantees
  1621. let prefix = quote! { ::serde_json::Value };
  1622. if num.is_u64() {
  1623. // guaranteed u64
  1624. let num = num.as_u64().unwrap();
  1625. quote! { #prefix::Number(#num.into()) }
  1626. } else if num.is_i64() {
  1627. // guaranteed i64
  1628. let num = num.as_i64().unwrap();
  1629. quote! { #prefix::Number(#num.into()) }
  1630. } else if num.is_f64() {
  1631. // guaranteed f64
  1632. let num = num.as_f64().unwrap();
  1633. quote! { #prefix::Number(#num.into()) }
  1634. } else {
  1635. // invalid number
  1636. quote! { #prefix::Null }
  1637. }
  1638. }
  1639. /// Create a `serde_json::Value` constructor `TokenStream`
  1640. fn json_value_lit(jv: &JsonValue) -> TokenStream {
  1641. let prefix = quote! { ::serde_json::Value };
  1642. match jv {
  1643. JsonValue::Null => quote! { #prefix::Null },
  1644. JsonValue::Bool(bool) => quote! { #prefix::Bool(#bool) },
  1645. JsonValue::Number(number) => json_value_number_lit(number),
  1646. JsonValue::String(str) => {
  1647. let s = str_lit(str);
  1648. quote! { #prefix::String(#s) }
  1649. }
  1650. JsonValue::Array(vec) => {
  1651. let items = vec.iter().map(json_value_lit);
  1652. quote! { #prefix::Array(vec![#(#items),*]) }
  1653. }
  1654. JsonValue::Object(map) => {
  1655. let map = map_lit(quote! { ::serde_json::Map }, map, str_lit, json_value_lit);
  1656. quote! { #prefix::Object(#map) }
  1657. }
  1658. }
  1659. }
  1660. /// Write a `TokenStream` of the `$struct`'s fields to the `$tokens`.
  1661. ///
  1662. /// All fields must represent a binding of the same name that implements `ToTokens`.
  1663. macro_rules! literal_struct {
  1664. ($tokens:ident, $struct:ident, $($field:ident),+) => {
  1665. $tokens.append_all(quote! {
  1666. ::tauri::utils::config::$struct {
  1667. $($field: #$field),+
  1668. }
  1669. });
  1670. };
  1671. }
  1672. impl ToTokens for WindowUrl {
  1673. fn to_tokens(&self, tokens: &mut TokenStream) {
  1674. let prefix = quote! { ::tauri::utils::config::WindowUrl };
  1675. tokens.append_all(match self {
  1676. Self::App(path) => {
  1677. let path = path_buf_lit(&path);
  1678. quote! { #prefix::App(#path) }
  1679. }
  1680. Self::External(url) => {
  1681. let url = url_lit(url);
  1682. quote! { #prefix::External(#url) }
  1683. }
  1684. })
  1685. }
  1686. }
  1687. impl ToTokens for WindowConfig {
  1688. fn to_tokens(&self, tokens: &mut TokenStream) {
  1689. let label = str_lit(&self.label);
  1690. let url = &self.url;
  1691. let file_drop_enabled = self.file_drop_enabled;
  1692. let center = self.center;
  1693. let x = opt_lit(self.x.as_ref());
  1694. let y = opt_lit(self.y.as_ref());
  1695. let width = self.width;
  1696. let height = self.height;
  1697. let min_width = opt_lit(self.min_width.as_ref());
  1698. let min_height = opt_lit(self.min_height.as_ref());
  1699. let max_width = opt_lit(self.max_width.as_ref());
  1700. let max_height = opt_lit(self.max_height.as_ref());
  1701. let resizable = self.resizable;
  1702. let title = str_lit(&self.title);
  1703. let fullscreen = self.fullscreen;
  1704. let focus = self.focus;
  1705. let transparent = self.transparent;
  1706. let maximized = self.maximized;
  1707. let visible = self.visible;
  1708. let decorations = self.decorations;
  1709. let always_on_top = self.always_on_top;
  1710. let skip_taskbar = self.skip_taskbar;
  1711. literal_struct!(
  1712. tokens,
  1713. WindowConfig,
  1714. label,
  1715. url,
  1716. file_drop_enabled,
  1717. center,
  1718. x,
  1719. y,
  1720. width,
  1721. height,
  1722. min_width,
  1723. min_height,
  1724. max_width,
  1725. max_height,
  1726. resizable,
  1727. title,
  1728. fullscreen,
  1729. focus,
  1730. transparent,
  1731. maximized,
  1732. visible,
  1733. decorations,
  1734. always_on_top,
  1735. skip_taskbar
  1736. );
  1737. }
  1738. }
  1739. impl ToTokens for CliArg {
  1740. fn to_tokens(&self, tokens: &mut TokenStream) {
  1741. let short = opt_lit(self.short.as_ref());
  1742. let name = str_lit(&self.name);
  1743. let description = opt_str_lit(self.description.as_ref());
  1744. let long_description = opt_str_lit(self.long_description.as_ref());
  1745. let takes_value = opt_lit(self.takes_value.as_ref());
  1746. let multiple = opt_lit(self.multiple.as_ref());
  1747. let multiple_occurrences = opt_lit(self.multiple_occurrences.as_ref());
  1748. let number_of_values = opt_lit(self.number_of_values.as_ref());
  1749. let possible_values = opt_vec_str_lit(self.possible_values.as_ref());
  1750. let min_values = opt_lit(self.min_values.as_ref());
  1751. let max_values = opt_lit(self.max_values.as_ref());
  1752. let required = opt_lit(self.required.as_ref());
  1753. let required_unless_present = opt_str_lit(self.required_unless_present.as_ref());
  1754. let required_unless_present_all = opt_vec_str_lit(self.required_unless_present_all.as_ref());
  1755. let required_unless_present_any = opt_vec_str_lit(self.required_unless_present_any.as_ref());
  1756. let conflicts_with = opt_str_lit(self.conflicts_with.as_ref());
  1757. let conflicts_with_all = opt_vec_str_lit(self.conflicts_with_all.as_ref());
  1758. let requires = opt_str_lit(self.requires.as_ref());
  1759. let requires_all = opt_vec_str_lit(self.requires_all.as_ref());
  1760. let requires_if = opt_vec_str_lit(self.requires_if.as_ref());
  1761. let required_if_eq = opt_vec_str_lit(self.required_if_eq.as_ref());
  1762. let require_equals = opt_lit(self.require_equals.as_ref());
  1763. let index = opt_lit(self.index.as_ref());
  1764. literal_struct!(
  1765. tokens,
  1766. CliArg,
  1767. short,
  1768. name,
  1769. description,
  1770. long_description,
  1771. takes_value,
  1772. multiple,
  1773. multiple_occurrences,
  1774. number_of_values,
  1775. possible_values,
  1776. min_values,
  1777. max_values,
  1778. required,
  1779. required_unless_present,
  1780. required_unless_present_all,
  1781. required_unless_present_any,
  1782. conflicts_with,
  1783. conflicts_with_all,
  1784. requires,
  1785. requires_all,
  1786. requires_if,
  1787. required_if_eq,
  1788. require_equals,
  1789. index
  1790. );
  1791. }
  1792. }
  1793. impl ToTokens for CliConfig {
  1794. fn to_tokens(&self, tokens: &mut TokenStream) {
  1795. let description = opt_str_lit(self.description.as_ref());
  1796. let long_description = opt_str_lit(self.long_description.as_ref());
  1797. let before_help = opt_str_lit(self.before_help.as_ref());
  1798. let after_help = opt_str_lit(self.after_help.as_ref());
  1799. let args = {
  1800. let args = self.args.as_ref().map(|args| {
  1801. let arg = args.iter().map(|a| quote! { #a });
  1802. quote! { vec![#(#arg),*] }
  1803. });
  1804. opt_lit(args.as_ref())
  1805. };
  1806. let subcommands = opt_lit(
  1807. self
  1808. .subcommands
  1809. .as_ref()
  1810. .map(|map| {
  1811. map_lit(
  1812. quote! { ::std::collections::HashMap },
  1813. map,
  1814. str_lit,
  1815. identity,
  1816. )
  1817. })
  1818. .as_ref(),
  1819. );
  1820. literal_struct!(
  1821. tokens,
  1822. CliConfig,
  1823. description,
  1824. long_description,
  1825. before_help,
  1826. after_help,
  1827. args,
  1828. subcommands
  1829. );
  1830. }
  1831. }
  1832. impl ToTokens for WindowsConfig {
  1833. fn to_tokens(&self, tokens: &mut TokenStream) {
  1834. let webview_fixed_runtime_path = opt_lit(
  1835. self
  1836. .webview_fixed_runtime_path
  1837. .as_ref()
  1838. .map(path_buf_lit)
  1839. .as_ref(),
  1840. );
  1841. tokens.append_all(quote! { ::tauri::utils::config::WindowsConfig {
  1842. webview_fixed_runtime_path: #webview_fixed_runtime_path,
  1843. ..Default::default()
  1844. }})
  1845. }
  1846. }
  1847. impl ToTokens for BundleConfig {
  1848. fn to_tokens(&self, tokens: &mut TokenStream) {
  1849. let identifier = str_lit(&self.identifier);
  1850. let icon = vec_lit(&self.icon, str_lit);
  1851. let active = self.active;
  1852. let targets = quote!(None);
  1853. let resources = quote!(None);
  1854. let copyright = quote!(None);
  1855. let category = quote!(None);
  1856. let short_description = quote!(None);
  1857. let long_description = quote!(None);
  1858. let deb = quote!(Default::default());
  1859. let macos = quote!(Default::default());
  1860. let external_bin = opt_vec_str_lit(self.external_bin.as_ref());
  1861. let windows = &self.windows;
  1862. literal_struct!(
  1863. tokens,
  1864. BundleConfig,
  1865. active,
  1866. identifier,
  1867. icon,
  1868. targets,
  1869. resources,
  1870. copyright,
  1871. category,
  1872. short_description,
  1873. long_description,
  1874. deb,
  1875. macos,
  1876. external_bin,
  1877. windows
  1878. );
  1879. }
  1880. }
  1881. impl ToTokens for AppUrl {
  1882. fn to_tokens(&self, tokens: &mut TokenStream) {
  1883. let prefix = quote! { ::tauri::utils::config::AppUrl };
  1884. tokens.append_all(match self {
  1885. Self::Url(url) => {
  1886. quote! { #prefix::Url(#url) }
  1887. }
  1888. Self::Files(files) => {
  1889. let files = vec_lit(files, path_buf_lit);
  1890. quote! { #prefix::Files(#files) }
  1891. }
  1892. })
  1893. }
  1894. }
  1895. impl ToTokens for BuildConfig {
  1896. fn to_tokens(&self, tokens: &mut TokenStream) {
  1897. let dev_path = &self.dev_path;
  1898. let dist_dir = &self.dist_dir;
  1899. let with_global_tauri = self.with_global_tauri;
  1900. let runner = quote!(None);
  1901. let before_dev_command = quote!(None);
  1902. let before_build_command = quote!(None);
  1903. let features = quote!(None);
  1904. literal_struct!(
  1905. tokens,
  1906. BuildConfig,
  1907. runner,
  1908. dev_path,
  1909. dist_dir,
  1910. with_global_tauri,
  1911. before_dev_command,
  1912. before_build_command,
  1913. features
  1914. );
  1915. }
  1916. }
  1917. impl ToTokens for UpdaterConfig {
  1918. fn to_tokens(&self, tokens: &mut TokenStream) {
  1919. let active = self.active;
  1920. let dialog = self.dialog;
  1921. let pubkey = str_lit(&self.pubkey);
  1922. let endpoints = opt_lit(
  1923. self
  1924. .endpoints
  1925. .as_ref()
  1926. .map(|list| {
  1927. vec_lit(list, |url| {
  1928. let url = url.0.as_str();
  1929. quote! { ::tauri::utils::config::UpdaterEndpoint(#url.parse().unwrap()) }
  1930. })
  1931. })
  1932. .as_ref(),
  1933. );
  1934. literal_struct!(tokens, UpdaterConfig, active, dialog, pubkey, endpoints);
  1935. }
  1936. }
  1937. impl ToTokens for SecurityConfig {
  1938. fn to_tokens(&self, tokens: &mut TokenStream) {
  1939. let csp = opt_str_lit(self.csp.as_ref());
  1940. let dev_csp = opt_str_lit(self.dev_csp.as_ref());
  1941. literal_struct!(tokens, SecurityConfig, csp, dev_csp);
  1942. }
  1943. }
  1944. impl ToTokens for SystemTrayConfig {
  1945. fn to_tokens(&self, tokens: &mut TokenStream) {
  1946. let icon_as_template = self.icon_as_template;
  1947. let icon_path = path_buf_lit(&self.icon_path);
  1948. literal_struct!(tokens, SystemTrayConfig, icon_path, icon_as_template);
  1949. }
  1950. }
  1951. impl ToTokens for FsAllowlistScope {
  1952. fn to_tokens(&self, tokens: &mut TokenStream) {
  1953. let allowed_paths = vec_lit(&self.0, path_buf_lit);
  1954. tokens.append_all(quote! { ::tauri::utils::config::FsAllowlistScope(#allowed_paths) })
  1955. }
  1956. }
  1957. impl ToTokens for FsAllowlistConfig {
  1958. fn to_tokens(&self, tokens: &mut TokenStream) {
  1959. let scope = &self.scope;
  1960. tokens.append_all(quote! { ::tauri::utils::config::FsAllowlistConfig { scope: #scope, ..Default::default() } })
  1961. }
  1962. }
  1963. impl ToTokens for ProtocolAllowlistConfig {
  1964. fn to_tokens(&self, tokens: &mut TokenStream) {
  1965. let asset_scope = &self.asset_scope;
  1966. tokens.append_all(quote! { ::tauri::utils::config::ProtocolAllowlistConfig { asset_scope: #asset_scope, ..Default::default() } })
  1967. }
  1968. }
  1969. impl ToTokens for HttpAllowlistScope {
  1970. fn to_tokens(&self, tokens: &mut TokenStream) {
  1971. let allowed_urls = vec_lit(&self.0, url_lit);
  1972. tokens.append_all(quote! { ::tauri::utils::config::HttpAllowlistScope(#allowed_urls) })
  1973. }
  1974. }
  1975. impl ToTokens for HttpAllowlistConfig {
  1976. fn to_tokens(&self, tokens: &mut TokenStream) {
  1977. let scope = &self.scope;
  1978. tokens.append_all(quote! { ::tauri::utils::config::HttpAllowlistConfig { scope: #scope, ..Default::default() } })
  1979. }
  1980. }
  1981. impl ToTokens for ShellAllowlistConfig {
  1982. fn to_tokens(&self, tokens: &mut TokenStream) {
  1983. let scope = &self.scope;
  1984. tokens.append_all(quote! { ::tauri::utils::config::ShellAllowlistConfig { scope: #scope, ..Default::default() } })
  1985. }
  1986. }
  1987. impl ToTokens for AllowlistConfig {
  1988. fn to_tokens(&self, tokens: &mut TokenStream) {
  1989. let fs = &self.fs;
  1990. let protocol = &self.protocol;
  1991. let http = &self.http;
  1992. let shell = &self.shell;
  1993. tokens.append_all(
  1994. quote! { ::tauri::utils::config::AllowlistConfig { fs: #fs, protocol: #protocol, http: #http, shell: #shell, ..Default::default() } },
  1995. )
  1996. }
  1997. }
  1998. impl ToTokens for TauriConfig {
  1999. fn to_tokens(&self, tokens: &mut TokenStream) {
  2000. let windows = vec_lit(&self.windows, identity);
  2001. let cli = opt_lit(self.cli.as_ref());
  2002. let bundle = &self.bundle;
  2003. let updater = &self.updater;
  2004. let security = &self.security;
  2005. let system_tray = opt_lit(self.system_tray.as_ref());
  2006. let allowlist = &self.allowlist;
  2007. let macos_private_api = self.macos_private_api;
  2008. literal_struct!(
  2009. tokens,
  2010. TauriConfig,
  2011. windows,
  2012. cli,
  2013. bundle,
  2014. updater,
  2015. security,
  2016. system_tray,
  2017. allowlist,
  2018. macos_private_api
  2019. );
  2020. }
  2021. }
  2022. impl ToTokens for PluginConfig {
  2023. fn to_tokens(&self, tokens: &mut TokenStream) {
  2024. let config = map_lit(
  2025. quote! { ::std::collections::HashMap },
  2026. &self.0,
  2027. str_lit,
  2028. json_value_lit,
  2029. );
  2030. tokens.append_all(quote! { ::tauri::utils::config::PluginConfig(#config) })
  2031. }
  2032. }
  2033. impl ToTokens for PackageConfig {
  2034. fn to_tokens(&self, tokens: &mut TokenStream) {
  2035. let product_name = opt_str_lit(self.product_name.as_ref());
  2036. let version = opt_str_lit(self.version.as_ref());
  2037. literal_struct!(tokens, PackageConfig, product_name, version);
  2038. }
  2039. }
  2040. impl ToTokens for Config {
  2041. fn to_tokens(&self, tokens: &mut TokenStream) {
  2042. let package = &self.package;
  2043. let tauri = &self.tauri;
  2044. let build = &self.build;
  2045. let plugins = &self.plugins;
  2046. literal_struct!(tokens, Config, package, tauri, build, plugins);
  2047. }
  2048. }
  2049. }
  2050. #[cfg(test)]
  2051. mod test {
  2052. use super::*;
  2053. // TODO: create a test that compares a config to a json config
  2054. #[test]
  2055. // test all of the default functions
  2056. fn test_defaults() {
  2057. // get default tauri config
  2058. let t_config = TauriConfig::default();
  2059. // get default build config
  2060. let b_config = BuildConfig::default();
  2061. // get default dev path
  2062. let d_path = default_dev_path();
  2063. // get default window
  2064. let d_windows = default_window_config();
  2065. // get default title
  2066. let d_title = default_title();
  2067. // get default bundle
  2068. let d_bundle = BundleConfig::default();
  2069. // get default updater
  2070. let d_updater = UpdaterConfig::default();
  2071. // create a tauri config.
  2072. let tauri = TauriConfig {
  2073. windows: vec![WindowConfig {
  2074. label: "main".to_string(),
  2075. url: WindowUrl::default(),
  2076. file_drop_enabled: true,
  2077. center: false,
  2078. x: None,
  2079. y: None,
  2080. width: 800f64,
  2081. height: 600f64,
  2082. min_width: None,
  2083. min_height: None,
  2084. max_width: None,
  2085. max_height: None,
  2086. resizable: true,
  2087. title: String::from("Tauri App"),
  2088. fullscreen: false,
  2089. focus: false,
  2090. transparent: false,
  2091. maximized: false,
  2092. visible: true,
  2093. decorations: true,
  2094. always_on_top: false,
  2095. skip_taskbar: false,
  2096. }],
  2097. bundle: BundleConfig {
  2098. active: false,
  2099. targets: None,
  2100. identifier: String::from(""),
  2101. icon: Vec::new(),
  2102. resources: None,
  2103. copyright: None,
  2104. category: None,
  2105. short_description: None,
  2106. long_description: None,
  2107. deb: Default::default(),
  2108. macos: Default::default(),
  2109. external_bin: None,
  2110. windows: Default::default(),
  2111. },
  2112. cli: None,
  2113. updater: UpdaterConfig {
  2114. active: false,
  2115. dialog: true,
  2116. pubkey: "".into(),
  2117. endpoints: None,
  2118. },
  2119. security: SecurityConfig {
  2120. csp: None,
  2121. dev_csp: None,
  2122. },
  2123. allowlist: AllowlistConfig::default(),
  2124. system_tray: None,
  2125. macos_private_api: false,
  2126. };
  2127. // create a build config
  2128. let build = BuildConfig {
  2129. runner: None,
  2130. dev_path: AppUrl::Url(WindowUrl::External(
  2131. Url::parse("http://localhost:8080").unwrap(),
  2132. )),
  2133. dist_dir: AppUrl::Url(WindowUrl::App("../dist".into())),
  2134. before_dev_command: None,
  2135. before_build_command: None,
  2136. features: None,
  2137. with_global_tauri: false,
  2138. };
  2139. // test the configs
  2140. assert_eq!(t_config, tauri);
  2141. assert_eq!(b_config, build);
  2142. assert_eq!(d_bundle, tauri.bundle);
  2143. assert_eq!(d_updater, tauri.updater);
  2144. assert_eq!(
  2145. d_path,
  2146. AppUrl::Url(WindowUrl::External(
  2147. Url::parse("http://localhost:8080").unwrap()
  2148. ))
  2149. );
  2150. assert_eq!(d_title, tauri.windows[0].title);
  2151. assert_eq!(d_windows, tauri.windows);
  2152. }
  2153. }