|
| 1 | +using System.IO; |
| 2 | +using System.Threading.Tasks; |
| 3 | +using JetBrains.Annotations; |
| 4 | +using Tmds.DBus.SourceGenerator; |
| 5 | + |
| 6 | +namespace LinuxDesktopUtils.XDGDesktopPortal; |
| 7 | + |
| 8 | +/// <summary> |
| 9 | +/// Portal for trashing files. |
| 10 | +/// |
| 11 | +/// This simple interface lets sandboxed applications send files to the trashcan. |
| 12 | +/// </summary> |
| 13 | +/// <remarks> |
| 14 | +/// https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Trash.html |
| 15 | +/// </remarks> |
| 16 | +[PublicAPI] |
| 17 | +public class TrashPortal : IPortal |
| 18 | +{ |
| 19 | + private readonly DesktopPortalConnectionManager _connectionManager; |
| 20 | + private readonly OrgFreedesktopPortalTrashProxy _instance; |
| 21 | + private readonly uint _version; |
| 22 | + |
| 23 | + /// <inheritdoc/> |
| 24 | + uint IPortal.Version => _version; |
| 25 | + |
| 26 | + private TrashPortal( |
| 27 | + DesktopPortalConnectionManager connectionManager, |
| 28 | + OrgFreedesktopPortalTrashProxy instance, |
| 29 | + uint version) |
| 30 | + { |
| 31 | + _connectionManager = connectionManager; |
| 32 | + _instance = instance; |
| 33 | + _version = version; |
| 34 | + } |
| 35 | + |
| 36 | + internal static async ValueTask<TrashPortal> CreateAsync(DesktopPortalConnectionManager connectionManager) |
| 37 | + { |
| 38 | + var instance = new OrgFreedesktopPortalTrashProxy(connectionManager.GetConnection(), destination: DBusHelper.BusName, path: DBusHelper.ObjectPath); |
| 39 | + var version = await instance.GetVersionPropertyAsync().ConfigureAwait(false); |
| 40 | + |
| 41 | + return new TrashPortal(connectionManager, instance, version); |
| 42 | + } |
| 43 | + |
| 44 | + /// <summary> |
| 45 | + /// Sends a file to the trashcan. Applications are allowed to trash a file if they can open it in r/w mode. |
| 46 | + /// </summary> |
| 47 | + /// <param name="file">Absolute path to the file.</param> |
| 48 | + /// <returns>Whether the file was trashed successfully</returns> |
| 49 | + public async Task<bool> TrashFileAsync(FilePath file) |
| 50 | + { |
| 51 | + using var safeFileHandle = File.OpenHandle(file.Value, FileMode.Open, FileAccess.ReadWrite); |
| 52 | + |
| 53 | + var result = await _instance.TrashFileAsync( |
| 54 | + fd: safeFileHandle |
| 55 | + ).ConfigureAwait(false); |
| 56 | + |
| 57 | + return result == 1; |
| 58 | + } |
| 59 | +} |
0 commit comments