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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
//! Native dialog types.

use std::{mem, path::PathBuf};

use zng_txt::Txt;

crate::declare_id! {
    /// Identifies an ongoing async native dialog with the user.
    pub struct DialogId(_);
}

/// Defines a native message dialog.
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct MsgDialog {
    /// Message dialog window title.
    pub title: Txt,
    /// Message text.
    pub message: Txt,
    /// Kind of message.
    pub icon: MsgDialogIcon,
    /// Message buttons.
    pub buttons: MsgDialogButtons,
}
impl Default for MsgDialog {
    fn default() -> Self {
        Self {
            title: Txt::from_str(""),
            message: Txt::from_str(""),
            icon: MsgDialogIcon::Info,
            buttons: MsgDialogButtons::Ok,
        }
    }
}

/// Icon of a message dialog.
///
/// Defines the overall *level* style of the dialog.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum MsgDialogIcon {
    /// Informational.
    Info,
    /// Warning.
    Warn,
    /// Error.
    Error,
}

/// Buttons of a message dialog.
///
/// Defines what kind of question the user is answering.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum MsgDialogButtons {
    /// Ok.
    ///
    /// Just a confirmation of message received.
    Ok,
    /// Ok or Cancel.
    ///
    /// Approve selected choice or cancel.
    OkCancel,
    /// Yes or No.
    YesNo,
}

/// Response to a message dialog.
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum MsgDialogResponse {
    /// Message received or approved.
    Ok,
    /// Question approved.
    Yes,
    /// Question denied.
    No,
    /// Message denied.
    Cancel,
    /// Failed to show the message.
    ///
    /// The associated string may contain debug information, caller should assume that native file dialogs
    /// are not available for the given window ID at the current view-process instance.
    Error(Txt),
}

/// File dialog filters builder.
///
/// # Syntax
///
/// ```txt
/// Display Name|ext1;ext2|All Files|*
/// ```
///
/// You can use the [`push_filter`] method to create filters. Note that the extensions are
/// not glob patterns, they must be an extension (without the dot prefix) or `*` for all files.
///
/// [`push_filter`]: FileDialogFilters::push_filter
#[derive(Debug, Default, PartialEq, Eq, Hash, Clone, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
pub struct FileDialogFilters(Txt);
impl FileDialogFilters {
    /// New default (empty).
    pub fn new() -> Self {
        Self::default()
    }

    /// Push a filter entry.
    pub fn push_filter<S: AsRef<str>>(&mut self, display_name: &str, extensions: &[S]) -> &mut Self {
        if !self.0.is_empty() && !self.0.ends_with('|') {
            self.0.push('|');
        }

        let mut extensions: Vec<_> = extensions
            .iter()
            .map(|s| s.as_ref())
            .filter(|&s| !s.contains('|') && !s.contains(';'))
            .collect();
        if extensions.is_empty() {
            extensions = vec!["*"];
        }

        let display_name = display_name.replace('|', " ");
        let display_name = display_name.trim();
        if !display_name.is_empty() {
            self.0.push_str(display_name);
            self.0.push_str(" (");
        }
        let mut prefix = "";
        for pat in &extensions {
            self.0.push_str(prefix);
            prefix = ", ";
            self.0.push_str("*.");
            self.0.push_str(pat);
        }
        if !display_name.is_empty() {
            self.0.push(')');
        }

        self.0.push('|');

        prefix = "";
        for pat in extensions {
            self.0.push_str(prefix);
            prefix = ";";
            self.0.push_str(pat);
        }

        self
    }

    /// Iterate over filter entries and patterns.
    pub fn iter_filters(&self) -> impl Iterator<Item = (&str, impl Iterator<Item = &str>)> {
        Self::iter_filters_str(self.0.as_str())
    }
    fn iter_filters_str(filters: &str) -> impl Iterator<Item = (&str, impl Iterator<Item = &str>)> {
        struct Iter<'a> {
            filters: &'a str,
        }
        struct PatternIter<'a> {
            patterns: &'a str,
        }
        impl<'a> Iterator for Iter<'a> {
            type Item = (&'a str, PatternIter<'a>);

            fn next(&mut self) -> Option<Self::Item> {
                if let Some(i) = self.filters.find('|') {
                    let display_name = &self.filters[..i];
                    self.filters = &self.filters[i + 1..];

                    let patterns = if let Some(i) = self.filters.find('|') {
                        let pat = &self.filters[..i];
                        self.filters = &self.filters[i + 1..];
                        pat
                    } else {
                        let pat = self.filters;
                        self.filters = "";
                        pat
                    };

                    if !patterns.is_empty() {
                        Some((display_name.trim(), PatternIter { patterns }))
                    } else {
                        self.filters = "";
                        None
                    }
                } else {
                    self.filters = "";
                    None
                }
            }
        }
        impl<'a> Iterator for PatternIter<'a> {
            type Item = &'a str;

            fn next(&mut self) -> Option<Self::Item> {
                if let Some(i) = self.patterns.find(';') {
                    let pattern = &self.patterns[..i];
                    self.patterns = &self.patterns[i + 1..];
                    Some(pattern.trim())
                } else if !self.patterns.is_empty() {
                    let pat = self.patterns;
                    self.patterns = "";
                    Some(pat)
                } else {
                    self.patterns = "";
                    None
                }
            }
        }
        Iter {
            filters: filters.trim_start().trim_start_matches('|'),
        }
    }

    /// Gets the filter text.
    pub fn build(mut self) -> Txt {
        self.0.end_mut();
        self.0
    }
}
#[cfg(feature = "var")]
zng_var::impl_from_and_into_var! {
    fn from(filter: Txt) -> FileDialogFilters {
        FileDialogFilters(filter)
    }

    fn from(filter: &'static str) -> FileDialogFilters {
        FileDialogFilters(filter.into())
    }
}

/// Defines a native file dialog.
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct FileDialog {
    /// Dialog window title.
    pub title: Txt,
    /// Selected directory when the dialog opens.
    pub starting_dir: PathBuf,
    /// Starting file name.
    pub starting_name: Txt,
    /// File extension filters.
    ///
    /// Syntax:
    ///
    /// ```txt
    /// Display Name|ext1;ext2|All Files|*
    /// ```
    ///
    /// You can use the [`push_filter`] method to create filters. Note that the extensions are
    /// not glob patterns, they must be an extension (without the dot prefix) or `*` for all files.
    ///
    /// [`push_filter`]: Self::push_filter
    pub filters: Txt,

    /// Defines the file dialog looks and what kind of result is expected.
    pub kind: FileDialogKind,
}
impl FileDialog {
    /// Push a filter entry.
    pub fn push_filter<S: AsRef<str>>(&mut self, display_name: &str, extensions: &[S]) -> &mut Self {
        let mut f = FileDialogFilters(mem::take(&mut self.filters));
        f.push_filter(display_name, extensions);
        self.filters = f.build();
        self
    }

    /// Iterate over filter entries and patterns.
    pub fn iter_filters(&self) -> impl Iterator<Item = (&str, impl Iterator<Item = &str>)> {
        FileDialogFilters::iter_filters_str(&self.filters)
    }
}
impl Default for FileDialog {
    fn default() -> Self {
        FileDialog {
            title: Txt::from_str(""),
            starting_dir: PathBuf::new(),
            starting_name: Txt::from_str(""),
            filters: Txt::from_str(""),
            kind: FileDialogKind::OpenFile,
        }
    }
}

/// Kind of file dialogs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum FileDialogKind {
    /// Pick one file for reading.
    OpenFile,
    /// Pick one or many files for reading.
    OpenFiles,
    /// Pick one directory for reading.
    SelectFolder,
    /// Pick one or many directories for reading.
    SelectFolders,
    /// Pick one file for writing.
    SaveFile,
}

/// Response to a message dialog.
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum FileDialogResponse {
    /// Selected paths.
    ///
    /// Is never empty.
    Selected(Vec<PathBuf>),
    /// User did not select any path.
    Cancel,
    /// Failed to show the dialog.
    ///
    /// The associated string may contain debug information, caller should assume that native file dialogs
    /// are not available for the given window ID at the current view-process instance.
    Error(Txt),
}
impl FileDialogResponse {
    /// Gets the selected paths, or empty for cancel.
    pub fn into_paths(self) -> Result<Vec<PathBuf>, Txt> {
        match self {
            FileDialogResponse::Selected(s) => Ok(s),
            FileDialogResponse::Cancel => Ok(vec![]),
            FileDialogResponse::Error(e) => Err(e),
        }
    }

    /// Gets the last selected path, or `None` for cancel.
    pub fn into_path(self) -> Result<Option<PathBuf>, Txt> {
        self.into_paths().map(|mut p| p.pop())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn file_filters() {
        let mut dlg = FileDialog {
            title: "".into(),
            starting_dir: "".into(),
            starting_name: "".into(),
            filters: "".into(),
            kind: FileDialogKind::OpenFile,
        };

        let expected = "Display Name (*.abc, *.bca)|abc;bca|All Files (*.*)|*";

        dlg.push_filter("Display Name", &["abc", "bca"]).push_filter("All Files", &["*"]);
        assert_eq!(expected, dlg.filters);

        let expected = vec![("Display Name (*.abc, *.bca)", vec!["abc", "bca"]), ("All Files (*.*)", vec!["*"])];
        let parsed: Vec<(&str, Vec<&str>)> = dlg.iter_filters().map(|(n, p)| (n, p.collect())).collect();
        assert_eq!(expected, parsed);
    }
}