Debian Codegraph @

src/desktop/file_chooser.rs

raw
1 //! The interface lets sandboxed applications ask the user for access to files
2 //! outside the sandbox. The portal backend will present the user with a file
3 //! chooser dialog.
4 //!
5 //! Wrapper of the DBus interface: [`org.freedesktop.portal.FileChooser`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.FileChooser.html).
6 //!
7 //! ### Examples
8 //!
9 //! #### Opening a file
10 //!
11 //! ```rust,no_run
12 //! use ashpd::desktop::file_chooser::{Choice, FileFilter, SelectedFiles};
13 //!
14 //! async fn run() -> ashpd::Result<()> {
15 //! let files = SelectedFiles::open_file()
16 //! .title("open a file to read")
17 //! .accept_label("read")
18 //! .modal(true)
19 //! .multiple(true)
20 //! .choice(
21 //! Choice::new("encoding", "Encoding", "latin15")
22 //! .insert("utf8", "Unicode (UTF-8)")
23 //! .insert("latin15", "Western"),
24 //! )
25 //! // A trick to have a checkbox
26 //! .choice(Choice::boolean("re-encode", "Re-encode", false))
27 //! .filter(FileFilter::new("SVG Image").mimetype("image/svg+xml"))
28 //! .send()
29 //! .await?
30 //! .response()?;
31 //!
32 //! println!("{:#?}", files);
33 //!
34 //! Ok(())
35 //! }
36 //! ```
37 //!
38 //! #### Ask to save a file
39 //!
40 //! ```rust,no_run
41 //! use ashpd::desktop::file_chooser::{FileFilter, SelectedFiles};
42 //!
43 //! async fn run() -> ashpd::Result<()> {
44 //! let files = SelectedFiles::save_file()
45 //! .title("open a file to write")
46 //! .accept_label("write")
47 //! .current_name("image.jpg")
48 //! .modal(true)
49 //! .filter(FileFilter::new("JPEG Image").glob("*.jpg"))
50 //! .send()
51 //! .await?
52 //! .response()?;
53 //!
54 //! println!("{:#?}", files);
55 //!
56 //! Ok(())
57 //! }
58 //! ```
59 //!
60 //! #### Ask to save multiple files
61 //!
62 //! ```rust,no_run
63 //! use ashpd::desktop::file_chooser::SelectedFiles;
64 //!
65 //! async fn run() -> ashpd::Result<()> {
66 //! let files = SelectedFiles::save_files()
67 //! .title("open files to write")
68 //! .accept_label("write files")
69 //! .modal(true)
70 //! .current_folder("/home/bilelmoussaoui/Pictures")?
71 //! .files(&["test.jpg", "awesome.png"])?
72 //! .send()
73 //! .await?
74 //! .response()?;
75 //!
76 //! println!("{:#?}", files);
77 //!
78 //! Ok(())
79 //! }
80 //! ```
81
82 use std::path::Path;
83
84 use serde::{Deserialize, Serialize};
85 use serde_repr::{Deserialize_repr, Serialize_repr};
86 use zbus::zvariant::{
87 Optional, Type,
88 as_value::{self, optional},
89 };
90
91 use super::{HandleToken, Request};
92 use crate::{Error, FilePath, Uri, WindowIdentifier, proxy::Proxy};
93
94 #[derive(Clone, Serialize, Deserialize, Type, Debug, PartialEq)]
95 /// A file filter, to limit the available file choices to a mimetype or a glob
96 /// pattern.
97 pub struct FileFilter(String, Vec<(FilterType, String)>);
98
99 #[derive(Clone, Serialize_repr, Deserialize_repr, Debug, Type, PartialEq)]
100 #[repr(u32)]
101 enum FilterType {
102 GlobPattern = 0,
103 MimeType = 1,
104 }
105
106 impl FilterType {
107 /// Whether it is a mime type filter.
108 fn is_mimetype(&self) -> bool {
109 matches!(self, FilterType::MimeType)
110 }
111
112 /// Whether it is a glob pattern type filter.
113 fn is_pattern(&self) -> bool {
114 matches!(self, FilterType::GlobPattern)
115 }
116 }
117
118 impl FileFilter {
119 /// Create a new file filter
120 ///
121 /// # Arguments
122 ///
123 /// * `label` - user-visible name of the file filter.
124 pub fn new(label: &str) -> Self {
125 Self(label.to_owned(), vec![])
126 }
127
128 /// Adds a mime type to the file filter.
129 #[must_use]
130 pub fn mimetype(mut self, mimetype: &str) -> Self {
131 self.1.push((FilterType::MimeType, mimetype.to_owned()));
132 self
133 }
134
135 /// Adds a glob pattern to the file filter.
136 #[must_use]
137 pub fn glob(mut self, pattern: &str) -> Self {
138 self.1.push((FilterType::GlobPattern, pattern.to_owned()));
139 self
140 }
141 }
142
143 impl FileFilter {
144 /// The label of the filter.
145 pub fn label(&self) -> &str {
146 &self.0
147 }
148
149 /// List of mimetypes filters.
150 pub fn mimetype_filters(&self) -> Vec<&str> {
151 self.1
152 .iter()
153 .filter_map(|(type_, string)| type_.is_mimetype().then_some(string.as_str()))
154 .collect()
155 }
156
157 /// List of glob patterns filters.
158 pub fn pattern_filters(&self) -> Vec<&str> {
159 self.1
160 .iter()
161 .filter_map(|(type_, string)| type_.is_pattern().then_some(string.as_str()))
162 .collect()
163 }
164 }
165
166 #[derive(Clone, Serialize, Deserialize, Type, Debug)]
167 /// Presents the user with a choice to select from or as a checkbox.
168 pub struct Choice(String, String, Vec<(String, String)>, String);
169
170 impl Choice {
171 /// Creates a checkbox choice.
172 ///
173 /// # Arguments
174 ///
175 /// * `id` - A unique identifier of the choice.
176 /// * `label` - user-visible name of the choice.
177 /// * `state` - the initial state value.
178 pub fn boolean(id: &str, label: &str, state: bool) -> Self {
179 Self::new(id, label, &state.to_string())
180 }
181
182 /// Creates a new choice.
183 ///
184 /// # Arguments
185 ///
186 /// * `id` - A unique identifier of the choice.
187 /// * `label` - user-visible name of the choice.
188 /// * `initial_selection` - the initially selected value.
189 pub fn new(id: &str, label: &str, initial_selection: &str) -> Self {
190 Self(
191 id.to_owned(),
192 label.to_owned(),
193 vec![],
194 initial_selection.to_owned(),
195 )
196 }
197
198 /// Adds a (key, value) as a choice.
199 #[must_use]
200 pub fn insert(mut self, key: &str, value: &str) -> Self {
201 self.2.push((key.to_owned(), value.to_owned()));
202 self
203 }
204
205 /// The choice's unique id
206 pub fn id(&self) -> &str {
207 &self.0
208 }
209
210 /// The user visible label of the choice.
211 pub fn label(&self) -> &str {
212 &self.1
213 }
214
215 /// Pairs of choices.
216 pub fn pairs(&self) -> Vec<(&str, &str)> {
217 self.2
218 .iter()
219 .map(|(x, y)| (x.as_str(), y.as_str()))
220 .collect::<Vec<_>>()
221 }
222
223 /// The initially selected value.
224 pub fn initial_selection(&self) -> &str {
225 &self.3
226 }
227 }
228
229 /// Options for opening a file.
230 #[derive(Serialize, Deserialize, Type, Debug, Default)]
231 #[zvariant(signature = "dict")]
232 pub struct OpenFileOptions {
233 #[serde(with = "as_value", skip_deserializing)]
234 handle_token: HandleToken,
235 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
236 accept_label: Option<String>,
237 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
238 modal: Option<bool>,
239 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
240 multiple: Option<bool>,
241 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
242 directory: Option<bool>,
243 #[serde(default, with = "as_value", skip_serializing_if = "Vec::is_empty")]
244 filters: Vec<FileFilter>,
245 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
246 current_filter: Option<FileFilter>,
247 #[serde(default, with = "as_value", skip_serializing_if = "Vec::is_empty")]
248 choices: Vec<Choice>,
249 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
250 current_folder: Option<FilePath>,
251 }
252
253 impl OpenFileOptions {
254 /// Sets the accept label.
255 #[must_use]
256 pub fn set_accept_label<'a>(mut self, accept_label: impl Into<Option<&'a str>>) -> Self {
257 self.accept_label = accept_label.into().map(ToOwned::to_owned);
258 self
259 }
260
261 /// Gets the accept label.
262 #[cfg(feature = "backend")]
263 pub fn accept_label(&self) -> Option<&str> {
264 self.accept_label.as_deref()
265 }
266
267 /// Sets whether the dialog should be modal.
268 #[must_use]
269 pub fn set_modal(mut self, modal: impl Into<Option<bool>>) -> Self {
270 self.modal = modal.into();
271 self
272 }
273
274 /// Gets whether the dialog should be modal.
275 #[cfg(feature = "backend")]
276 pub fn modal(&self) -> Option<bool> {
277 self.modal
278 }
279
280 /// Sets whether multiple files can be selected.
281 #[must_use]
282 pub fn set_multiple(mut self, multiple: impl Into<Option<bool>>) -> Self {
283 self.multiple = multiple.into();
284 self
285 }
286
287 /// Gets whether multiple files can be selected.
288 #[cfg(feature = "backend")]
289 pub fn multiple(&self) -> Option<bool> {
290 self.multiple
291 }
292
293 /// Sets whether to select directories instead of files.
294 #[must_use]
295 pub fn set_directory(mut self, directory: impl Into<Option<bool>>) -> Self {
296 self.directory = directory.into();
297 self
298 }
299
300 /// Gets whether to select directories instead of files.
301 #[cfg(feature = "backend")]
302 pub fn directory(&self) -> Option<bool> {
303 self.directory
304 }
305
306 /// Sets the file filters.
307 #[must_use]
308 pub fn set_filters(mut self, filters: impl IntoIterator<Item = FileFilter>) -> Self {
309 self.filters = filters.into_iter().collect();
310 self
311 }
312
313 /// Gets the file filters.
314 #[cfg(feature = "backend")]
315 pub fn filters(&self) -> &[FileFilter] {
316 &self.filters
317 }
318
319 /// Sets the current filter.
320 #[must_use]
321 pub fn set_current_filter(mut self, current_filter: impl Into<Option<FileFilter>>) -> Self {
322 self.current_filter = current_filter.into();
323 self
324 }
325
326 /// Gets the current filter.
327 #[cfg(feature = "backend")]
328 pub fn current_filter(&self) -> Option<&FileFilter> {
329 self.current_filter.as_ref()
330 }
331
332 /// Sets the choices.
333 #[must_use]
334 pub fn set_choices(mut self, choices: impl IntoIterator<Item = Choice>) -> Self {
335 self.choices = choices.into_iter().collect();
336 self
337 }
338
339 /// Gets the choices.
340 #[cfg(feature = "backend")]
341 pub fn choices(&self) -> &[Choice] {
342 &self.choices
343 }
344
345 /// Sets the current folder.
346 #[must_use]
347 pub fn set_current_folder(mut self, current_folder: impl Into<Option<FilePath>>) -> Self {
348 self.current_folder = current_folder.into();
349 self
350 }
351
352 /// Gets the current folder.
353 #[cfg(feature = "backend")]
354 pub fn current_folder(&self) -> Option<&FilePath> {
355 self.current_folder.as_ref()
356 }
357 }
358
359 /// Options for saving a file.
360 #[derive(Serialize, Deserialize, Type, Debug, Default)]
361 #[zvariant(signature = "dict")]
362 pub struct SaveFileOptions {
363 #[serde(with = "as_value", skip_deserializing)]
364 handle_token: HandleToken,
365 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
366 accept_label: Option<String>,
367 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
368 modal: Option<bool>,
369 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
370 current_name: Option<String>,
371 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
372 current_folder: Option<FilePath>,
373 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
374 current_file: Option<FilePath>,
375 #[serde(default, with = "as_value", skip_serializing_if = "Vec::is_empty")]
376 filters: Vec<FileFilter>,
377 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
378 current_filter: Option<FileFilter>,
379 #[serde(default, with = "as_value", skip_serializing_if = "Vec::is_empty")]
380 choices: Vec<Choice>,
381 }
382
383 impl SaveFileOptions {
384 /// Sets the accept label.
385 #[must_use]
386 pub fn set_accept_label<'a>(mut self, accept_label: impl Into<Option<&'a str>>) -> Self {
387 self.accept_label = accept_label.into().map(ToOwned::to_owned);
388 self
389 }
390
391 /// Gets the accept label.
392 #[cfg(feature = "backend")]
393 pub fn accept_label(&self) -> Option<&str> {
394 self.accept_label.as_deref()
395 }
396
397 /// Sets whether the dialog should be modal.
398 #[must_use]
399 pub fn set_modal(mut self, modal: impl Into<Option<bool>>) -> Self {
400 self.modal = modal.into();
401 self
402 }
403
404 /// Gets whether the dialog should be modal.
405 #[cfg(feature = "backend")]
406 pub fn modal(&self) -> Option<bool> {
407 self.modal
408 }
409
410 /// Sets the current name.
411 #[must_use]
412 pub fn set_current_name<'a>(mut self, current_name: impl Into<Option<&'a str>>) -> Self {
413 self.current_name = current_name.into().map(ToOwned::to_owned);
414 self
415 }
416
417 /// Gets the current name.
418 #[cfg(feature = "backend")]
419 pub fn current_name(&self) -> Option<&str> {
420 self.current_name.as_deref()
421 }
422
423 /// Sets the current folder.
424 #[must_use]
425 pub fn set_current_folder(mut self, current_folder: impl Into<Option<FilePath>>) -> Self {
426 self.current_folder = current_folder.into();
427 self
428 }
429
430 /// Gets the current folder.
431 #[cfg(feature = "backend")]
432 pub fn current_folder(&self) -> Option<&FilePath> {
433 self.current_folder.as_ref()
434 }
435
436 /// Sets the current file.
437 #[must_use]
438 pub fn set_current_file(mut self, current_file: impl Into<Option<FilePath>>) -> Self {
439 self.current_file = current_file.into();
440 self
441 }
442
443 /// Gets the current file.
444 #[cfg(feature = "backend")]
445 pub fn current_file(&self) -> Option<&FilePath> {
446 self.current_file.as_ref()
447 }
448
449 /// Sets the file filters.
450 #[must_use]
451 pub fn set_filters(mut self, filters: impl IntoIterator<Item = FileFilter>) -> Self {
452 self.filters = filters.into_iter().collect();
453 self
454 }
455
456 /// Gets the file filters.
457 #[cfg(feature = "backend")]
458 pub fn filters(&self) -> &[FileFilter] {
459 &self.filters
460 }
461
462 /// Sets the current filter.
463 #[must_use]
464 pub fn set_current_filter(mut self, current_filter: impl Into<Option<FileFilter>>) -> Self {
465 self.current_filter = current_filter.into();
466 self
467 }
468
469 /// Gets the current filter.
470 #[cfg(feature = "backend")]
471 pub fn current_filter(&self) -> Option<&FileFilter> {
472 self.current_filter.as_ref()
473 }
474
475 /// Sets the choices.
476 #[must_use]
477 pub fn set_choices(mut self, choices: impl IntoIterator<Item = Choice>) -> Self {
478 self.choices = choices.into_iter().collect();
479 self
480 }
481
482 /// Gets the choices.
483 #[cfg(feature = "backend")]
484 pub fn choices(&self) -> &[Choice] {
485 &self.choices
486 }
487 }
488
489 /// Options for saving multiple files.
490 #[derive(Serialize, Deserialize, Type, Debug, Default)]
491 #[zvariant(signature = "dict")]
492 pub struct SaveFilesOptions {
493 #[serde(with = "as_value", skip_deserializing)]
494 handle_token: HandleToken,
495 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
496 accept_label: Option<String>,
497 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
498 modal: Option<bool>,
499 #[serde(default, with = "as_value", skip_serializing_if = "Vec::is_empty")]
500 choices: Vec<Choice>,
501 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
502 current_folder: Option<FilePath>,
503 #[serde(default, with = "as_value", skip_serializing_if = "Vec::is_empty")]
504 files: Vec<FilePath>,
505 }
506
507 impl SaveFilesOptions {
508 /// Sets the accept label.
509 #[must_use]
510 pub fn set_accept_label<'a>(mut self, accept_label: impl Into<Option<&'a str>>) -> Self {
511 self.accept_label = accept_label.into().map(ToOwned::to_owned);
512 self
513 }
514
515 /// Gets the accept label.
516 #[cfg(feature = "backend")]
517 pub fn accept_label(&self) -> Option<&str> {
518 self.accept_label.as_deref()
519 }
520
521 /// Sets whether the dialog should be modal.
522 #[must_use]
523 pub fn set_modal(mut self, modal: impl Into<Option<bool>>) -> Self {
524 self.modal = modal.into();
525 self
526 }
527
528 /// Gets whether the dialog should be modal.
529 #[cfg(feature = "backend")]
530 pub fn modal(&self) -> Option<bool> {
531 self.modal
532 }
533
534 /// Sets the choices.
535 #[must_use]
536 pub fn set_choices(mut self, choices: impl IntoIterator<Item = Choice>) -> Self {
537 self.choices = choices.into_iter().collect();
538 self
539 }
540
541 /// Gets the choices.
542 #[cfg(feature = "backend")]
543 pub fn choices(&self) -> &[Choice] {
544 &self.choices
545 }
546
547 /// Sets the current folder.
548 #[must_use]
549 pub fn set_current_folder(mut self, current_folder: impl Into<Option<FilePath>>) -> Self {
550 self.current_folder = current_folder.into();
551 self
552 }
553
554 /// Gets the current folder.
555 #[cfg(feature = "backend")]
556 pub fn current_folder(&self) -> Option<&FilePath> {
557 self.current_folder.as_ref()
558 }
559
560 /// Sets the files.
561 #[must_use]
562 pub fn set_files(mut self, files: impl IntoIterator<Item = FilePath>) -> Self {
563 self.files = files.into_iter().collect();
564 self
565 }
566
567 /// Gets the files.
568 #[cfg(feature = "backend")]
569 pub fn files(&self) -> &[FilePath] {
570 &self.files
571 }
572 }
573
574 #[derive(Serialize, Deserialize, Type, Debug, Default)]
575 /// A response of [`OpenFileRequest`], [`SaveFileRequest`] or
576 /// [`SaveFilesRequest`].
577 #[zvariant(signature = "dict")]
578 pub struct SelectedFiles {
579 #[serde(default, with = "as_value", skip_serializing_if = "Vec::is_empty")]
580 uris: Vec<Uri>,
581 #[serde(default, with = "as_value", skip_serializing_if = "Vec::is_empty")]
582 choices: Vec<(String, String)>,
583 // Backend-only fields
584 /// Not relevant for SaveFiles
585 #[serde(
586 default,
587 with = "optional",
588 skip_serializing_if = "Option::is_none",
589 skip_deserializing
590 )]
591 current_filter: Option<FileFilter>,
592 /// Only relevant for OpenFile
593 #[serde(
594 default,
595 with = "optional",
596 skip_serializing_if = "Option::is_none",
597 skip_deserializing
598 )]
599 writable: Option<bool>,
600 }
601
602 impl SelectedFiles {
603 /// Start an open file request.
604 pub fn open_file() -> OpenFileRequest {
605 OpenFileRequest::default()
606 }
607
608 /// Start a save file request.
609 pub fn save_file() -> SaveFileRequest {
610 SaveFileRequest::default()
611 }
612
613 /// Start a save files request.
614 pub fn save_files() -> SaveFilesRequest {
615 SaveFilesRequest::default()
616 }
617
618 /// The selected files uris.
619 pub fn uris(&self) -> &[Uri] {
620 self.uris.as_slice()
621 }
622
623 /// The selected value of each choice as a tuple of (key, value)
624 pub fn choices(&self) -> &[(String, String)] {
625 &self.choices
626 }
627
628 /// Adds a URI to the selected files.
629 #[cfg(feature = "backend")]
630 pub fn uri(mut self, value: Uri) -> Self {
631 self.uris.push(value);
632 self
633 }
634
635 /// Adds a choice to the selected files.
636 #[cfg(feature = "backend")]
637 pub fn choice(mut self, choice_key: &str, choice_value: &str) -> Self {
638 self.choices
639 .push((choice_key.to_owned(), choice_value.to_owned()));
640 self
641 }
642
643 /// Sets the current filter.
644 #[cfg(feature = "backend")]
645 pub fn current_filter(mut self, value: impl Into<Option<FileFilter>>) -> Self {
646 self.current_filter = value.into();
647 self
648 }
649
650 /// Sets whether the file is writable.
651 #[cfg(feature = "backend")]
652 pub fn writable(mut self, value: impl Into<Option<bool>>) -> Self {
653 self.writable = value.into();
654 self
655 }
656 }
657
658 /// Wrapper of the DBus interface: [`org.freedesktop.portal.FileChooser`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.FileChooser.html).
659 #[doc(alias = "org.freedesktop.portal.FileChooser")]
660 pub struct FileChooserProxy(Proxy<'static>);
661
662 impl FileChooserProxy {
663 /// Create a new instance of [`FileChooserProxy`].
664 pub async fn new() -> Result<Self, Error> {
665 let proxy = Proxy::new_desktop("org.freedesktop.portal.FileChooser").await?;
666 Ok(Self(proxy))
667 }
668
669 /// Create a new instance of [`FileChooserProxy`] with a specific
670 /// connection.
671 pub async fn with_connection(connection: zbus::Connection) -> Result<Self, Error> {
672 let proxy =
673 Proxy::new_desktop_with_connection(connection, "org.freedesktop.portal.FileChooser")
674 .await?;
675 Ok(Self(proxy))
676 }
677
678 /// Returns the portal interface version.
679 pub fn version(&self) -> u32 {
680 self.0.version()
681 }
682
683 /// Asks to open one or more files.
684 #[doc(alias = "OpenFile")]
685 pub async fn open_file(
686 &self,
687 identifier: Option<&WindowIdentifier>,
688 title: &str,
689 options: OpenFileOptions,
690 ) -> Result<Request<SelectedFiles>, Error> {
691 let identifier = Optional::from(identifier);
692 self.0
693 .request(
694 &options.handle_token,
695 "OpenFile",
696 &(identifier, title, &options),
697 )
698 .await
699 }
700
701 /// Asks for a location to save a file.
702 #[doc(alias = "SaveFile")]
703 pub async fn save_file(
704 &self,
705 identifier: Option<&WindowIdentifier>,
706 title: &str,
707 options: SaveFileOptions,
708 ) -> Result<Request<SelectedFiles>, Error> {
709 let identifier = Optional::from(identifier);
710 self.0
711 .request(
712 &options.handle_token,
713 "SaveFile",
714 &(identifier, title, &options),
715 )
716 .await
717 }
718
719 /// Asks for a location to save one or more files.
720 #[doc(alias = "SaveFiles")]
721 pub async fn save_files(
722 &self,
723 identifier: Option<&WindowIdentifier>,
724 title: &str,
725 options: SaveFilesOptions,
726 ) -> Result<Request<SelectedFiles>, Error> {
727 let identifier = Optional::from(identifier);
728 self.0
729 .request(
730 &options.handle_token,
731 "SaveFiles",
732 &(identifier, title, &options),
733 )
734 .await
735 }
736 }
737
738 impl std::ops::Deref for FileChooserProxy {
739 type Target = zbus::Proxy<'static>;
740
741 fn deref(&self) -> &Self::Target {
742 &self.0
743 }
744 }
745
746 #[derive(Debug, Default)]
747 #[doc(alias = "xdp_portal_open_file")]
748 /// A [builder-pattern] type to open a file.
749 ///
750 /// [builder-pattern]: https://doc.rust-lang.org/1.0.0/style/ownership/builders.html
751 pub struct OpenFileRequest {
752 identifier: Option<WindowIdentifier>,
753 title: String,
754 options: OpenFileOptions,
755 connection: Option<zbus::Connection>,
756 }
757
758 impl OpenFileRequest {
759 #[must_use]
760 /// Sets a window identifier.
761 pub fn identifier(mut self, identifier: impl Into<Option<WindowIdentifier>>) -> Self {
762 self.identifier = identifier.into();
763 self
764 }
765
766 /// Sets a title for the file chooser dialog.
767 #[must_use]
768 pub fn title<'a>(mut self, title: impl Into<Option<&'a str>>) -> Self {
769 self.title = title.into().map(ToOwned::to_owned).unwrap_or_default();
770 self
771 }
772
773 /// Sets a user-visible string to the "accept" button.
774 #[must_use]
775 pub fn accept_label<'a>(mut self, accept_label: impl Into<Option<&'a str>>) -> Self {
776 self.options.accept_label = accept_label.into().map(ToOwned::to_owned);
777 self
778 }
779
780 /// Sets whether the dialog should be a modal.
781 #[must_use]
782 pub fn modal(mut self, modal: impl Into<Option<bool>>) -> Self {
783 self.options.modal = modal.into();
784 self
785 }
786
787 /// Sets whether to allow multiple files selection.
788 #[must_use]
789 pub fn multiple(mut self, multiple: impl Into<Option<bool>>) -> Self {
790 self.options.multiple = multiple.into();
791 self
792 }
793
794 /// Sets whether to select directories or not.
795 #[must_use]
796 pub fn directory(mut self, directory: impl Into<Option<bool>>) -> Self {
797 self.options.directory = directory.into();
798 self
799 }
800
801 /// Adds a files filter.
802 #[must_use]
803 pub fn filter(mut self, filter: FileFilter) -> Self {
804 self.options.filters.push(filter);
805 self
806 }
807
808 #[must_use]
809 /// Adds a list of files filters.
810 pub fn filters(mut self, filters: impl IntoIterator<Item = FileFilter>) -> Self {
811 self.options.filters = filters.into_iter().collect();
812 self
813 }
814
815 /// Specifies the default filter.
816 #[must_use]
817 pub fn current_filter(mut self, current_filter: impl Into<Option<FileFilter>>) -> Self {
818 self.options.current_filter = current_filter.into();
819 self
820 }
821
822 /// Adds a choice.
823 #[must_use]
824 pub fn choice(mut self, choice: Choice) -> Self {
825 self.options.choices.push(choice);
826 self
827 }
828
829 #[must_use]
830 /// Adds a list of choices.
831 pub fn choices(mut self, choices: impl IntoIterator<Item = Choice>) -> Self {
832 self.options.choices = choices.into_iter().collect();
833 self
834 }
835
836 /// Specifies the current folder path.
837 pub fn current_folder<P: AsRef<Path>>(
838 mut self,
839 current_folder: impl Into<Option<P>>,
840 ) -> Result<Self, crate::Error> {
841 self.options.current_folder = current_folder
842 .into()
843 .map(|c| FilePath::new(c))
844 .transpose()?;
845 Ok(self)
846 }
847
848 #[must_use]
849 /// Sets a connection to use other than the internal one.
850 pub fn connection(mut self, connection: Option<zbus::Connection>) -> Self {
851 self.connection = connection;
852 self
853 }
854
855 /// Send the request.
856 pub async fn send(self) -> Result<Request<SelectedFiles>, Error> {
857 let proxy = if let Some(connection) = self.connection {
858 FileChooserProxy::with_connection(connection).await?
859 } else {
860 FileChooserProxy::new().await?
861 };
862 proxy
863 .open_file(self.identifier.as_ref(), &self.title, self.options)
864 .await
865 }
866 }
867
868 #[derive(Debug, Default)]
869 #[doc(alias = "xdp_portal_save_files")]
870 /// A [builder-pattern] type to save multiple files.
871 ///
872 /// [builder-pattern]: https://doc.rust-lang.org/1.0.0/style/ownership/builders.html
873 pub struct SaveFilesRequest {
874 identifier: Option<WindowIdentifier>,
875 title: String,
876 options: SaveFilesOptions,
877 connection: Option<zbus::Connection>,
878 }
879
880 impl SaveFilesRequest {
881 #[must_use]
882 /// Sets a window identifier.
883 pub fn identifier(mut self, identifier: impl Into<Option<WindowIdentifier>>) -> Self {
884 self.identifier = identifier.into();
885 self
886 }
887
888 /// Sets a title for the file chooser dialog.
889 #[must_use]
890 pub fn title<'a>(mut self, title: impl Into<Option<&'a str>>) -> Self {
891 self.title = title.into().map(ToOwned::to_owned).unwrap_or_default();
892 self
893 }
894
895 /// Sets a user-visible string to the "accept" button.
896 #[must_use]
897 pub fn accept_label<'a>(mut self, accept_label: impl Into<Option<&'a str>>) -> Self {
898 self.options.accept_label = accept_label.into().map(ToOwned::to_owned);
899 self
900 }
901
902 /// Sets whether the dialog should be a modal.
903 #[must_use]
904 pub fn modal(mut self, modal: impl Into<Option<bool>>) -> Self {
905 self.options.modal = modal.into();
906 self
907 }
908
909 /// Adds a choice.
910 #[must_use]
911 pub fn choice(mut self, choice: Choice) -> Self {
912 self.options.choices.push(choice);
913 self
914 }
915
916 #[must_use]
917 /// Adds a list of choices.
918 pub fn choices(mut self, choices: impl IntoIterator<Item = Choice>) -> Self {
919 self.options.choices = choices.into_iter().collect();
920 self
921 }
922
923 /// Specifies the current folder path.
924 pub fn current_folder<P: AsRef<Path>>(
925 mut self,
926 current_folder: impl Into<Option<P>>,
927 ) -> Result<Self, crate::Error> {
928 self.options.current_folder = current_folder
929 .into()
930 .map(|c| FilePath::new(c))
931 .transpose()?;
932 Ok(self)
933 }
934
935 /// Sets a list of files to save.
936 pub fn files<P: IntoIterator<Item = impl AsRef<Path>>>(
937 mut self,
938 files: impl Into<Option<P>>,
939 ) -> Result<Self, crate::Error> {
940 if let Some(f) = files.into() {
941 self.options.files = f
942 .into_iter()
943 .map(|s| FilePath::new(s))
944 .collect::<Result<Vec<_>, _>>()?;
945 }
946 Ok(self)
947 }
948
949 #[must_use]
950 /// Sets a connection to use other than the internal one.
951 pub fn connection(mut self, connection: Option<zbus::Connection>) -> Self {
952 self.connection = connection;
953 self
954 }
955
956 /// Send the request.
957 pub async fn send(self) -> Result<Request<SelectedFiles>, Error> {
958 let proxy = if let Some(connection) = self.connection {
959 FileChooserProxy::with_connection(connection).await?
960 } else {
961 FileChooserProxy::new().await?
962 };
963 proxy
964 .save_files(self.identifier.as_ref(), &self.title, self.options)
965 .await
966 }
967 }
968
969 #[derive(Debug, Default)]
970 #[doc(alias = "xdp_portal_save_file")]
971 /// A [builder-pattern] type to save a file.
972 ///
973 /// [builder-pattern]: https://doc.rust-lang.org/1.0.0/style/ownership/builders.html
974 pub struct SaveFileRequest {
975 identifier: Option<WindowIdentifier>,
976 title: String,
977 options: SaveFileOptions,
978 connection: Option<zbus::Connection>,
979 }
980
981 impl SaveFileRequest {
982 #[must_use]
983 /// Sets a window identifier.
984 pub fn identifier(mut self, identifier: impl Into<Option<WindowIdentifier>>) -> Self {
985 self.identifier = identifier.into();
986 self
987 }
988
989 /// Sets a title for the file chooser dialog.
990 #[must_use]
991 pub fn title<'a>(mut self, title: impl Into<Option<&'a str>>) -> Self {
992 self.title = title.into().map(ToOwned::to_owned).unwrap_or_default();
993 self
994 }
995
996 /// Sets a user-visible string to the "accept" button.
997 #[must_use]
998 pub fn accept_label<'a>(mut self, accept_label: impl Into<Option<&'a str>>) -> Self {
999 self.options.accept_label = accept_label.into().map(ToOwned::to_owned);
1000 self
1001 }
1002
1003 /// Sets whether the dialog should be a modal.
1004 #[must_use]
1005 pub fn modal(mut self, modal: impl Into<Option<bool>>) -> Self {
1006 self.options.modal = modal.into();
1007 self
1008 }
1009
1010 /// Sets the current file name.
1011 #[must_use]
1012 pub fn current_name<'a>(mut self, current_name: impl Into<Option<&'a str>>) -> Self {
1013 self.options.current_name = current_name.into().map(ToOwned::to_owned);
1014 self
1015 }
1016
1017 /// Sets the current folder.
1018 pub fn current_folder<P: AsRef<Path>>(
1019 mut self,
1020 current_folder: impl Into<Option<P>>,
1021 ) -> Result<Self, crate::Error> {
1022 self.options.current_folder = current_folder
1023 .into()
1024 .map(|c| FilePath::new(c))
1025 .transpose()?;
1026 Ok(self)
1027 }
1028
1029 /// Sets the absolute path of the file.
1030 pub fn current_file<P: AsRef<Path>>(
1031 mut self,
1032 current_file: impl Into<Option<P>>,
1033 ) -> Result<Self, crate::Error> {
1034 self.options.current_file = current_file.into().map(|c| FilePath::new(c)).transpose()?;
1035 Ok(self)
1036 }
1037
1038 /// Adds a files filter.
1039 #[must_use]
1040 pub fn filter(mut self, filter: FileFilter) -> Self {
1041 self.options.filters.push(filter);
1042 self
1043 }
1044
1045 #[must_use]
1046 /// Adds a list of files filters.
1047 pub fn filters(mut self, filters: impl IntoIterator<Item = FileFilter>) -> Self {
1048 self.options.filters = filters.into_iter().collect();
1049 self
1050 }
1051
1052 /// Sets the default filter.
1053 #[must_use]
1054 pub fn current_filter(mut self, current_filter: impl Into<Option<FileFilter>>) -> Self {
1055 self.options.current_filter = current_filter.into();
1056 self
1057 }
1058
1059 /// Adds a choice.
1060 #[must_use]
1061 pub fn choice(mut self, choice: Choice) -> Self {
1062 self.options.choices.push(choice);
1063 self
1064 }
1065
1066 #[must_use]
1067 /// Adds a list of choices.
1068 pub fn choices(mut self, choices: impl IntoIterator<Item = Choice>) -> Self {
1069 self.options.choices = choices.into_iter().collect();
1070 self
1071 }
1072
1073 #[must_use]
1074 /// Sets a connection to use other than the internal one.
1075 pub fn connection(mut self, connection: Option<zbus::Connection>) -> Self {
1076 self.connection = connection;
1077 self
1078 }
1079
1080 /// Send the request.
1081 pub async fn send(self) -> Result<Request<SelectedFiles>, Error> {
1082 let proxy = if let Some(connection) = self.connection {
1083 FileChooserProxy::with_connection(connection).await?
1084 } else {
1085 FileChooserProxy::new().await?
1086 };
1087 proxy
1088 .save_file(self.identifier.as_ref(), &self.title, self.options)
1089 .await
1090 }
1091 }