Skip to content

RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process

Complete Files Trash management: restore, permanent delete, in-Trash workflow

oxydizerc2d11bb1755c
diff --git a/po/de.po b/po/de.po
index acbdbe1..2500db3 100644
--- a/po/de.po
+++ b/po/de.po
@@ -1566,6 +1566,14 @@ msgstr "CUPS-Start konnte nicht angefordert werden."
msgid "Could not request authentication. Check that polkit is running."
msgstr "Authentifizierung konnte nicht angefordert werden. Prüfe, ob polkit läuft."
+#: src/files/app_trash.zig
+msgid "Could not restore the items in Trash"
+msgstr "Die Objekte im Papierkorb konnten nicht wiederhergestellt werden"
+
+#: src/files/app_trash.zig
+msgid "Could not restore the selected items"
+msgstr "Die ausgewählten Objekte konnten nicht wiederhergestellt werden"
+
#: src/images/app_input.zig
msgid "Could not rotate: not enough memory."
msgstr "Drehen fehlgeschlagen: nicht genug Speicher."
@@ -1868,6 +1876,10 @@ msgstr "Standard-Terminal"
msgid "Deferred"
msgstr "Zurückgestellt"
+#: src/files/app_model.zig
+msgid "Delete Permanently"
+msgstr "Endgültig löschen"
+
#: src/delete_dialog.zig
msgid "Delete file?"
msgstr "Datei löschen?"
@@ -1888,6 +1900,10 @@ msgstr "Objekte löschen?"
msgid "Delete permanently"
msgstr "Endgültig löschen"
+#: src/files/app_dialogs.zig
+msgid "Delete permanently?"
+msgstr "Endgültig löschen?"
+
#: src/control_center/sections/users.zig
msgid "Delete user…"
msgstr "Benutzer löschen…"
@@ -4000,6 +4016,10 @@ msgstr "Wird geöffnet…"
msgid "Optimize"
msgstr "Optimieren"
+#: src/files/app_menu.zig
+msgid "Original location unknown: these items have no Trash information"
+msgstr "Ursprünglicher Ort unbekannt: Für diese Objekte gibt es keine Papierkorb-Informationen"
+
#: src/files/properties.zig
msgid "Others"
msgstr "Andere"
@@ -4820,6 +4840,14 @@ msgstr "Die Schreibtisch-Shell neu starten."
msgid "Restart? Activate Restart again to confirm."
msgstr "Neu starten? Aktiviere Neustart erneut zum Bestätigen."
+#: src/files/app_model.zig
+msgid "Restore"
+msgstr "Wiederherstellen"
+
+#: src/files/app_menu.zig
+msgid "Restore All"
+msgstr "Alle wiederherstellen"
+
#: src/control_center/sections/shortcuts.zig
msgid "Restore Layout"
msgstr "Anordnung wiederherstellen"
@@ -4844,6 +4872,20 @@ msgstr "Den Schreibtischzoom wiederherstellen."
msgid "Restore the focused window's size."
msgstr "Größe des fokussierten Fensters wiederherstellen."
+#: src/files/app_dialogs.zig
+msgid "Restore the folder to change what is inside it"
+msgstr "Stelle den Ordner wieder her, um seinen Inhalt zu ändern"
+
+#: src/files/app_trash.zig
+msgid "Restored"
+msgstr "Wiederhergestellt"
+
+#: src/files/app_trash.zig
+msgid "Restored {count} item"
+msgid_plural "Restored {count} items"
+msgstr[0] "{count} Objekt wiederhergestellt"
+msgstr[1] "{count} Objekte wiederhergestellt"
+
#: src/calculator/model.zig
msgid "Result is too large"
msgstr "Ergebnis ist zu groß"
@@ -5396,10 +5438,22 @@ msgstr "Socket"
msgid "Soft"
msgstr "Weich"
+#: src/files/app_trash.zig
+msgid "Some could not be restored"
+msgstr "Einige konnten nicht wiederhergestellt werden"
+
#: src/control_center/sections/users.zig
msgid "Some groups cannot be safely shown; group changes are disabled."
msgstr "Einige Gruppen können nicht sicher angezeigt werden; Gruppenänderungen sind deaktiviert."
+#: src/files/app_trash.zig
+msgid "Some have no Trash information"
+msgstr "Für einige gibt es keine Papierkorb-Informationen"
+
+#: src/files/app_trash.zig
+msgid "Some kept under a new name"
+msgstr "Einige unter neuem Namen behalten"
+
#: src/systemd/requests.zig
msgid "Some startup times are unavailable."
msgstr "Einige Startzeiten sind nicht verfügbar."
@@ -6180,10 +6234,18 @@ msgstr "Transformation"
msgid "Trash"
msgstr "Papierkorb"
+#: src/files/app_trash.zig
+msgid "Trash can't be edited. Restore items to change them."
+msgstr "Der Papierkorb kann nicht bearbeitet werden. Stelle Objekte wieder her, um sie zu ändern."
+
#: src/files/app_fileops.zig
msgid "Trash emptied"
msgstr "Papierkorb geleert"
+#: src/files/app_trash.zig
+msgid "Trash is empty"
+msgstr "Der Papierkorb ist leer"
+
#: src/images/app_dialogs.zig
msgid "Trash is unavailable: install gio to use it."
msgstr "Papierkorb nicht verfügbar: installiere gio."
@@ -6388,6 +6450,10 @@ msgstr "24-Stunden-Format verwenden"
msgid "Use 8–63 characters or a 64-digit hex key."
msgstr "Verwende 8–63 Zeichen oder einen 64-stelligen Hexadezimalschlüssel."
+#: src/files/app_fileops.zig
+msgid "Use Move to Trash to put items in Trash"
+msgstr "Verwende „In den Papierkorb verschieben“, um Objekte in den Papierkorb zu legen"
+
#: src/images/app_dialogs.zig
msgid "Use a .png filename to save a PNG copy."
msgstr "Nutze einen Dateinamen mit .png, um eine PNG-Kopie zu speichern."
@@ -7214,12 +7280,26 @@ msgid_plural "{columns} × {rows} · {n} screens total"
msgstr[0] "{columns} × {rows} · insgesamt {n} Bildschirm"
msgstr[1] "{columns} × {rows} · insgesamt {n} Bildschirme"
+#: src/files/app_trash.zig
+msgid "{count} could not be restored"
+msgstr "Nicht wiederhergestellt: {count}"
+
+#: src/files/app_trash.zig
+msgid "{count} has no Trash information"
+msgid_plural "{count} have no Trash information"
+msgstr[0] "{count} Objekt ohne Papierkorb-Informationen"
+msgstr[1] "{count} Objekte ohne Papierkorb-Informationen"
+
#: src/files/app_paint.zig
msgid "{count} item selected · {size}"
msgid_plural "{count} items selected · {size}"
msgstr[0] "{count} Objekt ausgewählt · {size}"
msgstr[1] "{count} Objekte ausgewählt · {size}"
+#: src/files/app_trash.zig
+msgid "{count} kept under a new name"
+msgstr "Unter neuem Namen behalten: {count}"
+
#: src/files/open_with.zig
msgid "{count} selected file"
msgid_plural "{count} selected files"
diff --git a/po/es.po b/po/es.po
index 37560c3..5edf62e 100644
--- a/po/es.po
+++ b/po/es.po
@@ -1563,6 +1563,14 @@ msgstr "No se pudo solicitar el inicio de CUPS."
msgid "Could not request authentication. Check that polkit is running."
msgstr "No se pudo solicitar autenticación. Comprueba que polkit esté en ejecución."
+#: src/files/app_trash.zig
+msgid "Could not restore the items in Trash"
+msgstr "No se pudieron restaurar los elementos de la papelera"
+
+#: src/files/app_trash.zig
+msgid "Could not restore the selected items"
+msgstr "No se pudieron restaurar los elementos seleccionados"
+
#: src/images/app_input.zig
msgid "Could not rotate: not enough memory."
msgstr "No se pudo girar: memoria insuficiente."
@@ -1865,6 +1873,10 @@ msgstr "Terminal predeterminado"
msgid "Deferred"
msgstr "Pospuesto"
+#: src/files/app_model.zig
+msgid "Delete Permanently"
+msgstr "Eliminar permanentemente"
+
#: src/delete_dialog.zig
msgid "Delete file?"
msgstr "¿Eliminar el archivo?"
@@ -1885,6 +1897,10 @@ msgstr "¿Eliminar los elementos?"
msgid "Delete permanently"
msgstr "Eliminar permanentemente"
+#: src/files/app_dialogs.zig
+msgid "Delete permanently?"
+msgstr "¿Eliminar permanentemente?"
+
#: src/control_center/sections/users.zig
msgid "Delete user…"
msgstr "Eliminar usuario…"
@@ -3997,6 +4013,10 @@ msgstr "Abriendo…"
msgid "Optimize"
msgstr "Optimizar"
+#: src/files/app_menu.zig
+msgid "Original location unknown: these items have no Trash information"
+msgstr "Ubicación original desconocida: estos elementos no tienen información de la papelera"
+
#: src/files/properties.zig
msgid "Others"
msgstr "Otros"
@@ -4817,6 +4837,14 @@ msgstr "Reiniciar la shell del escritorio."
msgid "Restart? Activate Restart again to confirm."
msgstr "¿Reiniciar? Activa Reiniciar otra vez para confirmar."
+#: src/files/app_model.zig
+msgid "Restore"
+msgstr "Restaurar"
+
+#: src/files/app_menu.zig
+msgid "Restore All"
+msgstr "Restaurar todo"
+
#: src/control_center/sections/shortcuts.zig
msgid "Restore Layout"
msgstr "Restaurar disposición"
@@ -4841,6 +4869,20 @@ msgstr "Restaurar la ampliación del escritorio."
msgid "Restore the focused window's size."
msgstr "Restaurar el tamaño de la ventana enfocada."
+#: src/files/app_dialogs.zig
+msgid "Restore the folder to change what is inside it"
+msgstr "Restaura la carpeta para cambiar su contenido"
+
+#: src/files/app_trash.zig
+msgid "Restored"
+msgstr "Restaurado"
+
+#: src/files/app_trash.zig
+msgid "Restored {count} item"
+msgid_plural "Restored {count} items"
+msgstr[0] "Se restauró {count} elemento"
+msgstr[1] "Se restauraron {count} elementos"
+
#: src/calculator/model.zig
msgid "Result is too large"
msgstr "El resultado es demasiado grande"
@@ -5393,10 +5435,22 @@ msgstr "Socket"
msgid "Soft"
msgstr "Suave"
+#: src/files/app_trash.zig
+msgid "Some could not be restored"
+msgstr "Algunos no se pudieron restaurar"
+
#: src/control_center/sections/users.zig
msgid "Some groups cannot be safely shown; group changes are disabled."
msgstr "Algunos grupos no se pueden mostrar con seguridad; sus cambios están desactivados."
+#: src/files/app_trash.zig
+msgid "Some have no Trash information"
+msgstr "Algunos no tienen información de la papelera"
+
+#: src/files/app_trash.zig
+msgid "Some kept under a new name"
+msgstr "Algunos se conservaron con un nombre nuevo"
+
#: src/systemd/requests.zig
msgid "Some startup times are unavailable."
msgstr "Algunos tiempos de inicio no están disponibles."
@@ -6177,10 +6231,18 @@ msgstr "Transformar"
msgid "Trash"
msgstr "Papelera"
+#: src/files/app_trash.zig
+msgid "Trash can't be edited. Restore items to change them."
+msgstr "La papelera no se puede editar. Restaura los elementos para cambiarlos."
+
#: src/files/app_fileops.zig
msgid "Trash emptied"
msgstr "Papelera vaciada"
+#: src/files/app_trash.zig
+msgid "Trash is empty"
+msgstr "La papelera está vacía"
+
#: src/images/app_dialogs.zig
msgid "Trash is unavailable: install gio to use it."
msgstr "Papelera no disponible: instala gio para usarla."
@@ -6385,6 +6447,10 @@ msgstr "Usar formato de 24 horas"
msgid "Use 8–63 characters or a 64-digit hex key."
msgstr "Usa entre 8 y 63 caracteres o una clave hexadecimal de 64 dígitos."
+#: src/files/app_fileops.zig
+msgid "Use Move to Trash to put items in Trash"
+msgstr "Usa «Mover a la papelera» para poner elementos en la papelera"
+
#: src/images/app_dialogs.zig
msgid "Use a .png filename to save a PNG copy."
msgstr "Usa un nombre terminado en .png para guardar una copia PNG."
@@ -7211,12 +7277,26 @@ msgid_plural "{columns} × {rows} · {n} screens total"
msgstr[0] "{columns} × {rows} · {n} pantalla en total"
msgstr[1] "{columns} × {rows} · {n} pantallas en total"
+#: src/files/app_trash.zig
+msgid "{count} could not be restored"
+msgstr "No restaurados: {count}"
+
+#: src/files/app_trash.zig
+msgid "{count} has no Trash information"
+msgid_plural "{count} have no Trash information"
+msgstr[0] "{count} elemento sin información de la papelera"
+msgstr[1] "{count} elementos sin información de la papelera"
+
#: src/files/app_paint.zig
msgid "{count} item selected · {size}"
msgid_plural "{count} items selected · {size}"
msgstr[0] "{count} elemento seleccionado · {size}"
msgstr[1] "{count} elementos seleccionados · {size}"
+#: src/files/app_trash.zig
+msgid "{count} kept under a new name"
+msgstr "Conservados con un nombre nuevo: {count}"
+
#: src/files/open_with.zig
msgid "{count} selected file"
msgid_plural "{count} selected files"
diff --git a/po/fr.po b/po/fr.po
index 9cbf4ff..c93b4f9 100644
--- a/po/fr.po
+++ b/po/fr.po
@@ -1566,6 +1566,14 @@ msgstr "Impossible de demander le démarrage de CUPS."
msgid "Could not request authentication. Check that polkit is running."
msgstr "Impossible de demander l'authentification. Vérifiez que polkit est actif."
+#: src/files/app_trash.zig
+msgid "Could not restore the items in Trash"
+msgstr "Impossible de restaurer les éléments de la corbeille"
+
+#: src/files/app_trash.zig
+msgid "Could not restore the selected items"
+msgstr "Impossible de restaurer les éléments sélectionnés"
+
#: src/images/app_input.zig
msgid "Could not rotate: not enough memory."
msgstr "Rotation impossible : mémoire insuffisante."
@@ -1868,6 +1876,10 @@ msgstr "Terminal par défaut"
msgid "Deferred"
msgstr "Différé"
+#: src/files/app_model.zig
+msgid "Delete Permanently"
+msgstr "Supprimer définitivement"
+
#: src/delete_dialog.zig
msgid "Delete file?"
msgstr "Supprimer le fichier ?"
@@ -1888,6 +1900,10 @@ msgstr "Supprimer les éléments ?"
msgid "Delete permanently"
msgstr "Supprimer définitivement"
+#: src/files/app_dialogs.zig
+msgid "Delete permanently?"
+msgstr "Supprimer définitivement ?"
+
#: src/control_center/sections/users.zig
msgid "Delete user…"
msgstr "Supprimer l'utilisateur…"
@@ -4000,6 +4016,10 @@ msgstr "Ouverture…"
msgid "Optimize"
msgstr "Optimiser"
+#: src/files/app_menu.zig
+msgid "Original location unknown: these items have no Trash information"
+msgstr "Emplacement d’origine inconnu : ces éléments n’ont aucune information de la corbeille"
+
#: src/files/properties.zig
msgid "Others"
msgstr "Autres"
@@ -4820,6 +4840,14 @@ msgstr "Redémarrer l'environnement du bureau."
msgid "Restart? Activate Restart again to confirm."
msgstr "Redémarrer ? Activez de nouveau Redémarrer pour confirmer."
+#: src/files/app_model.zig
+msgid "Restore"
+msgstr "Restaurer"
+
+#: src/files/app_menu.zig
+msgid "Restore All"
+msgstr "Tout restaurer"
+
#: src/control_center/sections/shortcuts.zig
msgid "Restore Layout"
msgstr "Restaurer la disposition"
@@ -4844,6 +4872,20 @@ msgstr "Restaurer le zoom du bureau."
msgid "Restore the focused window's size."
msgstr "Restaurer la taille de la fenêtre active."
+#: src/files/app_dialogs.zig
+msgid "Restore the folder to change what is inside it"
+msgstr "Restaurez le dossier pour modifier son contenu"
+
+#: src/files/app_trash.zig
+msgid "Restored"
+msgstr "Restauré"
+
+#: src/files/app_trash.zig
+msgid "Restored {count} item"
+msgid_plural "Restored {count} items"
+msgstr[0] "{count} élément restauré"
+msgstr[1] "{count} éléments restaurés"
+
#: src/calculator/model.zig
msgid "Result is too large"
msgstr "Le résultat est trop grand"
@@ -5396,10 +5438,22 @@ msgstr "Socket"
msgid "Soft"
msgstr "Doux"
+#: src/files/app_trash.zig
+msgid "Some could not be restored"
+msgstr "Certains n’ont pas pu être restaurés"
+
#: src/control_center/sections/users.zig
msgid "Some groups cannot be safely shown; group changes are disabled."
msgstr "Certains groupes ne peuvent pas être affichés de façon sûre ; les modifications des groupes sont désactivées."
+#: src/files/app_trash.zig
+msgid "Some have no Trash information"
+msgstr "Certains n’ont aucune information de la corbeille"
+
+#: src/files/app_trash.zig
+msgid "Some kept under a new name"
+msgstr "Certains ont été conservés sous un nouveau nom"
+
#: src/systemd/requests.zig
msgid "Some startup times are unavailable."
msgstr "Certains temps de démarrage sont indisponibles."
@@ -6180,10 +6234,18 @@ msgstr "Transformation"
msgid "Trash"
msgstr "Corbeille"
+#: src/files/app_trash.zig
+msgid "Trash can't be edited. Restore items to change them."
+msgstr "La corbeille ne peut pas être modifiée. Restaurez les éléments pour les modifier."
+
#: src/files/app_fileops.zig
msgid "Trash emptied"
msgstr "Corbeille vidée"
+#: src/files/app_trash.zig
+msgid "Trash is empty"
+msgstr "La corbeille est vide"
+
#: src/images/app_dialogs.zig
msgid "Trash is unavailable: install gio to use it."
msgstr "Corbeille indisponible : installez gio."
@@ -6388,6 +6450,10 @@ msgstr "Utiliser le format 24 heures"
msgid "Use 8–63 characters or a 64-digit hex key."
msgstr "Utilisez 8 à 63 caractères ou une clé hexadécimale de 64 chiffres."
+#: src/files/app_fileops.zig
+msgid "Use Move to Trash to put items in Trash"
+msgstr "Utilisez « Déplacer vers la corbeille » pour placer des éléments dans la corbeille"
+
#: src/images/app_dialogs.zig
msgid "Use a .png filename to save a PNG copy."
msgstr "Utilisez un nom se terminant par .png pour enregistrer une copie PNG."
@@ -7214,12 +7280,26 @@ msgid_plural "{columns} × {rows} · {n} screens total"
msgstr[0] "{columns} × {rows} · {n} écran au total"
msgstr[1] "{columns} × {rows} · {n} écrans au total"
+#: src/files/app_trash.zig
+msgid "{count} could not be restored"
+msgstr "Non restaurés : {count}"
+
+#: src/files/app_trash.zig
+msgid "{count} has no Trash information"
+msgid_plural "{count} have no Trash information"
+msgstr[0] "{count} élément sans information de la corbeille"
+msgstr[1] "{count} éléments sans information de la corbeille"
+
#: src/files/app_paint.zig
msgid "{count} item selected · {size}"
msgid_plural "{count} items selected · {size}"
msgstr[0] "{count} élément sélectionné · {size}"
msgstr[1] "{count} éléments sélectionnés · {size}"
+#: src/files/app_trash.zig
+msgid "{count} kept under a new name"
+msgstr "Conservés sous un nouveau nom : {count}"
+
#: src/files/open_with.zig
msgid "{count} selected file"
msgid_plural "{count} selected files"
diff --git a/po/pt_BR.po b/po/pt_BR.po
index 9c4db83..bc2713c 100644
--- a/po/pt_BR.po
+++ b/po/pt_BR.po
@@ -1563,6 +1563,14 @@ msgstr "Não foi possível solicitar a inicialização do CUPS."
msgid "Could not request authentication. Check that polkit is running."
msgstr "Não foi possível solicitar autenticação. Verifique se o polkit está em execução."
+#: src/files/app_trash.zig
+msgid "Could not restore the items in Trash"
+msgstr "Não foi possível restaurar os itens da lixeira"
+
+#: src/files/app_trash.zig
+msgid "Could not restore the selected items"
+msgstr "Não foi possível restaurar os itens selecionados"
+
#: src/images/app_input.zig
msgid "Could not rotate: not enough memory."
msgstr "Não foi possível girar: memória insuficiente."
@@ -1865,6 +1873,10 @@ msgstr "Terminal padrão"
msgid "Deferred"
msgstr "Adiado"
+#: src/files/app_model.zig
+msgid "Delete Permanently"
+msgstr "Excluir permanentemente"
+
#: src/delete_dialog.zig
msgid "Delete file?"
msgstr "Excluir o arquivo?"
@@ -1885,6 +1897,10 @@ msgstr "Excluir os itens?"
msgid "Delete permanently"
msgstr "Excluir permanentemente"
+#: src/files/app_dialogs.zig
+msgid "Delete permanently?"
+msgstr "Excluir permanentemente?"
+
#: src/control_center/sections/users.zig
msgid "Delete user…"
msgstr "Excluir usuário…"
@@ -3997,6 +4013,10 @@ msgstr "Abrindo…"
msgid "Optimize"
msgstr "Otimizar"
+#: src/files/app_menu.zig
+msgid "Original location unknown: these items have no Trash information"
+msgstr "Local original desconhecido: estes itens não têm informações da lixeira"
+
#: src/files/properties.zig
msgid "Others"
msgstr "Outros"
@@ -4817,6 +4837,14 @@ msgstr "Reiniciar o shell da área de trabalho."
msgid "Restart? Activate Restart again to confirm."
msgstr "Reiniciar? Ative Reiniciar novamente para confirmar."
+#: src/files/app_model.zig
+msgid "Restore"
+msgstr "Restaurar"
+
+#: src/files/app_menu.zig
+msgid "Restore All"
+msgstr "Restaurar tudo"
+
#: src/control_center/sections/shortcuts.zig
msgid "Restore Layout"
msgstr "Restaurar organização"
@@ -4841,6 +4869,20 @@ msgstr "Restaurar a ampliação da área de trabalho."
msgid "Restore the focused window's size."
msgstr "Restaurar o tamanho da janela em foco."
+#: src/files/app_dialogs.zig
+msgid "Restore the folder to change what is inside it"
+msgstr "Restaure a pasta para alterar o que há dentro dela"
+
+#: src/files/app_trash.zig
+msgid "Restored"
+msgstr "Restaurado"
+
+#: src/files/app_trash.zig
+msgid "Restored {count} item"
+msgid_plural "Restored {count} items"
+msgstr[0] "{count} item restaurado"
+msgstr[1] "{count} itens restaurados"
+
#: src/calculator/model.zig
msgid "Result is too large"
msgstr "O resultado é grande demais"
@@ -5393,10 +5435,22 @@ msgstr "Socket"
msgid "Soft"
msgstr "Suave"
+#: src/files/app_trash.zig
+msgid "Some could not be restored"
+msgstr "Alguns não puderam ser restaurados"
+
#: src/control_center/sections/users.zig
msgid "Some groups cannot be safely shown; group changes are disabled."
msgstr "Alguns grupos não podem ser exibidos com segurança; suas alterações estão desativadas."
+#: src/files/app_trash.zig
+msgid "Some have no Trash information"
+msgstr "Alguns não têm informações da lixeira"
+
+#: src/files/app_trash.zig
+msgid "Some kept under a new name"
+msgstr "Alguns foram mantidos com um novo nome"
+
#: src/systemd/requests.zig
msgid "Some startup times are unavailable."
msgstr "Alguns tempos de inicialização estão indisponíveis."
@@ -6177,10 +6231,18 @@ msgstr "Transformar"
msgid "Trash"
msgstr "Lixeira"
+#: src/files/app_trash.zig
+msgid "Trash can't be edited. Restore items to change them."
+msgstr "A lixeira não pode ser editada. Restaure os itens para alterá-los."
+
#: src/files/app_fileops.zig
msgid "Trash emptied"
msgstr "Lixeira esvaziada"
+#: src/files/app_trash.zig
+msgid "Trash is empty"
+msgstr "A lixeira está vazia"
+
#: src/images/app_dialogs.zig
msgid "Trash is unavailable: install gio to use it."
msgstr "Lixeira indisponível: instale o gio para usá-la."
@@ -6385,6 +6447,10 @@ msgstr "Usar formato de 24 horas"
msgid "Use 8–63 characters or a 64-digit hex key."
msgstr "Use de 8 a 63 caracteres ou uma chave hexadecimal de 64 dígitos."
+#: src/files/app_fileops.zig
+msgid "Use Move to Trash to put items in Trash"
+msgstr "Use “Mover para a lixeira” para colocar itens na lixeira"
+
#: src/images/app_dialogs.zig
msgid "Use a .png filename to save a PNG copy."
msgstr "Use um nome terminado em .png para salvar uma cópia PNG."
@@ -7211,12 +7277,26 @@ msgid_plural "{columns} × {rows} · {n} screens total"
msgstr[0] "{columns} × {rows} · {n} tela no total"
msgstr[1] "{columns} × {rows} · {n} telas no total"
+#: src/files/app_trash.zig
+msgid "{count} could not be restored"
+msgstr "Não restaurados: {count}"
+
+#: src/files/app_trash.zig
+msgid "{count} has no Trash information"
+msgid_plural "{count} have no Trash information"
+msgstr[0] "{count} item sem informações da lixeira"
+msgstr[1] "{count} itens sem informações da lixeira"
+
#: src/files/app_paint.zig
msgid "{count} item selected · {size}"
msgid_plural "{count} items selected · {size}"
msgstr[0] "{count} item selecionado · {size}"
msgstr[1] "{count} itens selecionados · {size}"
+#: src/files/app_trash.zig
+msgid "{count} kept under a new name"
+msgstr "Mantidos com um novo nome: {count}"
+
#: src/files/open_with.zig
msgid "{count} selected file"
msgid_plural "{count} selected files"
diff --git a/po/rediwm.pot b/po/rediwm.pot
index 755169e..ab78e76 100644
--- a/po/rediwm.pot
+++ b/po/rediwm.pot
@@ -1621,6 +1621,14 @@ msgstr ""
msgid "Could not reset. The previous settings were restored."
msgstr ""
+#: src/files/app_trash.zig
+msgid "Could not restore the items in Trash"
+msgstr ""
+
+#: src/files/app_trash.zig
+msgid "Could not restore the selected items"
+msgstr ""
+
#: src/images/app_input.zig
msgid "Could not rotate: not enough memory."
msgstr ""
@@ -1951,6 +1959,10 @@ msgstr ""
msgid "Deferred"
msgstr ""
+#: src/files/app_model.zig
+msgid "Delete Permanently"
+msgstr ""
+
#: src/delete_dialog.zig
msgid "Delete file?"
msgstr ""
@@ -1971,6 +1983,10 @@ msgstr ""
msgid "Delete permanently"
msgstr ""
+#: src/files/app_dialogs.zig
+msgid "Delete permanently?"
+msgstr ""
+
#: src/control_center/sections/users.zig
msgid "Delete user…"
msgstr ""
@@ -4215,6 +4231,10 @@ msgstr ""
msgid "Optimize"
msgstr ""
+#: src/files/app_menu.zig
+msgid "Original location unknown: these items have no Trash information"
+msgstr ""
+
#: src/files/properties.zig
msgid "Others"
msgstr ""
@@ -5103,6 +5123,14 @@ msgstr ""
msgid "Restart? Activate Restart again to confirm."
msgstr ""
+#: src/files/app_model.zig
+msgid "Restore"
+msgstr ""
+
+#: src/files/app_menu.zig
+msgid "Restore All"
+msgstr ""
+
#: src/control_center/sections/shortcuts.zig
msgid "Restore Layout"
msgstr ""
@@ -5127,6 +5155,20 @@ msgstr ""
msgid "Restore the focused window's size."
msgstr ""
+#: src/files/app_dialogs.zig
+msgid "Restore the folder to change what is inside it"
+msgstr ""
+
+#: src/files/app_trash.zig
+msgid "Restored"
+msgstr ""
+
+#: src/files/app_trash.zig
+msgid "Restored {count} item"
+msgid_plural "Restored {count} items"
+msgstr[0] ""
+msgstr[1] ""
+
#: src/calculator/model.zig
msgid "Result is too large"
msgstr ""
@@ -5707,10 +5749,22 @@ msgstr ""
msgid "Soft"
msgstr ""
+#: src/files/app_trash.zig
+msgid "Some could not be restored"
+msgstr ""
+
#: src/control_center/sections/users.zig
msgid "Some groups cannot be safely shown; group changes are disabled."
msgstr ""
+#: src/files/app_trash.zig
+msgid "Some have no Trash information"
+msgstr ""
+
+#: src/files/app_trash.zig
+msgid "Some kept under a new name"
+msgstr ""
+
#: src/systemd/requests.zig
msgid "Some startup times are unavailable."
msgstr ""
@@ -6519,10 +6573,18 @@ msgstr ""
msgid "Trash"
msgstr ""
+#: src/files/app_trash.zig
+msgid "Trash can't be edited. Restore items to change them."
+msgstr ""
+
#: src/files/app_fileops.zig
msgid "Trash emptied"
msgstr ""
+#: src/files/app_trash.zig
+msgid "Trash is empty"
+msgstr ""
+
#: src/images/app_dialogs.zig
msgid "Trash is unavailable: install gio to use it."
msgstr ""
@@ -6735,6 +6797,10 @@ msgstr ""
msgid "Use 8–63 characters or a 64-digit hex key."
msgstr ""
+#: src/files/app_fileops.zig
+msgid "Use Move to Trash to put items in Trash"
+msgstr ""
+
#: src/images/app_dialogs.zig
msgid "Use a .png filename to save a PNG copy."
msgstr ""
@@ -7669,12 +7735,26 @@ msgid_plural "{columns} × {rows} · {n} screens total"
msgstr[0] ""
msgstr[1] ""
+#: src/files/app_trash.zig
+msgid "{count} could not be restored"
+msgstr ""
+
+#: src/files/app_trash.zig
+msgid "{count} has no Trash information"
+msgid_plural "{count} have no Trash information"
+msgstr[0] ""
+msgstr[1] ""
+
#: src/files/app_paint.zig
msgid "{count} item selected · {size}"
msgid_plural "{count} items selected · {size}"
msgstr[0] ""
msgstr[1] ""
+#: src/files/app_trash.zig
+msgid "{count} kept under a new name"
+msgstr ""
+
#: src/files/open_with.zig
msgid "{count} selected file"
msgid_plural "{count} selected files"
diff --git a/po/ru.po b/po/ru.po
index 282ae53..9fe71db 100644
--- a/po/ru.po
+++ b/po/ru.po
@@ -1567,6 +1567,14 @@ msgstr "Не удалось запросить запуск CUPS."
msgid "Could not request authentication. Check that polkit is running."
msgstr "Не удалось запросить проверку подлинности. Убедитесь, что polkit запущена."
+#: src/files/app_trash.zig
+msgid "Could not restore the items in Trash"
+msgstr "Не удалось восстановить объекты из корзины"
+
+#: src/files/app_trash.zig
+msgid "Could not restore the selected items"
+msgstr "Не удалось восстановить выбранные объекты"
+
#: src/images/app_input.zig
msgid "Could not rotate: not enough memory."
msgstr "Не удалось повернуть: недостаточно памяти."
@@ -1870,6 +1878,10 @@ msgstr "Терминал по умолчанию"
msgid "Deferred"
msgstr "Отложено"
+#: src/files/app_model.zig
+msgid "Delete Permanently"
+msgstr "Удалить безвозвратно"
+
#: src/delete_dialog.zig
msgid "Delete file?"
msgstr "Удалить файл?"
@@ -1890,6 +1902,10 @@ msgstr "Удалить объекты?"
msgid "Delete permanently"
msgstr "Удалить безвозвратно"
+#: src/files/app_dialogs.zig
+msgid "Delete permanently?"
+msgstr "Удалить безвозвратно?"
+
#: src/control_center/sections/users.zig
msgid "Delete user…"
msgstr "Удалить пользователя…"
@@ -4002,6 +4018,10 @@ msgstr "Открытие…"
msgid "Optimize"
msgstr "Оптимизировать"
+#: src/files/app_menu.zig
+msgid "Original location unknown: these items have no Trash information"
+msgstr "Исходное расположение неизвестно: для этих объектов нет сведений корзины"
+
#: src/files/properties.zig
msgid "Others"
msgstr "Остальные"
@@ -4822,6 +4842,14 @@ msgstr "Перезапустить оболочку рабочего стола.
msgid "Restart? Activate Restart again to confirm."
msgstr "Перезапустить? Нажмите «Перезапустить» ещё раз для подтверждения."
+#: src/files/app_model.zig
+msgid "Restore"
+msgstr "Восстановить"
+
+#: src/files/app_menu.zig
+msgid "Restore All"
+msgstr "Восстановить всё"
+
#: src/control_center/sections/shortcuts.zig
msgid "Restore Layout"
msgstr "Восстановить расположение"
@@ -4846,6 +4874,21 @@ msgstr "Восстановить масштаб рабочего стола."
msgid "Restore the focused window's size."
msgstr "Восстановить размер активного окна."
+#: src/files/app_dialogs.zig
+msgid "Restore the folder to change what is inside it"
+msgstr "Восстановите папку, чтобы изменить её содержимое"
+
+#: src/files/app_trash.zig
+msgid "Restored"
+msgstr "Восстановлено"
+
+#: src/files/app_trash.zig
+msgid "Restored {count} item"
+msgid_plural "Restored {count} items"
+msgstr[0] "Восстановлен {count} объект"
+msgstr[1] "Восстановлено {count} объекта"
+msgstr[2] "Восстановлено {count} объектов"
+
#: src/calculator/model.zig
msgid "Result is too large"
msgstr "Результат слишком велик"
@@ -5398,10 +5441,22 @@ msgstr "Сокет"
msgid "Soft"
msgstr "Мягкий"
+#: src/files/app_trash.zig
+msgid "Some could not be restored"
+msgstr "Некоторые не удалось восстановить"
+
#: src/control_center/sections/users.zig
msgid "Some groups cannot be safely shown; group changes are disabled."
msgstr "Некоторые группы нельзя безопасно показать; изменение групп отключено."
+#: src/files/app_trash.zig
+msgid "Some have no Trash information"
+msgstr "У некоторых нет сведений корзины"
+
+#: src/files/app_trash.zig
+msgid "Some kept under a new name"
+msgstr "Некоторые сохранены под новым именем"
+
#: src/systemd/requests.zig
msgid "Some startup times are unavailable."
msgstr "Некоторые времена запуска недоступны."
@@ -6182,10 +6237,18 @@ msgstr "Преобразование"
msgid "Trash"
msgstr "Корзина"
+#: src/files/app_trash.zig
+msgid "Trash can't be edited. Restore items to change them."
+msgstr "Корзину нельзя изменять. Восстановите объекты, чтобы изменить их."
+
#: src/files/app_fileops.zig
msgid "Trash emptied"
msgstr "Корзина очищена"
+#: src/files/app_trash.zig
+msgid "Trash is empty"
+msgstr "Корзина пуста"
+
#: src/images/app_dialogs.zig
msgid "Trash is unavailable: install gio to use it."
msgstr "Корзина недоступна: установите gio."
@@ -6390,6 +6453,10 @@ msgstr "Использовать 24-часовой формат"
msgid "Use 8–63 characters or a 64-digit hex key."
msgstr "Используйте 8–63 символа или 64-значный шестнадцатеричный ключ."
+#: src/files/app_fileops.zig
+msgid "Use Move to Trash to put items in Trash"
+msgstr "Чтобы поместить объекты в корзину, используйте «Переместить в корзину»"
+
#: src/images/app_dialogs.zig
msgid "Use a .png filename to save a PNG copy."
msgstr "Для копии PNG используйте имя с расширением .png."
@@ -7217,6 +7284,17 @@ msgstr[0] "{columns} × {rows} · всего экранов: {n}"
msgstr[1] "{columns} × {rows} · всего экранов: {n}"
msgstr[2] "{columns} × {rows} · всего экранов: {n}"
+#: src/files/app_trash.zig
+msgid "{count} could not be restored"
+msgstr "Не восстановлено: {count}"
+
+#: src/files/app_trash.zig
+msgid "{count} has no Trash information"
+msgid_plural "{count} have no Trash information"
+msgstr[0] "{count} объект без сведений корзины"
+msgstr[1] "{count} объекта без сведений корзины"
+msgstr[2] "{count} объектов без сведений корзины"
+
#: src/files/app_paint.zig
msgid "{count} item selected · {size}"
msgid_plural "{count} items selected · {size}"
@@ -7224,6 +7302,10 @@ msgstr[0] "Выбран {count} объект · {size}"
msgstr[1] "Выбрано {count} объекта · {size}"
msgstr[2] "Выбрано {count} объектов · {size}"
+#: src/files/app_trash.zig
+msgid "{count} kept under a new name"
+msgstr "Сохранено под новым именем: {count}"
+
#: src/files/open_with.zig
msgid "{count} selected file"
msgid_plural "{count} selected files"
diff --git a/src/delete_dialog.zig b/src/delete_dialog.zig
index 5d77c4f..442141f 100644
--- a/src/delete_dialog.zig
+++ b/src/delete_dialog.zig
@@ -27,6 +27,9 @@ pub const State = struct {
preview: ?icons.Entry = null,
permanent: bool = false,
empty_trash: bool = false,
+ /// Deleting entries that are already in Trash: always permanent, so the
+ /// checkbox is gone, as for Empty Trash.
+ in_trash: bool = false,
focus: enum { cancel, toggle, confirm } = .cancel,
keyboard_focus: bool = false,
@@ -36,13 +39,18 @@ pub const State = struct {
const box = self.placement.box(g.box(), w, h);
g.x = box.x;
g.y = box.y;
- if (self.empty_trash) {
+ if (self.fixedChoice()) {
g.toggle.w = 0;
g.toggle.h = 0;
}
return g;
}
+ /// Nothing to choose between: the action is permanent either way.
+ pub fn fixedChoice(self: *const State) bool {
+ return self.empty_trash or self.in_trash;
+ }
+
pub fn pointerButton(self: *State, w: i32, h: i32, x: f64, y: f64, pressed: bool) bool {
return self.placement.button(Geometry.init(w, h).box(), w, h, x, y, pressed);
}
@@ -78,7 +86,7 @@ pub const State = struct {
if (sym == c.XKB_KEY_Tab or sym == c.XKB_KEY_ISO_Left_Tab) {
self.keyboard_focus = true;
const n: usize = @intFromEnum(self.focus);
- self.focus = if (self.empty_trash) (if (self.focus == .cancel) .confirm else .cancel) else @enumFromInt((n + (if (sym == c.XKB_KEY_Tab) @as(usize, 1) else 2)) % 3);
+ self.focus = if (self.fixedChoice()) (if (self.focus == .cancel) .confirm else .cancel) else @enumFromInt((n + (if (sym == c.XKB_KEY_Tab) @as(usize, 1) else 2)) % 3);
}
if (sym == c.XKB_KEY_space or ((sym == c.XKB_KEY_Return or sym == c.XKB_KEY_KP_Enter) and self.keyboard_focus)) return switch (self.focus) {
.cancel => .cancel,
@@ -147,7 +155,7 @@ pub const State = struct {
const detail = if (self.empty_trash) i18n.tr("Permanently delete all trashed files and folders") else if (self.paths.items.len > 1) i18n.tr("Files and folders in this selection") else if (self.folder) i18n.tr("Folder · includes its contents") else i18n.fmt(&detail_buf, i18n.tr("{kind} · {size} {unit}"), .{ .kind = if (std.ascii.eqlIgnoreCase(std.fs.path.extension(self.name), ".pdf")) i18n.tr("PDF document") else i18n.tr("File"), .size = size, .unit = if (self.bytes >= 1048576) "MB" else if (self.bytes >= 1024) "KB" else i18n.tr("bytes") }) catch i18n.tr("File");
if (inset_h >= 48) r.drawText(76, inset_y + (inset_h - 48) / 2 + 28, g.width - 108, 20, .{ .content = detail, .font_size = shell_ui.textSize(), .color = t.fg });
const focus = if (self.keyboard_focus) self.focus else null;
- if (!self.empty_trash) checkbox.paint(r, g.toggle, i18n.tr("Delete permanently"), .{ .checked = self.permanent, .focused = focus == .toggle });
+ if (!self.fixedChoice()) checkbox.paint(r, g.toggle, i18n.tr("Delete permanently"), .{ .checked = self.permanent, .focused = focus == .toggle });
button.paint(r, g.cancel, .{ .size = .sm, .label = i18n.tr("Cancel") }, .{ .focused = focus == .cancel, .pointer = if (hover == .cancel) .hover else .idle });
button.paint(r, g.confirm, .{ .variant = .primary, .size = .sm, .leading_icon = .trash, .label = if (self.empty_trash) i18n.tr("Empty Trash") else if (self.permanent) i18n.tr("Delete permanently") else i18n.tr("Move to Trash") }, .{ .focused = focus == .confirm, .pointer = if (hover == .confirm) .hover else .idle });
}
diff --git a/src/files/AGENTS.md b/src/files/AGENTS.md
index dd2f440..6d9f03f 100644
--- a/src/files/AGENTS.md
+++ b/src/files/AGENTS.md
@@ -14,7 +14,7 @@ are free functions taking `self: *App` in `app_*.zig`, grouped by concern:
`app_fileops`, `app_chooser`, `app_layout` (geometry), `app_folder_size`,
`app_places` (sidebar rows, pins, devices), `app_sidebar_paint`,
`app_git_sidebar`, `app_scroll`, `app_opening`, `app_pointer`,
-`app_keyboard`, `app_menu`, `app_paint`, `app_items`. Shared enums and
+`app_keyboard`, `app_menu`, `app_paint`, `app_items`, `app_trash`. Shared enums and
records are in `app_model.zig`, drawing helpers in `app_draw.zig`, tests in
`app_tests.zig` (with `app_*_tests.zig` by area). A new method goes in its
group file plus an alias line in `App`; a file that calls a sibling's
@@ -72,6 +72,36 @@ and headless fixtures. The pinned library is compiled only into Files/tests.
in place, uses its canonical absolute path and drops bundled TryExec,
working-directory, desktop-action and D-Bus activation references.
+## Trash
+
+* **Moving in stays on `gio trash`** (`ops.trashItems`, which knows the
+ per-volume rules) and so does Empty Trash (`gio trash --empty`, followed by
+ `trash.sweepOrphans`). Everything else on the home trash is native in
+ `trash.zig`: restore, permanent delete, `.trashinfo` parsing and the
+ `directorysizes` line. Tests build fixture trash directories, no `gio`.
+* **Home trash only.** Per-volume trashes (`$topdir/.Trash-$uid`) are neither
+ listed nor restored, though `gio trash --empty` still clears them. Their
+ `Path=` is relative to the volume and arrives from removable media, so it
+ needs containment checks (reject `..`, check `.Trash` sticky bits) first.
+* **Restore never overwrites.** The destination name comes from `Path=`, not
+ from the name in `files/` (collisions are renamed there). A taken name
+ (a dangling symlink counts) gets `generateUniqueName`, missing parents are
+ recreated and removed again if the move fails, and the move is
+ `renameat2(RENAME_NOREPLACE)` through `ops.moveItem`. The item moves first,
+ its metadata goes after; delete does the same, so a crash leaves orphan
+ metadata (`sweepOrphans`), never an unrestorable item.
+* **`trashRelation()`** (`app_trash.zig`) is the one test for "in Trash": `root`
+ lists the trashed entries, `inside` is a trashed folder (no metadata of its
+ own: open, copy and properties only). The view is read-only: no new,
+ rename, cut, paste or drop (`executeTransfer` refuses), and drags out offer
+ copy only, because a move would leave the `.trashinfo` behind.
+* **Restore is faded, not hidden,** when no selected entry has usable
+ metadata (`trash_restorable`, worked out when the menu opens, not per paint;
+ `context_menu.Row.disabled`). Delete inside the Trash uses the shared delete
+ dialog with `in_trash`: permanent, no checkbox.
+* Tests: `trash_tests.zig`, `app_trash_tests.zig`, `tests/files_trash.py`
+ (keyboard driven, filesystem as ground truth, fake `gio`).
+
## Git
`git.zig` never runs a repository's own programs: a folder's `.git` arrives
diff --git a/src/files/app.zig b/src/files/app.zig
index 6dab7a4..2717cd4 100644
--- a/src/files/app.zig
+++ b/src/files/app.zig
@@ -25,6 +25,7 @@ const app_hover = @import("app_hover.zig");
const app_listing = @import("app_listing.zig");
const app_dialogs = @import("app_dialogs.zig");
const app_fileops = @import("app_fileops.zig");
+const app_trash = @import("app_trash.zig");
const app_chooser = @import("app_chooser.zig");
const app_layout = @import("app_layout.zig");
const app_folder_size = @import("app_folder_size.zig");
@@ -138,6 +139,8 @@ pub const App = struct {
menu_x: f64 = 0,
menu_y: f64 = 0,
menu_selected: usize = 0,
+ /// Set when a file menu opens in the Trash: whether Restore applies.
+ trash_restorable: bool = false,
file_menu_labels: [12][]const u8 = undefined,
menu_label_text: [8][]const u8 = undefined,
column_label_text: [5][]const u8 = undefined,
@@ -565,6 +568,15 @@ pub const App = struct {
pub const executePasteExternal = app_fileops.executePasteExternal;
pub const deleteAction = app_fileops.deleteAction;
pub const executeDeletion = app_fileops.executeDeletion;
+ pub const deleteFromTrash = app_fileops.deleteFromTrash;
+
+ // app_trash.zig
+ pub const trashRelation = app_trash.trashRelation;
+ pub const inTrash = app_trash.inTrash;
+ pub const trashReadOnly = app_trash.trashReadOnly;
+ pub const refreshTrashRestorable = app_trash.refreshTrashRestorable;
+ pub const restoreSelected = app_trash.restoreSelected;
+ pub const restoreAll = app_trash.restoreAll;
// app_chooser.zig
pub const configureChooser = app_chooser.configureChooser;
@@ -882,6 +894,8 @@ pub const App = struct {
pub const menuHeight = app_menu.menuHeight;
pub const menuRowRect = app_menu.menuRowRect;
pub const menuIcon = app_menu.menuIcon;
+ pub const backgroundMenu = app_menu.backgroundMenu;
+ pub const menuDisabled = app_menu.menuDisabled;
pub const menuHint = app_menu.menuHint;
pub const hasSizeSelection = app_menu.hasSizeSelection;
pub const selectedArchive = app_menu.selectedArchive;
diff --git a/src/files/app_dialogs.zig b/src/files/app_dialogs.zig
index dea3b09..411b3b7 100644
--- a/src/files/app_dialogs.zig
+++ b/src/files/app_dialogs.zig
@@ -124,7 +124,7 @@ pub fn openWithAction(self: *App, action: open_with.Action) void {
}
pub fn openNewFolderDialog(self: *App) void {
- if (self.isRecent() or self.history.archive_len > 0) return;
+ if (self.isRecent() or self.history.archive_len > 0 or self.trashReadOnly()) return;
self.closeDialog();
var dlg = Dialog{
.kind = .new_folder,
@@ -156,7 +156,7 @@ pub fn switchBranch(self: *App, repo: git.Repository, name: []const u8, create:
}
pub fn openNewFileDialog(self: *App) void {
- if (self.isRecent() or self.history.archive_len > 0) return;
+ if (self.isRecent() or self.history.archive_len > 0 or self.trashReadOnly()) return;
self.closeDialog();
var dlg = Dialog{
.kind = .new_file,
@@ -170,7 +170,7 @@ pub fn openNewFileDialog(self: *App) void {
}
pub fn openRenameDialog(self: *App) void {
- if (self.history.archive_len > 0) return;
+ if (self.history.archive_len > 0 or self.trashReadOnly()) return;
const idx = self.focused_index orelse blk: {
for (self.items.items, 0..) |it, i| {
if (it.selected) break :blk i;
@@ -216,8 +216,19 @@ pub fn openTrashConfirmDialog(self: *App) void {
self.openTrashConfirmDialogWithMode(false);
}
-pub fn openTrashConfirmDialogWithMode(self: *App, permanent: bool) void {
+pub fn openTrashConfirmDialogWithMode(self: *App, permanent_requested: bool) void {
if (self.history.archive_len > 0) return;
+ // Entries already in Trash can only be deleted for good; the ones inside
+ // a trashed folder belong to it and go with it.
+ const in_trash = switch (self.trashRelation()) {
+ .none => false,
+ .root => true,
+ .inside => {
+ self.setStatusNotice(tr("Restore the folder to change what is inside it"), false);
+ return;
+ },
+ };
+ const permanent = permanent_requested or in_trash;
var count: usize = 0;
for (self.items.items) |it| {
if (it.selected and !it.missing) count += 1;
@@ -235,8 +246,8 @@ pub fn openTrashConfirmDialogWithMode(self: *App, permanent: bool) void {
self.closeDialog();
self.dialog = Dialog{
.kind = .trash_confirm,
- .title = tr("Move to Trash?"),
- .deletion = .{ .permanent = permanent },
+ .title = if (in_trash) tr("Delete permanently?") else tr("Move to Trash?"),
+ .deletion = .{ .permanent = permanent, .in_trash = in_trash },
};
for (self.items.items) |it| {
if (!it.selected or it.missing) continue;
diff --git a/src/files/app_fileops.zig b/src/files/app_fileops.zig
index 73a2f14..3dbdfbc 100644
--- a/src/files/app_fileops.zig
+++ b/src/files/app_fileops.zig
@@ -8,6 +8,7 @@ const recent = @import("recent.zig");
const ops_mod = @import("ops.zig");
const clipboard_mod = @import("clipboard.zig");
const deletion = @import("../delete_dialog.zig");
+const trash = @import("trash.zig");
pub fn copySelected(self: *App) void {
if (self.history.archive_len > 0) return;
@@ -31,7 +32,7 @@ pub fn copySelected(self: *App) void {
}
pub fn cutSelected(self: *App) void {
- if (self.history.archive_len > 0) return;
+ if (self.history.archive_len > 0 or self.trashReadOnly()) return;
if (!self.hasSelection()) return;
self.clipboard_is_text = false;
self.clearClipboard();
@@ -80,6 +81,11 @@ pub fn executePaste(self: *App, kind: ops_mod.OpKind, paths: []const []const u8)
pub fn executeTransfer(self: *App, kind: ops_mod.OpKind, paths: []const []const u8, directory: []const u8, clipboard: bool) bool {
if (self.history.archive_len > 0 or recent.isLocation(directory)) return false;
if (paths.len == 0) return false;
+ // Nothing is pasted or dropped into the Trash: Move to Trash is how items get there.
+ if (self.trash_dir) |dir| if (trash.relation(dir, directory) != .none) {
+ self.setStatusNotice(tr("Use Move to Trash to put items in Trash"), true);
+ return false;
+ };
const runner = self.job_runner orelse return false;
runner.start(kind, paths, directory, .ask) catch {
self.setStatusNotice(tr("Failed to start transfer job"), true);
@@ -119,7 +125,7 @@ pub fn deleteAction(self: *App, action: deletion.Action) void {
.cancel => self.closeDialog(),
.confirm => self.confirmDialog(),
.toggle => {
- if (self.dialog.?.deletion.empty_trash) return;
+ if (self.dialog.?.deletion.fixedChoice()) return;
self.dialog.?.deletion.permanent = !self.dialog.?.deletion.permanent;
self.dialog.?.deletion.focus = .toggle;
},
@@ -130,12 +136,41 @@ pub fn deleteAction(self: *App, action: deletion.Action) void {
pub fn executeDeletion(self: *App) void {
const state = &self.dialog.?.deletion;
+ if (state.in_trash) return self.deleteFromTrash(state.paths.items);
const result = if (state.empty_trash) ops_mod.emptyTrash(self.io) else if (state.permanent) ops_mod.deleteItems(self.io, state.paths.items) else ops_mod.trashItems(self.io, state.paths.items);
result catch |err| {
self.setStatusNotice(if (state.empty_trash) tr("Could not empty Trash") else if (state.permanent) tr("Could not delete all items") else if (err == error.GioNotAvailable) tr("Trash unavailable (gio not installed)") else tr("Could not move all items to Trash"), true);
self.refresh();
return;
};
+ // gio empties Trash; sweep what it leaves, so no metadata outlives its item.
+ if (state.empty_trash) if (self.trash_dir) |dir| trash.sweepOrphans(self.allocator, dir);
self.setStatusNotice(if (state.empty_trash) tr("Trash emptied") else if (state.permanent) tr("Items permanently deleted") else tr("Items moved to Trash"), false);
self.refresh();
}
+
+/// Permanently deletes entries of the Trash view with their metadata.
+pub fn deleteFromTrash(self: *App, paths: []const []const u8) void {
+ const dir = self.trash_dir orelse return;
+ var names: std.ArrayList([]const u8) = .empty;
+ defer names.deinit(self.allocator);
+ var stray: usize = 0;
+ for (paths) |path| {
+ // Only top-level entries of the trash have metadata and may go this way.
+ const parent = std.fs.path.dirname(path) orelse "";
+ if (!std.mem.eql(u8, parent, dir)) {
+ stray += 1;
+ continue;
+ }
+ names.append(self.allocator, std.fs.path.basename(path)) catch {
+ stray += 1;
+ };
+ }
+ const removed = trash.deleteMany(self.allocator, dir, names.items);
+ if (removed.failed + stray > 0) {
+ self.setStatusNotice(tr("Could not delete all items"), true);
+ } else {
+ self.setStatusNotice(tr("Items permanently deleted"), false);
+ }
+ self.refresh();
+}
diff --git a/src/files/app_hover.zig b/src/files/app_hover.zig
index 318c74d..58552c4 100644
--- a/src/files/app_hover.zig
+++ b/src/files/app_hover.zig
@@ -148,6 +148,19 @@ pub fn toolbarButtonEnabled(self: *App, action: header.Action) bool {
.new, .cut, .copy, .paste, .trash => return false,
else => {},
};
+ switch (self.trashRelation()) {
+ // Read-only: items are restored or deleted, not created, cut or pasted.
+ .root => switch (action) {
+ .new, .cut, .paste => return false,
+ else => {},
+ },
+ // Inside a trashed folder there is nothing to restore or delete either.
+ .inside => switch (action) {
+ .new, .cut, .paste, .trash => return false,
+ else => {},
+ },
+ .none => {},
+ }
return switch (action) {
.back => self.history.canBack(),
.forward => self.history.canForward(),
diff --git a/src/files/app_menu.zig b/src/files/app_menu.zig
index c3906b0..be49440 100644
--- a/src/files/app_menu.zig
+++ b/src/files/app_menu.zig
@@ -98,7 +98,7 @@ pub fn menuPadding(_: *App) usize {
pub fn menuSeparatorBefore(self: *App, row: usize) bool {
return switch (self.menu orelse return false) {
.file => switch (self.fileActions()[row]) {
- .cut, .extract, .properties => true,
+ .cut, .extract, .restore, .properties => true,
else => false,
},
.background => row == 2,
@@ -139,11 +139,35 @@ pub fn menuIcon(self: *App, row: usize) ?IconId {
// Reuse the shell glyphs until dedicated file-action artwork is available.
return switch (self.menu orelse return null) {
.file => self.fileActions()[row].icon(),
- .background => if (self.history.archive_len > 0 or self.isRecent()) .refresh else ([_]IconId{ .plus, .edit, .paste, .refresh })[row],
+ .background => switch (self.backgroundMenu()) {
+ .refresh_only => .refresh,
+ .trash => ([_]IconId{ .trash, .undo, .refresh })[row],
+ .normal => ([_]IconId{ .plus, .edit, .paste, .refresh })[row],
+ },
else => null,
};
}
+/// What the empty-space menu offers: Recent and archives only refresh, the
+/// Trash view manages its contents, other folders create and paste.
+pub fn backgroundMenu(self: *App) enum { normal, refresh_only, trash } {
+ if (self.history.archive_len > 0 or self.isRecent()) return .refresh_only;
+ return switch (self.trashRelation()) {
+ .none => .normal,
+ .root => .trash,
+ .inside => .refresh_only,
+ };
+}
+
+/// Restore stays visible but faded when no selected entry has the metadata
+/// to say where it belongs.
+pub fn menuDisabled(self: *App, row: usize) bool {
+ return switch (self.menu orelse return false) {
+ .file => row < self.fileActions().len and self.fileActions()[row] == .restore and !self.trash_restorable,
+ else => false,
+ };
+}
+
// Faint shortcut text shown on the right of a context-menu row.
pub fn menuHint(self: *App, row: usize) ?[]const u8 {
const label = self.menuLabels()[row];
@@ -205,6 +229,14 @@ pub fn fileActions(self: *App) []const FileAction {
}
if (only_transfers) return &.{.open};
if (self.history.archive_len > 0) return &.{.open};
+ // Entries here are already deleted: put back or remove for good, but never
+ // cut, rename, paste or trash again. Folders inside a trashed folder have
+ // no metadata, so they only open, copy and show properties.
+ switch (self.trashRelation()) {
+ .root => return &.{ .open, .copy, .restore, .delete_permanently, .properties },
+ .inside => return &.{ .open, .copy, .properties },
+ .none => {},
+ }
if (self.isRecent()) {
if (self.selectedAppImage() != null) return &.{ .open, .open_with, .add_application, .cut, .copy, .rename, .trash, .properties };
if (self.selectedArchive() != null) return &.{ .open, .open_with, .extract, .extract_to, .cut, .copy, .rename, .trash, .properties };
@@ -258,7 +290,11 @@ pub fn menuLabels(self: *App) []const []const u8 {
for (actions, 0..) |action, i| self.place_menu_labels[i] = action.label();
return self.place_menu_labels[0..actions.len];
},
- .background => if (self.history.archive_len > 0 or self.isRecent()) &.{i18n.msg("Refresh")} else &.{ i18n.msg("New Folder"), i18n.msg("New File"), i18n.msg("Paste"), i18n.msg("Refresh") },
+ .background => switch (self.backgroundMenu()) {
+ .refresh_only => &.{i18n.msg("Refresh")},
+ .trash => &.{ i18n.msg("Empty Trash…"), i18n.msg("Restore All"), i18n.msg("Refresh") },
+ .normal => &.{ i18n.msg("New Folder"), i18n.msg("New File"), i18n.msg("Paste"), i18n.msg("Refresh") },
+ },
.chooser_filter => return self.chooser_filter_labels.items,
};
for (messages, 0..) |message, i| self.menu_label_text[i] = message.get();
@@ -267,6 +303,7 @@ pub fn menuLabels(self: *App) []const []const u8 {
pub fn openMenu(self: *App, kind: MenuKind, x: f64, y: f64) void {
self.menu = kind;
+ if (kind == .file) self.refreshTrashRestorable();
const height = self.menuHeight();
self.menu_x = std.math.clamp(x, 4, @max(4, @as(f64, @floatFromInt(self.w)) - self.menuWidth() - 4));
self.menu_y = std.math.clamp(y, 4, @max(4, @as(f64, @floatFromInt(self.h)) - height - 4));
@@ -286,6 +323,10 @@ pub fn runMenu(self: *App, row: usize) void {
const kind = self.menu orelse return;
const place_action: ?PlaceAction = if ((kind == .sidebar or kind == .device) and row < self.placeActions().len) self.placeActions()[row] else null;
const file_action: ?FileAction = if (kind == .file and row < self.fileActions().len) self.fileActions()[row] else null;
+ if (file_action == .restore and !self.trash_restorable) {
+ self.setStatusNotice(tr("Original location unknown: these items have no Trash information"), true);
+ return;
+ }
self.menu = null;
switch (kind) {
.sidebar, .device => if (place_action) |action| switch (action) {
@@ -351,16 +392,26 @@ pub fn runMenu(self: *App, row: usize) void {
.copy => self.copySelected(),
.paste => self.paste_requested = true,
.rename => self.openRenameDialog(),
- .trash => self.openTrashConfirmDialog(),
+ .trash, .delete_permanently => self.openTrashConfirmDialog(),
+ .restore => self.restoreSelected(),
.size => self.calculateSizeSelected(),
.properties => self.openSelectedProperties(),
},
- .background => if (self.history.archive_len > 0 or self.isRecent()) self.refresh() else switch (row) {
- 0 => self.openNewFolderDialog(),
- 1 => self.openNewFileDialog(),
- 2 => self.paste_requested = true,
- 3 => self.refresh(),
- else => {},
+ .background => switch (self.backgroundMenu()) {
+ .refresh_only => self.refresh(),
+ .trash => switch (row) {
+ 0 => self.openEmptyTrashDialog(),
+ 1 => self.restoreAll(),
+ 2 => self.refresh(),
+ else => {},
+ },
+ .normal => switch (row) {
+ 0 => self.openNewFolderDialog(),
+ 1 => self.openNewFileDialog(),
+ 2 => self.paste_requested = true,
+ 3 => self.refresh(),
+ else => {},
+ },
},
}
self.invalidate();
@@ -382,6 +433,7 @@ pub fn renderMenu(self: *App, cr: *c.cairo_t) void {
.hint = if (context) self.menuHint(i) else null,
.selected = self.menu_selected == i,
.separator = self.menuSeparatorBefore(i),
+ .disabled = self.menuDisabled(i),
}, context);
}
}
diff --git a/src/files/app_model.zig b/src/files/app_model.zig
index 9e8223e..a535b6d 100644
--- a/src/files/app_model.zig
+++ b/src/files/app_model.zig
@@ -51,6 +51,9 @@ pub const FileAction = enum {
paste,
rename,
trash,
+ /// In the Trash: put the entry back, or remove it for good.
+ restore,
+ delete_permanently,
size,
properties,
pub fn label(self: FileAction) []const u8 {
@@ -65,6 +68,8 @@ pub const FileAction = enum {
.paste => tr("Paste"),
.rename => tr("Rename"),
.trash => tr("Move to Trash"),
+ .restore => tr("Restore"),
+ .delete_permanently => tr("Delete Permanently"),
.size => tr("Calculate size"),
.properties => tr("Properties"),
};
@@ -79,7 +84,8 @@ pub const FileAction = enum {
.copy => .copy,
.paste => .paste,
.rename => .edit,
- .trash => .trash,
+ .trash, .delete_permanently => .trash,
+ .restore => .undo,
.size, .properties => .view_list,
};
}
diff --git a/src/files/app_tests.zig b/src/files/app_tests.zig
index f97c286..81d86ff 100644
--- a/src/files/app_tests.zig
+++ b/src/files/app_tests.zig
@@ -527,3 +527,7 @@ test {
test {
_ = @import("app_views_tests.zig");
}
+
+test {
+ _ = @import("app_trash_tests.zig");
+}
diff --git a/src/files/app_trash.zig b/src/files/app_trash.zig
new file mode 100644
index 0000000..069e687
--- /dev/null
+++ b/src/files/app_trash.zig
@@ -0,0 +1,117 @@
+//! Files' Trash view: where we are relative to the trash, what is offered
+//! there, and restoring or deleting its entries (the work is in trash.zig).
+
+const std = @import("std");
+const i18n = @import("i18n");
+const tr = i18n.tr;
+const App = @import("app.zig").App;
+const trash = @import("trash.zig");
+
+/// Where the current location lies relative to the home trash.
+pub fn trashRelation(self: *const App) trash.Relation {
+ const dir = self.trash_dir orelse return .none;
+ return trash.relation(dir, self.history.current);
+}
+
+/// The Trash view or a folder inside it.
+pub fn inTrash(self: *const App) bool {
+ return trashRelation(self) != .none;
+}
+
+/// Nothing is created in, renamed in or moved out of the Trash by hand: new
+/// entries would have no metadata and moved ones would leave theirs behind.
+/// Restore puts items back, Copy takes a duplicate. Says why when it applies.
+pub fn trashReadOnly(self: *App) bool {
+ if (!inTrash(self)) return false;
+ self.setStatusNotice(tr("Trash can't be edited. Restore items to change them."), false);
+ return true;
+}
+
+/// Whether the file menu may offer Restore: at least one selected entry has
+/// usable metadata. Worked out when the menu opens, not on every paint.
+pub fn refreshTrashRestorable(self: *App) void {
+ self.trash_restorable = false;
+ if (trashRelation(self) != .root) return;
+ const dir = self.trash_dir.?;
+ for (self.items.items) |item| {
+ if (!item.selected or item.missing) continue;
+ if (trash.restorable(self.allocator, dir, std.fs.path.basename(item.path))) {
+ self.trash_restorable = true;
+ return;
+ }
+ }
+}
+
+pub fn restoreSelected(self: *App) void {
+ if (trashRelation(self) != .root) return;
+ var names: std.ArrayList([]const u8) = .empty;
+ defer names.deinit(self.allocator);
+ for (self.items.items) |item| {
+ if (!item.selected or item.missing) continue;
+ names.append(self.allocator, std.fs.path.basename(item.path)) catch {
+ self.setStatusNotice(tr("Could not restore the selected items"), true);
+ return;
+ };
+ }
+ if (names.items.len == 0) return;
+ restore(self, names.items);
+}
+
+pub fn restoreAll(self: *App) void {
+ if (trashRelation(self) != .root) return;
+ const names = trash.listEntries(self.allocator, self.trash_dir.?) catch {
+ self.setStatusNotice(tr("Could not restore the items in Trash"), true);
+ return;
+ };
+ defer self.allocator.free(names);
+ defer trash.freeNames(self.allocator, names);
+ if (names.len == 0) {
+ self.setStatusNotice(tr("Trash is empty"), false);
+ return;
+ }
+ const view: []const []const u8 = @ptrCast(names);
+ restore(self, view);
+}
+
+fn restore(self: *App, names: []const []const u8) void {
+ const summary = trash.restoreMany(self.allocator, self.trash_dir.?, names);
+ reportRestore(self, summary);
+ self.refresh();
+}
+
+/// "Restored 3 items. 1 kept under a new name. 1 has no Trash information."
+pub fn reportRestore(self: *App, summary: trash.Summary) void {
+ var buf: [384]u8 = undefined;
+ var len: usize = 0;
+ var piece: [128]u8 = undefined;
+ if (summary.restored > 0) {
+ const text = i18n.fmt(&piece, i18n.trn("Restored {count} item", "Restored {count} items", summary.restored), .{ .count = summary.restored }) catch tr("Restored");
+ len = append(&buf, len, text);
+ }
+ if (summary.renamed > 0) {
+ const text = i18n.fmt(&piece, tr("{count} kept under a new name"), .{ .count = summary.renamed }) catch tr("Some kept under a new name");
+ len = append(&buf, len, text);
+ }
+ if (summary.no_metadata > 0) {
+ const text = i18n.fmt(&piece, i18n.trn("{count} has no Trash information", "{count} have no Trash information", summary.no_metadata), .{ .count = summary.no_metadata }) catch tr("Some have no Trash information");
+ len = append(&buf, len, text);
+ }
+ if (summary.failed > 0) {
+ const text = i18n.fmt(&piece, tr("{count} could not be restored"), .{ .count = summary.failed }) catch tr("Some could not be restored");
+ len = append(&buf, len, text);
+ }
+ if (len == 0) return;
+ self.setStatusNotice(buf[0..len], summary.no_metadata > 0 or summary.failed > 0);
+}
+
+fn append(buf: []u8, len: usize, text: []const u8) usize {
+ var at = len;
+ if (at > 0 and at + 2 <= buf.len) {
+ buf[at] = '.';
+ buf[at + 1] = ' ';
+ at += 2;
+ }
+ const room = @min(text.len, buf.len - at);
+ @memcpy(buf[at .. at + room], text[0..room]);
+ return at + room;
+}
diff --git a/src/files/app_trash_tests.zig b/src/files/app_trash_tests.zig
new file mode 100644
index 0000000..1dfa925
--- /dev/null
+++ b/src/files/app_trash_tests.zig
@@ -0,0 +1,132 @@
+//! Files Trash view tests: which actions each location offers, and that the
+//! Trash stays read-only apart from Restore and permanent deletion.
+
+const std = @import("std");
+const App = @import("app.zig").App;
+const c = @import("c.zig").api;
+const FileAction = @import("app_model.zig").FileAction;
+const app_tests = @import("app_tests.zig");
+const testApp = app_tests.testApp;
+const testItems = app_tests.testItems;
+
+const trash_files = "/xdg/Trash/files";
+
+fn backgroundLabels(app: *App) []const []const u8 {
+ app.menu = .background;
+ return app.menuLabels();
+}
+
+fn trashApp() !App {
+ var app = try testApp();
+ errdefer app.deinit();
+ app.trash_dir = try std.testing.allocator.dupe(u8, trash_files);
+ try testItems(&app, 2);
+ app.items.items[0].selected = true;
+ return app;
+}
+
+test "the item menu is Trash-specific only in the Trash" {
+ var app = try trashApp();
+ defer app.deinit();
+
+ try std.testing.expect(std.mem.indexOfScalar(FileAction, app.fileActions(), .trash) != null);
+ try std.testing.expect(std.mem.indexOfScalar(FileAction, app.fileActions(), .restore) == null);
+
+ try app.history.navigate(trash_files);
+ try std.testing.expectEqualSlices(FileAction, &.{ .open, .copy, .restore, .delete_permanently, .properties }, app.fileActions());
+
+ try app.history.navigate(trash_files ++ "/Old Folder");
+ try std.testing.expectEqualSlices(FileAction, &.{ .open, .copy, .properties }, app.fileActions());
+}
+
+test "Restore is faded when no selected entry has metadata" {
+ var app = try trashApp();
+ defer app.deinit();
+ try app.history.navigate(trash_files);
+
+ app.openMenu(.file, 100, 100);
+ try std.testing.expect(!app.trash_restorable);
+ const restore_row = std.mem.indexOfScalar(FileAction, app.fileActions(), .restore).?;
+ try std.testing.expect(app.menuDisabled(restore_row));
+ try std.testing.expect(!app.menuDisabled(restore_row + 1));
+ // Activating it explains itself and leaves the menu open.
+ app.runMenu(restore_row);
+ try std.testing.expect(app.menu != null);
+ try std.testing.expect(app.status_is_error);
+}
+
+test "the empty-space menu manages the Trash and only refreshes inside it" {
+ var app = try trashApp();
+ defer app.deinit();
+
+ try std.testing.expectEqual(@as(usize, 4), backgroundLabels(&app).len);
+ try app.history.navigate(trash_files);
+ const labels = backgroundLabels(&app);
+ try std.testing.expectEqual(@as(usize, 3), labels.len);
+ try std.testing.expectEqualStrings("Empty Trash…", labels[0]);
+ try std.testing.expectEqualStrings("Restore All", labels[1]);
+ try std.testing.expectEqualStrings("Refresh", labels[2]);
+
+ try app.history.navigate(trash_files ++ "/Old Folder");
+ try std.testing.expectEqual(@as(usize, 1), backgroundLabels(&app).len);
+}
+
+test "toolbar buttons that create or move are off in the Trash" {
+ var app = try trashApp();
+ defer app.deinit();
+ const header = @import("header.zig");
+
+ for ([_]header.Action{ .new, .cut, .paste }) |action| try std.testing.expect(app.toolbarButtonEnabled(action));
+ try app.history.navigate(trash_files);
+ for ([_]header.Action{ .new, .cut, .paste }) |action| try std.testing.expect(!app.toolbarButtonEnabled(action));
+ try std.testing.expect(app.toolbarButtonEnabled(.copy));
+ try std.testing.expect(app.toolbarButtonEnabled(.trash));
+ try app.history.navigate(trash_files ++ "/Old Folder");
+ try std.testing.expect(!app.toolbarButtonEnabled(.trash));
+}
+
+test "Delete in the Trash asks for permanent deletion with no choice to make" {
+ var app = try trashApp();
+ defer app.deinit();
+ try app.history.navigate(trash_files);
+
+ for ([_]bool{ false, true }) |shift| {
+ app.shift = shift;
+ app.handleKey(c.XKB_KEY_Delete, "");
+ try std.testing.expect(app.dialog != null);
+ const state = app.dialog.?.deletion;
+ try std.testing.expect(state.in_trash and state.permanent and state.fixedChoice());
+ // The toggle has no area, so the dialog cannot be flipped to "Move to Trash".
+ try std.testing.expectEqual(@as(f32, 0), state.geometry(800, 600).toggle.w);
+ app.deleteAction(.toggle);
+ try std.testing.expect(app.dialog.?.deletion.permanent);
+ app.closeDialog();
+ }
+
+ // Inside a trashed folder the key explains instead of deleting.
+ try app.history.navigate(trash_files ++ "/Old Folder");
+ app.handleKey(c.XKB_KEY_Delete, "");
+ try std.testing.expect(app.dialog == null);
+}
+
+test "the Trash refuses new, renamed, cut and pasted items" {
+ var app = try trashApp();
+ defer app.deinit();
+ try app.history.navigate(trash_files);
+ app.focused_index = 0;
+
+ app.openNewFolderDialog();
+ app.openNewFileDialog();
+ app.openRenameDialog();
+ try std.testing.expect(app.dialog == null);
+ app.cutSelected();
+ try std.testing.expectEqual(@as(usize, 0), app.clipboard_paths.items.len);
+ // Copy still works, so items can be duplicated out of the Trash.
+ app.copySelected();
+ try std.testing.expectEqual(@as(usize, 1), app.clipboard_paths.items.len);
+
+ // Neither a paste nor a drop lands in the Trash or in a folder inside it.
+ try std.testing.expect(!app.executeTransfer(.copy, &.{"/tmp/a"}, trash_files, false));
+ try std.testing.expect(!app.executeTransfer(.move, &.{"/tmp/a"}, trash_files ++ "/Old Folder", true));
+ try std.testing.expect(app.status_is_error);
+}
diff --git a/src/files/client_dnd.zig b/src/files/client_dnd.zig
index 3606de9..8704519 100644
--- a/src/files/client_dnd.zig
+++ b/src/files/client_dnd.zig
@@ -235,7 +235,8 @@ pub fn startFileDrag(self: *Client) !void {
source.offer("text/uri-list");
source.offer("application/x-rediwm-file-transfer");
// The receiving file manager performs moves; upload targets choose copy.
- if (source.getVersion() >= 3) source.setActions(.{ .copy = true, .move = true });
+ // A move out of the Trash would leave the entry's metadata behind: Restore does it properly.
+ if (source.getVersion() >= 3) source.setActions(.{ .copy = true, .move = !self.app.inTrash() });
self.drag_source = clip;
self.app.cancelWheel();
self.app.cancelDrag();
diff --git a/src/files/trash.zig b/src/files/trash.zig
new file mode 100644
index 0000000..44ab001
--- /dev/null
+++ b/src/files/trash.zig
@@ -0,0 +1,443 @@
+//! The home trash (Freedesktop Trash specification 1.0): restoring and
+//! permanently deleting trashed entries, with their `.trashinfo` metadata.
+//!
+//! `files_dir` is `$XDG_DATA_HOME/Trash/files`; `info/` and `directorysizes`
+//! sit beside it. Only top-level entries of `files/` have metadata. Moving
+//! items *into* the trash stays with `gio trash` (`ops.trashItems`), which
+//! knows the per-volume rules; nothing here talks to GIO, so tests use plain
+//! fixture directories. Per-volume trashes (`$topdir/.Trash-$uid`) are not
+//! handled: their `Path=` is relative to the volume and comes from removable
+//! media, which needs its own containment checks.
+
+const std = @import("std");
+const c = @import("c.zig").api;
+const ops = @import("ops.zig");
+const Allocator = std.mem.Allocator;
+
+/// Where a path lies relative to the trash's `files/` directory.
+pub const Relation = enum {
+ /// Not in the trash.
+ none,
+ /// The `files/` directory itself: its entries are the trashed items.
+ root,
+ /// Inside a trashed folder: no metadata of its own.
+ inside,
+};
+
+/// By string, like the title and breadcrumb: `path` is a listing location.
+pub fn relation(files_dir: []const u8, path: []const u8) Relation {
+ var end = path.len;
+ while (end > 1 and path[end - 1] == '/') end -= 1;
+ const p = path[0..end];
+ if (std.mem.eql(u8, p, files_dir)) return .root;
+ if (p.len > files_dir.len and std.mem.startsWith(u8, p, files_dir) and p[files_dir.len] == '/') return .inside;
+ return .none;
+}
+
+pub const Info = struct {
+ /// Where the item was before it was trashed: absolute, normalised.
+ path: []u8,
+ /// `DeletionDate=` as written (local time, no zone), if present.
+ date: ?[]u8 = null,
+
+ pub fn deinit(self: Info, a: Allocator) void {
+ a.free(self.path);
+ if (self.date) |d| a.free(d);
+ }
+};
+
+pub const Restored = struct {
+ /// The final location, which differs from the original when it was taken.
+ path: []u8,
+ renamed: bool,
+
+ pub fn deinit(self: Restored, a: Allocator) void {
+ a.free(self.path);
+ }
+};
+
+pub const Summary = struct {
+ restored: usize = 0,
+ /// Included in `restored`: put back under a different name.
+ renamed: usize = 0,
+ /// No usable `.trashinfo`, so there is nowhere to put the entry.
+ no_metadata: usize = 0,
+ failed: usize = 0,
+};
+
+pub const Removed = struct { deleted: usize = 0, failed: usize = 0 };
+
+/// A trashed entry's name is a single path component of `files/`.
+pub fn validName(name: []const u8) bool {
+ if (name.len == 0 or name.len > 255) return false;
+ if (std.mem.eql(u8, name, ".") or std.mem.eql(u8, name, "..")) return false;
+ return std.mem.indexOfAny(u8, name, "/\x00") == null;
+}
+
+fn root(files_dir: []const u8) []const u8 {
+ return std.fs.path.dirname(files_dir) orelse "/";
+}
+
+fn within(dir: []const u8, path: []const u8) bool {
+ return std.mem.eql(u8, dir, path) or
+ (path.len > dir.len and std.mem.startsWith(u8, path, dir) and path[dir.len] == '/');
+}
+
+fn infoPath(buf: []u8, files_dir: []const u8, name: []const u8) ![:0]u8 {
+ return std.fmt.bufPrintSentinel(buf, "{s}/info/{s}.trashinfo", .{ root(files_dir), name }, 0) catch error.PathTooLong;
+}
+
+fn entryPath(buf: []u8, files_dir: []const u8, name: []const u8) ![:0]u8 {
+ return std.fmt.bufPrintSentinel(buf, "{s}/{s}", .{ files_dir, name }, 0) catch error.PathTooLong;
+}
+
+fn errno() c_int {
+ return std.c._errno().*;
+}
+
+fn readSmall(a: Allocator, path_z: [*:0]const u8, limit: usize) ![]u8 {
+ const fd = c.open(path_z, c.O_RDONLY | c.O_CLOEXEC);
+ if (fd < 0) return error.OpenFailed;
+ defer _ = c.close(fd);
+ var list: std.ArrayList(u8) = .empty;
+ errdefer list.deinit(a);
+ var buf: [4096]u8 = undefined;
+ while (true) {
+ const n = c.read(fd, &buf, buf.len);
+ if (n < 0) {
+ if (errno() == c.EINTR) continue;
+ return error.ReadFailed;
+ }
+ if (n == 0) break;
+ const len: usize = @intCast(n);
+ if (list.items.len + len > limit) return error.TooLarge;
+ try list.appendSlice(a, buf[0..len]);
+ }
+ return list.toOwnedSlice(a);
+}
+
+fn percentDecode(a: Allocator, text: []const u8) ![]u8 {
+ var out: std.ArrayList(u8) = .empty;
+ errdefer out.deinit(a);
+ var i: usize = 0;
+ while (i < text.len) : (i += 1) {
+ var ch = text[i];
+ if (ch == '%') {
+ if (i + 3 > text.len) return error.InvalidEscape;
+ ch = std.fmt.parseInt(u8, text[i + 1 .. i + 3], 16) catch return error.InvalidEscape;
+ i += 2;
+ }
+ try out.append(a, ch);
+ }
+ return out.toOwnedSlice(a);
+}
+
+/// Parses the `[Trash Info]` group of a `.trashinfo` file. `Path=` must be an
+/// absolute path without `.` or `..` components; anything else is invalid.
+pub fn parseInfo(a: Allocator, text: []const u8) !Info {
+ var in_group = false;
+ var found_group = false;
+ var raw_path: ?[]const u8 = null;
+ var raw_date: ?[]const u8 = null;
+ var lines = std.mem.splitScalar(u8, text, '\n');
+ while (lines.next()) |line_raw| {
+ const line = std.mem.trimEnd(u8, line_raw, "\r");
+ if (line.len > 0 and line[0] == '[') {
+ in_group = std.mem.eql(u8, std.mem.trimEnd(u8, line, " \t"), "[Trash Info]");
+ found_group = found_group or in_group;
+ continue;
+ }
+ if (!in_group) continue;
+ const eq = std.mem.indexOfScalar(u8, line, '=') orelse continue;
+ const key = std.mem.trim(u8, line[0..eq], " \t");
+ if (std.mem.eql(u8, key, "Path")) {
+ if (raw_path == null) raw_path = line[eq + 1 ..];
+ } else if (std.mem.eql(u8, key, "DeletionDate")) {
+ if (raw_date == null) raw_date = line[eq + 1 ..];
+ }
+ }
+ if (!found_group) return error.InvalidMetadata;
+ const encoded = raw_path orelse return error.InvalidMetadata;
+ const decoded = percentDecode(a, encoded) catch |err| switch (err) {
+ error.OutOfMemory => return error.OutOfMemory,
+ else => return error.InvalidMetadata,
+ };
+ defer a.free(decoded);
+ var end = decoded.len;
+ while (end > 1 and decoded[end - 1] == '/') end -= 1;
+ const path = decoded[0..end];
+ if (path.len < 2 or path[0] != '/' or path.len >= std.fs.max_path_bytes - 300) return error.InvalidMetadata;
+ if (std.mem.indexOfScalar(u8, path, 0) != null) return error.InvalidMetadata;
+ var parts = std.mem.splitScalar(u8, path[1..], '/');
+ while (parts.next()) |part| {
+ if (std.mem.eql(u8, part, ".") or std.mem.eql(u8, part, "..")) return error.InvalidMetadata;
+ }
+ const owned_path = try a.dupe(u8, path);
+ errdefer a.free(owned_path);
+ const owned_date: ?[]u8 = if (raw_date) |d| try a.dupe(u8, std.mem.trim(u8, d, " \t")) else null;
+ return .{ .path = owned_path, .date = owned_date };
+}
+
+/// The metadata of one top-level entry. `error.NoMetadata` when there is no
+/// `.trashinfo`, `error.InvalidMetadata` when it is unusable.
+pub fn readInfo(a: Allocator, files_dir: []const u8, name: []const u8) !Info {
+ if (!validName(name)) return error.InvalidName;
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const path = try infoPath(&buf, files_dir, name);
+ const text = readSmall(a, path, 16 * 1024) catch |err| switch (err) {
+ error.OutOfMemory => return error.OutOfMemory,
+ error.OpenFailed => return error.NoMetadata,
+ else => return error.InvalidMetadata,
+ };
+ defer a.free(text);
+ return parseInfo(a, text);
+}
+
+/// Whether `name` can be restored: it exists and its metadata names a place
+/// outside the trash.
+pub fn restorable(a: Allocator, files_dir: []const u8, name: []const u8) bool {
+ const info = readInfo(a, files_dir, name) catch return false;
+ defer info.deinit(a);
+ if (within(root(files_dir), info.path)) return false;
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const entry = entryPath(&buf, files_dir, name) catch return false;
+ var st: c.struct_stat = undefined;
+ return c.lstat(entry, &st) == 0;
+}
+
+fn isDir(path: []const u8) bool {
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const z = std.fmt.bufPrintSentinel(&buf, "{s}", .{path}, 0) catch return false;
+ var st: c.struct_stat = undefined;
+ return c.stat(z, &st) == 0 and (st.st_mode & c.S_IFMT) == c.S_IFDIR;
+}
+
+/// `mkdir -p`, remembering what it created so a failed restore can undo it.
+fn makeParents(a: Allocator, dir: []const u8, created: *std.ArrayList([]u8)) !void {
+ if (isDir(dir)) return;
+ if (std.fs.path.dirname(dir)) |parent| {
+ if (!std.mem.eql(u8, parent, dir)) try makeParents(a, parent, created);
+ }
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const z = std.fmt.bufPrintSentinel(&buf, "{s}", .{dir}, 0) catch return error.PathTooLong;
+ if (c.mkdir(z, 0o777) != 0) {
+ const err = errno();
+ if (err == c.EEXIST and isDir(dir)) return;
+ return switch (err) {
+ c.EACCES, c.EPERM, c.EROFS => error.AccessDenied,
+ else => error.NoParent,
+ };
+ }
+ const owned = try a.dupe(u8, dir);
+ errdefer a.free(owned);
+ try created.append(a, owned);
+}
+
+fn canEnterAndWrite(dir: []const u8) bool {
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const z = std.fmt.bufPrintSentinel(&buf, "{s}", .{dir}, 0) catch return false;
+ return c.access(z, c.W_OK | c.X_OK) == 0;
+}
+
+/// Puts `name` back where `.trashinfo` says it came from, never over an
+/// existing item: a taken name gets the first free "name (N).ext". Missing
+/// parent folders are recreated and removed again if the move fails.
+pub fn restoreEntry(a: Allocator, files_dir: []const u8, name: []const u8) !Restored {
+ if (!validName(name)) return error.InvalidName;
+ var src_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const src = try entryPath(&src_buf, files_dir, name);
+ var st: c.struct_stat = undefined;
+ if (c.lstat(src, &st) != 0) return error.NotFound;
+
+ const info = try readInfo(a, files_dir, name);
+ defer info.deinit(a);
+ if (within(root(files_dir), info.path)) return error.InvalidMetadata;
+
+ const parent = std.fs.path.dirname(info.path) orelse return error.InvalidMetadata;
+ const base = std.fs.path.basename(info.path);
+ if (!validName(base)) return error.InvalidMetadata;
+
+ var created: std.ArrayList([]u8) = .empty;
+ defer {
+ for (created.items) |dir| a.free(dir);
+ created.deinit(a);
+ }
+ var moved = false;
+ defer if (!moved) {
+ var i = created.items.len;
+ while (i > 0) : (i -= 1) {
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const z = std.fmt.bufPrintSentinel(&buf, "{s}", .{created.items[i - 1]}, 0) catch continue;
+ _ = c.rmdir(z);
+ }
+ };
+ try makeParents(a, parent, &created);
+ if (!canEnterAndWrite(parent)) return error.AccessDenied;
+
+ var attempt: usize = 0;
+ while (true) : (attempt += 1) {
+ const unique = try ops.generateUniqueName(a, parent, base);
+ defer a.free(unique);
+ const dest = try std.fs.path.join(a, &.{ parent, unique });
+ if (ops.moveItem(a, src, dest, null)) |_| {
+ moved = true;
+ removeMetadata(a, files_dir, name);
+ return .{ .path = dest, .renamed = !std.mem.eql(u8, unique, base) };
+ } else |err| {
+ a.free(dest);
+ // Lost a race for the name: pick again, never overwrite.
+ if (err == error.PathAlreadyExists and attempt < 8) continue;
+ return error.RestoreFailed;
+ }
+ }
+}
+
+/// Deletes the `.trashinfo` and the `directorysizes` line of `name`. The item
+/// itself is already gone, so a failure here only leaves harmless clutter.
+fn removeMetadata(a: Allocator, files_dir: []const u8, name: []const u8) void {
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ if (infoPath(&buf, files_dir, name)) |path| _ = c.unlink(path) else |_| {}
+ removeDirectorySize(a, files_dir, name) catch {};
+}
+
+fn sizeLineIsFor(a: Allocator, line: []const u8, name: []const u8) bool {
+ const first = std.mem.indexOfScalar(u8, line, ' ') orelse return false;
+ const second = std.mem.indexOfScalarPos(u8, line, first + 1, ' ') orelse return false;
+ const decoded = percentDecode(a, line[second + 1 ..]) catch return false;
+ defer a.free(decoded);
+ return std.mem.eql(u8, decoded, name);
+}
+
+/// Drops `name` from `directorysizes`, rewriting it through a temporary file
+/// and rename, as the specification asks of everyone who edits it.
+fn removeDirectorySize(a: Allocator, files_dir: []const u8, name: []const u8) !void {
+ var path_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const path = std.fmt.bufPrintSentinel(&path_buf, "{s}/directorysizes", .{root(files_dir)}, 0) catch return error.PathTooLong;
+ const data = readSmall(a, path, 16 * 1024 * 1024) catch return;
+ defer a.free(data);
+ var out: std.ArrayList(u8) = .empty;
+ defer out.deinit(a);
+ var changed = false;
+ var lines = std.mem.splitScalar(u8, data, '\n');
+ while (lines.next()) |line| {
+ if (line.len == 0) continue;
+ if (sizeLineIsFor(a, line, name)) {
+ changed = true;
+ continue;
+ }
+ try out.appendSlice(a, line);
+ try out.append(a, '\n');
+ }
+ if (!changed) return;
+ var tmp_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const tmp = std.fmt.bufPrintSentinel(&tmp_buf, "{s}/directorysizes.{d}", .{ root(files_dir), c.getpid() }, 0) catch return error.PathTooLong;
+ const fd = c.open(tmp, c.O_WRONLY | c.O_CREAT | c.O_EXCL | c.O_CLOEXEC, @as(c_uint, 0o600));
+ if (fd < 0) return error.WriteFailed;
+ var ok = true;
+ var written: usize = 0;
+ while (written < out.items.len) {
+ const n = c.write(fd, out.items[written..].ptr, out.items.len - written);
+ if (n <= 0) {
+ if (n < 0 and errno() == c.EINTR) continue;
+ ok = false;
+ break;
+ }
+ written += @intCast(n);
+ }
+ if (c.close(fd) != 0) ok = false;
+ if (!ok or c.rename(tmp, path) != 0) {
+ _ = c.unlink(tmp);
+ return error.WriteFailed;
+ }
+}
+
+/// Permanently removes one trashed entry and its metadata. The item goes
+/// first: a crash then leaves an orphaned `.trashinfo` (swept by
+/// `sweepOrphans`) instead of an item that can no longer be restored.
+pub fn deleteEntry(a: Allocator, files_dir: []const u8, name: []const u8) !void {
+ if (!validName(name)) return error.InvalidName;
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const entry = try entryPath(&buf, files_dir, name);
+ // deleteRecursive does not follow symlinks and treats a missing path as done.
+ ops.deleteRecursive(a, entry) catch return error.DeleteFailed;
+ removeMetadata(a, files_dir, name);
+}
+
+pub fn restoreMany(a: Allocator, files_dir: []const u8, names: []const []const u8) Summary {
+ var summary: Summary = .{};
+ for (names) |name| {
+ const restored = restoreEntry(a, files_dir, name) catch |err| {
+ switch (err) {
+ error.NoMetadata, error.InvalidMetadata => summary.no_metadata += 1,
+ else => summary.failed += 1,
+ }
+ continue;
+ };
+ defer restored.deinit(a);
+ summary.restored += 1;
+ if (restored.renamed) summary.renamed += 1;
+ }
+ return summary;
+}
+
+pub fn deleteMany(a: Allocator, files_dir: []const u8, names: []const []const u8) Removed {
+ var removed: Removed = .{};
+ for (names) |name| {
+ if (deleteEntry(a, files_dir, name)) |_| removed.deleted += 1 else |_| removed.failed += 1;
+ }
+ return removed;
+}
+
+/// Every top-level entry of `files/`, in directory order. Free with `freeNames`.
+pub fn listEntries(a: Allocator, files_dir: []const u8) ![][]u8 {
+ var names: std.ArrayList([]u8) = .empty;
+ errdefer names.deinit(a);
+ errdefer freeNames(a, names.items);
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const z = std.fmt.bufPrintSentinel(&buf, "{s}", .{files_dir}, 0) catch return error.PathTooLong;
+ const dir = c.opendir(z) orelse return names.toOwnedSlice(a);
+ defer _ = c.closedir(dir);
+ while (true) {
+ std.c._errno().* = 0;
+ const entry = c.readdir(dir) orelse break;
+ const name = std.mem.span(@as([*:0]const u8, @ptrCast(&entry.*.d_name)));
+ if (std.mem.eql(u8, name, ".") or std.mem.eql(u8, name, "..")) continue;
+ const owned = try a.dupe(u8, name);
+ errdefer a.free(owned);
+ try names.append(a, owned);
+ }
+ return names.toOwnedSlice(a);
+}
+
+pub fn freeNames(a: Allocator, names: []const []u8) void {
+ for (names) |name| a.free(name);
+}
+
+/// Removes `.trashinfo` files whose item no longer exists (a crash between the
+/// two deletions, or an item moved out by other means).
+pub fn sweepOrphans(a: Allocator, files_dir: []const u8) void {
+ var dir_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const info_dir = std.fmt.bufPrintSentinel(&dir_buf, "{s}/info", .{root(files_dir)}, 0) catch return;
+ const dir = c.opendir(info_dir) orelse return;
+ var orphans: std.ArrayList([]u8) = .empty;
+ defer {
+ for (orphans.items) |name| a.free(name);
+ orphans.deinit(a);
+ }
+ while (true) {
+ const entry = c.readdir(dir) orelse break;
+ const file = std.mem.span(@as([*:0]const u8, @ptrCast(&entry.*.d_name)));
+ if (!std.mem.endsWith(u8, file, ".trashinfo")) continue;
+ const stem = file[0 .. file.len - ".trashinfo".len];
+ if (!validName(stem)) continue;
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const item = entryPath(&buf, files_dir, stem) catch continue;
+ var st: c.struct_stat = undefined;
+ if (c.lstat(item, &st) == 0 or errno() != c.ENOENT) continue;
+ const owned = a.dupe(u8, stem) catch continue;
+ orphans.append(a, owned) catch a.free(owned);
+ }
+ _ = c.closedir(dir);
+ // Unlink after the scan so the directory is not changed while it is read.
+ for (orphans.items) |stem| removeMetadata(a, files_dir, stem);
+}
diff --git a/src/files/trash_tests.zig b/src/files/trash_tests.zig
new file mode 100644
index 0000000..842b7fc
--- /dev/null
+++ b/src/files/trash_tests.zig
@@ -0,0 +1,374 @@
+//! Trash restore and permanent-delete tests on fixture trash directories.
+
+const std = @import("std");
+const trash = @import("trash.zig");
+const ops = @import("ops.zig");
+const c = @import("c.zig").api;
+const files_tests = @import("../files_tests.zig");
+const ops_tests = @import("ops_tests.zig");
+
+const allocator = std.testing.allocator;
+
+fn exists(path: []const u8) bool {
+ var buf: [4096]u8 = undefined;
+ const z = std.fmt.bufPrintSentinel(&buf, "{s}", .{path}, 0) catch return false;
+ var st: c.struct_stat = undefined;
+ return c.lstat(z, &st) == 0;
+}
+
+fn encode(arena: std.mem.Allocator, path: []const u8) ![]u8 {
+ var out: std.ArrayList(u8) = .empty;
+ for (path) |ch| {
+ if (std.ascii.isAlphanumeric(ch) or ch == '/' or ch == '-' or ch == '_' or ch == '.' or ch == '~') {
+ try out.append(arena, ch);
+ } else try out.print(arena, "%{X:0>2}", .{ch});
+ }
+ return out.items;
+}
+
+const Fixture = struct {
+ arena: std.heap.ArenaAllocator,
+ tmp_buf: [256]u8 = undefined,
+ tmp: []const u8 = "",
+ /// `$XDG_DATA_HOME/Trash/files`.
+ files: []const u8 = "",
+ /// A stand-in for the home directory, where items came from.
+ home: []const u8 = "",
+
+ fn init(self: *Fixture) !void {
+ self.arena = std.heap.ArenaAllocator.init(allocator);
+ errdefer self.arena.deinit();
+ self.tmp = try files_tests.makeTestDir(&self.tmp_buf);
+ const a = self.arena.allocator();
+ for ([_][]const u8{ "Trash", "Trash/files", "Trash/info", "home" }) |dir| {
+ const full = try std.fmt.allocPrint(a, "{s}/{s}", .{ self.tmp, dir });
+ if (c.mkdir(try a.dupeSentinel(u8, full, 0), 0o755) != 0) return error.MkdirFailed;
+ }
+ self.files = try self.path("Trash/files");
+ self.home = try self.path("home");
+ }
+
+ fn deinit(self: *Fixture) void {
+ ops.deleteRecursive(allocator, self.tmp) catch {};
+ self.arena.deinit();
+ }
+
+ fn path(self: *Fixture, rel: []const u8) ![]const u8 {
+ return std.fmt.allocPrint(self.arena.allocator(), "{s}/{s}", .{ self.tmp, rel });
+ }
+
+ fn home_path(self: *Fixture, rel: []const u8) ![]const u8 {
+ return std.fmt.allocPrint(self.arena.allocator(), "{s}/{s}", .{ self.home, rel });
+ }
+
+ /// A trashed file or folder named `name` that came from `origin`.
+ fn put(self: *Fixture, name: []const u8, origin: []const u8, is_dir: bool, content: []const u8) !void {
+ const a = self.arena.allocator();
+ const item = try std.fmt.allocPrint(a, "{s}/{s}", .{ self.files, name });
+ if (is_dir) {
+ try ops.createFolder(allocator, self.files, name);
+ if (content.len > 0) try ops_tests.writeTestFile(try std.fmt.allocPrint(a, "{s}/inner.txt", .{item}), content);
+ } else try ops_tests.writeTestFile(item, content);
+ try self.info(name, origin);
+ }
+
+ fn info(self: *Fixture, name: []const u8, origin: []const u8) !void {
+ const a = self.arena.allocator();
+ const text = try std.fmt.allocPrint(a, "[Trash Info]\nPath={s}\nDeletionDate=2026-11-03T12:00:00\n", .{try encode(a, origin)});
+ try ops_tests.writeTestFile(try self.path(try std.fmt.allocPrint(a, "Trash/info/{s}.trashinfo", .{name})), text);
+ }
+
+ fn infoExists(self: *Fixture, name: []const u8) !bool {
+ return exists(try self.path(try std.fmt.allocPrint(self.arena.allocator(), "Trash/info/{s}.trashinfo", .{name})));
+ }
+};
+
+fn expectContent(path: []const u8, expected: []const u8) !void {
+ var buf: [256]u8 = undefined;
+ try std.testing.expectEqualStrings(expected, try ops_tests.readTestFile(path, &buf));
+}
+
+test "relation tells the trash root from folders inside it" {
+ const files = "/home/u/.local/share/Trash/files";
+ try std.testing.expectEqual(trash.Relation.root, trash.relation(files, files));
+ try std.testing.expectEqual(trash.Relation.root, trash.relation(files, files ++ "/"));
+ try std.testing.expectEqual(trash.Relation.inside, trash.relation(files, files ++ "/dir"));
+ try std.testing.expectEqual(trash.Relation.inside, trash.relation(files, files ++ "/dir/sub/"));
+ try std.testing.expectEqual(trash.Relation.none, trash.relation(files, files ++ "2"));
+ try std.testing.expectEqual(trash.Relation.none, trash.relation(files, "/home/u/.local/share/Trash"));
+ try std.testing.expectEqual(trash.Relation.none, trash.relation(files, "/home/u"));
+}
+
+test "parseInfo reads the Trash Info group and rejects unusable metadata" {
+ const info = try trash.parseInfo(allocator, "[Trash Info]\r\nPath=/home/u/caf%C3%A9%20menu.txt\r\nDeletionDate=2026-11-03T11:36:35\r\n");
+ defer info.deinit(allocator);
+ try std.testing.expectEqualStrings("/home/u/café menu.txt", info.path);
+ try std.testing.expectEqualStrings("2026-11-03T11:36:35", info.date.?);
+
+ // Only the [Trash Info] group counts, and a trailing slash is dropped.
+ const other = try trash.parseInfo(allocator, "[Other]\nPath=/wrong\n[Trash Info]\nPath=/right/dir/\n");
+ defer other.deinit(allocator);
+ try std.testing.expectEqualStrings("/right/dir", other.path);
+ try std.testing.expectEqual(@as(?[]u8, null), other.date);
+
+ for ([_][]const u8{
+ "",
+ "Path=/no/group\n",
+ "[Trash Info]\nDeletionDate=2026-11-03T11:36:35\n",
+ "[Trash Info]\nPath=relative/file\n",
+ "[Trash Info]\nPath=/\n",
+ "[Trash Info]\nPath=/a/../b\n",
+ "[Trash Info]\nPath=/a/./b\n",
+ "[Trash Info]\nPath=/a%00b\n",
+ "[Trash Info]\nPath=/a%4\n",
+ "[Trash Info]\nPath=/a%zz\n",
+ "[Other]\nPath=/a\n",
+ }) |text| {
+ try std.testing.expectError(error.InvalidMetadata, trash.parseInfo(allocator, text));
+ }
+}
+
+test "restoring puts a file back and removes its metadata" {
+ var fx: Fixture = undefined;
+ try fx.init();
+ defer fx.deinit();
+ const origin = try fx.home_path("note.txt");
+ try fx.put("note.txt", origin, false, "kept");
+
+ const restored = try trash.restoreEntry(allocator, fx.files, "note.txt");
+ defer restored.deinit(allocator);
+ try std.testing.expectEqualStrings(origin, restored.path);
+ try std.testing.expect(!restored.renamed);
+ try expectContent(origin, "kept");
+ try std.testing.expect(!exists(try fx.path("Trash/files/note.txt")));
+ try std.testing.expect(!try fx.infoExists("note.txt"));
+}
+
+test "restoring uses the original name, not the one chosen when trashing" {
+ var fx: Fixture = undefined;
+ try fx.init();
+ defer fx.deinit();
+ const origin = try fx.home_path("report.txt");
+ try fx.put("report.2.txt", origin, false, "second");
+
+ const restored = try trash.restoreEntry(allocator, fx.files, "report.2.txt");
+ defer restored.deinit(allocator);
+ try std.testing.expectEqualStrings(origin, restored.path);
+ try expectContent(origin, "second");
+}
+
+test "restoring never overwrites: a taken name gets a unique one" {
+ var fx: Fixture = undefined;
+ try fx.init();
+ defer fx.deinit();
+ const origin = try fx.home_path("a.txt");
+ try ops_tests.writeTestFile(origin, "current");
+ try fx.put("a.txt", origin, false, "trashed");
+
+ const first = try trash.restoreEntry(allocator, fx.files, "a.txt");
+ defer first.deinit(allocator);
+ try std.testing.expect(first.renamed);
+ try std.testing.expectEqualStrings(try fx.home_path("a (1).txt"), first.path);
+ try expectContent(origin, "current");
+ try expectContent(first.path, "trashed");
+ try std.testing.expect(!try fx.infoExists("a.txt"));
+
+ // A second trashed copy skips the name the first one took.
+ try fx.put("a.txt", origin, false, "again");
+ const second = try trash.restoreEntry(allocator, fx.files, "a.txt");
+ defer second.deinit(allocator);
+ try std.testing.expectEqualStrings(try fx.home_path("a (2).txt"), second.path);
+ try expectContent(first.path, "trashed");
+}
+
+test "a dangling symlink at the destination counts as taken" {
+ var fx: Fixture = undefined;
+ try fx.init();
+ defer fx.deinit();
+ const origin = try fx.home_path("link");
+ var buf: [4096]u8 = undefined;
+ try std.testing.expectEqual(@as(c_int, 0), c.symlink("/nonexistent/target", try std.fmt.bufPrintSentinel(&buf, "{s}", .{origin}, 0)));
+ try fx.put("link", origin, false, "data");
+
+ const restored = try trash.restoreEntry(allocator, fx.files, "link");
+ defer restored.deinit(allocator);
+ try std.testing.expect(restored.renamed);
+ try expectContent(restored.path, "data");
+ try std.testing.expect(exists(origin));
+}
+
+test "restoring recreates missing parent folders" {
+ var fx: Fixture = undefined;
+ try fx.init();
+ defer fx.deinit();
+ const origin = try fx.home_path("gone/deeper/file.txt");
+ try fx.put("file.txt", origin, false, "deep");
+
+ const restored = try trash.restoreEntry(allocator, fx.files, "file.txt");
+ defer restored.deinit(allocator);
+ try expectContent(origin, "deep");
+}
+
+test "a parent that cannot be created leaves the entry and creates nothing" {
+ var fx: Fixture = undefined;
+ try fx.init();
+ defer fx.deinit();
+ // "blocker" is a file, so "blocker/sub" can never be a folder.
+ try ops_tests.writeTestFile(try fx.home_path("blocker"), "x");
+ try fx.put("file.txt", try fx.home_path("blocker/sub/file.txt"), false, "stay");
+
+ try std.testing.expectError(error.NoParent, trash.restoreEntry(allocator, fx.files, "file.txt"));
+ try std.testing.expect(exists(try fx.path("Trash/files/file.txt")));
+ try std.testing.expect(try fx.infoExists("file.txt"));
+}
+
+test "an unwritable destination folder fails without touching the entry" {
+ if (c.geteuid() == 0) return error.SkipZigTest;
+ var fx: Fixture = undefined;
+ try fx.init();
+ defer fx.deinit();
+ const locked = try fx.home_path("locked");
+ try ops.createFolder(allocator, fx.home, "locked");
+ var buf: [4096]u8 = undefined;
+ const locked_z = try std.fmt.bufPrintSentinel(&buf, "{s}", .{locked}, 0);
+ try std.testing.expectEqual(@as(c_int, 0), c.chmod(locked_z, 0o555));
+ defer _ = c.chmod(locked_z, 0o755);
+ try fx.put("file.txt", try fx.home_path("locked/file.txt"), false, "stay");
+
+ try std.testing.expectError(error.AccessDenied, trash.restoreEntry(allocator, fx.files, "file.txt"));
+ try std.testing.expect(exists(try fx.path("Trash/files/file.txt")));
+ try std.testing.expect(try fx.infoExists("file.txt"));
+}
+
+test "entries without usable metadata are skipped and counted" {
+ var fx: Fixture = undefined;
+ try fx.init();
+ defer fx.deinit();
+ try fx.put("good.txt", try fx.home_path("good.txt"), false, "g");
+ // No .trashinfo at all, an unusable one, and one pointing into the trash.
+ try ops_tests.writeTestFile(try fx.path("Trash/files/bare.txt"), "b");
+ try ops_tests.writeTestFile(try fx.path("Trash/files/broken.txt"), "b");
+ try ops_tests.writeTestFile(try fx.path("Trash/info/broken.txt.trashinfo"), "[Trash Info]\nPath=relative\n");
+ try fx.put("inside.txt", try fx.path("Trash/files/elsewhere.txt"), false, "i");
+
+ try std.testing.expectError(error.NoMetadata, trash.restoreEntry(allocator, fx.files, "bare.txt"));
+ try std.testing.expectError(error.InvalidMetadata, trash.restoreEntry(allocator, fx.files, "broken.txt"));
+ try std.testing.expectError(error.InvalidMetadata, trash.restoreEntry(allocator, fx.files, "inside.txt"));
+ try std.testing.expect(trash.restorable(allocator, fx.files, "good.txt"));
+ try std.testing.expect(!trash.restorable(allocator, fx.files, "bare.txt"));
+ try std.testing.expect(!trash.restorable(allocator, fx.files, "broken.txt"));
+ try std.testing.expect(!trash.restorable(allocator, fx.files, "inside.txt"));
+ try std.testing.expect(!trash.restorable(allocator, fx.files, "missing.txt"));
+
+ const summary = trash.restoreMany(allocator, fx.files, &.{ "good.txt", "bare.txt", "broken.txt", "inside.txt", "../escape" });
+ try std.testing.expectEqual(@as(usize, 1), summary.restored);
+ try std.testing.expectEqual(@as(usize, 0), summary.renamed);
+ try std.testing.expectEqual(@as(usize, 3), summary.no_metadata);
+ try std.testing.expectEqual(@as(usize, 1), summary.failed);
+ // Skipped entries stay exactly where they were.
+ try std.testing.expect(exists(try fx.path("Trash/files/bare.txt")));
+ try std.testing.expect(exists(try fx.path("Trash/files/broken.txt")));
+ try std.testing.expect(exists(try fx.path("Trash/files/inside.txt")));
+}
+
+test "restoring a folder takes its directorysizes line and keeps the others" {
+ var fx: Fixture = undefined;
+ try fx.init();
+ defer fx.deinit();
+ const origin = try fx.home_path("Photos Old");
+ try fx.put("Photos Old", origin, true, "inner");
+ try fx.put("Other Dir", try fx.home_path("Other Dir"), true, "");
+ try ops_tests.writeTestFile(try fx.path("Trash/directorysizes"), "10 100 Photos%20Old\n20 200 Other%20Dir\n");
+
+ const restored = try trash.restoreEntry(allocator, fx.files, "Photos Old");
+ defer restored.deinit(allocator);
+ const inner = try fx.home_path("Photos Old/inner.txt");
+ try expectContent(inner, "inner");
+ var buf: [256]u8 = undefined;
+ try std.testing.expectEqualStrings("20 200 Other%20Dir\n", try ops_tests.readTestFile(try fx.path("Trash/directorysizes"), &buf));
+}
+
+test "deleting removes the item, its metadata and its directorysizes line" {
+ var fx: Fixture = undefined;
+ try fx.init();
+ defer fx.deinit();
+ const keep = try fx.home_path("keep.txt");
+ try ops_tests.writeTestFile(keep, "outside");
+ try fx.put("dir", try fx.home_path("dir"), true, "inner");
+ // A symlink inside the folder must not be followed.
+ var buf: [4096]u8 = undefined;
+ const link = try fx.path("Trash/files/dir/link");
+ try std.testing.expectEqual(@as(c_int, 0), c.symlink(try std.fmt.bufPrintSentinel(&buf, "{s}", .{keep}, 0), try fx.arena.allocator().dupeSentinel(u8, link, 0)));
+ try fx.put("file.txt", try fx.home_path("file.txt"), false, "f");
+ try ops_tests.writeTestFile(try fx.path("Trash/directorysizes"), "5 50 dir\n");
+
+ try trash.deleteEntry(allocator, fx.files, "dir");
+ try std.testing.expect(!exists(try fx.path("Trash/files/dir")));
+ try std.testing.expect(!try fx.infoExists("dir"));
+ try expectContent(keep, "outside");
+ var out: [64]u8 = undefined;
+ try std.testing.expectEqualStrings("", try ops_tests.readTestFile(try fx.path("Trash/directorysizes"), &out));
+ // Other entries are untouched.
+ try std.testing.expect(exists(try fx.path("Trash/files/file.txt")));
+ try std.testing.expect(try fx.infoExists("file.txt"));
+}
+
+test "deleting handles orphans, bad names and batches" {
+ var fx: Fixture = undefined;
+ try fx.init();
+ defer fx.deinit();
+ const outside = try fx.home_path("outside.txt");
+ try ops_tests.writeTestFile(outside, "safe");
+ try fx.put("a.txt", try fx.home_path("a.txt"), false, "a");
+ try fx.put("b.txt", try fx.home_path("b.txt"), false, "b");
+ // Metadata whose item is already gone.
+ try fx.info("ghost.txt", try fx.home_path("ghost.txt"));
+
+ try std.testing.expectError(error.InvalidName, trash.deleteEntry(allocator, fx.files, "../home/outside.txt"));
+ try std.testing.expectError(error.InvalidName, trash.deleteEntry(allocator, fx.files, ""));
+ try std.testing.expectError(error.InvalidName, trash.deleteEntry(allocator, fx.files, ".."));
+ try expectContent(outside, "safe");
+
+ const removed = trash.deleteMany(allocator, fx.files, &.{ "a.txt", "ghost.txt", "b.txt", "../x" });
+ try std.testing.expectEqual(@as(usize, 3), removed.deleted);
+ try std.testing.expectEqual(@as(usize, 1), removed.failed);
+ for ([_][]const u8{ "a.txt", "b.txt", "ghost.txt" }) |name| {
+ try std.testing.expect(!try fx.infoExists(name));
+ }
+ try expectContent(outside, "safe");
+}
+
+test "sweeping removes only metadata with no item" {
+ var fx: Fixture = undefined;
+ try fx.init();
+ defer fx.deinit();
+ try fx.put("live.txt", try fx.home_path("live.txt"), false, "l");
+ try fx.info("stale.txt", try fx.home_path("stale.txt"));
+ try fx.info("stale2", try fx.home_path("stale2"));
+ try ops_tests.writeTestFile(try fx.path("Trash/info/readme.md"), "not metadata");
+
+ trash.sweepOrphans(allocator, fx.files);
+ try std.testing.expect(try fx.infoExists("live.txt"));
+ try std.testing.expect(!try fx.infoExists("stale.txt"));
+ try std.testing.expect(!try fx.infoExists("stale2"));
+ try std.testing.expect(exists(try fx.path("Trash/info/readme.md")));
+}
+
+test "listing returns every top-level entry, hidden ones too" {
+ var fx: Fixture = undefined;
+ try fx.init();
+ defer fx.deinit();
+ try fx.put("one", try fx.home_path("one"), false, "1");
+ try fx.put(".hidden", try fx.home_path(".hidden"), false, "h");
+ try fx.put("folder", try fx.home_path("folder"), true, "x");
+
+ const names = try trash.listEntries(allocator, fx.files);
+ defer allocator.free(names);
+ defer trash.freeNames(allocator, names);
+ try std.testing.expectEqual(@as(usize, 3), names.len);
+ for ([_][]const u8{ "one", ".hidden", "folder" }) |want| {
+ var found = false;
+ for (names) |name| found = found or std.mem.eql(u8, name, want);
+ try std.testing.expect(found);
+ }
+}
diff --git a/src/files_tests.zig b/src/files_tests.zig
index 582e35e..0bf9d49 100644
--- a/src/files_tests.zig
+++ b/src/files_tests.zig
@@ -261,6 +261,7 @@ test {
_ = @import("files/thumbs.zig");
_ = @import("files/volumes.zig");
_ = @import("files/pins.zig");
+ _ = @import("files/trash_tests.zig");
_ = @import("files/terminal/tests.zig");
}
diff --git a/src/ui/context_menu.zig b/src/ui/context_menu.zig
index 66671e4..c7cf5bc 100644
--- a/src/ui/context_menu.zig
+++ b/src/ui/context_menu.zig
@@ -53,12 +53,14 @@ pub const Row = struct {
icon: ?IconId = null,
selected: bool = false,
separator: bool = false,
+ /// Shown faded, without a hover highlight; the owner ignores activation.
+ disabled: bool = false,
};
pub fn row(cr_any: *anyopaque, box: Rect, opts: Row, context: bool) void {
const cr: *c.cairo_t = @ptrCast(cr_any);
// Desktop menus use app surfaces without resolving the compositor's theme forApp.
- const foreground = theme.global.app_fg orelse theme.global.window_fg;
+ const foreground_color = theme.global.app_fg orelse theme.global.window_fg;
if (opts.separator) {
ui.setSource(cr, theme.global.app_divider);
c.cairo_set_line_width(cr, 1);
@@ -66,7 +68,9 @@ pub fn row(cr_any: *anyopaque, box: Rect, opts: Row, context: bool) void {
c.cairo_line_to(cr, box.x + box.w - 6, box.y - 3.5);
c.cairo_stroke(cr);
}
- if (opts.selected) {
+ var foreground = foreground_color;
+ if (opts.disabled) foreground[3] *= 0.4;
+ if (opts.selected and !opts.disabled) {
rounded(cr, box, if (context) 7 else 4);
ui.setSource(cr, if (context) theme.global.app_item_hover else theme.global.app_nav_selected);
c.cairo_fill(cr);
diff --git a/tests/files_trash.py b/tests/files_trash.py
new file mode 100644
index 0000000..151e26e
--- /dev/null
+++ b/tests/files_trash.py
@@ -0,0 +1,282 @@
+#!/usr/bin/env python3
+"""Files Trash view: restore, permanent delete, Restore All, Empty Trash and read-only rules.
+
+The trash is a fixture under a scratch XDG_DATA_HOME and `gio` is a fake, so
+nothing touches the host's trash. Ground truth is the filesystem.
+"""
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import time
+from urllib.parse import quote
+
+from files_browser import wait_for
+from ipc_client import IPCClient, spawn_compositor, stop_process
+
+ROOT = Path(__file__).resolve().parents[1]
+
+ESC, ENTER, TAB = 1, 28, 15
+CTRL, SHIFT = 29, 42
+KEY_A, KEY_N, KEY_X, KEY_L, F2 = 30, 49, 45, 38, 60
+HOME, UP, LEFT, RIGHT, DOWN, DELETE, MENU = 102, 103, 105, 106, 108, 111, 127
+
+
+def run():
+ with tempfile.TemporaryDirectory(prefix="rediwm-files-trash-") as directory:
+ tmp = Path(directory)
+ home = tmp / "home"
+ data = tmp / "data"
+ trash = data / "Trash"
+ files, info = trash / "files", trash / "info"
+ for d in (home, files, info, tmp / "bin", tmp / "state"):
+ d.mkdir(parents=True)
+ log = tmp / "gio.log"
+
+ def put(name, origin, content="", folder=False, meta=True):
+ """A trashed entry, with the .trashinfo gio would have written."""
+ item = files / name
+ if folder:
+ item.mkdir()
+ (item / "inner.txt").write_text(content)
+ else:
+ item.write_text(content)
+ if meta:
+ (info / (name + ".trashinfo")).write_text(
+ "[Trash Info]\nPath=" + quote(str(origin), safe="/") + "\nDeletionDate=2026-11-03T12:00:00\n")
+
+ put("a.txt", home / "a.txt", "alpha")
+ put("b.txt", home / "gone" / "dir" / "b.txt", "bravo")
+ put("c.txt", home / "c.txt", "charlie")
+ (home / "c.txt").write_text("current")
+ put("d dir", home / "d dir", "delta", folder=True)
+ put("e.txt", home / "e.txt", "echo")
+ put(".hidden", home / ".hidden", "shy")
+ put("nometa.txt", home / "nometa.txt", "no metadata", meta=False)
+ (info / "ghost.txt.trashinfo").write_text("[Trash Info]\nPath=" + str(home / "ghost.txt") + "\n")
+ (trash / "directorysizes").write_text("5 50 d%20dir\n7 70 other\n")
+
+ # A fake gio: Move to Trash is logged; Empty Trash removes the items but,
+ # like an interrupted run, leaves their metadata behind for us to sweep.
+ gio = tmp / "bin" / "gio"
+ gio.write_text(
+ "#!/bin/sh\n"
+ 'if [ "$1" = trash ] && [ "$2" = --empty ]; then\n'
+ f' find "{files}" -mindepth 1 -delete\n'
+ f' echo emptied >> "{log}"; exit 0\n'
+ "fi\n"
+ 'if [ "$1" = trash ] && [ "$2" = -- ]; then shift 2; '
+ f'for p in "$@"; do echo "trash $p" >> "{log}"; done; exit 0; fi\n'
+ "exit 1\n")
+ gio.chmod(0o755)
+
+ comp, comp_log = spawn_compositor(
+ tmp, config_content="[compositor]\nxwayland = false\n",
+ renderer=os.environ.get("REDIWM_TEST_RENDERER", "gles2"),
+ env_extra={"HOME": str(home), "XDG_DATA_HOME": str(data)})
+ peers = []
+ try:
+ with IPCClient(tmp).connect() as ipc:
+ display = next(p.name for p in tmp.glob("wayland-*") if not p.name.endswith(".lock"))
+ env = dict(os.environ, HOME=str(home), XDG_RUNTIME_DIR=str(tmp), XDG_DATA_HOME=str(data),
+ XDG_STATE_HOME=str(tmp / "state"), XDG_CONFIG_HOME=str(tmp / "config"),
+ REDIWM_CONFIG=str(tmp / "rediwm-config.toml"), WAYLAND_DISPLAY=display,
+ DBUS_SESSION_BUS_ADDRESS="unix:path=/nonexistent", REDIWM_FILES_DEVICES="0",
+ PATH=str(tmp / "bin") + ":" + os.environ["PATH"])
+ for name in ("DISPLAY", "REDIWM_SOCKET", "WAYLAND_DEBUG"):
+ env.pop(name, None)
+ with (tmp / "files.log").open("w") as out:
+ peers.append(subprocess.Popen([str(ROOT / "zig-out/bin/rediwm-files"), str(files)],
+ env=env, stdout=out, stderr=out))
+
+ def windows():
+ return [w for w in ipc.get_windows() if w["app_id"] == "rediwm-files"]
+
+ win = wait_for(lambda: next(iter(windows()), None), "Files did not map")
+ ipc.focus_window(win["id"])
+
+ def key(code, *mods):
+ for mod in mods:
+ ipc.key(mod, True)
+ ipc.key_down_up(code)
+ for mod in reversed(mods):
+ ipc.key(mod, False)
+ time.sleep(.15)
+
+ def title(value):
+ wait_for(lambda: windows() and windows()[0]["title"] == value + " — RediWM Files",
+ "Files did not reach " + value)
+
+ def settle():
+ time.sleep(.4)
+
+ def shot(name):
+ """Optional review pictures: REDIWM_TRASH_SHOTS=<directory>."""
+ if os.environ.get("REDIWM_TRASH_SHOTS"):
+ time.sleep(.3)
+ ipc.screenshot(str(Path(os.environ["REDIWM_TRASH_SHOTS"]) / (name + ".png")), window_id=win["id"])
+
+ def delete_key():
+ """Delete opens a confirmation; Enter before it is up would open the item instead."""
+ key(DELETE)
+ time.sleep(.4)
+
+ def select(index):
+ """Select the index-th item of the (name-sorted) listing."""
+ key(HOME)
+ for _ in range(index):
+ key(RIGHT)
+
+ def menu(*downs):
+ key(MENU)
+ for _ in range(downs[0] if downs else 0):
+ key(DOWN)
+
+ def gone(path):
+ return wait_for(lambda: not path.exists(), f"{path.name} was not removed")
+
+ title("Trash")
+ settle()
+
+ # Folders sort first: d dir, a.txt, b.txt, c.txt, e.txt, nometa.txt (.hidden is hidden).
+ # An entry without a .trashinfo cannot say where it belongs: Restore is faded and explains itself.
+ select(5)
+ menu(2)
+ shot("menu-no-metadata")
+ key(ENTER)
+ shot("notice-no-metadata")
+ key(ESC)
+ settle()
+ assert (files / "nometa.txt").exists() and not (home / "nometa.txt").exists()
+
+ # Restore one item from its context menu: Open, Copy, Restore, Delete Permanently, Properties.
+ select(1)
+ menu(2)
+ shot("menu-item")
+ key(ENTER)
+ wait_for(lambda: (home / "a.txt").exists(), "Restore did not put a.txt back")
+ assert (home / "a.txt").read_text() == "alpha"
+ gone(files / "a.txt")
+ gone(info / "a.txt.trashinfo")
+ assert (files / "b.txt").exists() and (info / "b.txt.trashinfo").exists(), "Restore touched other entries"
+ settle()
+
+ # Move to Trash is not offered: Delete deletes permanently, after confirmation.
+ select(3) # d dir, b.txt, c.txt, e.txt
+ delete_key()
+ shot("dialog-delete")
+ key(ESC)
+ settle()
+ assert (files / "e.txt").exists(), "Cancel deleted e.txt"
+ delete_key()
+ key(ENTER)
+ gone(files / "e.txt")
+ gone(info / "e.txt.trashinfo")
+ assert not log.exists() or "trash" not in log.read_text(), "Delete in Trash called gio trash"
+ assert (files / "c.txt").exists()
+ settle()
+
+ # The Trash is read-only apart from Restore and Delete.
+ key(ESC)
+ key(KEY_N, CTRL, SHIFT) # New Folder
+ key(ENTER)
+ key(KEY_N, CTRL) # New File
+ key(ENTER)
+ select(1) # b.txt
+ key(F2)
+ ipc.type_text("renamed") # would go to a rename dialog; there is none
+ time.sleep(.5)
+ assert sorted(p.name for p in files.iterdir()) == sorted(
+ [".hidden", "b.txt", "c.txt", "d dir", "nometa.txt"]), "Trash was edited: " + str(sorted(files.iterdir()))
+
+ # Restore All from the empty-space menu: Empty Trash…, Restore All, Refresh.
+ # Typing may have opened the search box; Escape closes it, then clears the selection.
+ key(ESC)
+ key(ESC)
+ menu(1)
+ shot("menu-background")
+ key(ENTER)
+ wait_for(lambda: (home / "gone/dir/b.txt").exists(), "Restore All did not recreate the parent folder")
+ assert (home / "gone/dir/b.txt").read_text() == "bravo"
+ # A taken name is never overwritten.
+ assert (home / "c.txt").read_text() == "current"
+ assert (home / "c (1).txt").read_text() == "charlie"
+ assert (home / "d dir/inner.txt").read_text() == "delta"
+ assert (home / ".hidden").read_text() == "shy", "Restore All skipped a hidden entry"
+ assert (trash / "directorysizes").read_text() == "7 70 other\n"
+ # An entry with no .trashinfo has nowhere to go and stays.
+ assert (files / "nometa.txt").read_text() == "no metadata"
+ assert sorted(p.name for p in files.iterdir()) == ["nometa.txt"], list(files.iterdir())
+ assert sorted(p.name for p in info.iterdir()) == ["ghost.txt.trashinfo"], list(info.iterdir())
+ settle()
+
+ # Several selected entries restore together; the one without metadata is skipped, not fatal.
+ for n in ("m1", "m2", "m3"):
+ put(n + ".txt", home / (n + ".txt"), n)
+ key(63) # F5
+ settle()
+ key(KEY_A, CTRL)
+ menu(2)
+ key(ENTER)
+ for n in ("m1", "m2", "m3"):
+ wait_for(lambda n=n: (home / (n + ".txt")).exists() and (home / (n + ".txt")).read_text() == n,
+ f"multi-select Restore skipped {n}.txt")
+ gone(info / (n + ".txt.trashinfo"))
+ assert sorted(p.name for p in files.iterdir()) == ["nometa.txt"], list(files.iterdir())
+ settle()
+
+ # Several selected entries are deleted together, metadata included (nometa.txt too).
+ for n in ("p1", "p2", "p3"):
+ put(n + ".txt", home / (n + ".txt"), n)
+ key(63)
+ settle()
+ key(KEY_A, CTRL)
+ delete_key()
+ key(ENTER)
+ wait_for(lambda: not list(files.iterdir()), "multi-select Delete left entries behind: " + str(list(files.iterdir())))
+ assert sorted(p.name for p in info.iterdir()) == ["ghost.txt.trashinfo"], list(info.iterdir())
+ assert not any((home / (n + ".txt")).exists() for n in ("p1", "p2", "p3")), "Delete restored instead of deleting"
+ put("left.txt", home / "left.txt", "l")
+ key(63)
+ settle()
+
+ # Empty Trash from the same menu; leftover metadata is swept.
+ key(ESC)
+ key(ESC)
+ menu(0)
+ key(ENTER) # opens the confirmation
+ time.sleep(.3)
+ shot("dialog-empty")
+ assert (files / "left.txt").exists(), "Empty Trash ran before confirmation"
+ key(ENTER)
+ wait_for(lambda: log.exists() and "emptied" in log.read_text(), "Empty Trash did not run gio trash --empty")
+ wait_for(lambda: not list(info.iterdir()), "orphaned metadata survived Empty Trash")
+ assert not list(files.iterdir())
+
+ # Elsewhere nothing changed: Move to Trash still goes through gio, and New works.
+ plain = tmp / "plain"
+ plain.mkdir()
+ (plain / "move-me.txt").write_text("m")
+ key(KEY_L, CTRL)
+ ipc.type_text(str(plain))
+ key(ENTER)
+ title("plain")
+ settle()
+ key(HOME)
+ delete_key()
+ key(ENTER)
+ wait_for(lambda: f"trash {plain / 'move-me.txt'}" in log.read_text(), "Move to Trash did not call gio trash")
+ key(KEY_N, CTRL, SHIFT)
+ ipc.type_text("made")
+ key(ENTER)
+ wait_for(lambda: (plain / "made").is_dir(), "New Folder no longer works outside the Trash")
+ finally:
+ for peer in peers:
+ stop_process(peer)
+ stop_process(comp)
+ print("files trash: ok")
+
+
+if __name__ == "__main__":
+ run()