ashpd 0.2.3

XDG portals wrapper in Rust using zbus
Documentation
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
//! # Examples
//!
//! ## Opening a file
//!
//! ```rust,no_run
//! use ashpd::desktop::file_chooser::{Choice, FileChooserProxy, FileFilter, OpenFileOptions};
//! use ashpd::WindowIdentifier;
//!
//! async fn run() -> ashpd::Result<()> {
//!     let connection = zbus::Connection::session().await?;
//!
//!     let proxy = FileChooserProxy::new(&connection).await?;
//!     let files = proxy
//!         .open_file(
//!             &WindowIdentifier::default(),
//!             "open a file to read",
//!             OpenFileOptions::default()
//!                 .accept_label("read")
//!                 .modal(true)
//!                 .multiple(true)
//!                 .add_choice(
//!                     Choice::new("encoding", "Encoding", "latin15")
//!                         .insert("utf8", "Unicode (UTF-8)")
//!                         .insert("latin15", "Western"),
//!                 )
//!                 // A trick to have a checkbox
//!                 .add_choice(Choice::boolean("re-encode", "Re-encode", false))
//!                 .add_filter(FileFilter::new("SVG Image").mimetype("image/svg+xml")),
//!         )
//!         .await?;
//!
//!     println!("{:#?}", files);
//!
//!     Ok(())
//! }
//! ```
//!
//! ## Ask to save a file
//!
//! ```rust,no_run
//! use ashpd::desktop::file_chooser::{FileChooserProxy, FileFilter, SaveFileOptions};
//! use ashpd::WindowIdentifier;
//!
//! async fn run() -> ashpd::Result<()> {
//!     let connection = zbus::Connection::session().await?;
//!     let proxy = FileChooserProxy::new(&connection).await?;
//!     let files = proxy
//!         .save_file(
//!             &WindowIdentifier::default(),
//!             "open a file to write",
//!             SaveFileOptions::default()
//!                 .accept_label("write")
//!                 .current_name("image.jpg")
//!                 .modal(true)
//!                 .add_filter(FileFilter::new("JPEG Image").glob("*.jpg")),
//!         )
//!         .await?;
//!
//!     println!("{:#?}", files);
//!
//!     Ok(())
//! }
//! ```
//!
//! ## Ask to save multiple files
//!
//! ```rust,no_run
//! use ashpd::desktop::file_chooser::{FileChooserProxy, SaveFilesOptions};
//! use ashpd::WindowIdentifier;
//!
//! async fn run() -> ashpd::Result<()> {
//!     let connection = zbus::Connection::session().await?;
//!
//!     let proxy = FileChooserProxy::new(&connection).await?;
//!     let files = proxy
//!         .save_files(
//!             &WindowIdentifier::default(),
//!             "open files to write",
//!             SaveFilesOptions::default()
//!                 .accept_label("write files")
//!                 .modal(true)
//!                 .current_folder("/home/bilelmoussaoui/Pictures")
//!                 .files(&["test.jpg", "awesome.png"]),
//!         )
//!         .await?;
//!
//!     println!("{:#?}", files);
//!
//!     Ok(())
//! }
//! ```

use serde::{Deserialize, Serialize};
use serde_repr::{Deserialize_repr, Serialize_repr};
use std::os::unix::ffi::OsStrExt;
use std::{ffi::CString, path::Path};
use zbus::zvariant::{DeserializeDict, SerializeDict, Type};

use super::{HandleToken, DESTINATION, PATH};
use crate::{helpers::call_request_method, Error, WindowIdentifier};

#[derive(Serialize, Deserialize, Type, Clone, Debug)]
/// A file filter, to limit the available file choices to a mimetype or a glob
/// pattern.
pub struct FileFilter(String, Vec<(FilterType, String)>);

#[derive(Serialize_repr, Clone, Deserialize_repr, PartialEq, Debug, Type)]
#[repr(u8)]
enum FilterType {
    GlobPattern = 0,
    MimeType = 1,
}

impl FileFilter {
    /// Create a new file filter
    ///
    /// # Arguments
    ///
    /// * `label` - user-visible name of the file filter.
    pub fn new(label: &str) -> Self {
        Self(label.to_string(), vec![])
    }

    /// Adds a mime type to the file filter.
    #[must_use]
    pub fn mimetype(mut self, mimetype: &str) -> Self {
        self.1.push((FilterType::MimeType, mimetype.to_string()));
        self
    }

    /// Adds a glob pattern to the file filter.
    #[must_use]
    pub fn glob(mut self, pattern: &str) -> Self {
        self.1.push((FilterType::GlobPattern, pattern.to_string()));
        self
    }
}

#[derive(Serialize, Deserialize, Type, Clone, Debug)]
/// Presents the user with a choice to select from or as a checkbox.
pub struct Choice(String, String, Vec<(String, String)>, String);

impl Choice {
    /// Creates a checkbox choice.
    ///
    /// # Arguments
    ///
    /// * `id` - A unique identifier of the choice.
    /// * `label` - user-visible name of the choice.
    /// * `state` - the initial state value.
    pub fn boolean(id: &str, label: &str, state: bool) -> Self {
        Self::new(id, label, &state.to_string())
    }

    /// Creates a new choice.
    ///
    /// # Arguments
    ///
    /// * `id` - A unique identifier of the choice.
    /// * `label` - user-visible name of the choice.
    /// * `initial_selection` - the initially selected value.
    pub fn new(id: &str, label: &str, initial_selection: &str) -> Self {
        Self(
            id.to_string(),
            label.to_string(),
            vec![],
            initial_selection.to_string(),
        )
    }

    /// Adds a (key, value) as a choice.
    #[must_use]
    pub fn insert(mut self, key: &str, value: &str) -> Self {
        self.2.push((key.to_string(), value.to_string()));
        self
    }

    /// The choice's unique id
    pub fn id(&self) -> &str {
        &self.0
    }

    /// The user visible label of the choice.
    pub fn label(&self) -> &str {
        &self.1
    }

    /// The initially selected value.
    pub fn initial_selection(&self) -> &str {
        &self.3
    }
}

#[derive(SerializeDict, DeserializeDict, Type, Clone, Debug, Default)]
/// Specified options for a [`FileChooserProxy::open_file`] request.
#[zvariant(signature = "dict")]
pub struct OpenFileOptions {
    /// A string that will be used as the last element of the handle.
    handle_token: HandleToken,
    /// Label for the accept button. Mnemonic underlines are allowed.
    accept_label: Option<String>,
    /// Whether the dialog should be modal.
    modal: Option<bool>,
    /// Whether multiple files can be selected or not.
    multiple: Option<bool>,
    /// Whether to select for folders instead of files.
    directory: Option<bool>,
    /// List of serialized file filters.
    filters: Vec<FileFilter>,
    /// Request that this filter be set by default at dialog creation.
    current_filter: Option<FileFilter>,
    /// List of serialized combo boxes to add to the file chooser
    choices: Vec<Choice>,
}

impl OpenFileOptions {
    /// Sets a user-visible string to the "accept" button.
    #[must_use]
    pub fn accept_label(mut self, accept_label: &str) -> Self {
        self.accept_label = Some(accept_label.to_string());
        self
    }

    /// Sets whether the dialog should be a modal.
    #[must_use]
    pub fn modal(mut self, modal: bool) -> Self {
        self.modal = Some(modal);
        self
    }

    /// Sets whether to allow multiple files selection.
    #[must_use]
    pub fn multiple(mut self, multiple: bool) -> Self {
        self.multiple = Some(multiple);
        self
    }

    /// Sets whether to select directories or not.
    #[must_use]
    pub fn directory(mut self, directory: bool) -> Self {
        self.directory = Some(directory);
        self
    }

    /// Adds a files filter.
    #[must_use]
    pub fn add_filter(mut self, filter: FileFilter) -> Self {
        self.filters.push(filter);
        self
    }

    /// Specifies the default filter.
    #[must_use]
    pub fn current_filter(mut self, current_filter: FileFilter) -> Self {
        self.current_filter = Some(current_filter);
        self
    }

    /// Adds a choice.
    #[must_use]
    pub fn add_choice(mut self, choice: Choice) -> Self {
        self.choices.push(choice);
        self
    }
}

#[derive(SerializeDict, DeserializeDict, Type, Debug, Default)]
/// Specified options for a [`FileChooserProxy::save_file`] request.
#[zvariant(signature = "dict")]
pub struct SaveFileOptions {
    /// A string that will be used as the last element of the handle.
    handle_token: HandleToken,
    /// Label for the accept button. Mnemonic underlines are allowed.
    accept_label: Option<String>,
    /// Whether the dialog should be modal.
    modal: Option<bool>,
    /// Suggested filename.
    current_name: Option<String>,
    /// Suggested folder to save the file in.
    current_folder: Option<Vec<u8>>,
    /// The current file (when saving an existing file).
    current_file: Option<Vec<u8>>,
    /// List of serialized file filters.
    filters: Vec<FileFilter>,
    /// Request that this filter be set by default at dialog creation.
    current_filter: Option<FileFilter>,
    /// List of serialized combo boxes to add to the file chooser
    choices: Vec<Choice>,
}

impl SaveFileOptions {
    /// Sets a user-visible string to the "accept" button.
    #[must_use]
    pub fn accept_label(mut self, accept_label: &str) -> Self {
        self.accept_label = Some(accept_label.to_string());
        self
    }

    /// Sets the current file name.
    #[must_use]
    pub fn current_name(mut self, current_name: &str) -> Self {
        self.current_name = Some(current_name.to_string());
        self
    }

    /// Sets the current folder.
    #[must_use]
    pub fn current_folder(mut self, current_folder: impl AsRef<Path> + Type + Serialize) -> Self {
        let cstr = CString::new(current_folder.as_ref().as_os_str().as_bytes())
            .expect("`current_folder` should not be null terminated");
        self.current_folder = Some(cstr.into_bytes_with_nul());
        self
    }

    /// Sets the absolute path of the file.
    #[must_use]
    pub fn current_file(mut self, current_file: impl AsRef<Path> + Type + Serialize) -> Self {
        let cstr = CString::new(current_file.as_ref().as_os_str().as_bytes())
            .expect("`current_file` should not be null terminated");
        self.current_file = Some(cstr.into_bytes_with_nul());
        self
    }

    /// Sets whether the dialog should be a modal.
    #[must_use]
    pub fn modal(mut self, modal: bool) -> Self {
        self.modal = Some(modal);
        self
    }

    /// Adds a files filter.
    #[must_use]
    pub fn add_filter(mut self, filter: FileFilter) -> Self {
        self.filters.push(filter);
        self
    }

    /// Sets the default filter.
    #[must_use]
    pub fn current_filter(mut self, current_filter: FileFilter) -> Self {
        self.current_filter = Some(current_filter);
        self
    }

    /// Adds a choice.
    #[must_use]
    pub fn add_choice(mut self, choice: Choice) -> Self {
        self.choices.push(choice);
        self
    }
}

#[derive(SerializeDict, DeserializeDict, Type, Debug, Default)]
/// Specified options for a [`FileChooserProxy::save_files`] request.
#[zvariant(signature = "dict")]
pub struct SaveFilesOptions {
    /// A string that will be used as the last element of the handle.
    handle_token: HandleToken,
    /// Label for the accept button. Mnemonic underlines are allowed.
    accept_label: Option<String>,
    /// Whether the dialog should be modal.
    modal: Option<bool>,
    /// List of serialized combo boxes to add to the file chooser
    choices: Vec<Choice>,
    /// Suggested folder to save the file in.
    current_folder: Option<Vec<u8>>,
    /// An array of file names to be saved.
    files: Option<Vec<Vec<u8>>>,
}

impl SaveFilesOptions {
    /// Sets a user-visible string to the "accept" button.
    #[must_use]
    pub fn accept_label(mut self, accept_label: &str) -> Self {
        self.accept_label = Some(accept_label.to_string());
        self
    }

    /// Sets whether the dialog should be a modal.
    #[must_use]
    pub fn modal(mut self, modal: bool) -> Self {
        self.modal = Some(modal);
        self
    }

    /// Adds a choice.
    #[must_use]
    pub fn add_choice(mut self, choice: Choice) -> Self {
        self.choices.push(choice);
        self
    }

    /// Specifies the current folder path.
    #[must_use]
    pub fn current_folder(mut self, current_folder: impl AsRef<Path> + Type + Serialize) -> Self {
        let cstr = CString::new(current_folder.as_ref().as_os_str().as_bytes())
            .expect("`current_folder` should not be null terminated");
        self.current_folder = Some(cstr.into_bytes_with_nul());
        self
    }

    /// Sets a list of files to save.
    #[must_use]
    pub fn files(mut self, files: &[impl AsRef<Path> + Type + Serialize]) -> Self {
        self.files = Some(
            files
                .iter()
                .map(|s| {
                    let cstr = CString::new(s.as_ref().as_os_str().as_bytes())
                        .expect("`files` should not be null terminated");
                    cstr.into_bytes_with_nul()
                })
                .collect(),
        );
        self
    }
}

#[derive(Debug, Type, SerializeDict, Clone, DeserializeDict)]
/// A response to a
/// [`FileChooserProxy::open_file`]/[`FileChooserProxy::save_file`]/
/// [`FileChooserProxy::save_files`] request.
#[zvariant(signature = "dict")]
pub struct SelectedFiles {
    uris: Vec<String>,
    choices: Option<Vec<(String, String)>>,
}

impl SelectedFiles {
    /// The selected files uris.
    pub fn uris(&self) -> &[String] {
        self.uris.as_slice()
    }

    /// The selected value of each choice as a tuple of (key, value)
    pub fn choices(&self) -> &[(String, String)] {
        self.choices.as_deref().unwrap_or_default()
    }
}

/// The interface lets sandboxed applications ask the user for access to files
/// outside the sandbox. The portal backend will present the user with a file
/// chooser dialog.
///
/// Wrapper of the DBus interface: [`org.freedesktop.portal.FileChooser`](https://flatpak.github.io/xdg-desktop-portal/index.html#gdbus-org.freedesktop.portal.FileChooser).
#[derive(Debug)]
#[doc(alias = "org.freedesktop.portal.FileChooser")]
pub struct FileChooserProxy<'a>(zbus::Proxy<'a>);

impl<'a> FileChooserProxy<'a> {
    /// Create a new instance of [`FileChooserProxy`].
    pub async fn new(connection: &zbus::Connection) -> Result<FileChooserProxy<'a>, Error> {
        let proxy = zbus::ProxyBuilder::new_bare(connection)
            .interface("org.freedesktop.portal.FileChooser")?
            .path(PATH)?
            .destination(DESTINATION)?
            .build()
            .await?;
        Ok(Self(proxy))
    }

    /// Get a reference to the underlying Proxy.
    pub fn inner(&self) -> &zbus::Proxy<'_> {
        &self.0
    }

    /// Asks to open one or more files.
    ///
    /// # Arguments
    ///
    /// * `identifier` - Identifier for the application window.
    /// * `title` - Title for the file chooser dialog.
    /// * `options` - [`OpenFileOptions`].
    ///
    /// # Specifications
    ///
    /// See also [`OpenFile`](https://flatpak.github.io/xdg-desktop-portal/index.html#gdbus-method-org-freedesktop-portal-FileChooser.OpenFile).
    #[doc(alias = "OpenFile")]
    #[doc(alias = "xdp_portal_open_file")]
    pub async fn open_file(
        &self,
        identifier: &WindowIdentifier,
        title: &str,
        options: OpenFileOptions,
    ) -> Result<SelectedFiles, Error> {
        call_request_method(
            self.inner(),
            &options.handle_token,
            "OpenFile",
            &(&identifier, title, &options),
        )
        .await
    }

    /// Asks for a location to save a file.
    ///
    /// # Arguments
    ///
    /// * `identifier` - Identifier for the application window.
    /// * `title` - Title for the file chooser dialog.
    /// * `options` - [`SaveFileOptions`].
    ///
    /// # Specifications
    ///
    /// See also [`SaveFile`](https://flatpak.github.io/xdg-desktop-portal/index.html#gdbus-method-org-freedesktop-portal-FileChooser.SaveFile).
    #[doc(alias = "SaveFile")]
    #[doc(alias = "xdp_portal_save_file")]
    pub async fn save_file(
        &self,
        identifier: &WindowIdentifier,
        title: &str,
        options: SaveFileOptions,
    ) -> Result<SelectedFiles, Error> {
        call_request_method(
            self.inner(),
            &options.handle_token,
            "SaveFile",
            &(&identifier, title, &options),
        )
        .await
    }

    /// Asks for a folder as a location to save one or more files.
    /// The names of the files will be used as-is and appended to the
    /// selected folder's path in the list of returned files.
    /// If the selected folder already contains a file with one of the given
    /// names, the portal may prompt or take some other action to
    /// construct a unique file name and return that instead.
    ///
    /// # Arguments
    ///
    /// * `identifier` - Identifier for the application window.
    /// * `title` - Title for the file chooser dialog.
    /// * `options` - [`SaveFilesOptions`].
    ///
    /// # Specifications
    ///
    /// See also [`SaveFiles`](https://flatpak.github.io/xdg-desktop-portal/index.html#gdbus-method-org-freedesktop-portal-FileChooser.SaveFiles).
    #[doc(alias = "SaveFiles")]
    #[doc(alias = "xdp_portal_save_files")]
    pub async fn save_files(
        &self,
        identifier: &WindowIdentifier,
        title: &str,
        options: SaveFilesOptions,
    ) -> Result<SelectedFiles, Error> {
        call_request_method(
            self.inner(),
            &options.handle_token,
            "SaveFiles",
            &(&identifier, title, &options),
        )
        .await
    }
}