Skip to content

Commit 59784c7

Browse files
authored
feat(core): implement CommandArg for AppHandle (#2037)
1 parent 1006c1c commit 59784c7

3 files changed

Lines changed: 27 additions & 1 deletion

File tree

.changes/command-app-handle.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"tauri": patch
3+
---
4+
5+
Allow accessing an `AppHandle` instance on a command through dependency injection.

core/tauri/src/app.rs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ pub(crate) mod tray;
99
use crate::{
1010
api::assets::Assets,
1111
api::config::{Config, WindowUrl},
12+
command::{CommandArg, CommandItem},
1213
hooks::{InvokeHandler, OnPageLoad, PageLoadPayload, SetupHook},
1314
manager::{Args, WindowManager},
1415
plugin::{Plugin, PluginStore},
@@ -19,7 +20,7 @@ use crate::{
1920
Dispatch, MenuId, Params, RunEvent, Runtime,
2021
},
2122
sealed::{ManagerBase, RuntimeOrDispatch},
22-
Context, Invoke, Manager, StateManager, Window,
23+
Context, Invoke, InvokeError, Manager, StateManager, Window,
2324
};
2425

2526
use tauri_utils::PackageInfo;
@@ -133,6 +134,13 @@ impl<P: Params> Clone for AppHandle<P> {
133134
}
134135
}
135136

137+
impl<'de, P: Params> CommandArg<'de, P> for AppHandle<P> {
138+
/// Grabs the [`Window`] from the [`CommandItem`] and returns the associated [`AppHandle`]. This will never fail.
139+
fn from_command(command: CommandItem<'de, P>) -> Result<Self, InvokeError> {
140+
Ok(command.message.window().app_handle)
141+
}
142+
}
143+
136144
impl<P: Params> AppHandle<P> {
137145
/// Removes the system tray.
138146
#[cfg(all(windows, feature = "system-tray"))]

docs/usage/guides/command.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,19 @@ async fn my_custom_command(window: tauri::Window) {
137137
}
138138
```
139139

140+
## Accessing an AppHandle in Commands
141+
142+
Commands can access an `AppHandle` instance:
143+
144+
```rust
145+
#[tauri::command]
146+
async fn my_custom_command(app_handle: tauri::AppHandle) {
147+
let app_dir = app_handle.path_resolver().app_dir();
148+
use tauri::GlobalShortcutManager;
149+
app_handle.global_shortcut_manager().register("CTRL + U", move || {});
150+
}
151+
```
152+
140153
## Accessing managed state
141154

142155
Tauri can manage state using the `manage` function on `tauri::Builder`.

0 commit comments

Comments
 (0)