Trait tauri::Manager

source ·
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§

The application handle associated with this manager.

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/window.rs (line 183)
181
182
183
184
185
186
187
188
189
190
191
192
193
  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,
    }
  }
src/app/tray.rs (line 422)
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
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
  pub fn build<R: Runtime, M: Manager<R>>(
    mut self,
    manager: &M,
  ) -> crate::Result<SystemTrayHandle<R>> {
    let mut ids = HashMap::new();
    if let Some(menu) = self.menu() {
      get_menu_ids(&mut ids, menu);
    }
    let ids = Arc::new(Mutex::new(ids));

    if self.icon.is_none() {
      if let Some(tray_icon) = &manager.manager().inner.tray_icon {
        self = self.with_icon(tray_icon.clone());
      }
    }
    #[cfg(target_os = "macos")]
    {
      if !self.icon_as_template_set {
        self.icon_as_template = manager
          .config()
          .tauri
          .system_tray
          .as_ref()
          .map_or(false, |t| t.icon_as_template);
      }
      if !self.menu_on_left_click_set {
        self.menu_on_left_click = manager
          .config()
          .tauri
          .system_tray
          .as_ref()
          .map_or(false, |t| t.menu_on_left_click);
      }
      if self.title.is_none() {
        self.title = manager
          .config()
          .tauri
          .system_tray
          .as_ref()
          .and_then(|t| t.title.clone())
      }
    }

    let tray_id = self.id.clone();

    let mut runtime_tray = tauri_runtime::SystemTray::new();
    runtime_tray = runtime_tray.with_id(hash(&self.id));
    if let Some(i) = self.icon {
      runtime_tray = runtime_tray.with_icon(i);
    }

    if let Some(menu) = self.menu {
      runtime_tray = runtime_tray.with_menu(menu);
    }

    if let Some(on_event) = self.on_event {
      let ids_ = ids.clone();
      let tray_id_ = tray_id.clone();
      runtime_tray = runtime_tray.on_event(move |event| {
        on_event(SystemTrayEvent::from_runtime_event(
          event,
          tray_id_.clone(),
          &ids_,
        ))
      });
    }

    #[cfg(target_os = "macos")]
    {
      runtime_tray = runtime_tray.with_icon_as_template(self.icon_as_template);
      runtime_tray = runtime_tray.with_menu_on_left_click(self.menu_on_left_click);
      if let Some(title) = self.title {
        runtime_tray = runtime_tray.with_title(&title);
      }
    }

    let id = runtime_tray.id;
    let tray_handler = match manager.runtime() {
      RuntimeOrDispatch::Runtime(r) => r.system_tray(runtime_tray),
      RuntimeOrDispatch::RuntimeHandle(h) => h.system_tray(runtime_tray),
      RuntimeOrDispatch::Dispatch(_) => manager
        .app_handle()
        .runtime_handle
        .system_tray(runtime_tray),
    }?;

    let tray_handle = SystemTrayHandle {
      id,
      ids,
      inner: tray_handler,
    };
    manager.manager().attach_tray(tray_id, tray_handle.clone());

    Ok(tray_handle)
  }

The Config the manager was created with.

Emits a event to all windows.

Examples found in repository?
src/endpoints/event.rs (line 156)
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
  fn emit<R: Runtime>(
    context: InvokeContext<R>,
    event: EventId,
    window_label: Option<WindowLabel>,
    payload: Option<JsonValue>,
  ) -> super::Result<()> {
    // dispatch the event to Rust listeners
    context.window.trigger(
      &event.0,
      // TODO: dispatch any serializable value instead of a string in v2
      payload.as_ref().and_then(|p| {
        serde_json::to_string(&p)
          .map_err(|e| {
            #[cfg(debug_assertions)]
            eprintln!("{e}");
            e
          })
          .ok()
      }),
    );

    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
Hide additional examples
src/updater/mod.rs (lines 313-320)
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
  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));
}

Emits an event to a window with the specified label.

Examples found in repository?
src/endpoints/event.rs (line 151)
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
  fn emit<R: Runtime>(
    context: InvokeContext<R>,
    event: EventId,
    window_label: Option<WindowLabel>,
    payload: Option<JsonValue>,
  ) -> super::Result<()> {
    // dispatch the event to Rust listeners
    context.window.trigger(
      &event.0,
      // TODO: dispatch any serializable value instead of a string in v2
      payload.as_ref().and_then(|p| {
        serde_json::to_string(&p)
          .map_err(|e| {
            #[cfg(debug_assertions)]
            eprintln!("{e}");
            e
          })
          .ok()
      }),
    );

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

Listen to a global event.

Examples found in repository?
src/updater/mod.rs (lines 442-447)
439
440
441
442
443
444
445
446
447
448
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;
    });
  });
}
More examples
Hide additional examples
src/app.rs (lines 955-964)
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
975
  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 responsibilities 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);
      }
    }
  }

Listen to a global event only once.

Examples found in repository?
src/updater/mod.rs (lines 331-335)
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
  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)
      }
    }
  }

Trigger a global event.

Remove an event listener.

Fetch a single window from the manager.

Examples found in repository?
src/endpoints/window.rs (line 244)
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
  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(all(desktop, window_center))]
      WindowManagerCmd::Center => window.center()?,
      #[cfg(all(desktop, window_request_user_attention))]
      WindowManagerCmd::RequestUserAttention(request_type) => {
        window.request_user_attention(request_type)?
      }
      #[cfg(all(desktop, window_set_resizable))]
      WindowManagerCmd::SetResizable(resizable) => window.set_resizable(resizable)?,
      #[cfg(all(desktop, window_set_title))]
      WindowManagerCmd::SetTitle(title) => window.set_title(&title)?,
      #[cfg(all(desktop, window_maximize))]
      WindowManagerCmd::Maximize => window.maximize()?,
      #[cfg(all(desktop, window_unmaximize))]
      WindowManagerCmd::Unmaximize => window.unmaximize()?,
      #[cfg(all(desktop, window_maximize, window_unmaximize))]
      WindowManagerCmd::ToggleMaximize => match window.is_maximized()? {
        true => window.unmaximize()?,
        false => window.maximize()?,
      },
      #[cfg(all(desktop, window_minimize))]
      WindowManagerCmd::Minimize => window.minimize()?,
      #[cfg(all(desktop, window_unminimize))]
      WindowManagerCmd::Unminimize => window.unminimize()?,
      #[cfg(all(desktop, window_show))]
      WindowManagerCmd::Show => window.show()?,
      #[cfg(all(desktop, window_hide))]
      WindowManagerCmd::Hide => window.hide()?,
      #[cfg(all(desktop, window_close))]
      WindowManagerCmd::Close => window.close()?,
      #[cfg(all(desktop, window_set_decorations))]
      WindowManagerCmd::SetDecorations(decorations) => window.set_decorations(decorations)?,
      #[cfg(all(desktop, window_set_always_on_top))]
      WindowManagerCmd::SetAlwaysOnTop(always_on_top) => window.set_always_on_top(always_on_top)?,
      #[cfg(all(desktop, window_set_size))]
      WindowManagerCmd::SetSize(size) => window.set_size(size)?,
      #[cfg(all(desktop, window_set_min_size))]
      WindowManagerCmd::SetMinSize(size) => window.set_min_size(size)?,
      #[cfg(all(desktop, window_set_max_size))]
      WindowManagerCmd::SetMaxSize(size) => window.set_max_size(size)?,
      #[cfg(all(desktop, window_set_position))]
      WindowManagerCmd::SetPosition(position) => window.set_position(position)?,
      #[cfg(all(desktop, window_set_fullscreen))]
      WindowManagerCmd::SetFullscreen(fullscreen) => window.set_fullscreen(fullscreen)?,
      #[cfg(all(desktop, window_set_focus))]
      WindowManagerCmd::SetFocus => window.set_focus()?,
      #[cfg(all(desktop, window_set_icon))]
      WindowManagerCmd::SetIcon { icon } => window.set_icon(icon.into())?,
      #[cfg(all(desktop, window_set_skip_taskbar))]
      WindowManagerCmd::SetSkipTaskbar(skip) => window.set_skip_taskbar(skip)?,
      #[cfg(all(desktop, window_set_cursor_grab))]
      WindowManagerCmd::SetCursorGrab(grab) => window.set_cursor_grab(grab)?,
      #[cfg(all(desktop, window_set_cursor_visible))]
      WindowManagerCmd::SetCursorVisible(visible) => window.set_cursor_visible(visible)?,
      #[cfg(all(desktop, window_set_cursor_icon))]
      WindowManagerCmd::SetCursorIcon(icon) => window.set_cursor_icon(icon)?,
      #[cfg(all(desktop, window_set_cursor_position))]
      WindowManagerCmd::SetCursorPosition(position) => window.set_cursor_position(position)?,
      #[cfg(all(desktop, window_set_ignore_cursor_events))]
      WindowManagerCmd::SetIgnoreCursorEvents(ignore_cursor) => {
        window.set_ignore_cursor_events(ignore_cursor)?
      }
      #[cfg(all(desktop, window_start_dragging))]
      WindowManagerCmd::StartDragging => window.start_dragging()?,
      #[cfg(all(desktop, window_print))]
      WindowManagerCmd::Print => window.print()?,
      // internals
      #[cfg(all(desktop, window_maximize, window_unmaximize))]
      WindowManagerCmd::InternalToggleMaximize => {
        if window.is_resizable()? {
          match window.is_maximized()? {
            true => window.unmaximize()?,
            false => window.maximize()?,
          }
        }
      }
      #[cfg(all(desktop, any(debug_assertions, feature = "devtools")))]
      WindowManagerCmd::InternalToggleDevtools => {
        if window.is_devtools_open() {
          window.close_devtools();
        } else {
          window.open_devtools();
        }
      }
      #[allow(unreachable_patterns)]
      _ => (),
    }
    #[allow(unreachable_code)]
    Ok(().into())
  }

Fetch all managed windows.

Examples found in repository?
src/updater/mod.rs (line 561)
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 {app_name} is available! "#),
    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(())
}

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?
src/app.rs (lines 1605-1623)
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
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
  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(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 mut webview_attributes =
        WebviewAttributes::new(url).accept_first_mouse(config.accept_first_mouse);
      if let Some(ua) = &config.user_agent {
        webview_attributes = webview_attributes.user_agent(&ua.to_string());
      }
      if !config.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(all(desktop, feature = "global-shortcut"))]
    let global_shortcut_manager = runtime.global_shortcut_manager();

    #[cfg(feature = "clipboard")]
    let clipboard_manager = runtime.clipboard_manager();

    #[allow(unused_mut)]
    let mut app = App {
      runtime: Some(runtime),
      pending_windows: Some(self.pending_windows),
      setup: Some(self.setup),
      manager: manager.clone(),
      #[cfg(all(desktop, feature = "global-shortcut"))]
      global_shortcut_manager: global_shortcut_manager.clone(),
      #[cfg(feature = "clipboard")]
      clipboard_manager: clipboard_manager.clone(),
      handle: AppHandle {
        runtime_handle,
        manager,
        #[cfg(all(desktop, feature = "global-shortcut"))]
        global_shortcut_manager,
        #[cfg(feature = "clipboard")]
        clipboard_manager,
        #[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(&app.manager.config(), app.package_info(), &env, 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(all(desktop, feature = "system-tray"))]
    {
      if let Some(tray) = self.system_tray {
        tray.build(&app)?;
      }

      for listener in self.system_tray_event_listeners {
        let app_handle = app.handle();
        let listener = Arc::new(std::sync::Mutex::new(listener));
        app
          .runtime
          .as_mut()
          .unwrap()
          .on_system_tray_event(move |tray_id, event| {
            if let Some((tray_id, tray)) = app_handle.manager().get_tray_by_runtime_id(tray_id) {
              let app_handle = app_handle.clone();
              let event = tray::SystemTrayEvent::from_runtime_event(event, tray_id, &tray.ids);
              let listener = listener.clone();
              listener.lock().unwrap()(&app_handle, event);
            }
          });
      }
    }

    app.manager.initialize_plugins(&app.handle())?;

    Ok(app)
  }

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?
src/lib.rs (line 804)
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
  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
Hide additional examples
src/endpoints/path.rs (line 54)
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)
  }
src/endpoints/file_system.rs (line 204)
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
  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)
  }

  #[module_command_handler(fs_exists)]
  fn exists<R: Runtime>(
    context: InvokeContext<R>,
    path: SafePathBuf,
    options: Option<FileOperationOptions>,
  ) -> super::Result<bool> {
    let resolved_path = resolve_path(
      &context.config,
      &context.package_info,
      &context.window,
      path,
      options.and_then(|o| o.dir),
    )?;
    Ok(resolved_path.as_ref().exists())
  }
}

#[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)),
  }
}
src/endpoints/http.rs (line 89)
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())
    }
  }
src/app.rs (line 948)
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
975
  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 responsibilities 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);
      }
    }
  }
src/endpoints/dialog.rs (line 182)
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)
  }

Attempts to retrieve the managed state for the type T.

Returns Some if the state has previously been managed. Otherwise returns None.

Gets the managed Env.

Examples found in repository?
src/app.rs (line 540)
538
539
540
541
  pub fn restart(&self) {
    self.cleanup_before_exit();
    crate::api::process::restart(&self.env());
  }

Gets the scope for the filesystem APIs.

Gets the scope for the asset protocol.

Gets the scope for the shell execute APIs.

Implementors§