tauri_api/
dialog.rs

1use std::path::Path;
2
3pub use nfd::Response;
4use nfd::{open_dialog, DialogType};
5pub use tauri_dialog::DialogSelection;
6use tauri_dialog::{DialogBuilder, DialogButtons, DialogStyle};
7
8fn open_dialog_internal(
9  dialog_type: DialogType,
10  filter: Option<impl AsRef<str>>,
11  default_path: Option<impl AsRef<Path>>,
12) -> crate::Result<Response> {
13  let response = open_dialog(
14    filter.map(|s| s.as_ref().to_string()).as_deref(),
15    default_path
16      .map(|s| s.as_ref().to_string_lossy().to_string())
17      .as_deref(),
18    dialog_type,
19  )?;
20  match response {
21    Response::Cancel => Err(crate::Error::Dialog("user cancelled".into()).into()),
22    _ => Ok(response),
23  }
24}
25
26/// Displays a dialog with a message and an optional title with a "yes" and a "no" button
27pub fn ask(message: impl AsRef<str>, title: impl AsRef<str>) -> DialogSelection {
28  DialogBuilder::new()
29    .message(message.as_ref())
30    .title(title.as_ref())
31    .style(DialogStyle::Question)
32    .buttons(DialogButtons::YesNo)
33    .build()
34    .show()
35}
36
37/// Displays a message dialog
38pub fn message(message: impl AsRef<str>, title: impl AsRef<str>) {
39  DialogBuilder::new()
40    .message(message.as_ref())
41    .title(title.as_ref())
42    .style(DialogStyle::Info)
43    .build()
44    .show();
45}
46
47/// Open single select file dialog
48pub fn select(
49  filter_list: Option<impl AsRef<str>>,
50  default_path: Option<impl AsRef<Path>>,
51) -> crate::Result<Response> {
52  open_dialog_internal(DialogType::SingleFile, filter_list, default_path)
53}
54
55/// Open multiple select file dialog
56pub fn select_multiple(
57  filter_list: Option<impl AsRef<str>>,
58  default_path: Option<impl AsRef<Path>>,
59) -> crate::Result<Response> {
60  open_dialog_internal(DialogType::MultipleFiles, filter_list, default_path)
61}
62
63/// Open save dialog
64pub fn save_file(
65  filter_list: Option<impl AsRef<str>>,
66  default_path: Option<impl AsRef<Path>>,
67) -> crate::Result<Response> {
68  open_dialog_internal(DialogType::SaveFile, filter_list, default_path)
69}
70
71/// Open pick folder dialog
72pub fn pick_folder(default_path: Option<impl AsRef<Path>>) -> crate::Result<Response> {
73  let filter: Option<String> = None;
74  open_dialog_internal(DialogType::PickFolder, filter, default_path)
75}