Skip to main content

tauri_macros/
lib.rs

1// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
2// SPDX-License-Identifier: Apache-2.0
3// SPDX-License-Identifier: MIT
4
5//! Create macros for `tauri::Context`, invoke handler and commands leveraging the `tauri-codegen` crate.
6//!
7//! Don't depend on this crate directly, use the re-exported types from tauri instead.
8
9#![doc(
10  html_logo_url = "https://github.com/tauri-apps/tauri/raw/dev/.github/icon.png",
11  html_favicon_url = "https://github.com/tauri-apps/tauri/raw/dev/.github/icon.png"
12)]
13
14use std::path::PathBuf;
15
16use crate::context::ContextItems;
17use proc_macro::TokenStream;
18use quote::{ToTokens, quote};
19use syn::{LitStr, parse_macro_input, parse2};
20use tauri_codegen::image::CachedIcon;
21
22mod command;
23mod menu;
24mod mobile;
25mod runtime;
26
27#[macro_use]
28mod context;
29
30/// Mark a function as a command handler. It creates a wrapper function with the necessary glue code.
31///
32/// The wrapped function can then be passed to [`generate_handler!`] so it can be called
33/// from the frontend with `invoke()`.
34///
35/// ```rust,ignore
36/// #[tauri::command]
37/// fn greet(name: String) -> String {
38///   format!("Hello, {name}!")
39/// }
40/// ```
41///
42/// # Options
43///
44/// The attribute accepts a comma separated list of the following options:
45///
46/// ## `async`
47///
48/// Runs the command on the async runtime instead of blocking the main thread.
49///
50/// `async fn` commands are always executed asynchronously, so this option is only needed
51/// for synchronous functions that should not run on the main thread:
52///
53/// ```rust,ignore
54/// #[tauri::command(async)]
55/// fn expensive_computation() -> u64 {
56///   // the body runs on the async runtime, so the main thread is not blocked
57///   42
58/// }
59/// ```
60///
61/// ## `rename_all`
62///
63/// Sets the case convention used to match the command arguments with the keys of the
64/// payload sent by the frontend. Either `"camelCase"` (default) or `"snake_case"`.
65///
66/// ```rust,ignore
67/// // called from JavaScript with `invoke("send_message", { messageBody: "Hello" })`
68/// #[tauri::command]
69/// fn send_message(message_body: String) {}
70///
71/// // called from JavaScript with `invoke("send_message", { message_body: "Hello" })`
72/// #[tauri::command(rename_all = "snake_case")]
73/// fn send_message_snake(message_body: String) {}
74/// ```
75///
76/// ## `rename`
77///
78/// Changes the name used to call the command from the frontend.
79/// By default it is the name of the function.
80///
81/// ```rust,ignore
82/// // called from JavaScript with `invoke("greetUser")`
83/// // and still registered as `generate_handler![greet_user]`
84/// #[tauri::command(rename = "greetUser")]
85/// fn greet_user() {}
86/// ```
87///
88/// ## `root`
89///
90/// Path to the `tauri` crate, used when it is renamed in `Cargo.toml` or re-exported
91/// by another crate. Defaults to `::tauri`, and the special value `"crate"` resolves
92/// to `$crate` (used internally by Tauri itself).
93///
94/// ```rust,ignore
95/// // Cargo.toml: tauri_framework = { package = "tauri", version = "2" }
96/// #[tauri::command(root = "tauri_framework")]
97/// fn my_command() {}
98/// ```
99///
100/// # Inline plugins
101///
102/// When the command belongs to a plugin that is part of your application instead of a
103/// standalone crate, annotate it in the [`generate_handler!`] list with the
104/// `#![plugin(your_plugin_name)]` inner attribute so `build > removeUnusedCommands` can
105/// match it against the plugin permissions.
106///
107/// # Stability
108/// The output of this macro is managed internally by Tauri,
109/// and should not be accessed directly on normal applications.
110/// It may have breaking changes in the future.
111#[proc_macro_attribute]
112pub fn command(attributes: TokenStream, item: TokenStream) -> TokenStream {
113  command::wrapper(attributes, item)
114}
115
116/// Marks a function as the entry point of a mobile application.
117///
118/// It must be applied to the function that builds and runs your Tauri application on the
119/// library target (`run()` on `src-tauri/src/lib.rs` for apps created by the Tauri CLI),
120/// which is the function the generated Android and iOS projects call on startup.
121///
122/// The canonical usage only applies it on mobile targets, so the same function can be called
123/// by the `main.rs` of the desktop binary:
124///
125/// ```rust,ignore
126/// #[cfg_attr(mobile, tauri::mobile_entry_point)]
127/// pub fn run() {
128///   tauri::Builder::default()
129///     .run(tauri::generate_context!())
130///     .expect("error while running tauri application");
131/// }
132/// ```
133///
134/// The macro generates a `start_app` C symbol (checked by the Tauri CLI) that catches
135/// panics instead of unwinding across the FFI boundary, blocks on the function when it is
136/// `async`, sets up the stdout logger on iOS and the JNI bindings on Android using the
137/// package name derived from the `identifier` in your Tauri configuration.
138///
139/// Because the Android package name is read from environment variables set by `tauri-build`,
140/// your application must have a build script calling [`tauri_build::build`] - otherwise the
141/// macro fails to compile with a `env var not set` error.
142///
143/// [`tauri_build::build`]: https://docs.rs/tauri-build/latest/tauri_build/fn.build.html
144#[proc_macro_attribute]
145pub fn mobile_entry_point(attributes: TokenStream, item: TokenStream) -> TokenStream {
146  mobile::entry_point(attributes, item)
147}
148
149/// Accepts a list of command functions. Creates a handler that allows commands to be called from JS with invoke().
150///
151/// You can optionally annotate the commands with a inner attribute tag `#![plugin(your_plugin_name)]`
152/// for `build > removeUnusedCommands` to work for plugins not defined in a standalone crate like `tauri-plugin-fs`
153///
154/// # Examples
155///
156/// ```rust,ignore
157/// use tauri_macros::{command, generate_handler};
158/// #[command]
159/// fn command_one() {
160///   println!("command one called");
161/// }
162/// #[command]
163/// fn command_two() {
164///   println!("command two called");
165/// }
166/// fn main() {
167///   let _handler = generate_handler![command_one, command_two];
168/// }
169/// ```
170///
171/// # Stability
172///
173/// The output of this macro is managed internally by Tauri,
174/// and should not be accessed directly on normal applications.
175/// It may have breaking changes in the future.
176#[proc_macro]
177pub fn generate_handler(item: TokenStream) -> TokenStream {
178  parse_macro_input!(item as command::Handler).into()
179}
180
181/// Reads a Tauri config file and generates a `::tauri::Context` based on the content.
182///
183/// The context embeds the frontend assets, the application icons, the resolved Access Control List
184/// and the parsed configuration into the binary, and is passed to
185/// `tauri::Builder::run`/`tauri::Builder::build`.
186///
187/// ```rust,ignore
188/// tauri::Builder::default()
189///   .run(tauri::generate_context!())
190///   .expect("error while running tauri application");
191/// ```
192///
193/// # Options
194///
195/// All options are optional and can be combined in a comma separated list.
196///
197/// ## Configuration file path
198///
199/// A string literal as the first argument sets the path of the Tauri configuration file to read,
200/// relative to `CARGO_MANIFEST_DIR`. Defaults to `tauri.conf.json` on the crate directory.
201/// Platform specific configuration files (e.g. `tauri.windows.conf.json`) that sit next to it are
202/// merged as usual.
203///
204/// ```rust,ignore
205/// tauri::generate_context!("../tauri.conf.json");
206/// ```
207///
208/// ## Root path
209///
210/// A path (any item that is not a `key = value` pair) changes the crate path the generated code
211/// refers to. Defaults to `::tauri`, and is only needed when the `tauri` crate is renamed,
212/// re-exported by another crate, or is the crate being compiled (`crate`).
213///
214/// ```rust,ignore
215/// tauri::generate_context!("../tauri.conf.json", ::my_framework::tauri);
216/// ```
217///
218/// ## `capabilities`
219///
220/// A list of additional capability files to include in the generated Access Control List,
221/// on top of the ones defined in the `capabilities` directory and in the
222/// `app > security > capabilities` configuration value.
223///
224/// Each item is a path (relative to the current working directory of the compiler,
225/// usually the crate directory) to a JSON or TOML file containing a capability,
226/// a list of capabilities or a named list of capabilities.
227///
228/// ```rust,ignore
229/// tauri::generate_context!(capabilities = ["./capabilities/extra.json"]);
230/// ```
231///
232/// ## `assets`
233///
234/// An expression resolving to a custom [`tauri::Assets`] implementation, used instead of
235/// embedding the files from `build > frontendDist`. Useful for serving the frontend from a
236/// custom source, or for skipping asset embedding on tests.
237///
238/// ```rust,ignore
239/// tauri::generate_context!(assets = tauri::test::noop_assets());
240/// ```
241///
242/// ## `test`
243///
244/// When `true`, skips code generation that misbehaves when the context is created inside a
245/// test binary - currently the `Info.plist` embedding performed on macOS development builds.
246/// Defaults to `false`.
247///
248/// ```rust,ignore
249/// let context = tauri::generate_context!("../tauri.conf.json", test = true);
250/// ```
251///
252/// [`tauri::Assets`]: https://docs.rs/tauri/latest/tauri/trait.Assets.html
253///
254/// # Stability
255/// The output of this macro is managed internally by Tauri,
256/// and should not be accessed directly on normal applications.
257/// It may have breaking changes in the future.
258#[proc_macro]
259pub fn generate_context(items: TokenStream) -> TokenStream {
260  // this macro is exported from the context module
261  let path = parse_macro_input!(items as ContextItems);
262  context::generate_context(path).into()
263}
264
265/// Adds the default type for the last parameter (assumed to be runtime) for a specific feature.
266///
267/// e.g. To default the runtime generic to type `crate::Wry` when the `wry` feature is enabled, the
268/// syntax would look like `#[default_runtime(crate::Wry, wry)`. This is **always** set for the last
269/// generic, so make sure the last generic is the runtime when using this macro.
270#[doc(hidden)]
271#[proc_macro_attribute]
272pub fn default_runtime(attributes: TokenStream, input: TokenStream) -> TokenStream {
273  let attributes = parse_macro_input!(attributes as runtime::Attributes);
274  let input = parse_macro_input!(input as runtime::Input);
275  runtime::default_runtime(attributes, input).into()
276}
277
278/// Accepts a closure-like syntax to call arbitrary code on a menu item
279/// after matching against `kind` and retrieving it from `resources_table` using `rid`.
280///
281/// You can optionally pass a 5th parameter to select which item kinds
282/// to match against, by providing a `|` separated list of item kinds
283/// ```ignore
284/// do_menu_item!(resources_table, rid, kind, |i| i.set_text(text), Check | Submenu);
285/// ```
286/// You could also provide a negated list
287/// ```ignore
288/// do_menu_item!(resources_table, rid, kind, |i| i.set_text(text), !Check);
289/// do_menu_item!(resources_table, rid, kind, |i| i.set_text(text), !Check | !Submenu);
290/// ```
291/// but you can't have mixed negations and positive kinds.
292/// ```ignore
293/// do_menu_item!(resources_table, rid, kind, |i| i.set_text(text), !Check | Submenu);
294/// ```
295///
296/// ## Examples
297///
298/// ```ignore
299///  let rid = 23;
300///  let kind = ItemKind::Check;
301///  let resources_table = app.resources_table();
302///  do_menu_item!(resources_table, rid, kind, |i| i.set_text(text))
303/// ```
304/// which will expand into:
305/// ```ignore
306///  let rid = 23;
307///  let kind = ItemKind::Check;
308///  let resources_table = app.resources_table();
309///  match kind {
310///    ItemKind::Submenu => {
311///      let i = resources_table.get::<Submenu<R>>(rid)?;
312///      i.set_text(text)
313///    }
314///    ItemKind::MenuItem => {
315///      let i = resources_table.get::<MenuItem<R>>(rid)?;
316///      i.set_text(text)
317///    }
318///    ItemKind::Predefined => {
319///      let i = resources_table.get::<PredefinedMenuItem<R>>(rid)?;
320///      i.set_text(text)
321///    }
322///    ItemKind::Check => {
323///      let i = resources_table.get::<CheckMenuItem<R>>(rid)?;
324///      i.set_text(text)
325///    }
326///    ItemKind::Icon => {
327///      let i = resources_table.get::<IconMenuItem<R>>(rid)?;
328///      i.set_text(text)
329///    }
330///    _ => return Err(crate::Error::UnexpectedMenuKind),
331///  }
332/// ```
333#[doc(hidden)]
334#[proc_macro]
335pub fn do_menu_item(input: TokenStream) -> TokenStream {
336  let tokens = parse_macro_input!(input as menu::DoMenuItemInput);
337  menu::do_menu_item(tokens).into()
338}
339
340/// Convert a .png or .ico icon to an Image
341/// for things like `tauri::tray::TrayIconBuilder` to consume,
342/// relative paths are resolved from `CARGO_MANIFEST_DIR`, not current file
343///
344/// ### Examples
345///
346/// ```ignore
347/// const APP_ICON: Image<'_> = include_image!("./icons/32x32.png");
348///
349/// // then use it with tray
350/// TrayIconBuilder::new().icon(APP_ICON).build().unwrap();
351///
352/// // or with window
353/// WebviewWindowBuilder::new(app, "main", WebviewUrl::default())
354///     .icon(APP_ICON)
355///     .unwrap()
356///     .build()
357///     .unwrap();
358///
359/// // or with any other functions that takes `Image` struct
360/// ```
361///
362/// Note: this stores the image in raw pixels to the final binary,
363/// so keep the icon size (width and height) small
364/// or else it's going to bloat your final executable
365#[proc_macro]
366pub fn include_image(tokens: TokenStream) -> TokenStream {
367  let path = match parse2::<LitStr>(tokens.into()) {
368    Ok(path) => path,
369    Err(err) => return err.into_compile_error().into(),
370  };
371  let path = PathBuf::from(path.value());
372  let resolved_path = if path.is_relative() {
373    if let Ok(base_dir) = std::env::var("CARGO_MANIFEST_DIR").map(PathBuf::from) {
374      base_dir.join(path)
375    } else {
376      return quote!(compile_error!("$CARGO_MANIFEST_DIR is not defined")).into();
377    }
378  } else {
379    path
380  };
381  if !resolved_path.exists() {
382    let error_string = format!(
383      "Provided Image path \"{}\" doesn't exists",
384      resolved_path.display()
385    );
386    return quote!(compile_error!(#error_string)).into();
387  }
388
389  match CachedIcon::new(&quote!(::tauri), &resolved_path).map_err(|error| error.to_string()) {
390    Ok(icon) => icon.into_token_stream(),
391    Err(error) => quote!(compile_error!(#error)),
392  }
393  .into()
394}