build.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. use heck::AsShoutySnakeCase;
  5. use tauri_utils::write_if_changed;
  6. use std::env::var_os;
  7. use std::fs::create_dir_all;
  8. use std::fs::read_dir;
  9. use std::fs::read_to_string;
  10. use std::{
  11. env::var,
  12. path::{Path, PathBuf},
  13. sync::{Mutex, OnceLock},
  14. };
  15. static CHECKED_FEATURES: OnceLock<Mutex<Vec<String>>> = OnceLock::new();
  16. const PLUGINS: &[(&str, &[(&str, bool)])] = &[
  17. // (plugin_name, &[(command, enabled-by_default)])
  18. // note that when adding new core plugins, they must be added to the ACL resolver aswell
  19. (
  20. "core:path",
  21. &[
  22. ("resolve_directory", true),
  23. ("resolve", true),
  24. ("normalize", true),
  25. ("join", true),
  26. ("dirname", true),
  27. ("extname", true),
  28. ("basename", true),
  29. ("is_absolute", true),
  30. ],
  31. ),
  32. (
  33. "core:event",
  34. &[
  35. ("listen", true),
  36. ("unlisten", true),
  37. ("emit", true),
  38. ("emit_to", true),
  39. ],
  40. ),
  41. (
  42. "core:window",
  43. &[
  44. ("create", false),
  45. // getters
  46. ("get_all_windows", true),
  47. ("scale_factor", true),
  48. ("inner_position", true),
  49. ("outer_position", true),
  50. ("inner_size", true),
  51. ("outer_size", true),
  52. ("is_fullscreen", true),
  53. ("is_minimized", true),
  54. ("is_maximized", true),
  55. ("is_focused", true),
  56. ("is_decorated", true),
  57. ("is_resizable", true),
  58. ("is_maximizable", true),
  59. ("is_minimizable", true),
  60. ("is_closable", true),
  61. ("is_visible", true),
  62. ("title", true),
  63. ("current_monitor", true),
  64. ("primary_monitor", true),
  65. ("monitor_from_point", true),
  66. ("available_monitors", true),
  67. ("cursor_position", true),
  68. ("theme", true),
  69. // setters
  70. ("center", false),
  71. ("request_user_attention", false),
  72. ("set_resizable", false),
  73. ("set_maximizable", false),
  74. ("set_minimizable", false),
  75. ("set_closable", false),
  76. ("set_title", false),
  77. ("maximize", false),
  78. ("unmaximize", false),
  79. ("minimize", false),
  80. ("unminimize", false),
  81. ("show", false),
  82. ("hide", false),
  83. ("close", false),
  84. ("destroy", false),
  85. ("set_decorations", false),
  86. ("set_shadow", false),
  87. ("set_effects", false),
  88. ("set_always_on_top", false),
  89. ("set_always_on_bottom", false),
  90. ("set_visible_on_all_workspaces", false),
  91. ("set_content_protected", false),
  92. ("set_size", false),
  93. ("set_min_size", false),
  94. ("set_size_constraints", false),
  95. ("set_max_size", false),
  96. ("set_position", false),
  97. ("set_fullscreen", false),
  98. ("set_focus", false),
  99. ("set_skip_taskbar", false),
  100. ("set_cursor_grab", false),
  101. ("set_cursor_visible", false),
  102. ("set_cursor_icon", false),
  103. ("set_cursor_position", false),
  104. ("set_ignore_cursor_events", false),
  105. ("start_dragging", false),
  106. ("start_resize_dragging", false),
  107. ("set_progress_bar", false),
  108. ("set_icon", false),
  109. ("set_title_bar_style", false),
  110. ("toggle_maximize", false),
  111. // internal
  112. ("internal_toggle_maximize", true),
  113. ],
  114. ),
  115. (
  116. "core:webview",
  117. &[
  118. ("create_webview", false),
  119. ("create_webview_window", false),
  120. // getters
  121. ("get_all_webviews", true),
  122. ("webview_position", true),
  123. ("webview_size", true),
  124. // setters
  125. ("webview_close", false),
  126. ("set_webview_size", false),
  127. ("set_webview_position", false),
  128. ("set_webview_focus", false),
  129. ("set_webview_zoom", false),
  130. ("print", false),
  131. ("reparent", false),
  132. // internal
  133. ("internal_toggle_devtools", true),
  134. ],
  135. ),
  136. (
  137. "core:app",
  138. &[
  139. ("version", true),
  140. ("name", true),
  141. ("tauri_version", true),
  142. ("app_show", false),
  143. ("app_hide", false),
  144. ("default_window_icon", false),
  145. ],
  146. ),
  147. (
  148. "core:image",
  149. &[
  150. ("new", true),
  151. ("from_bytes", true),
  152. ("from_path", true),
  153. ("rgba", true),
  154. ("size", true),
  155. ],
  156. ),
  157. ("core:resources", &[("close", true)]),
  158. (
  159. "core:menu",
  160. &[
  161. ("new", true),
  162. ("append", true),
  163. ("prepend", true),
  164. ("insert", true),
  165. ("remove", true),
  166. ("remove_at", true),
  167. ("items", true),
  168. ("get", true),
  169. ("popup", true),
  170. ("create_default", true),
  171. ("set_as_app_menu", true),
  172. ("set_as_window_menu", true),
  173. ("text", true),
  174. ("set_text", true),
  175. ("is_enabled", true),
  176. ("set_enabled", true),
  177. ("set_accelerator", true),
  178. ("set_as_windows_menu_for_nsapp", true),
  179. ("set_as_help_menu_for_nsapp", true),
  180. ("is_checked", true),
  181. ("set_checked", true),
  182. ("set_icon", true),
  183. ],
  184. ),
  185. (
  186. "core:tray",
  187. &[
  188. ("new", true),
  189. ("get_by_id", true),
  190. ("remove_by_id", true),
  191. ("set_icon", true),
  192. ("set_menu", true),
  193. ("set_tooltip", true),
  194. ("set_title", true),
  195. ("set_visible", true),
  196. ("set_temp_dir_path", true),
  197. ("set_icon_as_template", true),
  198. ("set_show_menu_on_left_click", true),
  199. ],
  200. ),
  201. ];
  202. // checks if the given Cargo feature is enabled.
  203. fn has_feature(feature: &str) -> bool {
  204. CHECKED_FEATURES
  205. .get_or_init(Default::default)
  206. .lock()
  207. .unwrap()
  208. .push(feature.to_string());
  209. // when a feature is enabled, Cargo sets the `CARGO_FEATURE_<name>` env var to 1
  210. // <https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts>
  211. std::env::var(format!("CARGO_FEATURE_{}", AsShoutySnakeCase(feature)))
  212. .map(|x| x == "1")
  213. .unwrap_or(false)
  214. }
  215. // creates a cfg alias if `has_feature` is true.
  216. // `alias` must be a snake case string.
  217. fn alias(alias: &str, has_feature: bool) {
  218. println!("cargo:rustc-check-cfg=cfg({alias})");
  219. if has_feature {
  220. println!("cargo:rustc-cfg={alias}");
  221. }
  222. }
  223. fn main() {
  224. let custom_protocol = has_feature("custom-protocol");
  225. let dev = !custom_protocol;
  226. alias("custom_protocol", custom_protocol);
  227. alias("dev", dev);
  228. println!("cargo:dev={dev}");
  229. let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
  230. let mobile = target_os == "ios" || target_os == "android";
  231. alias("desktop", !mobile);
  232. alias("mobile", mobile);
  233. let out_dir = PathBuf::from(var("OUT_DIR").unwrap());
  234. let checked_features_out_path = out_dir.join("checked_features");
  235. std::fs::write(
  236. checked_features_out_path,
  237. CHECKED_FEATURES.get().unwrap().lock().unwrap().join(","),
  238. )
  239. .expect("failed to write checked_features file");
  240. // workaround needed to prevent `STATUS_ENTRYPOINT_NOT_FOUND` error
  241. // see https://github.com/tauri-apps/tauri/pull/4383#issuecomment-1212221864
  242. let target_env = std::env::var("CARGO_CFG_TARGET_ENV");
  243. let is_tauri_workspace = std::env::var("__TAURI_WORKSPACE__").map_or(false, |v| v == "true");
  244. if is_tauri_workspace && target_os == "windows" && Ok("msvc") == target_env.as_deref() {
  245. add_manifest();
  246. }
  247. if target_os == "android" {
  248. if let Ok(kotlin_out_dir) = std::env::var("WRY_ANDROID_KOTLIN_FILES_OUT_DIR") {
  249. fn env_var(var: &str) -> String {
  250. std::env::var(var).unwrap_or_else(|_| {
  251. panic!("`{var}` is not set, which is needed to generate the kotlin files for android.")
  252. })
  253. }
  254. let package = env_var("WRY_ANDROID_PACKAGE");
  255. let library = env_var("WRY_ANDROID_LIBRARY");
  256. let kotlin_out_dir = PathBuf::from(&kotlin_out_dir)
  257. .canonicalize()
  258. .unwrap_or_else(move |_| {
  259. panic!("Failed to canonicalize `WRY_ANDROID_KOTLIN_FILES_OUT_DIR` path {kotlin_out_dir}")
  260. });
  261. let kotlin_files_path =
  262. PathBuf::from(env_var("CARGO_MANIFEST_DIR")).join("mobile/android-codegen");
  263. println!("cargo:rerun-if-changed={}", kotlin_files_path.display());
  264. let kotlin_files =
  265. read_dir(kotlin_files_path).expect("failed to read Android codegen directory");
  266. for file in kotlin_files {
  267. let file = file.unwrap();
  268. let content = read_to_string(file.path())
  269. .expect("failed to read kotlin file as string")
  270. .replace("{{package}}", &package)
  271. .replace("{{library}}", &library);
  272. let out_path = kotlin_out_dir.join(file.file_name());
  273. // Overwrite only if changed to not trigger rebuilds
  274. write_if_changed(&out_path, &content).expect("Failed to write kotlin file");
  275. println!("cargo:rerun-if-changed={}", out_path.display());
  276. }
  277. }
  278. if let Some(project_dir) = var_os("TAURI_ANDROID_PROJECT_PATH").map(PathBuf::from) {
  279. let tauri_proguard = include_str!("./mobile/proguard-tauri.pro").replace(
  280. "$PACKAGE",
  281. &var("WRY_ANDROID_PACKAGE").expect("missing `WRY_ANDROID_PACKAGE` environment variable"),
  282. );
  283. std::fs::write(
  284. project_dir.join("app").join("proguard-tauri.pro"),
  285. tauri_proguard,
  286. )
  287. .expect("failed to write proguard-tauri.pro");
  288. }
  289. let lib_path =
  290. PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap()).join("mobile/android");
  291. println!("cargo:android_library_path={}", lib_path.display());
  292. }
  293. #[cfg(target_os = "macos")]
  294. {
  295. if target_os == "ios" {
  296. let lib_path =
  297. PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap()).join("mobile/ios-api");
  298. tauri_utils::build::link_apple_library("Tauri", &lib_path);
  299. println!("cargo:ios_library_path={}", lib_path.display());
  300. }
  301. }
  302. define_permissions(&out_dir);
  303. }
  304. fn define_permissions(out_dir: &Path) {
  305. let license_header = r"# Copyright 2019-2024 Tauri Programme within The Commons Conservancy
  306. # SPDX-License-Identifier: Apache-2.0
  307. # SPDX-License-Identifier: MIT
  308. ";
  309. for (plugin, commands) in PLUGINS {
  310. let plugin_directory_name = plugin.strip_prefix("core:").unwrap_or(plugin);
  311. let permissions_out_dir = out_dir.join("permissions").join(plugin_directory_name);
  312. let autogenerated =
  313. permissions_out_dir.join(tauri_utils::acl::build::AUTOGENERATED_FOLDER_NAME);
  314. let commands_dir = autogenerated.join("commands");
  315. tauri_utils::acl::build::autogenerate_command_permissions(
  316. &commands_dir,
  317. &commands.iter().map(|(cmd, _)| *cmd).collect::<Vec<_>>(),
  318. license_header,
  319. false,
  320. );
  321. let default_permissions = commands
  322. .iter()
  323. .filter(|(_cmd, default)| *default)
  324. .map(|(cmd, _)| {
  325. let slugified_command = cmd.replace('_', "-");
  326. format!("\"allow-{slugified_command}\"")
  327. })
  328. .collect::<Vec<_>>()
  329. .join(", ");
  330. let default_toml = format!(
  331. r###"{license_header}# Automatically generated - DO NOT EDIT!
  332. [default]
  333. description = "Default permissions for the plugin."
  334. permissions = [{default_permissions}]
  335. "###,
  336. );
  337. let out_path = autogenerated.join("default.toml");
  338. if default_toml != read_to_string(&out_path).unwrap_or_default() {
  339. std::fs::write(out_path, default_toml)
  340. .unwrap_or_else(|_| panic!("unable to autogenerate default permissions"));
  341. }
  342. let permissions = tauri_utils::acl::build::define_permissions(
  343. &permissions_out_dir
  344. .join("**")
  345. .join("*.toml")
  346. .to_string_lossy(),
  347. &format!("tauri:{plugin}"),
  348. out_dir,
  349. |_| true,
  350. )
  351. .unwrap_or_else(|e| panic!("failed to define permissions for {plugin}: {e}"));
  352. let docs_out_dir = Path::new("permissions")
  353. .join(plugin_directory_name)
  354. .join("autogenerated");
  355. create_dir_all(&docs_out_dir).expect("failed to create plugin documentation directory");
  356. tauri_utils::acl::build::generate_docs(
  357. &permissions,
  358. &docs_out_dir,
  359. plugin.strip_prefix("tauri-plugin-").unwrap_or(plugin),
  360. )
  361. .expect("failed to generate plugin documentation page");
  362. }
  363. }
  364. fn add_manifest() {
  365. static WINDOWS_MANIFEST_FILE: &str = "window-app-manifest.xml";
  366. let manifest = std::env::current_dir()
  367. .unwrap()
  368. .join("../tauri-build/src")
  369. .join(WINDOWS_MANIFEST_FILE);
  370. println!("cargo:rerun-if-changed={}", manifest.display());
  371. // Embed the Windows application manifest file.
  372. println!("cargo:rustc-link-arg=/MANIFEST:EMBED");
  373. println!(
  374. "cargo:rustc-link-arg=/MANIFESTINPUT:{}",
  375. manifest.to_str().unwrap()
  376. );
  377. // Turn linker warnings into errors.
  378. println!("cargo:rustc-link-arg=/WX");
  379. }