context.rs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright 2019-2021 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. use crate::embedded_assets::{EmbeddedAssets, EmbeddedAssetsError};
  5. use proc_macro2::TokenStream;
  6. use quote::quote;
  7. use std::path::PathBuf;
  8. use tauri_utils::config::Config;
  9. /// Necessary data needed by [`context_codegen`] to generate code for a Tauri application context.
  10. pub struct ContextData {
  11. pub dev: bool,
  12. pub config: Config,
  13. pub config_parent: PathBuf,
  14. pub root: TokenStream,
  15. }
  16. /// Build a `tauri::Context` for including in application code.
  17. pub fn context_codegen(data: ContextData) -> Result<TokenStream, EmbeddedAssetsError> {
  18. let ContextData {
  19. dev,
  20. config,
  21. config_parent,
  22. root,
  23. } = data;
  24. let assets_path = if dev {
  25. // if dev_path is a dev server, we don't have any assets to embed
  26. if config.build.dev_path.starts_with("http") {
  27. None
  28. } else {
  29. Some(config_parent.join(&config.build.dev_path))
  30. }
  31. } else {
  32. Some(config_parent.join(&config.build.dist_dir))
  33. };
  34. // generate the assets inside the dist dir into a perfect hash function
  35. let assets = if let Some(assets_path) = assets_path {
  36. EmbeddedAssets::new(&assets_path)?
  37. } else {
  38. Default::default()
  39. };
  40. // handle default window icons for Windows targets
  41. let default_window_icon = if cfg!(windows) {
  42. let icon_path = config
  43. .tauri
  44. .bundle
  45. .icon
  46. .iter()
  47. .find(|i| i.ends_with(".ico"))
  48. .cloned()
  49. .unwrap_or_else(|| "icons/icon.ico".to_string());
  50. let icon_path = config_parent.join(icon_path).display().to_string();
  51. quote!(Some(include_bytes!(#icon_path).to_vec()))
  52. } else {
  53. quote!(None)
  54. };
  55. let package_name = if let Some(product_name) = &config.package.product_name {
  56. quote!(#product_name.to_string())
  57. } else {
  58. quote!(env!("CARGO_PKG_NAME").to_string())
  59. };
  60. let package_version = if let Some(version) = &config.package.version {
  61. quote!(#version.to_string())
  62. } else {
  63. quote!(env!("CARGO_PKG_VERSION").to_string())
  64. };
  65. // double braces are purposeful to force the code into a block expression
  66. Ok(quote!(#root::Context {
  67. config: #config,
  68. assets: #assets,
  69. default_window_icon: #default_window_icon,
  70. package_info: #root::api::PackageInfo {
  71. name: #package_name,
  72. version: #package_version,
  73. },
  74. }))
  75. }