1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
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
161
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
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
// Copyright 2019-2021 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

#![allow(unused_imports)]

use super::{InvokeContext, InvokeResponse};
use crate::Runtime;
#[cfg(any(dialog_open, dialog_save))]
use crate::{api::dialog::blocking::FileDialogBuilder, Manager, Scopes};
use serde::{Deserialize, Deserializer};
use tauri_macros::{command_enum, module_command_handler, CommandModule};

use std::path::PathBuf;

macro_rules! message_dialog {
  ($fn_name: ident, $allowlist: ident, $buttons: expr) => {
    #[module_command_handler($allowlist)]
    fn $fn_name<R: Runtime>(
      context: InvokeContext<R>,
      title: Option<String>,
      message: String,
      level: Option<MessageDialogType>,
    ) -> super::Result<bool> {
      let mut builder = crate::api::dialog::blocking::MessageDialogBuilder::new(
        title.unwrap_or_else(|| context.window.app_handle.package_info().name.clone()),
        message,
      )
      .buttons($buttons);
      #[cfg(any(windows, target_os = "macos"))]
      {
        builder = builder.parent(&context.window);
      }
      if let Some(level) = level {
        builder = builder.kind(level.into());
      }
      Ok(builder.show())
    }
  };
}

#[allow(dead_code)]
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DialogFilter {
  name: String,
  extensions: Vec<String>,
}

/// The options for the open dialog API.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OpenDialogOptions {
  /// The title of the dialog window.
  pub title: Option<String>,
  /// The filters of the dialog.
  #[serde(default)]
  pub filters: Vec<DialogFilter>,
  /// Whether the dialog allows multiple selection or not.
  #[serde(default)]
  pub multiple: bool,
  /// Whether the dialog is a directory selection (`true` value) or file selection (`false` value).
  #[serde(default)]
  pub directory: bool,
  /// The initial path of the dialog.
  pub default_path: Option<PathBuf>,
  /// If [`Self::directory`] is true, indicates that it will be read recursively later.
  /// Defines whether subdirectories will be allowed on the scope or not.
  #[serde(default)]
  pub recursive: bool,
}

/// The options for the save dialog API.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SaveDialogOptions {
  /// The title of the dialog window.
  pub title: Option<String>,
  /// The filters of the dialog.
  #[serde(default)]
  pub filters: Vec<DialogFilter>,
  /// The initial path of the dialog.
  pub default_path: Option<PathBuf>,
}

/// Types of message, ask and confirm dialogs.
#[non_exhaustive]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum MessageDialogType {
  /// Information dialog.
  Info,
  /// Warning dialog.
  Warning,
  /// Error dialog.
  Error,
}

impl<'de> Deserialize<'de> for MessageDialogType {
  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  where
    D: Deserializer<'de>,
  {
    let s = String::deserialize(deserializer)?;
    Ok(match s.to_lowercase().as_str() {
      "info" => MessageDialogType::Info,
      "warning" => MessageDialogType::Warning,
      "error" => MessageDialogType::Error,
      _ => MessageDialogType::Info,
    })
  }
}

#[cfg(any(dialog_message, dialog_ask, dialog_confirm))]
impl From<MessageDialogType> for crate::api::dialog::MessageDialogKind {
  fn from(kind: MessageDialogType) -> Self {
    match kind {
      MessageDialogType::Info => Self::Info,
      MessageDialogType::Warning => Self::Warning,
      MessageDialogType::Error => Self::Error,
    }
  }
}

/// The API descriptor.
#[command_enum]
#[derive(Deserialize, CommandModule)]
#[serde(tag = "cmd", rename_all = "camelCase")]
#[allow(clippy::enum_variant_names)]
pub enum Cmd {
  /// The open dialog API.
  #[cmd(dialog_open, "dialog > open")]
  OpenDialog { options: OpenDialogOptions },
  /// The save dialog API.
  #[cmd(dialog_save, "dialog > save")]
  SaveDialog { options: SaveDialogOptions },
  #[cmd(dialog_message, "dialog > message")]
  MessageDialog {
    title: Option<String>,
    message: String,
    #[serde(rename = "type")]
    level: Option<MessageDialogType>,
  },
  #[cmd(dialog_ask, "dialog > ask")]
  AskDialog {
    title: Option<String>,
    message: String,
    #[serde(rename = "type")]
    level: Option<MessageDialogType>,
  },
  #[cmd(dialog_confirm, "dialog > confirm")]
  ConfirmDialog {
    title: Option<String>,
    message: String,
    #[serde(rename = "type")]
    level: Option<MessageDialogType>,
  },
}

impl Cmd {
  #[module_command_handler(dialog_open)]
  #[allow(unused_variables)]
  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)
  }

  message_dialog!(
    message_dialog,
    dialog_message,
    crate::api::dialog::MessageDialogButtons::Ok
  );

  message_dialog!(
    ask_dialog,
    dialog_ask,
    crate::api::dialog::MessageDialogButtons::YesNo
  );

  message_dialog!(
    confirm_dialog,
    dialog_confirm,
    crate::api::dialog::MessageDialogButtons::OkCancel
  );
}

#[cfg(any(dialog_open, dialog_save))]
fn set_default_path(
  mut dialog_builder: FileDialogBuilder,
  default_path: PathBuf,
) -> FileDialogBuilder {
  if default_path.is_file() || !default_path.exists() {
    if let (Some(parent), Some(file_name)) = (default_path.parent(), default_path.file_name()) {
      if parent.components().count() > 0 {
        dialog_builder = dialog_builder.set_directory(parent);
      }
      dialog_builder = dialog_builder.set_file_name(&file_name.to_string_lossy());
    } else {
      dialog_builder = dialog_builder.set_directory(default_path);
    }
    dialog_builder
  } else {
    dialog_builder.set_directory(default_path)
  }
}

#[cfg(test)]
mod tests {
  use super::{OpenDialogOptions, SaveDialogOptions};
  use quickcheck::{Arbitrary, Gen};

  impl Arbitrary for OpenDialogOptions {
    fn arbitrary(g: &mut Gen) -> Self {
      Self {
        filters: Vec::new(),
        multiple: bool::arbitrary(g),
        directory: bool::arbitrary(g),
        default_path: Option::arbitrary(g),
        title: Option::arbitrary(g),
        recursive: bool::arbitrary(g),
      }
    }
  }

  impl Arbitrary for SaveDialogOptions {
    fn arbitrary(g: &mut Gen) -> Self {
      Self {
        filters: Vec::new(),
        default_path: Option::arbitrary(g),
        title: Option::arbitrary(g),
      }
    }
  }

  #[tauri_macros::module_command_test(dialog_open, "dialog > open")]
  #[quickcheck_macros::quickcheck]
  fn open_dialog(_options: OpenDialogOptions) {}

  #[tauri_macros::module_command_test(dialog_save, "dialog > save")]
  #[quickcheck_macros::quickcheck]
  fn save_dialog(_options: SaveDialogOptions) {}
}