lib.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. #![cfg_attr(doc_cfg, feature(doc_cfg))]
  5. pub use anyhow::Result;
  6. use cargo_toml::{Dependency, Manifest};
  7. use heck::AsShoutySnakeCase;
  8. use tauri_utils::{
  9. config::Config,
  10. resources::{external_binaries, resource_relpath, ResourcePaths},
  11. };
  12. use std::path::{Path, PathBuf};
  13. #[cfg(feature = "codegen")]
  14. mod codegen;
  15. mod static_vcruntime;
  16. #[cfg(feature = "codegen")]
  17. #[cfg_attr(doc_cfg, doc(cfg(feature = "codegen")))]
  18. pub use codegen::context::CodegenContext;
  19. fn copy_file(from: impl AsRef<Path>, to: impl AsRef<Path>) -> Result<()> {
  20. let from = from.as_ref();
  21. let to = to.as_ref();
  22. if !from.exists() {
  23. return Err(anyhow::anyhow!("{:?} does not exist", from));
  24. }
  25. if !from.is_file() {
  26. return Err(anyhow::anyhow!("{:?} is not a file", from));
  27. }
  28. let dest_dir = to.parent().expect("No data in parent");
  29. std::fs::create_dir_all(dest_dir)?;
  30. std::fs::copy(from, to)?;
  31. Ok(())
  32. }
  33. fn copy_binaries(
  34. binaries: ResourcePaths,
  35. target_triple: &str,
  36. path: &Path,
  37. package_name: Option<&String>,
  38. ) -> Result<()> {
  39. for src in binaries {
  40. let src = src?;
  41. println!("cargo:rerun-if-changed={}", src.display());
  42. let file_name = src
  43. .file_name()
  44. .expect("failed to extract external binary filename")
  45. .to_string_lossy()
  46. .replace(&format!("-{target_triple}"), "");
  47. if package_name.map_or(false, |n| n == &file_name) {
  48. return Err(anyhow::anyhow!(
  49. "Cannot define a sidecar with the same name as the Cargo package name `{}`. Please change the sidecar name in the filesystem and the Tauri configuration.",
  50. file_name
  51. ));
  52. }
  53. let dest = path.join(file_name);
  54. if dest.exists() {
  55. std::fs::remove_file(&dest).unwrap();
  56. }
  57. copy_file(&src, &dest)?;
  58. }
  59. Ok(())
  60. }
  61. /// Copies resources to a path.
  62. fn copy_resources(resources: ResourcePaths<'_>, path: &Path) -> Result<()> {
  63. for src in resources {
  64. let src = src?;
  65. println!("cargo:rerun-if-changed={}", src.display());
  66. let dest = path.join(resource_relpath(&src));
  67. copy_file(&src, dest)?;
  68. }
  69. Ok(())
  70. }
  71. // checks if the given Cargo feature is enabled.
  72. fn has_feature(feature: &str) -> bool {
  73. // when a feature is enabled, Cargo sets the `CARGO_FEATURE_<name` env var to 1
  74. // https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts
  75. std::env::var(format!("CARGO_FEATURE_{}", AsShoutySnakeCase(feature)))
  76. .map(|x| x == "1")
  77. .unwrap_or(false)
  78. }
  79. // creates a cfg alias if `has_feature` is true.
  80. // `alias` must be a snake case string.
  81. fn cfg_alias(alias: &str, has_feature: bool) {
  82. if has_feature {
  83. println!("cargo:rustc-cfg={alias}");
  84. }
  85. }
  86. /// Attributes used on Windows.
  87. #[allow(dead_code)]
  88. #[derive(Debug, Default)]
  89. pub struct WindowsAttributes {
  90. window_icon_path: Option<PathBuf>,
  91. /// The path to the sdk location.
  92. ///
  93. /// For the GNU toolkit this has to be the path where MinGW put windres.exe and ar.exe.
  94. /// This could be something like: "C:\Program Files\mingw-w64\x86_64-5.3.0-win32-seh-rt_v4-rev0\mingw64\bin"
  95. ///
  96. /// For MSVC the Windows SDK has to be installed. It comes with the resource compiler rc.exe.
  97. /// This should be set to the root directory of the Windows SDK, e.g., "C:\Program Files (x86)\Windows Kits\10" or,
  98. /// if multiple 10 versions are installed, set it directly to the correct bin directory "C:\Program Files (x86)\Windows Kits\10\bin\10.0.14393.0\x64"
  99. ///
  100. /// If it is left unset, it will look up a path in the registry, i.e. HKLM\SOFTWARE\Microsoft\Windows Kits\Installed Roots
  101. sdk_dir: Option<PathBuf>,
  102. /// A string containing an [application manifest] to be included with the application on Windows.
  103. ///
  104. /// Defaults to:
  105. /// ```ignore
  106. #[doc = include_str!("window-app-manifest.xml")]
  107. /// ```
  108. ///
  109. /// [application manifest]: https://learn.microsoft.com/en-us/windows/win32/sbscs/application-manifests
  110. app_manifest: Option<String>,
  111. }
  112. impl WindowsAttributes {
  113. /// Creates the default attribute set.
  114. pub fn new() -> Self {
  115. Self::default()
  116. }
  117. /// Sets the icon to use on the window. Currently only used on Windows.
  118. /// It must be in `ico` format. Defaults to `icons/icon.ico`.
  119. #[must_use]
  120. pub fn window_icon_path<P: AsRef<Path>>(mut self, window_icon_path: P) -> Self {
  121. self
  122. .window_icon_path
  123. .replace(window_icon_path.as_ref().into());
  124. self
  125. }
  126. /// Sets the sdk dir for windows. Currently only used on Windows. This must be a valid UTF-8
  127. /// path. Defaults to whatever the `winres` crate determines is best.
  128. #[must_use]
  129. pub fn sdk_dir<P: AsRef<Path>>(mut self, sdk_dir: P) -> Self {
  130. self.sdk_dir = Some(sdk_dir.as_ref().into());
  131. self
  132. }
  133. /// Sets the Windows app [manifest].
  134. ///
  135. /// # Example
  136. ///
  137. /// The following manifest will brand the exe as requesting administrator privileges.
  138. /// Thus, everytime it is executed, a Windows UAC dialog will appear.
  139. ///
  140. /// Note that you can move the manifest contents to a separate file and use `include_str!("manifest.xml")`
  141. /// instead of the inline string.
  142. ///
  143. /// ```rust,no_run
  144. /// let mut windows = tauri_build::WindowsAttributes::new();
  145. /// windows = windows.app_manifest(r#"
  146. /// <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  147. /// <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
  148. /// <security>
  149. /// <requestedPrivileges>
  150. /// <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
  151. /// </requestedPrivileges>
  152. /// </security>
  153. /// </trustInfo>
  154. /// </assembly>
  155. /// "#);
  156. /// tauri_build::try_build(
  157. /// tauri_build::Attributes::new().windows_attributes(windows)
  158. /// ).expect("failed to run build script");
  159. /// ```
  160. ///
  161. /// Defaults to:
  162. /// ```ignore
  163. #[doc = include_str!("window-app-manifest.xml")]
  164. /// [manifest]: https://learn.microsoft.com/en-us/windows/win32/sbscs/application-manifests
  165. /// ```
  166. #[must_use]
  167. pub fn app_manifest<S: AsRef<str>>(mut self, manifest: S) -> Self {
  168. self.app_manifest = Some(manifest.as_ref().to_string());
  169. self
  170. }
  171. }
  172. /// The attributes used on the build.
  173. #[derive(Debug, Default)]
  174. pub struct Attributes {
  175. #[allow(dead_code)]
  176. windows_attributes: WindowsAttributes,
  177. }
  178. impl Attributes {
  179. /// Creates the default attribute set.
  180. pub fn new() -> Self {
  181. Self::default()
  182. }
  183. /// Sets the icon to use on the window. Currently only used on Windows.
  184. #[must_use]
  185. pub fn windows_attributes(mut self, windows_attributes: WindowsAttributes) -> Self {
  186. self.windows_attributes = windows_attributes;
  187. self
  188. }
  189. }
  190. /// Run all build time helpers for your Tauri Application.
  191. ///
  192. /// The current helpers include the following:
  193. /// * Generates a Windows Resource file when targeting Windows.
  194. ///
  195. /// # Platforms
  196. ///
  197. /// [`build()`] should be called inside of `build.rs` regardless of the platform:
  198. /// * New helpers may target more platforms in the future.
  199. /// * Platform specific code is handled by the helpers automatically.
  200. /// * A build script is required in order to activate some cargo environmental variables that are
  201. /// used when generating code and embedding assets - so [`build()`] may as well be called.
  202. ///
  203. /// In short, this is saying don't put the call to [`build()`] behind a `#[cfg(windows)]`.
  204. ///
  205. /// # Panics
  206. ///
  207. /// If any of the build time helpers fail, they will [`std::panic!`] with the related error message.
  208. /// This is typically desirable when running inside a build script; see [`try_build`] for no panics.
  209. pub fn build() {
  210. if let Err(error) = try_build(Attributes::default()) {
  211. let error = format!("{error:#}");
  212. println!("{error}");
  213. if error.starts_with("unknown field") {
  214. print!("found an unknown configuration field. This usually means that you are using a CLI version that is newer than `tauri-build` and is incompatible. ");
  215. println!(
  216. "Please try updating the Rust crates by running `cargo update` in the Tauri app folder."
  217. );
  218. }
  219. std::process::exit(1);
  220. }
  221. }
  222. /// Non-panicking [`build()`].
  223. #[allow(unused_variables)]
  224. pub fn try_build(attributes: Attributes) -> Result<()> {
  225. use anyhow::anyhow;
  226. println!("cargo:rerun-if-env-changed=TAURI_CONFIG");
  227. println!("cargo:rerun-if-changed=tauri.conf.json");
  228. #[cfg(feature = "config-json5")]
  229. println!("cargo:rerun-if-changed=tauri.conf.json5");
  230. #[cfg(feature = "config-toml")]
  231. println!("cargo:rerun-if-changed=Tauri.toml");
  232. let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
  233. let mobile = target_os == "ios" || target_os == "android";
  234. cfg_alias("desktop", !mobile);
  235. cfg_alias("mobile", mobile);
  236. let mut config = serde_json::from_value(tauri_utils::config::parse::read_from(
  237. std::env::current_dir().unwrap(),
  238. )?)?;
  239. if let Ok(env) = std::env::var("TAURI_CONFIG") {
  240. let merge_config: serde_json::Value = serde_json::from_str(&env)?;
  241. json_patch::merge(&mut config, &merge_config);
  242. }
  243. let config: Config = serde_json::from_value(config)?;
  244. cfg_alias("dev", !has_feature("custom-protocol"));
  245. let ws_path = get_workspace_dir()?;
  246. let mut manifest =
  247. Manifest::<cargo_toml::Value>::from_slice_with_metadata(&std::fs::read("Cargo.toml")?)?;
  248. if let Ok(ws_manifest) = Manifest::from_path(ws_path.join("Cargo.toml")) {
  249. Manifest::complete_from_path_and_workspace(
  250. &mut manifest,
  251. Path::new("Cargo.toml"),
  252. Some((&ws_manifest, ws_path.as_path())),
  253. )?;
  254. } else {
  255. Manifest::complete_from_path(&mut manifest, Path::new("Cargo.toml"))?;
  256. }
  257. if let Some(tauri_build) = manifest.build_dependencies.remove("tauri-build") {
  258. let error_message = check_features(&config, tauri_build, true);
  259. if !error_message.is_empty() {
  260. return Err(anyhow!("
  261. The `tauri-build` dependency features on the `Cargo.toml` file does not match the allowlist defined under `tauri.conf.json`.
  262. Please run `tauri dev` or `tauri build` or {}.
  263. ", error_message));
  264. }
  265. }
  266. if let Some(tauri) = manifest.dependencies.remove("tauri") {
  267. let error_message = check_features(&config, tauri, false);
  268. if !error_message.is_empty() {
  269. return Err(anyhow!("
  270. The `tauri` dependency features on the `Cargo.toml` file does not match the allowlist defined under `tauri.conf.json`.
  271. Please run `tauri dev` or `tauri build` or {}.
  272. ", error_message));
  273. }
  274. }
  275. let target_triple = std::env::var("TARGET").unwrap();
  276. let out_dir = PathBuf::from(std::env::var("OUT_DIR").unwrap());
  277. // TODO: far from ideal, but there's no other way to get the target dir, see <https://github.com/rust-lang/cargo/issues/5457>
  278. let target_dir = out_dir
  279. .parent()
  280. .unwrap()
  281. .parent()
  282. .unwrap()
  283. .parent()
  284. .unwrap();
  285. if let Some(paths) = &config.tauri.bundle.external_bin {
  286. copy_binaries(
  287. ResourcePaths::new(external_binaries(paths, &target_triple).as_slice(), true),
  288. &target_triple,
  289. target_dir,
  290. manifest.package.as_ref().map(|p| &p.name),
  291. )?;
  292. }
  293. #[allow(unused_mut, clippy::redundant_clone)]
  294. let mut resources = config.tauri.bundle.resources.clone().unwrap_or_default();
  295. if target_triple.contains("windows") {
  296. if let Some(fixed_webview2_runtime_path) =
  297. &config.tauri.bundle.windows.webview_fixed_runtime_path
  298. {
  299. resources.push(fixed_webview2_runtime_path.display().to_string());
  300. }
  301. }
  302. copy_resources(ResourcePaths::new(resources.as_slice(), true), target_dir)?;
  303. if target_triple.contains("darwin") {
  304. if let Some(version) = &config.tauri.bundle.macos.minimum_system_version {
  305. println!("cargo:rustc-env=MACOSX_DEPLOYMENT_TARGET={}", version);
  306. }
  307. }
  308. if target_triple.contains("windows") {
  309. use anyhow::Context;
  310. use semver::Version;
  311. use tauri_winres::{VersionInfo, WindowsResource};
  312. fn find_icon<F: Fn(&&String) -> bool>(config: &Config, predicate: F, default: &str) -> PathBuf {
  313. let icon_path = config
  314. .tauri
  315. .bundle
  316. .icon
  317. .iter()
  318. .find(|i| predicate(i))
  319. .cloned()
  320. .unwrap_or_else(|| default.to_string());
  321. icon_path.into()
  322. }
  323. let window_icon_path = attributes
  324. .windows_attributes
  325. .window_icon_path
  326. .unwrap_or_else(|| find_icon(&config, |i| i.ends_with(".ico"), "icons/icon.ico"));
  327. if window_icon_path.exists() {
  328. let mut res = WindowsResource::new();
  329. if let Some(manifest) = attributes.windows_attributes.app_manifest {
  330. res.set_manifest(&manifest);
  331. } else {
  332. res.set_manifest(include_str!("window-app-manifest.xml"));
  333. }
  334. if let Some(sdk_dir) = &attributes.windows_attributes.sdk_dir {
  335. if let Some(sdk_dir_str) = sdk_dir.to_str() {
  336. res.set_toolkit_path(sdk_dir_str);
  337. } else {
  338. return Err(anyhow!(
  339. "sdk_dir path is not valid; only UTF-8 characters are allowed"
  340. ));
  341. }
  342. }
  343. if let Some(version) = &config.package.version {
  344. if let Ok(v) = Version::parse(version) {
  345. let version = v.major << 48 | v.minor << 32 | v.patch << 16;
  346. res.set_version_info(VersionInfo::FILEVERSION, version);
  347. res.set_version_info(VersionInfo::PRODUCTVERSION, version);
  348. }
  349. res.set("FileVersion", version);
  350. res.set("ProductVersion", version);
  351. }
  352. if let Some(product_name) = &config.package.product_name {
  353. res.set("ProductName", product_name);
  354. res.set("FileDescription", product_name);
  355. }
  356. res.set_icon_with_id(&window_icon_path.display().to_string(), "32512");
  357. res.compile().with_context(|| {
  358. format!(
  359. "failed to compile `{}` into a Windows Resource file during tauri-build",
  360. window_icon_path.display()
  361. )
  362. })?;
  363. } else {
  364. return Err(anyhow!(format!(
  365. "`{}` not found; required for generating a Windows Resource file during tauri-build",
  366. window_icon_path.display()
  367. )));
  368. }
  369. let target_env = std::env::var("CARGO_CFG_TARGET_ENV").unwrap();
  370. match target_env.as_str() {
  371. "gnu" => {
  372. let target_arch = match std::env::var("CARGO_CFG_TARGET_ARCH").unwrap().as_str() {
  373. "x86_64" => Some("x64"),
  374. "x86" => Some("x86"),
  375. "aarch64" => Some("arm64"),
  376. arch => None,
  377. };
  378. if let Some(target_arch) = target_arch {
  379. for entry in std::fs::read_dir(target_dir.join("build"))? {
  380. let path = entry?.path();
  381. let webview2_loader_path = path
  382. .join("out")
  383. .join(target_arch)
  384. .join("WebView2Loader.dll");
  385. if path.to_string_lossy().contains("webview2-com-sys") && webview2_loader_path.exists()
  386. {
  387. std::fs::copy(webview2_loader_path, target_dir.join("WebView2Loader.dll"))?;
  388. break;
  389. }
  390. }
  391. }
  392. }
  393. "msvc" => {
  394. if std::env::var("STATIC_VCRUNTIME").map_or(false, |v| v == "true") {
  395. static_vcruntime::build();
  396. }
  397. }
  398. _ => (),
  399. }
  400. }
  401. Ok(())
  402. }
  403. #[derive(Debug, Default, PartialEq, Eq)]
  404. struct Diff {
  405. remove: Vec<String>,
  406. add: Vec<String>,
  407. }
  408. fn features_diff(current: &[String], expected: &[String]) -> Diff {
  409. let mut remove = Vec::new();
  410. let mut add = Vec::new();
  411. for feature in current {
  412. if !expected.contains(feature) {
  413. remove.push(feature.clone());
  414. }
  415. }
  416. for feature in expected {
  417. if !current.contains(feature) {
  418. add.push(feature.clone());
  419. }
  420. }
  421. Diff { remove, add }
  422. }
  423. fn check_features(config: &Config, dependency: Dependency, is_tauri_build: bool) -> String {
  424. use tauri_utils::config::{PatternKind, TauriConfig};
  425. let features = match dependency {
  426. Dependency::Simple(_) => Vec::new(),
  427. Dependency::Detailed(dep) => dep.features,
  428. Dependency::Inherited(dep) => dep.features,
  429. };
  430. let all_cli_managed_features = if is_tauri_build {
  431. vec!["isolation"]
  432. } else {
  433. TauriConfig::all_features()
  434. };
  435. let expected = if is_tauri_build {
  436. match config.tauri.pattern {
  437. PatternKind::Isolation { .. } => vec!["isolation".to_string()],
  438. _ => vec![],
  439. }
  440. } else {
  441. config
  442. .tauri
  443. .features()
  444. .into_iter()
  445. .map(|f| f.to_string())
  446. .collect::<Vec<String>>()
  447. };
  448. let diff = features_diff(
  449. &features
  450. .into_iter()
  451. .filter(|f| all_cli_managed_features.contains(&f.as_str()))
  452. .collect::<Vec<String>>(),
  453. &expected,
  454. );
  455. let mut error_message = String::new();
  456. if !diff.remove.is_empty() {
  457. error_message.push_str("remove the `");
  458. error_message.push_str(&diff.remove.join(", "));
  459. error_message.push_str(if diff.remove.len() == 1 {
  460. "` feature"
  461. } else {
  462. "` features"
  463. });
  464. if !diff.add.is_empty() {
  465. error_message.push_str(" and ");
  466. }
  467. }
  468. if !diff.add.is_empty() {
  469. error_message.push_str("add the `");
  470. error_message.push_str(&diff.add.join(", "));
  471. error_message.push_str(if diff.add.len() == 1 {
  472. "` feature"
  473. } else {
  474. "` features"
  475. });
  476. }
  477. error_message
  478. }
  479. #[derive(serde::Deserialize)]
  480. struct CargoMetadata {
  481. workspace_root: PathBuf,
  482. }
  483. fn get_workspace_dir() -> Result<PathBuf> {
  484. let output = std::process::Command::new("cargo")
  485. .args(["metadata", "--no-deps", "--format-version", "1"])
  486. .output()?;
  487. if !output.status.success() {
  488. return Err(anyhow::anyhow!(
  489. "cargo metadata command exited with a non zero exit code: {}",
  490. String::from_utf8(output.stderr)?
  491. ));
  492. }
  493. Ok(serde_json::from_slice::<CargoMetadata>(&output.stdout)?.workspace_root)
  494. }
  495. #[cfg(test)]
  496. mod tests {
  497. use super::Diff;
  498. #[test]
  499. fn array_diff() {
  500. for (current, expected, result) in [
  501. (vec![], vec![], Default::default()),
  502. (
  503. vec!["a".into()],
  504. vec![],
  505. Diff {
  506. remove: vec!["a".into()],
  507. add: vec![],
  508. },
  509. ),
  510. (vec!["a".into()], vec!["a".into()], Default::default()),
  511. (
  512. vec!["a".into(), "b".into()],
  513. vec!["a".into()],
  514. Diff {
  515. remove: vec!["b".into()],
  516. add: vec![],
  517. },
  518. ),
  519. (
  520. vec!["a".into(), "b".into()],
  521. vec!["a".into(), "c".into()],
  522. Diff {
  523. remove: vec!["b".into()],
  524. add: vec!["c".into()],
  525. },
  526. ),
  527. ] {
  528. assert_eq!(super::features_diff(&current, &expected), result);
  529. }
  530. }
  531. }