Expand description
A handle to the currently running application.
This type implements Manager
which allows for manipulation of global application items.
Implementations§
source§impl AppHandle<Wry>
impl AppHandle<Wry>
APIs specific to the wry runtime.
sourcepub fn create_tao_window<F: FnOnce() -> (String, WryWindowBuilder) + Send + 'static>(
&self,
f: F
) -> Result<Weak<Window>>
pub fn create_tao_window<F: FnOnce() -> (String, WryWindowBuilder) + Send + 'static>(
&self,
f: F
) -> Result<Weak<Window>>
Create a new tao window using a callback. The event loop must be running at this point.
sourcepub fn send_tao_window_event(
&self,
window_id: WindowId,
message: WindowMessage
) -> Result<()>
pub fn send_tao_window_event(
&self,
window_id: WindowId,
message: WindowMessage
) -> Result<()>
Sends a window message to the event loop.
source§impl<R: Runtime> AppHandle<R>
impl<R: Runtime> AppHandle<R>
sourcepub fn run_on_main_thread<F: FnOnce() + Send + 'static>(
&self,
f: F
) -> Result<()>
pub fn run_on_main_thread<F: FnOnce() + Send + 'static>(
&self,
f: F
) -> Result<()>
Runs the given closure on the main thread.
sourcepub fn plugin<P: Plugin<R> + 'static>(&self, plugin: P) -> Result<()>
pub fn plugin<P: Plugin<R> + 'static>(&self, plugin: P) -> Result<()>
Adds a Tauri application plugin.
This function can be used to register a plugin that is loaded dynamically e.g. after login.
For plugins that are created when the app is started, prefer Builder::plugin
.
See Builder::plugin
for more information.
Examples
use tauri::{plugin::{Builder as PluginBuilder, TauriPlugin}, Runtime};
fn init_plugin<R: Runtime>() -> TauriPlugin<R> {
PluginBuilder::new("dummy").build()
}
tauri::Builder::default()
.setup(move |app| {
let handle = app.handle();
std::thread::spawn(move || {
handle.plugin(init_plugin());
});
Ok(())
});
sourcepub fn remove_plugin(&self, plugin: &'static str) -> bool
pub fn remove_plugin(&self, plugin: &'static str) -> bool
Removes the plugin with the given name.
Examples
use tauri::{plugin::{Builder as PluginBuilder, TauriPlugin, Plugin}, Runtime};
fn init_plugin<R: Runtime>() -> TauriPlugin<R> {
PluginBuilder::new("dummy").build()
}
let plugin = init_plugin();
// `.name()` requires the `PLugin` trait import
let plugin_name = plugin.name();
tauri::Builder::default()
.plugin(plugin)
.setup(move |app| {
let handle = app.handle();
std::thread::spawn(move || {
handle.remove_plugin(plugin_name);
});
Ok(())
});
sourcepub fn exit(&self, exit_code: i32)
pub fn exit(&self, exit_code: i32)
Exits the app. This is the same as std::process::exit
, but it performs cleanup on this application.
sourcepub fn restart(&self)
pub fn restart(&self)
Restarts the app. This is the same as crate::api::process::restart
, but it performs cleanup on this application.
Examples found in repository?
More examples
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
async fn prompt_for_install<R: Runtime>(
update: &self::core::Update<R>,
app_name: &str,
body: &str,
pubkey: String,
) -> Result<()> {
let windows = update.app.windows();
let parent_window = windows.values().next();
// todo(lemarier): We should review this and make sure we have
// something more conventional.
let should_install = ask(
parent_window,
format!(r#"A new version of {} is available! "#, app_name),
format!(
r#"{} {} is now available -- you have {}.
Would you like to install it now?
Release Notes:
{}"#,
app_name, update.version, update.current_version, body,
),
);
if should_install {
// Launch updater download process
// macOS we display the `Ready to restart dialog` asking to restart
// Windows is closing the current App and launch the downloaded MSI when ready (the process stop here)
// Linux we replace the AppImage by launching a new install, it start a new AppImage instance, so we're closing the previous. (the process stop here)
update
.download_and_install(pubkey.clone(), |_, _| (), || ())
.await?;
// Ask user if we need to restart the application
let should_exit = ask(
parent_window,
"Ready to Restart",
"The installation was successful, do you want to restart the application now?",
);
if should_exit {
update.app.restart();
}
}
Ok(())
}
source§impl<R: Runtime> AppHandle<R>
impl<R: Runtime> AppHandle<R>
sourcepub fn updater(&self) -> UpdateBuilder<R>
Available on crate feature updater
only.
pub fn updater(&self) -> UpdateBuilder<R>
updater
only.Gets the updater builder to manually check if an update is available.
Examples
tauri::Builder::default()
.setup(|app| {
let handle = app.handle();
tauri::async_runtime::spawn(async move {
let response = handle.updater().check().await;
});
Ok(())
});
sourcepub fn tray_handle(&self) -> SystemTrayHandle<R>
Available on crate feature system-tray
only.
pub fn tray_handle(&self) -> SystemTrayHandle<R>
system-tray
only.Gets a handle handle to the system tray.
sourcepub fn path_resolver(&self) -> PathResolver
pub fn path_resolver(&self) -> PathResolver
The path resolver for the application.
sourcepub fn global_shortcut_manager(&self) -> R::GlobalShortcutManager
Available on crate feature global-shortcut
only.
pub fn global_shortcut_manager(&self) -> R::GlobalShortcutManager
global-shortcut
only.Gets a copy of the global shortcut manager instance.
Examples found in repository?
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
fn register<R: Runtime>(
context: InvokeContext<R>,
shortcut: String,
handler: CallbackFn,
) -> super::Result<()> {
let mut manager = context.window.app_handle.global_shortcut_manager();
register_shortcut(context.window, &mut manager, shortcut, handler)?;
Ok(())
}
#[module_command_handler(global_shortcut_all)]
fn register_all<R: Runtime>(
context: InvokeContext<R>,
shortcuts: Vec<String>,
handler: CallbackFn,
) -> super::Result<()> {
let mut manager = context.window.app_handle.global_shortcut_manager();
for shortcut in shortcuts {
register_shortcut(context.window.clone(), &mut manager, shortcut, handler)?;
}
Ok(())
}
#[module_command_handler(global_shortcut_all)]
fn unregister<R: Runtime>(context: InvokeContext<R>, shortcut: String) -> super::Result<()> {
context
.window
.app_handle
.global_shortcut_manager()
.unregister(&shortcut)
.map_err(crate::error::into_anyhow)?;
Ok(())
}
#[module_command_handler(global_shortcut_all)]
fn unregister_all<R: Runtime>(context: InvokeContext<R>) -> super::Result<()> {
context
.window
.app_handle
.global_shortcut_manager()
.unregister_all()
.map_err(crate::error::into_anyhow)?;
Ok(())
}
#[cfg(not(global_shortcut_all))]
fn unregister_all<R: Runtime>(_: InvokeContext<R>) -> super::Result<()> {
Err(crate::Error::ApiNotAllowlisted("globalShortcut > all".into()).into_anyhow())
}
#[module_command_handler(global_shortcut_all)]
fn is_registered<R: Runtime>(context: InvokeContext<R>, shortcut: String) -> super::Result<bool> {
context
.window
.app_handle
.global_shortcut_manager()
.is_registered(&shortcut)
.map_err(crate::error::into_anyhow)
}
sourcepub fn clipboard_manager(&self) -> R::ClipboardManager
Available on crate feature clipboard
only.
pub fn clipboard_manager(&self) -> R::ClipboardManager
clipboard
only.Gets a copy of the clipboard manager instance.
Examples found in repository?
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
fn write_text<R: Runtime>(context: InvokeContext<R>, text: String) -> super::Result<()> {
context
.window
.app_handle
.clipboard_manager()
.write_text(text)
.map_err(crate::error::into_anyhow)
}
#[module_command_handler(clipboard_read_text)]
fn read_text<R: Runtime>(context: InvokeContext<R>) -> super::Result<Option<String>> {
context
.window
.app_handle
.clipboard_manager()
.read_text()
.map_err(crate::error::into_anyhow)
}
sourcepub fn config(&self) -> Arc<Config>
pub fn config(&self) -> Arc<Config>
Gets the app’s configuration, defined on the tauri.conf.json
file.
Examples found in repository?
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
pub fn plugin<P: Plugin<R> + 'static>(&self, mut plugin: P) -> crate::Result<()> {
plugin
.initialize(
self,
self
.config()
.plugins
.0
.get(plugin.name())
.cloned()
.unwrap_or_default(),
)
.map_err(|e| crate::Error::PluginInitialization(plugin.name().to_string(), e.to_string()))?;
self
.manager()
.inner
.plugins
.lock()
.unwrap()
.register(plugin);
Ok(())
}
More examples
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
pub(crate) async fn check_update_with_dialog<R: Runtime>(handle: AppHandle<R>) {
let updater_config = handle.config().tauri.updater.clone();
let package_info = handle.package_info().clone();
if let Some(endpoints) = updater_config.endpoints.clone() {
let endpoints = endpoints
.iter()
.map(|e| e.to_string())
.collect::<Vec<String>>();
let mut builder = self::core::builder(handle.clone())
.urls(&endpoints[..])
.current_version(package_info.version);
if let Some(target) = &handle.updater_settings.target {
builder = builder.target(target);
}
// check updates
match builder.build().await {
Ok(updater) => {
let pubkey = updater_config.pubkey.clone();
// if dialog enabled only
if updater.should_update && updater_config.dialog {
let body = updater.body.clone().unwrap_or_else(|| String::from(""));
let dialog =
prompt_for_install(&updater.clone(), &package_info.name, &body.clone(), pubkey).await;
if let Err(e) = dialog {
send_status_update(&handle, UpdaterEvent::Error(e.to_string()));
}
}
}
Err(e) => {
send_status_update(&handle, UpdaterEvent::Error(e.to_string()));
}
}
}
}
/// Updater listener
/// This function should be run on the main thread once.
pub(crate) fn listener<R: Runtime>(handle: AppHandle<R>) {
// Wait to receive the event `"tauri://update"`
let handle_ = handle.clone();
handle.listen_global(EVENT_CHECK_UPDATE, move |_msg| {
let handle_ = handle_.clone();
crate::async_runtime::spawn(async move {
let _ = builder(handle_.clone()).check().await;
});
});
}
pub(crate) async fn download_and_install<R: Runtime>(update: core::Update<R>) -> Result<()> {
// Start installation
// emit {"status": "PENDING"}
send_status_update(&update.app, UpdaterEvent::Pending);
let handle = update.app.clone();
let handle_ = handle.clone();
// Launch updater download process
// macOS we display the `Ready to restart dialog` asking to restart
// Windows is closing the current App and launch the downloaded MSI when ready (the process stop here)
// Linux we replace the AppImage by launching a new install, it start a new AppImage instance, so we're closing the previous. (the process stop here)
let update_result = update
.download_and_install(
update.app.config().tauri.updater.pubkey.clone(),
move |chunk_length, content_length| {
send_download_progress_event(&handle, chunk_length, content_length);
},
move || {
send_status_update(&handle_, UpdaterEvent::Downloaded);
},
)
.await;
if let Err(err) = &update_result {
// emit {"status": "ERROR", "error": "The error message"}
send_status_update(&update.app, UpdaterEvent::Error(err.to_string()));
} else {
// emit {"status": "DONE"}
send_status_update(&update.app, UpdaterEvent::Updated);
}
update_result
}
/// Initializes the [`UpdateBuilder`] using the app configuration.
pub fn builder<R: Runtime>(handle: AppHandle<R>) -> UpdateBuilder<R> {
let updater_config = &handle.config().tauri.updater;
let package_info = handle.package_info().clone();
// prepare our endpoints
let endpoints = updater_config
.endpoints
.as_ref()
.expect("Something wrong with endpoints")
.iter()
.map(|e| e.to_string())
.collect::<Vec<String>>();
let mut builder = self::core::builder(handle.clone())
.urls(&endpoints[..])
.current_version(package_info.version);
if let Some(target) = &handle.updater_settings.target {
builder = builder.target(target);
}
UpdateBuilder {
inner: builder,
events: true,
}
}
sourcepub fn package_info(&self) -> &PackageInfo
pub fn package_info(&self) -> &PackageInfo
Gets the app’s package information.
Examples found in repository?
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
pub(crate) async fn check_update_with_dialog<R: Runtime>(handle: AppHandle<R>) {
let updater_config = handle.config().tauri.updater.clone();
let package_info = handle.package_info().clone();
if let Some(endpoints) = updater_config.endpoints.clone() {
let endpoints = endpoints
.iter()
.map(|e| e.to_string())
.collect::<Vec<String>>();
let mut builder = self::core::builder(handle.clone())
.urls(&endpoints[..])
.current_version(package_info.version);
if let Some(target) = &handle.updater_settings.target {
builder = builder.target(target);
}
// check updates
match builder.build().await {
Ok(updater) => {
let pubkey = updater_config.pubkey.clone();
// if dialog enabled only
if updater.should_update && updater_config.dialog {
let body = updater.body.clone().unwrap_or_else(|| String::from(""));
let dialog =
prompt_for_install(&updater.clone(), &package_info.name, &body.clone(), pubkey).await;
if let Err(e) = dialog {
send_status_update(&handle, UpdaterEvent::Error(e.to_string()));
}
}
}
Err(e) => {
send_status_update(&handle, UpdaterEvent::Error(e.to_string()));
}
}
}
}
/// Updater listener
/// This function should be run on the main thread once.
pub(crate) fn listener<R: Runtime>(handle: AppHandle<R>) {
// Wait to receive the event `"tauri://update"`
let handle_ = handle.clone();
handle.listen_global(EVENT_CHECK_UPDATE, move |_msg| {
let handle_ = handle_.clone();
crate::async_runtime::spawn(async move {
let _ = builder(handle_.clone()).check().await;
});
});
}
pub(crate) async fn download_and_install<R: Runtime>(update: core::Update<R>) -> Result<()> {
// Start installation
// emit {"status": "PENDING"}
send_status_update(&update.app, UpdaterEvent::Pending);
let handle = update.app.clone();
let handle_ = handle.clone();
// Launch updater download process
// macOS we display the `Ready to restart dialog` asking to restart
// Windows is closing the current App and launch the downloaded MSI when ready (the process stop here)
// Linux we replace the AppImage by launching a new install, it start a new AppImage instance, so we're closing the previous. (the process stop here)
let update_result = update
.download_and_install(
update.app.config().tauri.updater.pubkey.clone(),
move |chunk_length, content_length| {
send_download_progress_event(&handle, chunk_length, content_length);
},
move || {
send_status_update(&handle_, UpdaterEvent::Downloaded);
},
)
.await;
if let Err(err) = &update_result {
// emit {"status": "ERROR", "error": "The error message"}
send_status_update(&update.app, UpdaterEvent::Error(err.to_string()));
} else {
// emit {"status": "DONE"}
send_status_update(&update.app, UpdaterEvent::Updated);
}
update_result
}
/// Initializes the [`UpdateBuilder`] using the app configuration.
pub fn builder<R: Runtime>(handle: AppHandle<R>) -> UpdateBuilder<R> {
let updater_config = &handle.config().tauri.updater;
let package_info = handle.package_info().clone();
// prepare our endpoints
let endpoints = updater_config
.endpoints
.as_ref()
.expect("Something wrong with endpoints")
.iter()
.map(|e| e.to_string())
.collect::<Vec<String>>();
let mut builder = self::core::builder(handle.clone())
.urls(&endpoints[..])
.current_version(package_info.version);
if let Some(target) = &handle.updater_settings.target {
builder = builder.target(target);
}
UpdateBuilder {
inner: builder,
events: true,
}
}
sourcepub fn asset_resolver(&self) -> AssetResolver<R>
pub fn asset_resolver(&self) -> AssetResolver<R>
The application’s asset resolver.
Trait Implementations§
source§impl<'de, R: Runtime> CommandArg<'de, R> for AppHandle<R>
impl<'de, R: Runtime> CommandArg<'de, R> for AppHandle<R>
source§fn from_command(command: CommandItem<'de, R>) -> Result<Self, InvokeError>
fn from_command(command: CommandItem<'de, R>) -> Result<Self, InvokeError>
Grabs the Window
from the CommandItem
and returns the associated AppHandle
. This will never fail.
source§impl<R: Debug + Runtime> Debug for AppHandle<R>where
R::Handle: Debug,
R::GlobalShortcutManager: Debug,
R::ClipboardManager: Debug,
impl<R: Debug + Runtime> Debug for AppHandle<R>where
R::Handle: Debug,
R::GlobalShortcutManager: Debug,
R::ClipboardManager: Debug,
source§impl<R: Runtime> Manager<R> for AppHandle<R>
impl<R: Runtime> Manager<R> for AppHandle<R>
source§fn app_handle(&self) -> AppHandle<R>
fn app_handle(&self) -> AppHandle<R>
source§fn emit_all<S: Serialize + Clone>(&self, event: &str, payload: S) -> Result<()>
fn emit_all<S: Serialize + Clone>(&self, event: &str, payload: S) -> Result<()>
source§fn emit_to<S: Serialize + Clone>(
&self,
label: &str,
event: &str,
payload: S
) -> Result<()>
fn emit_to<S: Serialize + Clone>(
&self,
label: &str,
event: &str,
payload: S
) -> Result<()>
source§fn listen_global<F>(&self, event: impl Into<String>, handler: F) -> EventHandlerwhere
F: Fn(Event) + Send + 'static,
fn listen_global<F>(&self, event: impl Into<String>, handler: F) -> EventHandlerwhere
F: Fn(Event) + Send + 'static,
source§fn once_global<F>(&self, event: impl Into<String>, handler: F) -> EventHandlerwhere
F: FnOnce(Event) + Send + 'static,
fn once_global<F>(&self, event: impl Into<String>, handler: F) -> EventHandlerwhere
F: FnOnce(Event) + Send + 'static,
source§fn unlisten(&self, handler_id: EventHandler)
fn unlisten(&self, handler_id: EventHandler)
source§fn get_window(&self, label: &str) -> Option<Window<R>>
fn get_window(&self, label: &str) -> Option<Window<R>>
source§fn manage<T>(&self, state: T) -> boolwhere
T: Send + Sync + 'static,
fn manage<T>(&self, state: T) -> boolwhere
T: Send + Sync + 'static,
state
to the state managed by the application. Read moresource§fn state<T>(&self) -> State<'_, T>where
T: Send + Sync + 'static,
fn state<T>(&self) -> State<'_, T>where
T: Send + Sync + 'static,
T
. Read moresource§fn try_state<T>(&self) -> Option<State<'_, T>>where
T: Send + Sync + 'static,
fn try_state<T>(&self) -> Option<State<'_, T>>where
T: Send + Sync + 'static,
T
. Read more