pub trait Manager<R: Runtime>: ManagerBase<R> {
Show 17 methods
fn app_handle(&self) -> AppHandle<R> { ... }
fn config(&self) -> Arc<Config> { ... }
fn emit_all<S: Serialize + Clone>(
&self,
event: &str,
payload: S
) -> Result<()> { ... }
fn emit_to<S: Serialize + Clone>(
&self,
label: &str,
event: &str,
payload: S
) -> Result<()> { ... }
fn listen_global<F>(
&self,
event: impl Into<String>,
handler: F
) -> EventHandler
where
F: Fn(Event) + Send + 'static,
{ ... }
fn once_global<F>(&self, event: impl Into<String>, handler: F) -> EventHandler
where
F: FnOnce(Event) + Send + 'static,
{ ... }
fn trigger_global(&self, event: &str, data: Option<String>) { ... }
fn unlisten(&self, handler_id: EventHandler) { ... }
fn get_window(&self, label: &str) -> Option<Window<R>> { ... }
fn windows(&self) -> HashMap<String, Window<R>> { ... }
fn manage<T>(&self, state: T) -> bool
where
T: Send + Sync + 'static,
{ ... }
fn state<T>(&self) -> State<'_, T>
where
T: Send + Sync + 'static,
{ ... }
fn try_state<T>(&self) -> Option<State<'_, T>>
where
T: Send + Sync + 'static,
{ ... }
fn env(&self) -> Env { ... }
fn fs_scope(&self) -> FsScope { ... }
fn asset_protocol_scope(&self) -> FsScope { ... }
fn shell_scope(&self) -> ShellScope { ... }
}
Expand description
Manages a running application.
Provided Methods§
sourcefn app_handle(&self) -> AppHandle<R>
fn app_handle(&self) -> AppHandle<R>
The application handle associated with this manager.
Examples found in repository?
More examples
171 172 173 174 175 176 177 178 179 180 181 182 183
pub fn new<M: Manager<R>, L: Into<String>>(manager: &'a M, label: L, url: WindowUrl) -> Self {
let runtime = manager.runtime();
let app_handle = manager.app_handle();
Self {
manager: manager.manager().clone(),
runtime,
app_handle,
label: label.into(),
window_builder: <R::Dispatcher as Dispatch<EventLoopMessage>>::WindowBuilder::new(),
webview_attributes: WebviewAttributes::new(url),
web_resource_request_handler: None,
}
}
sourcefn emit_all<S: Serialize + Clone>(&self, event: &str, payload: S) -> Result<()>
fn emit_all<S: Serialize + Clone>(&self, event: &str, payload: S) -> Result<()>
Emits a event to all windows.
Examples found in repository?
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
fn emit<R: Runtime>(
context: InvokeContext<R>,
event: EventId,
window_label: Option<WindowLabel>,
payload: Option<String>,
) -> super::Result<()> {
// dispatch the event to Rust listeners
context.window.trigger(&event.0, payload.clone());
if let Some(target) = window_label {
context
.window
.emit_to(&target.0, &event.0, payload)
.map_err(crate::error::into_anyhow)?;
} else {
context
.window
.emit_all(&event.0, payload)
.map_err(crate::error::into_anyhow)?;
}
Ok(())
}
More examples
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 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 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
pub async fn check(self) -> Result<UpdateResponse<R>> {
let handle = self.inner.app.clone();
let events = self.events;
// check updates
match self.inner.build().await {
Ok(update) => {
if events {
// send notification if we need to update
if update.should_update {
let body = update.body.clone().unwrap_or_else(|| String::from(""));
// Emit `tauri://update-available`
let _ = handle.emit_all(
EVENT_UPDATE_AVAILABLE,
UpdateManifest {
body: body.clone(),
date: update.date.map(|d| d.to_string()),
version: update.version.clone(),
},
);
let _ = handle.create_proxy().send_event(EventLoopMessage::Updater(
UpdaterEvent::UpdateAvailable {
body,
date: update.date,
version: update.version.clone(),
},
));
// Listen for `tauri://update-install`
let update_ = update.clone();
handle.once_global(EVENT_INSTALL_UPDATE, move |_msg| {
crate::async_runtime::spawn(async move {
let _ = download_and_install(update_).await;
});
});
} else {
send_status_update(&handle, UpdaterEvent::AlreadyUpToDate);
}
}
Ok(UpdateResponse { update })
}
Err(e) => {
if self.events {
send_status_update(&handle, UpdaterEvent::Error(e.to_string()));
}
Err(e)
}
}
}
}
/// The response of an updater check.
pub struct UpdateResponse<R: Runtime> {
update: core::Update<R>,
}
impl<R: Runtime> Clone for UpdateResponse<R> {
fn clone(&self) -> Self {
Self {
update: self.update.clone(),
}
}
}
impl<R: Runtime> UpdateResponse<R> {
/// Whether the updater found a newer release or not.
pub fn is_update_available(&self) -> bool {
self.update.should_update
}
/// The current version of the application as read by the updater.
pub fn current_version(&self) -> &Version {
&self.update.current_version
}
/// The latest version of the application found by the updater.
pub fn latest_version(&self) -> &str {
&self.update.version
}
/// The update date.
pub fn date(&self) -> Option<&OffsetDateTime> {
self.update.date.as_ref()
}
/// The update description.
pub fn body(&self) -> Option<&String> {
self.update.body.as_ref()
}
/// Downloads and installs the update.
pub async fn download_and_install(self) -> Result<()> {
download_and_install(self.update).await
}
}
/// Check if there is any new update with builtin dialog.
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,
}
}
// Send a status update via `tauri://update-download-progress` event.
fn send_download_progress_event<R: Runtime>(
handle: &AppHandle<R>,
chunk_length: usize,
content_length: Option<u64>,
) {
let _ = handle.emit_all(
EVENT_DOWNLOAD_PROGRESS,
DownloadProgressEvent {
chunk_length,
content_length,
},
);
let _ =
handle
.create_proxy()
.send_event(EventLoopMessage::Updater(UpdaterEvent::DownloadProgress {
chunk_length,
content_length,
}));
}
// Send a status update via `tauri://update-status` event.
fn send_status_update<R: Runtime>(handle: &AppHandle<R>, message: UpdaterEvent) {
let _ = handle.emit_all(
EVENT_STATUS_UPDATE,
if let UpdaterEvent::Error(error) = &message {
StatusEvent {
error: Some(error.clone()),
status: message.clone().status_message().into(),
}
} else {
StatusEvent {
error: None,
status: message.clone().status_message().into(),
}
},
);
let _ = handle
.create_proxy()
.send_event(EventLoopMessage::Updater(message));
}
sourcefn 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<()>
Emits an event to a window with the specified label.
Examples found in repository?
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
fn emit<R: Runtime>(
context: InvokeContext<R>,
event: EventId,
window_label: Option<WindowLabel>,
payload: Option<String>,
) -> super::Result<()> {
// dispatch the event to Rust listeners
context.window.trigger(&event.0, payload.clone());
if let Some(target) = window_label {
context
.window
.emit_to(&target.0, &event.0, payload)
.map_err(crate::error::into_anyhow)?;
} else {
context
.window
.emit_all(&event.0, payload)
.map_err(crate::error::into_anyhow)?;
}
Ok(())
}
sourcefn 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,
Listen to a global event.
Examples found in repository?
More examples
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
fn run_updater(&self) {
let handle = self.handle();
let handle_ = handle.clone();
let updater_config = self.manager.config().tauri.updater.clone();
// check if updater is active or not
if updater_config.active {
if updater_config.dialog {
#[cfg(not(target_os = "linux"))]
let updater_enabled = true;
#[cfg(target_os = "linux")]
let updater_enabled = cfg!(dev) || self.state::<Env>().appimage.is_some();
if updater_enabled {
// if updater dialog is enabled spawn a new task
self.run_updater_dialog();
// When dialog is enabled, if user want to recheck
// if an update is available after first start
// invoke the Event `tauri://update` from JS or rust side.
handle.listen_global(updater::EVENT_CHECK_UPDATE, move |_msg| {
let handle = handle_.clone();
// re-spawn task inside tokyo to launch the download
// we don't need to emit anything as everything is handled
// by the process (user is asked to restart at the end)
// and it's handled by the updater
crate::async_runtime::spawn(
async move { updater::check_update_with_dialog(handle).await },
);
});
}
} else {
// we only listen for `tauri://update`
// once we receive the call, we check if an update is available or not
// if there is a new update we emit `tauri://update-available` with details
// this is the user responsabilities to display dialog and ask if user want to install
// to install the update you need to invoke the Event `tauri://update-install`
updater::listener(handle);
}
}
}
sourcefn 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,
Listen to a global event only once.
Examples found in repository?
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
pub async fn check(self) -> Result<UpdateResponse<R>> {
let handle = self.inner.app.clone();
let events = self.events;
// check updates
match self.inner.build().await {
Ok(update) => {
if events {
// send notification if we need to update
if update.should_update {
let body = update.body.clone().unwrap_or_else(|| String::from(""));
// Emit `tauri://update-available`
let _ = handle.emit_all(
EVENT_UPDATE_AVAILABLE,
UpdateManifest {
body: body.clone(),
date: update.date.map(|d| d.to_string()),
version: update.version.clone(),
},
);
let _ = handle.create_proxy().send_event(EventLoopMessage::Updater(
UpdaterEvent::UpdateAvailable {
body,
date: update.date,
version: update.version.clone(),
},
));
// Listen for `tauri://update-install`
let update_ = update.clone();
handle.once_global(EVENT_INSTALL_UPDATE, move |_msg| {
crate::async_runtime::spawn(async move {
let _ = download_and_install(update_).await;
});
});
} else {
send_status_update(&handle, UpdaterEvent::AlreadyUpToDate);
}
}
Ok(UpdateResponse { update })
}
Err(e) => {
if self.events {
send_status_update(&handle, UpdaterEvent::Error(e.to_string()));
}
Err(e)
}
}
}
sourcefn trigger_global(&self, event: &str, data: Option<String>)
fn trigger_global(&self, event: &str, data: Option<String>)
Trigger a global event.
sourcefn unlisten(&self, handler_id: EventHandler)
fn unlisten(&self, handler_id: EventHandler)
Remove an event listener.
sourcefn get_window(&self, label: &str) -> Option<Window<R>>
fn get_window(&self, label: &str) -> Option<Window<R>>
Fetch a single window from the manager.
Examples found in repository?
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
async fn _manage<R: Runtime>(
context: InvokeContext<R>,
label: Option<String>,
cmd: WindowManagerCmd,
) -> crate::Result<InvokeResponse> {
let window = match label {
Some(l) if !l.is_empty() => context
.window
.get_window(&l)
.ok_or(crate::Error::WebviewNotFound)?,
_ => context.window,
};
match cmd {
// Getters
WindowManagerCmd::ScaleFactor => return Ok(window.scale_factor()?.into()),
WindowManagerCmd::InnerPosition => return Ok(window.inner_position()?.into()),
WindowManagerCmd::OuterPosition => return Ok(window.outer_position()?.into()),
WindowManagerCmd::InnerSize => return Ok(window.inner_size()?.into()),
WindowManagerCmd::OuterSize => return Ok(window.outer_size()?.into()),
WindowManagerCmd::IsFullscreen => return Ok(window.is_fullscreen()?.into()),
WindowManagerCmd::IsMaximized => return Ok(window.is_maximized()?.into()),
WindowManagerCmd::IsDecorated => return Ok(window.is_decorated()?.into()),
WindowManagerCmd::IsResizable => return Ok(window.is_resizable()?.into()),
WindowManagerCmd::IsVisible => return Ok(window.is_visible()?.into()),
WindowManagerCmd::CurrentMonitor => return Ok(window.current_monitor()?.into()),
WindowManagerCmd::PrimaryMonitor => return Ok(window.primary_monitor()?.into()),
WindowManagerCmd::AvailableMonitors => return Ok(window.available_monitors()?.into()),
WindowManagerCmd::Theme => return Ok(window.theme()?.into()),
// Setters
#[cfg(window_center)]
WindowManagerCmd::Center => window.center()?,
#[cfg(window_request_user_attention)]
WindowManagerCmd::RequestUserAttention(request_type) => {
window.request_user_attention(request_type)?
}
#[cfg(window_set_resizable)]
WindowManagerCmd::SetResizable(resizable) => window.set_resizable(resizable)?,
#[cfg(window_set_title)]
WindowManagerCmd::SetTitle(title) => window.set_title(&title)?,
#[cfg(window_maximize)]
WindowManagerCmd::Maximize => window.maximize()?,
#[cfg(window_unmaximize)]
WindowManagerCmd::Unmaximize => window.unmaximize()?,
#[cfg(all(window_maximize, window_unmaximize))]
WindowManagerCmd::ToggleMaximize => match window.is_maximized()? {
true => window.unmaximize()?,
false => window.maximize()?,
},
#[cfg(window_minimize)]
WindowManagerCmd::Minimize => window.minimize()?,
#[cfg(window_unminimize)]
WindowManagerCmd::Unminimize => window.unminimize()?,
#[cfg(window_show)]
WindowManagerCmd::Show => window.show()?,
#[cfg(window_hide)]
WindowManagerCmd::Hide => window.hide()?,
#[cfg(window_close)]
WindowManagerCmd::Close => window.close()?,
#[cfg(window_set_decorations)]
WindowManagerCmd::SetDecorations(decorations) => window.set_decorations(decorations)?,
#[cfg(window_set_always_on_top)]
WindowManagerCmd::SetAlwaysOnTop(always_on_top) => window.set_always_on_top(always_on_top)?,
#[cfg(window_set_size)]
WindowManagerCmd::SetSize(size) => window.set_size(size)?,
#[cfg(window_set_min_size)]
WindowManagerCmd::SetMinSize(size) => window.set_min_size(size)?,
#[cfg(window_set_max_size)]
WindowManagerCmd::SetMaxSize(size) => window.set_max_size(size)?,
#[cfg(window_set_position)]
WindowManagerCmd::SetPosition(position) => window.set_position(position)?,
#[cfg(window_set_fullscreen)]
WindowManagerCmd::SetFullscreen(fullscreen) => window.set_fullscreen(fullscreen)?,
#[cfg(window_set_focus)]
WindowManagerCmd::SetFocus => window.set_focus()?,
#[cfg(window_set_icon)]
WindowManagerCmd::SetIcon { icon } => window.set_icon(icon.into())?,
#[cfg(window_set_skip_taskbar)]
WindowManagerCmd::SetSkipTaskbar(skip) => window.set_skip_taskbar(skip)?,
#[cfg(window_set_cursor_grab)]
WindowManagerCmd::SetCursorGrab(grab) => window.set_cursor_grab(grab)?,
#[cfg(window_set_cursor_visible)]
WindowManagerCmd::SetCursorVisible(visible) => window.set_cursor_visible(visible)?,
#[cfg(window_set_cursor_icon)]
WindowManagerCmd::SetCursorIcon(icon) => window.set_cursor_icon(icon)?,
#[cfg(window_set_cursor_position)]
WindowManagerCmd::SetCursorPosition(position) => window.set_cursor_position(position)?,
#[cfg(window_start_dragging)]
WindowManagerCmd::StartDragging => window.start_dragging()?,
#[cfg(window_print)]
WindowManagerCmd::Print => window.print()?,
// internals
#[cfg(all(window_maximize, window_unmaximize))]
WindowManagerCmd::InternalToggleMaximize => {
if window.is_resizable()? {
match window.is_maximized()? {
true => window.unmaximize()?,
false => window.maximize()?,
}
}
}
#[cfg(any(debug_assertions, feature = "devtools"))]
WindowManagerCmd::InternalToggleDevtools => {
if window.is_devtools_open() {
window.close_devtools();
} else {
window.open_devtools();
}
}
}
#[allow(unreachable_code)]
Ok(().into())
}
sourcefn windows(&self) -> HashMap<String, Window<R>>
fn windows(&self) -> HashMap<String, Window<R>>
Fetch all managed windows.
Examples found in repository?
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(())
}
sourcefn manage<T>(&self, state: T) -> boolwhere
T: Send + Sync + 'static,
fn manage<T>(&self, state: T) -> boolwhere
T: Send + Sync + 'static,
Add state
to the state managed by the application.
This method can be called any number of times as long as each call
refers to a different T
.
If a state for T
is already managed, the function returns false and the value is ignored.
Managed state can be retrieved by any command handler via the
State
guard. In particular, if a value of type T
is managed by Tauri, adding State<T>
to the list of arguments in a
command handler instructs Tauri to retrieve the managed value.
Panics
Panics if state of type T
is already being managed.
Mutability
Since the managed state is global and must be Send
+ Sync
, mutations can only happen through interior mutability:
use std::{collections::HashMap, sync::Mutex};
use tauri::State;
// here we use Mutex to achieve interior mutability
struct Storage {
store: Mutex<HashMap<u64, String>>,
}
struct Connection;
struct DbConnection {
db: Mutex<Option<Connection>>,
}
#[tauri::command]
fn connect(connection: State<DbConnection>) {
// initialize the connection, mutating the state with interior mutability
*connection.db.lock().unwrap() = Some(Connection {});
}
#[tauri::command]
fn storage_insert(key: u64, value: String, storage: State<Storage>) {
// mutate the storage behind the Mutex
storage.store.lock().unwrap().insert(key, value);
}
tauri::Builder::default()
.manage(Storage { store: Default::default() })
.manage(DbConnection { db: Default::default() })
.invoke_handler(tauri::generate_handler![connect, storage_insert])
// on an actual app, remove the string argument
.run(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
.expect("error while running tauri application");
Examples
use tauri::{Manager, State};
struct MyInt(isize);
struct MyString(String);
#[tauri::command]
fn int_command(state: State<MyInt>) -> String {
format!("The stateful int is: {}", state.0)
}
#[tauri::command]
fn string_command<'r>(state: State<'r, MyString>) {
println!("state: {}", state.inner().0);
}
tauri::Builder::default()
.setup(|app| {
app.manage(MyInt(0));
app.manage(MyString("tauri".into()));
// `MyInt` is already managed, so `manage()` returns false
assert!(!app.manage(MyInt(1)));
// read the `MyInt` managed state with the turbofish syntax
let int = app.state::<MyInt>();
assert_eq!(int.0, 0);
// read the `MyString` managed state with the `State` guard
let val: State<MyString> = app.state();
assert_eq!(val.0, "tauri");
Ok(())
})
.invoke_handler(tauri::generate_handler![int_command, string_command])
// on an actual app, remove the string argument
.run(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
.expect("error while running tauri application");
Examples found in repository?
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
pub fn build<A: Assets>(mut self, context: Context<A>) -> crate::Result<App<R>> {
#[cfg(target_os = "macos")]
if self.menu.is_none() && self.enable_macos_default_menu {
self.menu = Some(Menu::os_default(&context.package_info().name));
}
#[cfg(feature = "system-tray")]
let system_tray_icon = context.system_tray_icon.clone();
#[cfg(all(feature = "system-tray", target_os = "macos"))]
let (system_tray_icon_as_template, system_tray_menu_on_left_click) = context
.config
.tauri
.system_tray
.as_ref()
.map(|t| (t.icon_as_template, t.menu_on_left_click))
.unwrap_or_default();
#[cfg(shell_scope)]
let shell_scope = context.shell_scope.clone();
let manager = WindowManager::with_handlers(
context,
self.plugins,
self.invoke_handler,
self.on_page_load,
self.uri_scheme_protocols,
self.state,
self.window_event_listeners,
(self.menu, self.menu_event_listeners),
(self.invoke_responder, self.invoke_initialization_script),
);
// set up all the windows defined in the config
for config in manager.config().tauri.windows.clone() {
let url = config.url.clone();
let label = config.label.clone();
let file_drop_enabled = config.file_drop_enabled;
let mut webview_attributes = WebviewAttributes::new(url);
if !file_drop_enabled {
webview_attributes = webview_attributes.disable_file_drop_handler();
}
self.pending_windows.push(PendingWindow::with_config(
config,
webview_attributes,
label,
)?);
}
#[cfg(any(windows, target_os = "linux"))]
let runtime = if self.runtime_any_thread {
R::new_any_thread()?
} else {
R::new()?
};
#[cfg(not(any(windows, target_os = "linux")))]
let runtime = R::new()?;
let runtime_handle = runtime.handle();
#[cfg(feature = "global-shortcut")]
let global_shortcut_manager = runtime.global_shortcut_manager();
#[cfg(feature = "clipboard")]
let clipboard_manager = runtime.clipboard_manager();
let mut app = App {
runtime: Some(runtime),
manager: manager.clone(),
#[cfg(feature = "global-shortcut")]
global_shortcut_manager: global_shortcut_manager.clone(),
#[cfg(feature = "clipboard")]
clipboard_manager: clipboard_manager.clone(),
#[cfg(feature = "system-tray")]
tray_handle: None,
handle: AppHandle {
runtime_handle,
manager,
#[cfg(feature = "global-shortcut")]
global_shortcut_manager,
#[cfg(feature = "clipboard")]
clipboard_manager,
#[cfg(feature = "system-tray")]
tray_handle: None,
#[cfg(updater)]
updater_settings: self.updater_settings,
},
};
let env = Env::default();
app.manage(Scopes {
fs: FsScope::for_fs_api(
&app.manager.config(),
app.package_info(),
&env,
&app.config().tauri.allowlist.fs.scope,
)?,
#[cfg(protocol_asset)]
asset_protocol: FsScope::for_fs_api(
&app.manager.config(),
app.package_info(),
&env,
&app.config().tauri.allowlist.protocol.asset_scope,
)?,
#[cfg(http_request)]
http: crate::scope::HttpScope::for_http_api(&app.config().tauri.allowlist.http.scope),
#[cfg(shell_scope)]
shell: ShellScope::new(shell_scope),
});
app.manage(env);
#[cfg(windows)]
{
if let crate::utils::config::WebviewInstallMode::FixedRuntime { path } = &app
.manager
.config()
.tauri
.bundle
.windows
.webview_install_mode
{
if let Some(resource_dir) = app.path_resolver().resource_dir() {
std::env::set_var(
"WEBVIEW2_BROWSER_EXECUTABLE_FOLDER",
resource_dir.join(path),
);
} else {
#[cfg(debug_assertions)]
eprintln!(
"failed to resolve resource directory; fallback to the installed Webview2 runtime."
);
}
}
}
#[cfg(feature = "system-tray")]
if let Some(system_tray) = self.system_tray {
let mut ids = HashMap::new();
if let Some(menu) = system_tray.menu() {
tray::get_menu_ids(&mut ids, menu);
}
let tray_icon = if let Some(icon) = system_tray.icon {
Some(icon)
} else if let Some(tray_icon) = system_tray_icon {
Some(tray_icon.try_into()?)
} else {
None
};
let mut tray = tray::SystemTray::new()
.with_icon(tray_icon.expect("tray icon not found; please configure it on tauri.conf.json"));
if let Some(menu) = system_tray.menu {
tray = tray.with_menu(menu);
}
#[cfg(target_os = "macos")]
let tray = tray
.with_icon_as_template(system_tray_icon_as_template)
.with_menu_on_left_click(system_tray_menu_on_left_click);
let tray_handler = app
.runtime
.as_ref()
.unwrap()
.system_tray(tray)
.expect("failed to run tray");
let tray_handle = tray::SystemTrayHandle {
ids: Arc::new(std::sync::Mutex::new(ids)),
inner: tray_handler,
};
let ids = tray_handle.ids.clone();
app.tray_handle.replace(tray_handle.clone());
app.handle.tray_handle.replace(tray_handle);
for listener in self.system_tray_event_listeners {
let app_handle = app.handle();
let ids = ids.clone();
let listener = Arc::new(std::sync::Mutex::new(listener));
app
.runtime
.as_mut()
.unwrap()
.on_system_tray_event(move |event| {
let app_handle = app_handle.clone();
let event = match event {
RuntimeSystemTrayEvent::MenuItemClick(id) => tray::SystemTrayEvent::MenuItemClick {
id: ids.lock().unwrap().get(id).unwrap().clone(),
},
RuntimeSystemTrayEvent::LeftClick { position, size } => {
tray::SystemTrayEvent::LeftClick {
position: *position,
size: *size,
}
}
RuntimeSystemTrayEvent::RightClick { position, size } => {
tray::SystemTrayEvent::RightClick {
position: *position,
size: *size,
}
}
RuntimeSystemTrayEvent::DoubleClick { position, size } => {
tray::SystemTrayEvent::DoubleClick {
position: *position,
size: *size,
}
}
};
let listener = listener.clone();
listener.lock().unwrap()(&app_handle, event);
});
}
}
app.manager.initialize_plugins(&app.handle())?;
let window_labels = self
.pending_windows
.iter()
.map(|p| p.label.clone())
.collect::<Vec<_>>();
for pending in self.pending_windows {
let pending =
app
.manager
.prepare_window(app.handle.clone(), pending, &window_labels, None)?;
let detached = app.runtime.as_ref().unwrap().create_window(pending)?;
let _window = app.manager.attach_window(app.handle(), detached);
}
(self.setup)(&mut app).map_err(|e| crate::Error::Setup(e.into()))?;
#[cfg(updater)]
app.run_updater();
Ok(app)
}
sourcefn state<T>(&self) -> State<'_, T>where
T: Send + Sync + 'static,
fn state<T>(&self) -> State<'_, T>where
T: Send + Sync + 'static,
Retrieves the managed state for the type T
.
Panics
Panics if the state for the type T
has not been previously managed.
Use try_state for a non-panicking version.
Examples found in repository?
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
fn env(&self) -> Env {
self.state::<Env>().inner().clone()
}
/// Gets the scope for the filesystem APIs.
fn fs_scope(&self) -> FsScope {
self.state::<Scopes>().inner().fs.clone()
}
/// Gets the scope for the asset protocol.
#[cfg(protocol_asset)]
fn asset_protocol_scope(&self) -> FsScope {
self.state::<Scopes>().inner().asset_protocol.clone()
}
/// Gets the scope for the shell execute APIs.
#[cfg(shell_scope)]
fn shell_scope(&self) -> ShellScope {
self.state::<Scopes>().inner().shell.clone()
}
More examples
46 47 48 49 50 51 52 53 54 55 56 57 58 59
fn resolve_path<R: Runtime>(
context: InvokeContext<R>,
path: String,
directory: Option<BaseDirectory>,
) -> super::Result<PathBuf> {
crate::api::path::resolve_path(
&context.config,
&context.package_info,
context.window.state::<Env>().inner(),
path,
directory,
)
.map_err(Into::into)
}
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
fn read_dir<R: Runtime>(
context: InvokeContext<R>,
path: SafePathBuf,
options: Option<DirOperationOptions>,
) -> super::Result<Vec<dir::DiskEntry>> {
let (recursive, dir) = if let Some(options_value) = options {
(options_value.recursive, options_value.dir)
} else {
(false, None)
};
let resolved_path = resolve_path(
&context.config,
&context.package_info,
&context.window,
path,
dir,
)?;
dir::read_dir_with_options(
&resolved_path,
recursive,
dir::ReadDirOptions {
scope: Some(&context.window.state::<Scopes>().fs),
},
)
.with_context(|| format!("path: {}", resolved_path.display()))
.map_err(Into::into)
}
#[module_command_handler(fs_copy_file)]
fn copy_file<R: Runtime>(
context: InvokeContext<R>,
source: SafePathBuf,
destination: SafePathBuf,
options: Option<FileOperationOptions>,
) -> super::Result<()> {
let (src, dest) = match options.and_then(|o| o.dir) {
Some(dir) => (
resolve_path(
&context.config,
&context.package_info,
&context.window,
source,
Some(dir),
)?,
resolve_path(
&context.config,
&context.package_info,
&context.window,
destination,
Some(dir),
)?,
),
None => (source, destination),
};
fs::copy(src.clone(), dest.clone())
.with_context(|| format!("source: {}, dest: {}", src.display(), dest.display()))?;
Ok(())
}
#[module_command_handler(fs_create_dir)]
fn create_dir<R: Runtime>(
context: InvokeContext<R>,
path: SafePathBuf,
options: Option<DirOperationOptions>,
) -> super::Result<()> {
let (recursive, dir) = if let Some(options_value) = options {
(options_value.recursive, options_value.dir)
} else {
(false, None)
};
let resolved_path = resolve_path(
&context.config,
&context.package_info,
&context.window,
path,
dir,
)?;
if recursive {
fs::create_dir_all(&resolved_path)
.with_context(|| format!("path: {}", resolved_path.display()))?;
} else {
fs::create_dir(&resolved_path)
.with_context(|| format!("path: {} (non recursive)", resolved_path.display()))?;
}
Ok(())
}
#[module_command_handler(fs_remove_dir)]
fn remove_dir<R: Runtime>(
context: InvokeContext<R>,
path: SafePathBuf,
options: Option<DirOperationOptions>,
) -> super::Result<()> {
let (recursive, dir) = if let Some(options_value) = options {
(options_value.recursive, options_value.dir)
} else {
(false, None)
};
let resolved_path = resolve_path(
&context.config,
&context.package_info,
&context.window,
path,
dir,
)?;
if recursive {
fs::remove_dir_all(&resolved_path)
.with_context(|| format!("path: {}", resolved_path.display()))?;
} else {
fs::remove_dir(&resolved_path)
.with_context(|| format!("path: {} (non recursive)", resolved_path.display()))?;
}
Ok(())
}
#[module_command_handler(fs_remove_file)]
fn remove_file<R: Runtime>(
context: InvokeContext<R>,
path: SafePathBuf,
options: Option<FileOperationOptions>,
) -> super::Result<()> {
let resolved_path = resolve_path(
&context.config,
&context.package_info,
&context.window,
path,
options.and_then(|o| o.dir),
)?;
fs::remove_file(&resolved_path)
.with_context(|| format!("path: {}", resolved_path.display()))?;
Ok(())
}
#[module_command_handler(fs_rename_file)]
fn rename_file<R: Runtime>(
context: InvokeContext<R>,
old_path: SafePathBuf,
new_path: SafePathBuf,
options: Option<FileOperationOptions>,
) -> super::Result<()> {
let (old, new) = match options.and_then(|o| o.dir) {
Some(dir) => (
resolve_path(
&context.config,
&context.package_info,
&context.window,
old_path,
Some(dir),
)?,
resolve_path(
&context.config,
&context.package_info,
&context.window,
new_path,
Some(dir),
)?,
),
None => (old_path, new_path),
};
fs::rename(&old, &new)
.with_context(|| format!("old: {}, new: {}", old.display(), new.display()))
.map_err(Into::into)
}
}
#[allow(dead_code)]
fn resolve_path<R: Runtime>(
config: &Config,
package_info: &PackageInfo,
window: &Window<R>,
path: SafePathBuf,
dir: Option<BaseDirectory>,
) -> super::Result<SafePathBuf> {
let env = window.state::<Env>().inner();
match crate::api::path::resolve_path(config, package_info, env, &path, dir) {
Ok(path) => {
if window.state::<Scopes>().fs.is_allowed(&path) {
Ok(
// safety: the path is resolved by Tauri so it is safe
unsafe { SafePathBuf::new_unchecked(path) },
)
} else {
Err(anyhow::anyhow!(
crate::Error::PathNotAllowed(path).to_string()
))
}
}
Err(e) => super::Result::<SafePathBuf>::Err(e.into())
.with_context(|| format!("path: {}, base dir: {:?}", path.display(), dir)),
}
}
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
async fn http_request<R: Runtime>(
context: InvokeContext<R>,
client_id: ClientId,
options: Box<HttpRequestBuilder>,
) -> super::Result<ResponseData> {
use crate::Manager;
let scopes = context.window.state::<crate::Scopes>();
if scopes.http.is_allowed(&options.url) {
let client = clients()
.lock()
.unwrap()
.get(&client_id)
.ok_or_else(|| crate::Error::HttpClientNotInitialized.into_anyhow())?
.clone();
let options = *options;
if let Some(crate::api::http::Body::Form(form)) = &options.body {
for value in form.0.values() {
if let crate::api::http::FormPart::File {
file: crate::api::http::FilePart::Path(path),
..
} = value
{
if crate::api::file::SafePathBuf::new(path.clone()).is_err()
|| !scopes.fs.is_allowed(&path)
{
return Err(crate::Error::PathNotAllowed(path.clone()).into_anyhow());
}
}
}
}
let response = client.send(options).await?;
Ok(response.read().await?)
} else {
Err(crate::Error::UrlNotAllowed(options.url).into_anyhow())
}
}
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
fn run_updater(&self) {
let handle = self.handle();
let handle_ = handle.clone();
let updater_config = self.manager.config().tauri.updater.clone();
// check if updater is active or not
if updater_config.active {
if updater_config.dialog {
#[cfg(not(target_os = "linux"))]
let updater_enabled = true;
#[cfg(target_os = "linux")]
let updater_enabled = cfg!(dev) || self.state::<Env>().appimage.is_some();
if updater_enabled {
// if updater dialog is enabled spawn a new task
self.run_updater_dialog();
// When dialog is enabled, if user want to recheck
// if an update is available after first start
// invoke the Event `tauri://update` from JS or rust side.
handle.listen_global(updater::EVENT_CHECK_UPDATE, move |_msg| {
let handle = handle_.clone();
// re-spawn task inside tokyo to launch the download
// we don't need to emit anything as everything is handled
// by the process (user is asked to restart at the end)
// and it's handled by the updater
crate::async_runtime::spawn(
async move { updater::check_update_with_dialog(handle).await },
);
});
}
} else {
// we only listen for `tauri://update`
// once we receive the call, we check if an update is available or not
// if there is a new update we emit `tauri://update-available` with details
// this is the user responsabilities to display dialog and ask if user want to install
// to install the update you need to invoke the Event `tauri://update-install`
updater::listener(handle);
}
}
}
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
fn open_dialog<R: Runtime>(
context: InvokeContext<R>,
options: OpenDialogOptions,
) -> super::Result<InvokeResponse> {
let mut dialog_builder = FileDialogBuilder::new();
#[cfg(any(windows, target_os = "macos"))]
{
dialog_builder = dialog_builder.set_parent(&context.window);
}
if let Some(title) = options.title {
dialog_builder = dialog_builder.set_title(&title);
}
if let Some(default_path) = options.default_path {
dialog_builder = set_default_path(dialog_builder, default_path);
}
for filter in options.filters {
let extensions: Vec<&str> = filter.extensions.iter().map(|s| &**s).collect();
dialog_builder = dialog_builder.add_filter(filter.name, &extensions);
}
let scopes = context.window.state::<Scopes>();
let res = if options.directory {
if options.multiple {
let folders = dialog_builder.pick_folders();
if let Some(folders) = &folders {
for folder in folders {
scopes
.allow_directory(folder, options.recursive)
.map_err(crate::error::into_anyhow)?;
}
}
folders.into()
} else {
let folder = dialog_builder.pick_folder();
if let Some(path) = &folder {
scopes
.allow_directory(path, options.recursive)
.map_err(crate::error::into_anyhow)?;
}
folder.into()
}
} else if options.multiple {
let files = dialog_builder.pick_files();
if let Some(files) = &files {
for file in files {
scopes.allow_file(file).map_err(crate::error::into_anyhow)?;
}
}
files.into()
} else {
let file = dialog_builder.pick_file();
if let Some(file) = &file {
scopes.allow_file(file).map_err(crate::error::into_anyhow)?;
}
file.into()
};
Ok(res)
}
#[module_command_handler(dialog_save)]
#[allow(unused_variables)]
fn save_dialog<R: Runtime>(
context: InvokeContext<R>,
options: SaveDialogOptions,
) -> super::Result<Option<PathBuf>> {
let mut dialog_builder = FileDialogBuilder::new();
#[cfg(any(windows, target_os = "macos"))]
{
dialog_builder = dialog_builder.set_parent(&context.window);
}
if let Some(title) = options.title {
dialog_builder = dialog_builder.set_title(&title);
}
if let Some(default_path) = options.default_path {
dialog_builder = set_default_path(dialog_builder, default_path);
}
for filter in options.filters {
let extensions: Vec<&str> = filter.extensions.iter().map(|s| &**s).collect();
dialog_builder = dialog_builder.add_filter(filter.name, &extensions);
}
let scopes = context.window.state::<Scopes>();
let path = dialog_builder.save_file();
if let Some(p) = &path {
scopes.allow_file(p).map_err(crate::error::into_anyhow)?;
}
Ok(path)
}
sourcefn 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,
Attempts to retrieve the managed state for the type T
.
Returns Some
if the state has previously been managed. Otherwise returns None
.
sourcefn asset_protocol_scope(&self) -> FsScope
fn asset_protocol_scope(&self) -> FsScope
Gets the scope for the asset protocol.
sourcefn shell_scope(&self) -> ShellScope
fn shell_scope(&self) -> ShellScope
Gets the scope for the shell execute APIs.