Skip to main content

cosmic/dialog/file_chooser/
open.rs

1// Copyright 2023 System76 <info@system76.com>
2// SPDX-License-Identifier: MPL-2.0
3
4//! Request to open files and/or directories.
5//!
6//! Check out the [open-dialog](https://github.com/pop-os/libcosmic/tree/master/examples/open-dialog)
7//! example in our repository.
8
9#[cfg(xdg_portal)]
10pub use portal::{FileResponse, MultiFileResponse, file, files, folder, folders};
11
12#[cfg(feature = "rfd")]
13pub use rust_fd::{FileResponse, MultiFileResponse, file, files, folder, folders};
14
15use super::Error;
16use std::path::PathBuf;
17
18/// A builder for an open file dialog
19#[derive(derive_setters::Setters)]
20#[must_use]
21pub struct Dialog {
22    /// The label for the dialog's window title.
23    #[setters(into)]
24    title: String,
25
26    /// The label for the accept button. Mnemonic underlines are allowed.
27    #[cfg(xdg_portal)]
28    #[setters(skip)]
29    accept_label: Option<String>,
30
31    /// Sets the starting directory of the dialog.
32    #[setters(into, strip_option)]
33    #[allow(dead_code)] // TODO: ashpd does not expose this yet
34    directory: Option<PathBuf>,
35
36    /// Set starting file name of the dialog.
37    #[setters(into, strip_option)]
38    #[allow(dead_code)] // TODO: ashpd does not expose this yet
39    file_name: Option<String>,
40
41    /// Modal dialogs require user input before continuing the program.
42    #[cfg(xdg_portal)]
43    #[setters(skip)]
44    modal: bool,
45
46    /// Adds a list of choices.
47    #[cfg(xdg_portal)]
48    #[setters(skip)]
49    choices: Vec<super::Choice>,
50
51    /// Specifies the default file filter.
52    #[cfg(xdg_portal)]
53    #[setters(skip)]
54    current_filter: Option<super::FileFilter>,
55
56    /// A collection of file filters.
57    #[setters(skip)]
58    pub(self) filters: Vec<super::FileFilter>,
59}
60
61impl Default for Dialog {
62    fn default() -> Self {
63        Self::new()
64    }
65}
66
67impl Dialog {
68    pub const fn new() -> Self {
69        Self {
70            title: String::new(),
71            #[cfg(xdg_portal)]
72            accept_label: None,
73            directory: None,
74            file_name: None,
75            #[cfg(xdg_portal)]
76            modal: true,
77            #[cfg(xdg_portal)]
78            current_filter: None,
79            #[cfg(xdg_portal)]
80            choices: Vec::new(),
81            filters: Vec::new(),
82        }
83    }
84
85    /// The label for the accept button. Mnemonic underlines are allowed.
86    #[cfg(xdg_portal)]
87    pub fn accept_label(mut self, label: impl Into<String>) -> Self {
88        self.accept_label = Some(label.into());
89        self
90    }
91
92    /// Adds a choice.
93    #[cfg(xdg_portal)]
94    pub fn choice(mut self, choice: impl Into<super::Choice>) -> Self {
95        self.choices.push(choice.into());
96        self
97    }
98
99    /// Specifies the default file filter.
100    #[cfg(xdg_portal)]
101    pub fn current_filter(mut self, filter: impl Into<super::FileFilter>) -> Self {
102        self.current_filter = Some(filter.into());
103        self
104    }
105
106    /// Adds a files filter.
107    pub fn filter(mut self, filter: impl Into<super::FileFilter>) -> Self {
108        self.filters.push(filter.into());
109        self
110    }
111
112    /// Modal dialogs require user input before continuing the program.
113    #[cfg(xdg_portal)]
114    pub fn modal(mut self, modal: bool) -> Self {
115        self.modal = modal;
116        self
117    }
118
119    /// Create an open file dialog.
120    pub async fn open_file(self) -> Result<FileResponse, Error> {
121        file(self).await
122    }
123
124    /// Create an open file dialog with multiple file select.
125    pub async fn open_files(self) -> Result<MultiFileResponse, Error> {
126        files(self).await
127    }
128
129    /// Create an open folder dialog.
130    pub async fn open_folder(self) -> Result<FileResponse, Error> {
131        folder(self).await
132    }
133
134    /// Create an open folder dialog with multi file select.
135    pub async fn open_folders(self) -> Result<MultiFileResponse, Error> {
136        folders(self).await
137    }
138}
139
140#[cfg(xdg_portal)]
141mod portal {
142    use super::Dialog;
143    use crate::dialog::file_chooser::{Error, parse_uri};
144    use ashpd::desktop::file_chooser::SelectedFiles;
145    use url::Url;
146
147    fn error_or_cancel(error: ashpd::Error) -> Error {
148        if let ashpd::Error::Response(ashpd::desktop::ResponseError::Cancelled) = error {
149            Error::Cancelled
150        } else {
151            Error::Open(error)
152        }
153    }
154
155    /// Creates a new file dialog, and begins to await its responses.
156    #[cfg(xdg_portal)]
157    pub async fn create(
158        dialog: super::Dialog,
159        folders: bool,
160        multiple: bool,
161    ) -> Result<ashpd::desktop::Request<SelectedFiles>, Error> {
162        // TODO: Set window identifier
163        ashpd::desktop::file_chooser::OpenFileRequest::default()
164            .title(Some(dialog.title.as_str()))
165            .accept_label(dialog.accept_label.as_deref())
166            .directory(folders)
167            .modal(dialog.modal)
168            .multiple(multiple)
169            .choices(dialog.choices)
170            .filters(dialog.filters)
171            .current_filter(dialog.current_filter)
172            .send()
173            .await
174            .map_err(error_or_cancel)
175    }
176
177    fn file_response(
178        request: ashpd::desktop::Request<SelectedFiles>,
179    ) -> Result<FileResponse, Error> {
180        let files = request.response().map_err(error_or_cancel)?;
181        let url = parse_uri(files.uris().first().ok_or(Error::Cancelled)?)?;
182        Ok(FileResponse { files, url })
183    }
184
185    fn multi_file_response(
186        request: ashpd::desktop::Request<SelectedFiles>,
187    ) -> Result<MultiFileResponse, Error> {
188        let files = request.response().map_err(error_or_cancel)?;
189        let urls = files
190            .uris()
191            .iter()
192            .map(parse_uri)
193            .collect::<Result<Vec<Url>, _>>()?;
194        Ok(MultiFileResponse { files, urls })
195    }
196
197    pub async fn file(dialog: Dialog) -> Result<FileResponse, Error> {
198        file_response(create(dialog, false, false).await?)
199    }
200
201    pub async fn files(dialog: Dialog) -> Result<MultiFileResponse, Error> {
202        multi_file_response(create(dialog, false, true).await?)
203    }
204
205    pub async fn folder(dialog: Dialog) -> Result<FileResponse, Error> {
206        file_response(create(dialog, true, false).await?)
207    }
208
209    pub async fn folders(dialog: Dialog) -> Result<MultiFileResponse, Error> {
210        multi_file_response(create(dialog, true, true).await?)
211    }
212
213    /// A dialog response containing the selected file or folder.
214    pub struct FileResponse {
215        pub files: SelectedFiles,
216        url: Url,
217    }
218
219    impl FileResponse {
220        pub fn choices(&self) -> &[(String, String)] {
221            self.files.choices()
222        }
223
224        pub fn url(&self) -> &Url {
225            &self.url
226        }
227    }
228
229    /// A dialog response containing the selected file(s) or folder(s).
230    pub struct MultiFileResponse {
231        pub files: SelectedFiles,
232        urls: Vec<Url>,
233    }
234
235    impl MultiFileResponse {
236        pub fn choices(&self) -> &[(String, String)] {
237            self.files.choices()
238        }
239
240        pub fn urls(&self) -> &[Url] {
241            &self.urls
242        }
243    }
244}
245
246#[cfg(feature = "rfd")]
247mod rust_fd {
248    use super::Dialog;
249    use crate::dialog::file_chooser::Error;
250    use url::Url;
251
252    pub fn create(dialog: Dialog) -> rfd::AsyncFileDialog {
253        let mut builder = rfd::AsyncFileDialog::new().set_title(dialog.title);
254
255        if let Some(directory) = dialog.directory {
256            builder = builder.set_directory(directory);
257        }
258
259        if let Some(file_name) = dialog.file_name {
260            builder = builder.set_file_name(file_name);
261        }
262
263        for filter in dialog.filters {
264            builder = builder.add_filter(filter.description, &filter.extensions);
265        }
266
267        builder
268    }
269
270    fn file_response(request: Option<rfd::FileHandle>) -> Result<FileResponse, Error> {
271        if let Some(handle) = request {
272            let url = Url::from_file_path(handle.path()).map_err(|_| Error::UrlAbsolute)?;
273
274            return Ok(FileResponse(url));
275        }
276
277        Err(Error::Cancelled)
278    }
279
280    fn multi_file_response(
281        request: Option<Vec<rfd::FileHandle>>,
282    ) -> Result<MultiFileResponse, Error> {
283        if let Some(handles) = request {
284            let mut urls = Vec::with_capacity(handles.len());
285
286            for handle in &handles {
287                urls.push(Url::from_file_path(handle.path()).map_err(|()| Error::UrlAbsolute)?);
288            }
289
290            return Ok(MultiFileResponse(urls));
291        }
292
293        Err(Error::Cancelled)
294    }
295
296    pub async fn file(dialog: Dialog) -> Result<FileResponse, Error> {
297        file_response(create(dialog).pick_file().await)
298    }
299
300    pub async fn files(dialog: Dialog) -> Result<MultiFileResponse, Error> {
301        multi_file_response(create(dialog).pick_files().await)
302    }
303
304    pub async fn folder(dialog: Dialog) -> Result<FileResponse, Error> {
305        file_response(create(dialog).pick_folder().await)
306    }
307
308    pub async fn folders(dialog: Dialog) -> Result<MultiFileResponse, Error> {
309        multi_file_response(create(dialog).pick_folders().await)
310    }
311
312    /// A dialog response containing the selected file or folder.
313    pub struct FileResponse(Url);
314
315    impl FileResponse {
316        pub fn choices(&self) -> &[(String, String)] {
317            &[]
318        }
319
320        pub fn url(&self) -> &Url {
321            &self.0
322        }
323    }
324
325    /// A dialog response containing the selected file(s) or folder(s).
326    pub struct MultiFileResponse(Vec<Url>);
327
328    impl MultiFileResponse {
329        pub fn choices(&self) -> &[(String, String)] {
330            &[]
331        }
332
333        pub fn urls(&self) -> &[Url] {
334            &self.0
335        }
336    }
337}