Skip to content

Commit

Permalink
feat(core): implement CommandArg for AppHandle (#2037)
Browse files Browse the repository at this point in the history
  • Loading branch information
lucasfernog committed Jun 21, 2021
1 parent 1006c1c commit 59784c7
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changes/command-app-handle.md
@@ -0,0 +1,5 @@
---
"tauri": patch
---

Allow accessing an `AppHandle` instance on a command through dependency injection.
10 changes: 9 additions & 1 deletion core/tauri/src/app.rs
Expand Up @@ -9,6 +9,7 @@ pub(crate) mod tray;
use crate::{
api::assets::Assets,
api::config::{Config, WindowUrl},
command::{CommandArg, CommandItem},
hooks::{InvokeHandler, OnPageLoad, PageLoadPayload, SetupHook},
manager::{Args, WindowManager},
plugin::{Plugin, PluginStore},
Expand All @@ -19,7 +20,7 @@ use crate::{
Dispatch, MenuId, Params, RunEvent, Runtime,
},
sealed::{ManagerBase, RuntimeOrDispatch},
Context, Invoke, Manager, StateManager, Window,
Context, Invoke, InvokeError, Manager, StateManager, Window,
};

use tauri_utils::PackageInfo;
Expand Down Expand Up @@ -133,6 +134,13 @@ impl<P: Params> Clone for AppHandle<P> {
}
}

impl<'de, P: Params> CommandArg<'de, P> for AppHandle<P> {
/// Grabs the [`Window`] from the [`CommandItem`] and returns the associated [`AppHandle`]. This will never fail.
fn from_command(command: CommandItem<'de, P>) -> Result<Self, InvokeError> {
Ok(command.message.window().app_handle)
}
}

impl<P: Params> AppHandle<P> {
/// Removes the system tray.
#[cfg(all(windows, feature = "system-tray"))]
Expand Down
13 changes: 13 additions & 0 deletions docs/usage/guides/command.md
Expand Up @@ -137,6 +137,19 @@ async fn my_custom_command(window: tauri::Window) {
}
```

## Accessing an AppHandle in Commands

Commands can access an `AppHandle` instance:

```rust
#[tauri::command]
async fn my_custom_command(app_handle: tauri::AppHandle) {
let app_dir = app_handle.path_resolver().app_dir();
use tauri::GlobalShortcutManager;
app_handle.global_shortcut_manager().register("CTRL + U", move || {});
}
```

## Accessing managed state

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

0 comments on commit 59784c7

Please sign in to comment.