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
use crate::dialog::{
    Dialog, DialogImpl, OpenMultipleFile, OpenSingleDir, OpenSingleFile, SaveSingleFile,
};
use crate::Result;
use std::path::Path;

/// Represents a set of file extensions and their description.
#[derive(Debug, Clone)]
pub struct Filter<'a> {
    #[cfg_attr(target_os = "macos", allow(dead_code))]
    pub(crate) description: &'a str,
    pub(crate) extensions: &'a [&'a str],
}

/// Builds and shows file dialogs.
#[derive(Debug, Clone)]
pub struct FileDialog<'a> {
    pub(crate) location: Option<&'a Path>,
    pub(crate) filters: Vec<Filter<'a>>,
}

impl<'a> FileDialog<'a> {
    pub fn new() -> Self {
        FileDialog {
            location: None,
            filters: vec![],
        }
    }

    pub fn set_location<P: AsRef<Path> + ?Sized>(mut self, path: &'a P) -> Self {
        self.location = Some(path.as_ref());
        self
    }

    pub fn reset_location(mut self) -> Self {
        self.location = None;
        self
    }

    pub fn add_filter(mut self, description: &'a str, extensions: &'a [&'a str]) -> Self {
        if extensions.is_empty() {
            panic!("The file extensions of a filter must be specified.")
        }
        self.filters.push(Filter {
            description,
            extensions,
        });
        self
    }

    pub fn remove_all_filters(mut self) -> Self {
        self.filters = vec![];
        self
    }

    pub fn show_open_single_file(self) -> Result<<OpenSingleFile<'a> as Dialog>::Output> {
        let mut dialog = OpenSingleFile {
            location: self.location,
            filters: self.filters,
        };
        dialog.show()
    }

    pub fn show_open_multiple_file(self) -> Result<<OpenMultipleFile<'a> as Dialog>::Output> {
        let mut dialog = OpenMultipleFile {
            location: self.location,
            filters: self.filters,
        };
        dialog.show()
    }

    pub fn show_open_single_dir(self) -> Result<<OpenSingleDir<'a> as Dialog>::Output> {
        let mut dialog = OpenSingleDir {
            location: self.location,
        };
        dialog.show()
    }

    pub fn show_save_single_file(self) -> Result<<SaveSingleFile<'a> as Dialog>::Output> {
        let mut dialog = SaveSingleFile {
            location: self.location,
            filters: self.filters,
        };
        dialog.show()
    }
}

impl Default for FileDialog<'_> {
    fn default() -> Self {
        Self::new()
    }
}