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
//! Move a file to the trash.
//!
//! # Examples
//!
//!
//! ```rust,no_run
//! use std::{fs::File, os::fd::AsFd};
//!
//! use ashpd::desktop::trash;
//!
//! async fn run() -> ashpd::Result<()> {
//!     let file = File::open("/home/bilelmoussaoui/adwaita-night.jpg").unwrap();
//!     trash::trash_file(&file.as_fd()).await?;
//!     Ok(())
//! }
//! ```
//!
//! Or by using the Proxy directly
//!
//! ```rust,no_run
//! use std::{fs::File, os::fd::AsFd};
//!
//! use ashpd::desktop::trash::TrashProxy;
//!
//! async fn run() -> ashpd::Result<()> {
//!     let file = File::open("/home/bilelmoussaoui/Downloads/adwaita-night.jpg").unwrap();
//!     let proxy = TrashProxy::new().await?;
//!     proxy.trash_file(&file.as_fd()).await?;
//!     Ok(())
//! }
//! ```

use std::os::fd::BorrowedFd;

use serde_repr::{Deserialize_repr, Serialize_repr};
use zbus::zvariant::{Fd, Type};

use crate::{error::PortalError, proxy::Proxy, Error};

#[derive(Debug, Deserialize_repr, Serialize_repr, PartialEq, Type)]
#[repr(u32)]
enum TrashStatus {
    Failed = 0,
    Succeeded = 1,
}

/// The interface lets sandboxed applications send files to the trashcan.
///
/// Wrapper of the DBus interface: [`org.freedesktop.portal.Trash`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Trash.html).
#[derive(Debug)]
#[doc(alias = "org.freedesktop.portal.Trash")]
pub struct TrashProxy<'a>(Proxy<'a>);

impl<'a> TrashProxy<'a> {
    /// Create a new instance of [`TrashProxy`].
    pub async fn new() -> Result<TrashProxy<'a>, Error> {
        let proxy = Proxy::new_desktop("org.freedesktop.portal.Trash").await?;
        Ok(Self(proxy))
    }

    /// Sends a file to the trashcan.
    /// Applications are allowed to trash a file if they can open it in
    /// read/write mode.
    ///
    /// # Arguments
    ///
    /// * `fd` - The file descriptor.
    ///
    /// # Specifications
    ///
    /// See also [`TrashFile`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Trash.html#org-freedesktop-portal-trash-trashfile).
    #[doc(alias = "TrashFile")]
    #[doc(alias = "xdp_portal_trash_file")]
    pub async fn trash_file(&self, fd: &BorrowedFd<'_>) -> Result<(), Error> {
        let status = self.0.call("TrashFile", &(Fd::from(fd))).await?;
        match status {
            TrashStatus::Failed => Err(Error::Portal(PortalError::Failed(
                "Failed to trash file".to_string(),
            ))),
            TrashStatus::Succeeded => Ok(()),
        }
    }
}

impl<'a> std::ops::Deref for TrashProxy<'a> {
    type Target = zbus::Proxy<'a>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

#[doc(alias = "xdp_portal_trash_file")]
/// A handy wrapper around [`TrashProxy::trash_file`].
pub async fn trash_file(fd: &BorrowedFd<'_>) -> Result<(), Error> {
    let proxy = TrashProxy::new().await?;
    proxy.trash_file(fd).await
}

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

    #[test]
    fn status_serde() {
        #[derive(serde::Serialize, serde::Deserialize)]
        struct Test {
            status: TrashStatus,
        }

        let status = Test {
            status: TrashStatus::Failed,
        };

        let x = serde_json::to_string(&status).unwrap();
        let y: Test = serde_json::from_str(&x).unwrap();
        assert_eq!(y.status, TrashStatus::Failed);
    }
}