lib.rs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. //! [![](https://github.com/tauri-apps/tauri/raw/dev/.github/splash.png)](https://tauri.app)
  5. //!
  6. //! Create macros for `tauri::Context`, invoke handler and commands leveraging the `tauri-codegen` crate.
  7. #![doc(
  8. html_logo_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png",
  9. html_favicon_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png"
  10. )]
  11. use std::path::PathBuf;
  12. use crate::context::ContextItems;
  13. use proc_macro::TokenStream;
  14. use quote::{quote, ToTokens};
  15. use syn::{parse2, parse_macro_input, LitStr};
  16. use tauri_codegen::image::CachedIcon;
  17. mod command;
  18. mod menu;
  19. mod mobile;
  20. mod runtime;
  21. #[macro_use]
  22. mod context;
  23. /// Mark a function as a command handler. It creates a wrapper function with the necessary glue code.
  24. ///
  25. /// # Stability
  26. /// The output of this macro is managed internally by Tauri,
  27. /// and should not be accessed directly on normal applications.
  28. /// It may have breaking changes in the future.
  29. #[proc_macro_attribute]
  30. pub fn command(attributes: TokenStream, item: TokenStream) -> TokenStream {
  31. command::wrapper(attributes, item)
  32. }
  33. #[proc_macro_attribute]
  34. pub fn mobile_entry_point(attributes: TokenStream, item: TokenStream) -> TokenStream {
  35. mobile::entry_point(attributes, item)
  36. }
  37. /// Accepts a list of command functions. Creates a handler that allows commands to be called from JS with invoke().
  38. ///
  39. /// # Examples
  40. /// ```rust,ignore
  41. /// use tauri_macros::{command, generate_handler};
  42. /// #[command]
  43. /// fn command_one() {
  44. /// println!("command one called");
  45. /// }
  46. /// #[command]
  47. /// fn command_two() {
  48. /// println!("command two called");
  49. /// }
  50. /// fn main() {
  51. /// let _handler = generate_handler![command_one, command_two];
  52. /// }
  53. /// ```
  54. /// # Stability
  55. /// The output of this macro is managed internally by Tauri,
  56. /// and should not be accessed directly on normal applications.
  57. /// It may have breaking changes in the future.
  58. #[proc_macro]
  59. pub fn generate_handler(item: TokenStream) -> TokenStream {
  60. parse_macro_input!(item as command::Handler).into()
  61. }
  62. /// Reads a Tauri config file and generates a `::tauri::Context` based on the content.
  63. ///
  64. /// # Stability
  65. /// The output of this macro is managed internally by Tauri,
  66. /// and should not be accessed directly on normal applications.
  67. /// It may have breaking changes in the future.
  68. #[proc_macro]
  69. pub fn generate_context(items: TokenStream) -> TokenStream {
  70. // this macro is exported from the context module
  71. let path = parse_macro_input!(items as ContextItems);
  72. context::generate_context(path).into()
  73. }
  74. /// Adds the default type for the last parameter (assumed to be runtime) for a specific feature.
  75. ///
  76. /// e.g. To default the runtime generic to type `crate::Wry` when the `wry` feature is enabled, the
  77. /// syntax would look like `#[default_runtime(crate::Wry, wry)`. This is **always** set for the last
  78. /// generic, so make sure the last generic is the runtime when using this macro.
  79. #[doc(hidden)]
  80. #[proc_macro_attribute]
  81. pub fn default_runtime(attributes: TokenStream, input: TokenStream) -> TokenStream {
  82. let attributes = parse_macro_input!(attributes as runtime::Attributes);
  83. let input = parse_macro_input!(input as runtime::Input);
  84. runtime::default_runtime(attributes, input).into()
  85. }
  86. /// Accepts a closure-like syntax to call arbitrary code on a menu item
  87. /// after matching against `kind` and retrieving it from `resources_table` using `rid`.
  88. ///
  89. /// You can optionally pass a 5th parameter to select which item kinds
  90. /// to match against, by providing a `|` separated list of item kinds
  91. /// ```ignore
  92. /// do_menu_item!(resources_table, rid, kind, |i| i.set_text(text), Check | Submenu);
  93. /// ```
  94. /// You could also provide a negated list
  95. /// ```ignore
  96. /// do_menu_item!(resources_table, rid, kind, |i| i.set_text(text), !Check);
  97. /// do_menu_item!(resources_table, rid, kind, |i| i.set_text(text), !Check | !Submenu);
  98. /// ```
  99. /// but you can't have mixed negations and positive kinds.
  100. /// ```ignore
  101. /// do_menu_item!(resources_table, rid, kind, |i| i.set_text(text), !Check | Submenu);
  102. /// ```
  103. ///
  104. /// #### Example
  105. ///
  106. /// ```ignore
  107. /// let rid = 23;
  108. /// let kind = ItemKind::Check;
  109. /// let resources_table = app.resources_table();
  110. /// do_menu_item!(resources_table, rid, kind, |i| i.set_text(text))
  111. /// ```
  112. /// which will expand into:
  113. /// ```ignore
  114. /// let rid = 23;
  115. /// let kind = ItemKind::Check;
  116. /// let resources_table = app.resources_table();
  117. /// match kind {
  118. /// ItemKind::Submenu => {
  119. /// let i = resources_table.get::<Submenu<R>>(rid)?;
  120. /// i.set_text(text)
  121. /// }
  122. /// ItemKind::MenuItem => {
  123. /// let i = resources_table.get::<MenuItem<R>>(rid)?;
  124. /// i.set_text(text)
  125. /// }
  126. /// ItemKind::Predefined => {
  127. /// let i = resources_table.get::<PredefinedMenuItem<R>>(rid)?;
  128. /// i.set_text(text)
  129. /// }
  130. /// ItemKind::Check => {
  131. /// let i = resources_table.get::<CheckMenuItem<R>>(rid)?;
  132. /// i.set_text(text)
  133. /// }
  134. /// ItemKind::Icon => {
  135. /// let i = resources_table.get::<IconMenuItem<R>>(rid)?;
  136. /// i.set_text(text)
  137. /// }
  138. /// _ => unreachable!(),
  139. /// }
  140. /// ```
  141. #[proc_macro]
  142. pub fn do_menu_item(input: TokenStream) -> TokenStream {
  143. let tokens = parse_macro_input!(input as menu::DoMenuItemInput);
  144. menu::do_menu_item(tokens).into()
  145. }
  146. /// Convert a .png or .ico icon to an Image
  147. /// for things like `tauri::tray::TrayIconBuilder` to consume,
  148. /// relative paths are resolved from `CARGO_MANIFEST_DIR`, not current file
  149. ///
  150. /// ### Examples
  151. ///
  152. /// ```ignore
  153. /// const APP_ICON: Image<'_> = include_image!("./icons/32x32.png");
  154. ///
  155. /// // then use it with tray
  156. /// TrayIconBuilder::new().icon(APP_ICON).build().unwrap();
  157. ///
  158. /// // or with window
  159. /// WebviewWindowBuilder::new(app, "main", WebviewUrl::default())
  160. /// .icon(APP_ICON)
  161. /// .unwrap()
  162. /// .build()
  163. /// .unwrap();
  164. ///
  165. /// // or with any other functions that takes `Image` struct
  166. /// ```
  167. ///
  168. /// Note: this stores the image in raw pixels to the final binary,
  169. /// so keep the icon size (width and height) small
  170. /// or else it's going to bloat your final executable
  171. #[proc_macro]
  172. pub fn include_image(tokens: TokenStream) -> TokenStream {
  173. let path = match parse2::<LitStr>(tokens.into()) {
  174. Ok(path) => path,
  175. Err(err) => return err.into_compile_error().into(),
  176. };
  177. let path = PathBuf::from(path.value());
  178. let resolved_path = if path.is_relative() {
  179. if let Ok(base_dir) = std::env::var("CARGO_MANIFEST_DIR").map(PathBuf::from) {
  180. base_dir.join(path)
  181. } else {
  182. return quote!(compile_error!("$CARGO_MANIFEST_DIR is not defined")).into();
  183. }
  184. } else {
  185. path
  186. };
  187. if !resolved_path.exists() {
  188. let error_string = format!(
  189. "Provided Image path \"{}\" doesn't exists",
  190. resolved_path.display()
  191. );
  192. return quote!(compile_error!(#error_string)).into();
  193. }
  194. match CachedIcon::new(&quote!(::tauri), &resolved_path).map_err(|error| error.to_string()) {
  195. Ok(icon) => icon.into_token_stream(),
  196. Err(error) => quote!(compile_error!(#error)),
  197. }
  198. .into()
  199. }