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.

Examples found in repository?
src/endpoints/process.rs (line 44)
40
41
42
43
44
45
46
  fn exit<R: Runtime>(context: InvokeContext<R>, exit_code: i32) -> super::Result<()> {
    // would be great if we can have a handler inside tauri
    // who close all window and emit an event that user can catch
    // if they want to process something before closing the app
    context.window.app_handle.exit(exit_code);
    Ok(())
  }

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 596)
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
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 to the first system tray.

Prefer Self::tray_handle_by_id when multiple system trays are created.

Examples
use tauri::{CustomMenuItem, SystemTray, SystemTrayMenu};

tauri::Builder::default()
  .setup(|app| {
    let app_handle = app.handle();
    SystemTray::new()
      .with_menu(
        SystemTrayMenu::new()
          .add_item(CustomMenuItem::new("quit", "Quit"))
          .add_item(CustomMenuItem::new("open", "Open"))
      )
      .on_event(move |event| {
        let tray_handle = app_handle.tray_handle();
      })
      .build(app)?;
    Ok(())
  });
Available on crate feature system-tray only.

Gets a handle to a system tray by its id.

use tauri::{CustomMenuItem, SystemTray, SystemTrayMenu};

tauri::Builder::default()
  .setup(|app| {
    let app_handle = app.handle();
    let tray_id = "my-tray";
    SystemTray::new()
      .with_id(tray_id)
      .with_menu(
        SystemTrayMenu::new()
          .add_item(CustomMenuItem::new("quit", "Quit"))
          .add_item(CustomMenuItem::new("open", "Open"))
      )
      .on_event(move |event| {
        let tray_handle = app_handle.tray_handle_by_id(tray_id).unwrap();
      })
      .build(app)?;
    Ok(())
  });

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 477)
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
  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 399)
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
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 400)
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
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