Struct tauri::AppHandle

source ·
pub struct AppHandle<R: Runtime = Wry> { /* private fields */ }
Expand description

A handle to the currently running application.

This type implements Manager which allows for manipulation of global application items.

Implementations§

APIs specific to the wry runtime.

Create a new tao window using a callback. The event loop must be running at this point.

Sends a window message to the event loop.

Runs the given closure on the main thread.

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(())
  });

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(())
  });

Exits the app. This is the same as std::process::exit, but it performs cleanup on this application.

Restarts the app. This is the same as crate::api::process::restart, but it performs cleanup on this application.

Examples found in repository?
src/endpoints/process.rs (line 30)
29
30
31
32
  fn relaunch<R: Runtime>(context: InvokeContext<R>) -> super::Result<()> {
    context.window.app_handle().restart();
    Ok(())
  }
More examples
Hide additional examples
src/updater/mod.rs (line 969)
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(())
}
Available on crate feature 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(())
  });
Available on crate feature system-tray only.

Gets a handle handle to the system tray.

The path resolver for the application.

Available on crate feature global-shortcut only.

Gets a copy of the global shortcut manager instance.

Examples found in repository?
src/endpoints/global_shortcut.rs (line 49)
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)
  }
Available on crate feature clipboard only.

Gets a copy of the clipboard manager instance.

Examples found in repository?
src/endpoints/clipboard.rs (line 32)
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)
  }

Gets the app’s configuration, defined on the tauri.conf.json file.

Examples found in repository?
src/app.rs (line 443)
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
Hide additional examples
src/updater/mod.rs (line 772)
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,
  }
}

Gets the app’s package information.

Examples found in repository?
src/updater/mod.rs (line 773)
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,
  }
}

The application’s asset resolver.

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more

Grabs the Window from the CommandItem and returns the associated AppHandle. This will never fail.

Formats the value using the given formatter. Read more
The application handle associated with this manager.
The Config the manager was created with.
Emits a event to all windows.
Emits an event to a window with the specified label.
Listen to a global event.
Listen to a global event only once.
Trigger a global event.
Remove an event listener.
Fetch a single window from the manager.
Fetch all managed windows.
Add state to the state managed by the application. Read more
Retrieves the managed state for the type T. Read more
Attempts to retrieve the managed state for the type T. Read more
Gets the managed Env.
Gets the scope for the filesystem APIs.
Gets the scope for the asset protocol.
Gets the scope for the shell execute APIs.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more