lib.rs 6.9 KB

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