fix(trash): list a large trash, empty it, and browse it by folder

A large trash never finished listing, so the Trash page kept the rows of
the last refresh that got anywhere, and Empty Trash listed the trash before
sending the delete and hung there (B293). The paging fix is in
proton-drive-rs 0.12.5.

- The refresh reads only nodes it has not stored yet, without unlocking
  file keys, keeps the time the server says each was trashed, and drops
  rows only once the whole listing is in.
- Empty Trash sends the delete at once under the trash call time limit
  and clears the stored listing. Restore and Delete Permanently drop their
  rows right away.
- Schema v47 indexes trash.parent_uid and drops the stored rows once, so
  they are read again with real deletion times.
- The Trash page groups items by the folder they were deleted from, opens
  deleted folders through the new ListTrashedFolder request, and has a
  search box and a switch back to one list. Restore and Delete Permanently
  on a folder row act on everything deleted from it.
- pdfs trash takes --by-folder and --folder UID.
This commit is contained in:
nvrl committed 2026-11-22 02:38:48 +01:00
1 parent f141d88d97
commit d0f9681593
30 files changed
+2661 -1306

No files matched your search

+42 -9
View File
@@ -1,6 +1,6 @@
//! `pdfs` — command-line front-end for the Proton Drive Linux client.
use std::collections::HashMap;
use std::collections::{BTreeMap, HashMap};
use std::fs::OpenOptions;
use std::io::Write;
use std::os::unix::fs::FileTypeExt;
@@ -436,7 +436,14 @@ enum Command {
Diagnostics,
/// List what is in the account's trash, with the uids the restore and
/// delete-forever commands take.
Trash,
Trash {
/// Group the trash by the folder each item was deleted from.
#[arg(long, conflicts_with = "folder")]
by_folder: bool,
/// List what a trashed folder holds, by its uid.
#[arg(long, value_name = "UID")]
folder: Option<String>,
},
/// Restore trashed items, by uid, to the folders they were trashed from.
Restore {
/// Node uids (`volume~link`), as printed by `pdfs trash`.
@@ -1139,7 +1146,7 @@ fn main() -> Result<()> {
Command::Upload { sources, parent } => cmd_upload(sources, parent),
Command::Transfers => cmd_transfers(),
Command::Diagnostics => cmd_diagnostics(),
Command::Trash => cmd_trash(),
Command::Trash { by_folder, folder } => cmd_trash(by_folder, folder),
Command::Restore { uids } => cmd_restore(uids),
Command::DeleteForever { uids } => cmd_delete_forever(uids),
Command::EmptyTrash => cmd_empty_trash(),
@@ -3617,17 +3624,37 @@ fn cmd_diagnostics() -> Result<()> {
Ok(())
}
fn cmd_trash() -> Result<()> {
let response = control_request(CtlRequest::ListTrash)?;
fn cmd_trash(by_folder: bool, folder: Option<String>) -> Result<()> {
let request = match folder {
Some(uid) => CtlRequest::ListTrashedFolder { uid },
None => CtlRequest::ListTrash,
};
let response = control_request(request)?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::Entries { entries } if entries.is_empty() => println!("(trash is empty)"),
CtlResponse::Entries { entries } if entries.is_empty() => println!("(nothing here)"),
CtlResponse::Entries { entries } if by_folder => {
let mut groups: BTreeMap<String, Vec<&pdfs_core::control::DirEntry>> = BTreeMap::new();
for e in entries.iter().filter(|e| e.trashed_parent.is_none()) {
let folder = match e.trashed_from.as_deref() {
None => "(unknown folder)".to_string(),
Some("") => "/".to_string(),
Some(path) => format!("/{path}"),
};
groups.entry(folder).or_default().push(e);
}
for (folder, items) in groups {
println!("{folder} ({} item(s))", items.len());
for e in items {
print_trashed(e, " ");
}
}
}
CtlResponse::Entries { entries } => {
for e in entries {
let kind = if e.is_dir { "d" } else { "-" };
println!("{kind} {:>12} {} [{}]", e.size, e.name, e.uid);
for e in &entries {
print_trashed(e, "");
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
@@ -3636,6 +3663,11 @@ fn cmd_trash() -> Result<()> {
Ok(())
}
fn print_trashed(e: &pdfs_core::control::DirEntry, indent: &str) {
let kind = if e.is_dir { "d" } else { "-" };
println!("{indent}{kind} {:>12} {} [{}]", e.size, e.name, e.uid);
}
fn cmd_restore(uids: Vec<String>) -> Result<()> {
match control_request(CtlRequest::Restore { uids })? {
CtlResponse::Ok { message } => println!("{message}"),
@@ -5091,6 +5123,7 @@ mod login_wait_tests {
shared_by_unverified: false,
trashed_at: 0,
trashed_from: None,
trashed_parent: None,
issue: None,
};
assert_eq!(shared_by_line(&entry), None, "no invitation, no line");
+59
View File
@@ -337,6 +337,12 @@ impl Demo {
Request::ListDir { path } => Response::Entries {
entries: self.dir(path),
},
Request::ListTrash => Response::Entries {
entries: self.trash(),
},
Request::ListTrashedFolder { uid } => Response::Entries {
entries: self.trashed_folder(uid),
},
Request::ReserveFileThumbGeneration => Response::FileThumbGeneration { generation: 1 },
Request::FileThumbs { items, .. } => Response::Thumbs {
items: items
@@ -591,6 +597,59 @@ impl Demo {
.collect()
}
/// The trash: things deleted from a few folders, and a deleted folder with
/// a file deleted from it before it went.
fn trash(&self) -> Vec<DirEntry> {
let item = |name: &str, size: u64, hours: i64, from: &str| DirEntry {
name: name.into(),
is_dir: size == 0,
size,
modified: self.now - 40 * DAY,
uid: format!("demo-trash~{from}/{name}"),
trashed_at: self.now - hours * 3600,
trashed_from: Some(from.into()),
..Default::default()
};
let mut inside = item("Draft 3.odt", 48_120, 30, "");
inside.uid = "demo-trash~Old drafts/Draft 3.odt".into();
inside.trashed_from = None;
inside.trashed_parent = Some("demo-trash~Work/Old drafts".into());
vec![
item("Budget 2025.ods", 51_200, 2, "Documents"),
item("Scan 0042.pdf", 1_204_331, 5, "Documents"),
item("Scan 0043.pdf", 1_198_002, 5, "Documents"),
item("IMG_2041.jpg", 3_402_112, 20, "Pictures/Lisbon"),
item("IMG_2042.jpg", 3_311_870, 20, "Pictures/Lisbon"),
item("IMG_2043.jpg", 3_587_004, 20, "Pictures/Lisbon"),
item("Old drafts", 0, 26, "Work"),
item("Meeting notes (copy).md", 6_120, 50, ""),
item("Invoice 118.pdf", 88_341, 80, "Taxes/2025"),
inside,
]
}
/// What the deleted folder in [`Self::trash`] holds.
fn trashed_folder(&self, uid: &str) -> Vec<DirEntry> {
if uid != "demo-trash~Work/Old drafts" {
return Vec::new();
}
let file = |name: &str, size: u64| DirEntry {
name: name.into(),
size,
modified: self.now - 50 * DAY,
uid: format!("demo-trash~Old drafts/{name}"),
trashed_parent: Some(uid.into()),
..Default::default()
};
let mut gone = file("Draft 3.odt", 48_120);
gone.trashed_at = self.now - 30 * 3600;
vec![
file("Draft 1.odt", 41_002),
file("Draft 2.odt", 44_870),
gone,
]
}
/// My files: folders first, then a few files, some of them pictures with
/// thumbnails. Any folder below the root holds the same few documents.
fn dir(&self, path: &str) -> Vec<DirEntry> {
+17 -2
View File
@@ -515,6 +515,13 @@ pub enum Request {
/// its `uid` — the handle for [`Request::Restore`] and
/// [`Request::DeleteForever`] — and its `path` is empty.
ListTrash,
/// List what a trashed folder holds, by the folder's `uid`. Replies with
/// [`Response::Entries`]; each entry's `trashed_parent` is that folder.
/// The contents went to the trash with the folder, so only the entries
/// [`Request::ListTrash`] also lists can be restored on their own.
ListTrashedFolder {
uid: String,
},
/// Restore trashed nodes, by uid, to the folders they were trashed from.
/// Replies with [`Response::Ok`].
Restore {
@@ -1566,8 +1573,8 @@ pub struct DirEntry {
#[serde(default)]
pub shared_by_unverified: bool,
/// When a [`Request::ListTrash`] entry went to the trash, epoch seconds; 0
/// when unknown, and for anything not in the trash. The API does not report
/// it to this client, so the daemon notes when it first saw the node there.
/// when unknown, and for anything not in the trash. Taken from the server;
/// when it gives none, the daemon notes when it first saw the node there.
#[serde(default)]
pub trashed_at: i64,
/// The folder a [`Request::ListTrash`] entry goes back to on restore, as a
@@ -1575,6 +1582,11 @@ pub struct DirEntry {
/// not known, and for anything not in the trash.
#[serde(default)]
pub trashed_from: Option<String>,
/// The trashed folder a [`Request::ListTrash`] entry was trashed inside, by
/// uid, when that folder is in the trash too; `None` otherwise. Lets a
/// front end show the trash as folders.
#[serde(default)]
pub trashed_parent: Option<String>,
/// Why Drive refused a change queued on the node, for a [`Request::ListDir`]
/// entry; `None` otherwise.
#[serde(default)]
@@ -3625,6 +3637,9 @@ mod tests {
fn trash_requests_roundtrip() {
let reqs = [
Request::ListTrash,
Request::ListTrashedFolder {
uid: "vol~folder".into(),
},
Request::Restore {
uids: vec!["vol~link".into(), "vol~other".into()],
},
+20 -1
View File
@@ -11,7 +11,7 @@ use super::Db;
use crate::Result;
/// Current schema version. Bump on every forward migration added below.
pub(super) const SCHEMA_VERSION: i64 = 46;
pub(super) const SCHEMA_VERSION: i64 = 47;
impl Db {
pub(super) fn migrate(&self) -> Result<()> {
@@ -501,6 +501,16 @@ impl Db {
tx.execute_batch(MIGRATION_V46_ALBUM_PHOTOS)?;
}
}
if current < 47 {
let has_trash: bool = tx.query_row(
"SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'trash'",
[],
|row| row.get::<_, i64>(0).map(|n| n > 0),
)?;
if has_trash {
tx.execute_batch(MIGRATION_V47)?;
}
}
tx.execute(
"INSERT INTO sync_state (key, value) VALUES ('schema_version', ?1)
ON CONFLICT(key) DO UPDATE SET value = excluded.value",
@@ -1480,3 +1490,12 @@ const MIGRATION_V46_ALBUM_PHOTOS: &str = "
ALTER TABLE album_photos ADD COLUMN resolved INTEGER NOT NULL DEFAULT 0;
UPDATE album_photos SET resolved=1 WHERE name IS NOT NULL;
";
/// Index the trash by parent, for browsing it by folder. The rows are dropped
/// so the next refresh reads them again with the time each was trashed, which
/// earlier builds did not get from the server and made up instead.
const MIGRATION_V47: &str = "
CREATE INDEX IF NOT EXISTS trash_parent ON trash(parent_uid);
DELETE FROM trash;
DELETE FROM sync_state WHERE key IN ('trash_synced_ms', 'trash_complete_ms');
";
+48
View File
@@ -650,6 +650,54 @@ fn trash_replace_lists_folders_first() {
assert!(db.trash_list().unwrap().is_empty());
}
fn stored_trash(uid: &str, name: &str, trashed_at: Option<i64>) -> StoredTrash {
StoredTrash {
uid: uid.into(),
name: name.into(),
is_dir: false,
size: 1,
mtime: 1,
parent_uid: None,
trashed_at,
}
}
#[test]
fn trash_upsert_keeps_other_rows_and_retain_drops_unlisted_ones() {
let db = Db::open_in_memory().unwrap();
db.trash_upsert(&[
stored_trash("a", "a.txt", Some(1)),
stored_trash("b", "b.txt", None),
])
.unwrap();
// A later refresh adds what is new without touching what it kept.
db.trash_upsert(&[
stored_trash("c", "c.txt", Some(3)),
stored_trash("b", "b2.txt", Some(2)),
])
.unwrap();
let mut names: Vec<String> = db
.trash_list()
.unwrap()
.into_iter()
.map(|i| i.name)
.collect();
names.sort();
assert_eq!(names, ["a.txt", "b2.txt", "c.txt"]);
// Rows the server no longer lists go; the listed ones stay.
let keep: std::collections::HashSet<String> = ["a", "c"].map(String::from).into();
assert_eq!(db.trash_retain(&keep).unwrap(), 1);
assert_eq!(db.trash_remove(&["a".into(), "gone".into()]).unwrap(), 1);
let left: Vec<String> = db
.trash_list()
.unwrap()
.into_iter()
.map(|i| i.uid)
.collect();
assert_eq!(left, ["c"]);
}
#[test]
fn state_stamps_round_trip_and_clear() {
let db = Db::open_in_memory().unwrap();
+55 -1
View File
@@ -1,6 +1,6 @@
//! Trashed nodes, persisted so the trash view opens without a round-trip.
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use rusqlite::params;
@@ -48,6 +48,60 @@ impl Db {
Ok(())
}
/// Add or update trashed nodes, keeping every other row.
pub fn trash_upsert(&self, items: &[StoredTrash]) -> Result<()> {
let mut conn = self.conn.lock();
let tx = conn.transaction()?;
{
let mut stmt = tx.prepare(
"INSERT INTO trash (uid, name, is_dir, size, mtime, parent_uid, trashed_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
ON CONFLICT(uid) DO UPDATE SET
name = excluded.name, is_dir = excluded.is_dir, size = excluded.size,
mtime = excluded.mtime, parent_uid = excluded.parent_uid,
trashed_at = excluded.trashed_at",
)?;
for item in items {
stmt.execute(params![
item.uid,
item.name,
item.is_dir as i64,
item.size,
item.mtime,
item.parent_uid,
item.trashed_at
])?;
}
}
tx.commit()?;
Ok(())
}
/// Drop the trashed nodes with these uids. Returns how many rows went.
pub fn trash_remove(&self, uids: &[String]) -> Result<usize> {
let mut conn = self.conn.lock();
let tx = conn.transaction()?;
let mut removed = 0;
{
let mut stmt = tx.prepare("DELETE FROM trash WHERE uid = ?1")?;
for uid in uids {
removed += stmt.execute(params![uid])?;
}
}
tx.commit()?;
Ok(removed)
}
/// Drop every trashed node not in `keep`. Returns how many rows went.
pub fn trash_retain(&self, keep: &HashSet<String>) -> Result<usize> {
let gone: Vec<String> = self
.trash_seen()?
.into_keys()
.filter(|uid| !keep.contains(uid))
.collect();
self.trash_remove(&gone)
}
/// The persisted trash listing, folders first then by name — the order the
/// Trash page shows it in.
pub fn trash_list(&self) -> Result<Vec<StoredTrash>> {
+4
View File
@@ -1342,6 +1342,10 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
Ok(entries) => CtlResponse::Entries { entries },
Err(e) => CtlResponse::error(e),
},
Ok(CtlRequest::ListTrashedFolder { uid }) => match core.list_trashed_folder(&uid) {
Ok(entries) => CtlResponse::Entries { entries },
Err(e) => CtlResponse::error(e),
},
Ok(CtlRequest::Restore { uids }) => match core.restore(&uids) {
Ok(n) => {
core.log_activity(ActivityKind::Restore, format!("{n} item(s)"), "", true);
+26 -1
View File
@@ -29,7 +29,7 @@ use proton_drive_rs::proton_sdk::error::Result;
use proton_drive_rs::proton_sdk::ids::{DriveEventId, NodeUid, ShareId};
use proton_drive_rs::{
AvailableNameTarget, Device, DeviceType, DriveEvent, DriveEventScopeId, Node, NodeMoveItem,
ProtonDriveClient, RevisionReader, Thumbnail, ThumbnailType,
ProtonDriveClient, RevisionReader, Thumbnail, ThumbnailType, TrashedNode,
};
/// One outcome per node of a batch request; see [`ProtonDriveClient::trash_nodes`].
@@ -180,6 +180,23 @@ pub(crate) trait DriveApi: Send + Sync {
async fn enumerate_trash_node_uids(&self) -> Result<Vec<NodeUid>>;
/// Permanently delete everything in the trash.
async fn empty_trash(&self) -> Result<()>;
/// As [`DriveApi::enumerate_nodes_light`], for nodes in the trash, each
/// with the time it was trashed when the server reports one.
async fn enumerate_trashed_nodes_light(&self, uids: &[NodeUid]) -> Result<Vec<TrashedNode>> {
Ok(self
.enumerate_nodes_light(uids)
.await?
.into_iter()
.map(|node| TrashedNode {
node,
trash_time: None,
})
.collect())
}
/// The account's storage, across every Proton product.
async fn quota(&self) -> Result<Quota>;
@@ -538,6 +555,14 @@ impl DriveApi for ProtonDriveClient {
ProtonDriveClient::enumerate_trash_node_uids(self).await
}
async fn enumerate_trashed_nodes_light(&self, uids: &[NodeUid]) -> Result<Vec<TrashedNode>> {
ProtonDriveClient::enumerate_trashed_nodes_light(self, uids).await
}
async fn empty_trash(&self) -> Result<()> {
ProtonDriveClient::empty_trash(self).await
}
async fn quota(&self) -> Result<Quota> {
ProtonDriveClient::quota(self).await
}
+194 -50
View File
@@ -75,7 +75,7 @@ use proton_drive_rs::proton_sdk::error::ProtonError;
use proton_drive_rs::proton_sdk::ids::{DriveEventId, LinkId, NodeUid, ShareId, VolumeId};
use proton_drive_rs::{
AvailableNameTarget, DriveEvent, DriveEventScopeId, MemberRole, Node, NodeKind, NodeMoveItem,
ProtonDriveClient, ProtonPhotosClient, SharedWithMeItem, ThumbnailType,
ProtonDriveClient, ProtonPhotosClient, SharedWithMeItem, ThumbnailType, TrashedNode,
};
mod albums;
@@ -4611,6 +4611,7 @@ impl Core {
shared_by_unverified: false,
trashed_at: 0,
trashed_from: None,
trashed_parent: None,
issue: state::ino_lid(ino)
.and_then(|lid| issues.get(&lid))
.map(|issue| SyncIssue::parse(issue)),
@@ -5604,20 +5605,29 @@ impl Core {
self.await_trash_refresh(TRASH_FIRST_WAIT);
}
let items = self.db.trash_list().map_err(CoreError::from)?;
let trashed: HashSet<&str> = items.iter().map(|item| item.uid.as_str()).collect();
let trashed_parents: Vec<Option<String>> = items
.iter()
.map(|item| {
item.parent_uid
.clone()
.filter(|parent| trashed.contains(parent.as_str()))
})
.collect();
// Most of a trash comes from a handful of folders.
let mut origins: HashMap<String, Option<String>> = HashMap::new();
Ok(self
.db
.trash_list()
.map_err(CoreError::from)?
Ok(items
.into_iter()
.map(|item| DirEntry {
.zip(trashed_parents)
.map(|(item, trashed_parent)| DirEntry {
trashed_from: item.parent_uid.as_ref().and_then(|parent| {
origins
.entry(parent.clone())
.or_insert_with(|| self.db.node_path(parent).ok().flatten())
.clone()
}),
trashed_parent,
trashed_at: item.trashed_at.unwrap_or(0),
name: item.name,
is_dir: item.is_dir,
@@ -5639,13 +5649,86 @@ impl Core {
.collect())
}
/// What a trashed folder holds: its children on the server, and the
/// stored trash entries trashed inside it before it went.
fn list_trashed_folder(&self, uid: &str) -> CoreResult<Vec<DirEntry>> {
let folder =
parse_uid(uid).ok_or_else(|| CoreError::invalid(format!("invalid uid: {uid}")))?;
let children = self
.rt
.block_on(within_trash_call(
"enumerate trashed folder",
self.drive.enumerate_folder_children_node_uids(&folder),
))?
.map_err(|e| CoreError::from_api(&e, "enumerate trashed folder"))?;
let mut nodes = Vec::with_capacity(children.len());
for chunk in children.chunks(TRASH_MATERIALIZE_CHUNK) {
nodes.extend(
self.rt
.block_on(within_trash_call(
"enumerate nodes",
self.drive.enumerate_trashed_nodes_light(chunk),
))?
.map_err(|e| CoreError::from_api(&e, "enumerate nodes"))?,
);
}
let stored = self.db.trash_list().map_err(CoreError::from)?;
let stored_at: HashMap<&str, Option<i64>> = stored
.iter()
.map(|item| (item.uid.as_str(), item.trashed_at))
.collect();
let mut entries: Vec<DirEntry> = nodes
.iter()
.map(|TrashedNode { node, trash_time }| {
let uid = node.uid.to_string();
let trashed_at = trash_time
.or_else(|| stored_at.get(uid.as_str()).copied().flatten())
.unwrap_or(0);
trashed_entry(
uid,
node.name.clone(),
node.is_folder(),
node_size(node) as i64,
node.modification_time,
trashed_at,
folder.to_string(),
)
})
.collect();
let listed: HashSet<String> = entries.iter().map(|e| e.uid.clone()).collect();
entries.extend(
stored
.into_iter()
.filter(|item| {
item.parent_uid.as_deref() == Some(uid) && !listed.contains(&item.uid)
})
.map(|item| {
trashed_entry(
item.uid,
item.name,
item.is_dir,
item.size,
item.mtime,
item.trashed_at.unwrap_or(0),
folder.to_string(),
)
}),
);
entries.sort_by(|a, b| {
b.is_dir
.cmp(&a.is_dir)
.then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
});
Ok(entries)
}
/// Re-fetch the trash listing from the server and persist it.
///
/// Materialized in chunks of [`TRASH_MATERIALIZE_CHUNK`], each persisted as
/// it lands: decrypting a trashed node costs an S2K unlock, so a trash of a
/// few thousand nodes takes minutes, and an all-or-nothing write would throw
/// that away on the first failure and show the user nothing until the very
/// end. Every batch is a usable listing.
/// Only nodes the stored listing does not hold yet are read, and light: a
/// trashed file needs no content key, so none is unlocked. Each chunk of
/// [`TRASH_MATERIALIZE_CHUNK`] is stored as it lands, so a large trash
/// fills the page while it loads. Rows the server no longer lists go once
/// the whole listing is in, never earlier.
async fn refresh_trash(&self) -> CoreResult<()> {
let started = Instant::now();
let uids = within_trash_call("enumerate trash", self.drive.enumerate_trash_node_uids())
@@ -5657,8 +5740,6 @@ impl Core {
"trash refresh: enumerated"
);
// What the listing held before, and whether it was the whole trash: the
// chunks below overwrite it, so both are read up front.
let seen = self.db.trash_seen().unwrap_or_default();
let complete = self
.db
@@ -5666,36 +5747,51 @@ impl Core {
.ok()
.flatten()
.is_some();
let _ = self.db.clear_state(TRASH_COMPLETE_MS);
let now = now_secs();
if uids.is_empty() {
self.db.trash_replace(&[]).map_err(CoreError::from)?;
}
let mut items: Vec<StoredTrash> = Vec::with_capacity(uids.len());
for chunk in uids.chunks(TRASH_MATERIALIZE_CHUNK) {
let chunk_started = Instant::now();
let nodes = within_trash_call("enumerate nodes", self.drive.enumerate_nodes(chunk))
.await?
.map_err(|e| CoreError::from_api(&e, "enumerate nodes"))?;
items.extend(nodes.into_iter().map(|node| StoredTrash {
uid: node.uid.to_string(),
name: node.name.clone(),
is_dir: node.is_folder(),
size: node_size(&node) as i64,
mtime: node.modification_time,
// The folder the node will go back to, which is also what tells
// a restore whether that folder is itself in the trash.
parent_uid: node.parent_uid.as_ref().map(|uid| uid.to_string()),
trashed_at: first_seen_in_trash(&seen, &node.uid.to_string(), complete, now),
}));
// Cumulative, so the table is always a prefix of the real trash
// rather than a mix of this refresh and the last one.
self.db.trash_replace(&items).map_err(CoreError::from)?;
let listed: HashSet<String> = uids.iter().map(ToString::to_string).collect();
let removed = self.db.trash_retain(&listed).map_err(CoreError::from)?;
if removed > 0 {
self.trash_progress.notify_waiters();
}
let missing: Vec<NodeUid> = uids
.into_iter()
.filter(|uid| !seen.contains_key(&uid.to_string()))
.collect();
let mut materialized = 0usize;
for chunk in missing.chunks(TRASH_MATERIALIZE_CHUNK) {
let chunk_started = Instant::now();
let nodes = within_trash_call(
"enumerate nodes",
self.drive.enumerate_trashed_nodes_light(chunk),
)
.await?
.map_err(|e| CoreError::from_api(&e, "enumerate nodes"))?;
let items: Vec<StoredTrash> = nodes
.into_iter()
.map(|TrashedNode { node, trash_time }| {
let uid = node.uid.to_string();
StoredTrash {
trashed_at: trash_time
.or_else(|| first_seen_in_trash(&seen, &uid, complete, now)),
uid,
name: node.name.clone(),
is_dir: node.is_folder(),
size: node_size(&node) as i64,
mtime: node.modification_time,
// The folder the node will go back to, which is also what
// tells a restore whether that folder is itself in the trash.
parent_uid: node.parent_uid.as_ref().map(|uid| uid.to_string()),
}
})
.collect();
materialized += items.len();
self.db.trash_upsert(&items).map_err(CoreError::from)?;
self.trash_progress.notify_waiters();
self.events.publish(&[Topic::Trash]);
debug!(
materialized = items.len(),
total = uids.len(),
materialized,
total = missing.len(),
chunk_ms = chunk_started.elapsed().as_millis() as u64,
"trash refresh: batch"
);
@@ -5704,7 +5800,9 @@ impl Core {
let _ = self.db.set_state_i64(TRASH_SYNCED_MS, now_ms());
let _ = self.db.set_state_i64(TRASH_COMPLETE_MS, now_ms());
info!(
count = items.len(),
count = listed.len(),
new = materialized,
removed,
elapsed_ms = started.elapsed().as_millis() as u64,
"trash refresh: done"
);
@@ -5885,6 +5983,8 @@ impl Core {
}
}
});
let back: Vec<String> = restored.iter().map(ToString::to_string).collect();
let _ = self.db.trash_remove(&back);
self.invalidate_trash();
Ok(restored.len())
}
@@ -5898,6 +5998,7 @@ impl Core {
// daemon interrupted mid-batch has already forgotten exactly the nodes
// the server destroyed — never more, never fewer.
let mut deleted = 0usize;
let mut gone: Vec<String> = Vec::new();
let mut first_error: Option<ProtonError> = None;
self.rt
.block_on(async {
@@ -5907,6 +6008,7 @@ impl Core {
match outcome {
Ok(()) => {
self.drop_local(std::slice::from_ref(&uid));
gone.push(uid.to_string());
deleted += 1;
}
Err(e) => {
@@ -5923,23 +6025,34 @@ impl Core {
{
return Err(CoreError::from_api(&error, "delete"));
}
let _ = self.db.trash_remove(&gone);
self.invalidate_trash();
Ok(deleted)
}
/// Permanently delete everything in the trash. The uids are listed first so
/// the blobs of items trashed by *another* client — which this daemon may
/// still hold in its cache — are reclaimed too, not just the ones it trashed.
/// Permanently delete everything in the trash.
///
/// The stored listing says what goes, so the blobs of items trashed by
/// another client, which this daemon may still hold, are reclaimed too. It
/// is not read from the server again first: on a large trash that listing
/// is what kept the delete from ever being sent (`docs/BUGS.md` B293).
/// The stored listing is cleared at once, and the server is asked again
/// after [`TRASH_TTL`], so anything it still holds then shows up again.
fn empty_trash(&self) -> CoreResult<usize> {
let uids = self
.rt
.block_on(self.drive.enumerate_trash_node_uids())
.map_err(|e| CoreError::from_api(&e, "enumerate trash"))?;
let uids: Vec<String> = self
.db
.trash_seen()
.map_err(CoreError::from)?
.into_keys()
.collect();
self.rt
.block_on(self.client.empty_trash())
.block_on(within_trash_call("empty trash", self.drive.empty_trash()))?
.map_err(|e| CoreError::from_api(&e, "empty trash"))?;
self.drop_local(&uids);
self.invalidate_trash();
let parsed: Vec<NodeUid> = uids.iter().filter_map(|uid| parse_uid(uid)).collect();
self.drop_local(&parsed);
let _ = self.db.trash_replace(&[]);
let _ = self.db.set_state_i64(TRASH_SYNCED_MS, now_ms());
self.events.publish(&[Topic::Trash]);
Ok(uids.len())
}
@@ -6841,6 +6954,37 @@ async fn within_trash_call<T>(what: &str, call: impl Future<Output = T>) -> Core
})
}
/// An entry inside a trashed folder, for [`Core::list_trashed_folder`].
fn trashed_entry(
uid: String,
name: String,
is_dir: bool,
size: i64,
mtime: i64,
trashed_at: i64,
parent: String,
) -> DirEntry {
DirEntry {
name,
is_dir,
size: size.max(0) as u64,
modified: mtime,
pinned: false,
pinned_by_folder: false,
cached: false,
uid,
path: String::new(),
role: String::new(),
shared_by: String::new(),
shared_at: 0,
shared_by_unverified: false,
trashed_at,
trashed_from: None,
trashed_parent: Some(parent),
issue: None,
}
}
/// When a node a trash refresh found went to the trash, as far as the daemon
/// can tell. A node the stored listing already had keeps the time it had. A new
/// one went there since the last refresh, so now is close, but only when that
+1
View File
@@ -77,6 +77,7 @@ fn shared_entry_of(core: &Core, n: Node) -> DirEntry {
shared_by_unverified,
trashed_at: 0,
trashed_from: None,
trashed_parent: None,
issue: None,
}
}
+75
View File
@@ -1918,6 +1918,81 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn the_trash_lists_by_folder_and_empties() {
let drive = FakeDrive::new();
let dir = scratch("trash-by-folder");
let daemon = Daemon::start(&dir, drive.client(1, Faults::none())).unwrap();
let mount = &daemon.mountpoint;
std::fs::create_dir_all(mount.join("album/inner")).unwrap();
std::fs::write(mount.join("album/inner/a.jpg"), b"a").unwrap();
std::fs::write(mount.join("album/b.jpg"), b"b").unwrap();
std::fs::write(mount.join("loose.txt"), b"c").unwrap();
assert!(wait_until(Duration::from_secs(30), || daemon.drained()
&& drive.lookup("album/inner/a.jpg").is_some()
&& drive.lookup("loose.txt").is_some()));
let album = drive.lookup("album").unwrap();
let inner = drive.lookup("album/inner").unwrap();
// A file trashed on its own, then the folder that held it.
drive.device().trash("album/b.jpg");
drive.device().trash("album");
std::fs::remove_file(mount.join("loose.txt")).unwrap();
assert!(wait_until(Duration::from_secs(30), || daemon.drained()));
let list = |request: &Request| match daemon.request(request) {
Ok(Response::Entries { entries }) => entries,
other => panic!("unexpected reply: {other:?}"),
};
daemon
.request(&Request::Refresh {
scope: RefreshScope::Trash,
})
.unwrap();
let mut trash = Vec::new();
assert!(wait_until(Duration::from_secs(30), || {
trash = list(&Request::ListTrash);
trash.len() == 3
}));
let b = trash.iter().find(|e| e.name == "b.jpg").unwrap();
assert_eq!(
b.trashed_parent.as_deref(),
Some(album.to_string().as_str())
);
let top: Vec<&str> = trash
.iter()
.filter(|e| e.trashed_parent.is_none())
.map(|e| e.name.as_str())
.collect();
assert_eq!(top.len(), 2);
assert!(top.contains(&"album") && top.contains(&"loose.txt"));
let inside = list(&Request::ListTrashedFolder {
uid: album.to_string(),
});
let names: Vec<&str> = inside.iter().map(|e| e.name.as_str()).collect();
assert!(names.contains(&"inner"), "{names:?}");
assert!(names.contains(&"b.jpg"), "{names:?}");
assert!(inside.iter().any(|e| e.uid == inner.to_string()));
assert!(matches!(
daemon.request(&Request::EmptyTrash),
Ok(Response::Ok { .. })
));
assert!(list(&Request::ListTrash).is_empty());
daemon
.request(&Request::Refresh {
scope: RefreshScope::Trash,
})
.unwrap();
assert!(list(&Request::ListTrash).is_empty());
assert!(drive.lookup("album").is_none());
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_move_blocked_by_trash_can_be_retried_after_restore() {
+5
View File
@@ -1746,6 +1746,11 @@ impl DriveApi for FakeClient {
.await
}
async fn empty_trash(&self) -> Result<()> {
let trashed = self.enumerate_trash_node_uids().await?;
self.batch(&trashed, delete_one).await.map(|_| ())
}
async fn enumerate_trash_node_uids(&self) -> Result<Vec<NodeUid>> {
self.request(false, |server| {
Ok(server
+7
View File
@@ -547,6 +547,13 @@ fn build_window(app: &adw::Application) {
selection_bar: trash_widgets.selection_bar.clone(),
selection_label: trash_widgets.selection_label.clone(),
loader: Loader::new(&trash_widgets.content),
back: trash_widgets.back.clone(),
crumb: trash_widgets.crumb.clone(),
search: trash_widgets.search.clone(),
grouped: trash_widgets.grouped.clone(),
all: RefCell::new(Vec::new()),
nav: RefCell::new(Vec::new()),
folder_rows: RefCell::new(None),
},
gallery: GalleryState {
model: gallery_widgets.model.clone(),
+2
View File
@@ -3185,6 +3185,7 @@ pub(crate) fn repaint_search(ui: &Rc<Ui>, hits: &[SearchHit]) {
shared_by_unverified: false,
trashed_at: 0,
trashed_from: None,
trashed_parent: None,
issue: None,
})
.collect();
@@ -3249,6 +3250,7 @@ mod tests {
shared_by_unverified: false,
trashed_at: 0,
trashed_from: None,
trashed_parent: None,
issue: None,
}
}
@@ -635,6 +635,7 @@ pub(crate) fn shared_item_as_entry(item: &SharedItem) -> DirEntry {
shared_by_unverified: false,
trashed_at: 0,
trashed_from: None,
trashed_parent: None,
issue: None,
}
}
+503 -24
View File
@@ -16,6 +16,28 @@ pub(crate) struct TrashState {
pub(crate) selection_label: gtk4::Label,
/// Runs the loads; the rows stay up while one runs.
pub(crate) loader: Rc<Loader>,
/// Back, the breadcrumb and the search entry over the list.
pub(crate) back: gtk4::Button,
pub(crate) crumb: gtk4::Box,
pub(crate) search: gtk4::SearchEntry,
/// On: the trash as the folders things were deleted from. Off: one list.
pub(crate) grouped: gtk4::ToggleButton,
/// The whole trash as last read, newest deletion first.
pub(crate) all: RefCell<Vec<DirEntry>>,
/// Where the list is, below the top level.
pub(crate) nav: RefCell<Vec<TrashNav>>,
/// What the trashed folder on screen holds, once read.
pub(crate) folder_rows: RefCell<Option<Vec<DirEntry>>>,
}
/// One step down from the top of the Trash page.
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum TrashNav {
/// The things deleted from one folder: its path, `""` for My files, `None`
/// when the folder is not known.
Location { key: Option<String>, label: String },
/// Inside a trashed folder.
Folder { uid: String, name: String },
}
/// The widgets of the Trash page that a load repaints.
@@ -30,8 +52,18 @@ pub(crate) struct TrashWidgets {
pub(crate) selection_label: gtk4::Label,
pub(crate) restore_selected: gtk4::Button,
pub(crate) delete_selected: gtk4::Button,
pub(crate) back: gtk4::Button,
pub(crate) crumb: gtk4::Box,
pub(crate) search: gtk4::SearchEntry,
pub(crate) grouped: gtk4::ToggleButton,
}
/// The uid prefix of a row that stands for a folder things were deleted from.
/// Such a row is made here, never sent to the daemon.
const LOCATION_UID: &str = "trash-location:";
/// The location key of the folder that is not known.
const UNKNOWN_LOCATION: &str = "\u{0}";
/// The Trash page: everything Drive is holding in the trash, as a list with
/// the folder each item came from and when it was deleted, or as a grid, where
/// photos are easier to recognise. Restore and Delete Permanently sit in the
@@ -75,11 +107,41 @@ pub(crate) fn build_trash_page() -> (gtk4::Widget, TrashWidgets) {
content.add_named(&files.views, Some("list"));
content.add_named(&status, Some("status"));
let back = gtk4::Button::builder()
.icon_name("go-previous-symbolic")
.tooltip_text(gettext("Back"))
.visible(false)
.build();
back.add_css_class("flat");
let crumb = gtk4::Box::new(gtk4::Orientation::Horizontal, 2);
crumb.set_valign(gtk4::Align::Center);
let crumb_scroll = gtk4::ScrolledWindow::builder()
.hscrollbar_policy(gtk4::PolicyType::External)
.vscrollbar_policy(gtk4::PolicyType::Never)
.hexpand(true)
.child(&crumb)
.build();
let search = gtk4::SearchEntry::builder()
.placeholder_text(gettext("Search the trash"))
.width_chars(24)
.build();
let path_bar = gtk4::Box::new(gtk4::Orientation::Horizontal, 8);
path_bar.append(&back);
path_bar.append(&crumb_scroll);
path_bar.append(&search);
let grouped = gtk4::ToggleButton::builder()
.icon_name("folder-symbolic")
.tooltip_text(gettext("Group by original folder"))
.active(true)
.build();
let inner = gtk4::Box::new(gtk4::Orientation::Vertical, 12);
inner.set_margin_top(12);
inner.set_margin_bottom(12);
inner.set_margin_start(12);
inner.set_margin_end(12);
inner.append(&path_bar);
inner.append(&content);
// Bulk Delete Permanently always confirms with the count, so a stale
@@ -101,6 +163,7 @@ pub(crate) fn build_trash_page() -> (gtk4::Widget, TrashWidgets) {
let (frame, header, subtitle) = page_frame(&gettext("Trash"), &inner);
header.pack_start(&empty);
header.pack_end(&layout);
header.pack_end(&grouped);
(
frame.upcast(),
@@ -115,6 +178,10 @@ pub(crate) fn build_trash_page() -> (gtk4::Widget, TrashWidgets) {
selection_label,
restore_selected,
delete_selected,
back,
crumb,
search,
grouped,
},
)
}
@@ -151,7 +218,10 @@ pub(crate) fn wire_trash(ui: &Rc<Ui>, widgets: &TrashWidgets) {
files
.column_view
.append_column(&text_column(&pgettext("column", "Size"), |e| {
if e.is_dir {
if location_key(&e.uid).is_some() {
// A location row carries how many items it holds as its size.
ngettext_f("{n} item", "{n} items", e.size, &[])
} else if e.is_dir {
"—".to_string()
} else {
human_bytes(e.size)
@@ -163,6 +233,21 @@ pub(crate) fn wire_trash(ui: &Rc<Ui>, widgets: &TrashWidgets) {
.empty
.connect_clicked(move |_| prompt_empty_trash(&ui_empty));
let ui_back = ui.clone();
widgets.back.connect_clicked(move |_| {
ui_back.trash.nav.borrow_mut().pop();
show_trash_place(&ui_back);
});
let ui_search = ui.clone();
widgets
.search
.connect_search_changed(move |_| render_trash(&ui_search));
let ui_grouped = ui.clone();
widgets.grouped.connect_toggled(move |_| {
ui_grouped.trash.nav.borrow_mut().clear();
show_trash_place(&ui_grouped);
});
let ui_sel = ui.clone();
files
.selection
@@ -193,17 +278,52 @@ fn trashed_from_label(entry: &DirEntry) -> String {
}
}
/// A trashed file can't be opened; say what would let it be.
/// Open a location or a trashed folder in place. A trashed file can't be
/// opened; say what would let it be.
fn activate_trashed(ui: &Rc<Ui>, entry: &DirEntry) {
toast(
ui,
if let Some(key) = location_key(&entry.uid) {
ui.trash.nav.borrow_mut().push(TrashNav::Location {
key,
label: entry.name.clone(),
});
show_trash_place(ui);
} else if entry.is_dir {
ui.trash.nav.borrow_mut().push(TrashNav::Folder {
uid: entry.uid.clone(),
name: entry.name.clone(),
});
show_trash_place(ui);
} else {
let name = match outer_folder(ui) {
Some(folder) if !in_trash(ui, &entry.uid) => folder.name,
_ => entry.name.clone(),
};
// Translators: {name} is a file or folder name.
&gettext_f("Restore “{name}” to open it", &[("name", &entry.name)]),
);
toast(
ui,
&gettext_f("Restore “{name}” to open it", &[("name", &name)]),
);
}
}
fn trash_entry_menu(ui: &Rc<Ui>, entry: &DirEntry) -> ActionMenu {
let mut menu = ActionMenu::new();
if location_key(&entry.uid).is_none()
&& !in_trash(ui, &entry.uid)
&& let Some(folder) = outer_folder(ui)
{
// Went to the trash with the folder, so only the folder goes back.
let ui_c = ui.clone();
let label = gettext_f(
// Translators: {name} is a folder name.
"Restore “{name}”",
&[("name", &folder.name)],
);
menu.item(&label, move || {
restore_entries(&ui_c, std::slice::from_ref(&folder))
});
return menu;
}
let (ui_c, entry_c) = (ui.clone(), entry.clone());
menu.item(&pgettext("verb", "Restore"), move || {
restore_entries(&ui_c, std::slice::from_ref(&entry_c))
@@ -244,7 +364,7 @@ fn trash_background_menu(ui: &Rc<Ui>) -> ActionMenu {
});
let ui_c = ui.clone();
menu.item(&gettext("Refresh"), move || reload_current_page(&ui_c));
if ui.trash.files.model.n_items() > 0 {
if !ui.trash.all.borrow().is_empty() {
menu.section();
let ui_c = ui.clone();
menu.item(&gettext("Empty Trash…"), move || {
@@ -300,7 +420,17 @@ pub(crate) fn load_trash(ui: &Rc<Ui>) {
clear_trash(&ui);
}
match result {
Ok(Ok(Response::Entries { entries })) => repaint_trash(&ui, &entries),
Ok(Ok(Response::Entries { entries })) => {
let mut entries = entries;
sort_trash(&mut entries);
*ui.trash.all.borrow_mut() = entries;
keep_trash_place(&ui);
if matches!(ui.trash.nav.borrow().last(), Some(TrashNav::Folder { .. })) {
load_trashed_folder(&ui);
} else {
render_trash(&ui);
}
}
Ok(Ok(Response::Error { message, .. })) => trash_status(
&ui,
"dialog-warning-symbolic",
@@ -338,14 +468,125 @@ pub(crate) fn trash_status(ui: &Rc<Ui>, icon: &str, title: &str, description: &s
ui.trash.subtitle.set_subtitle("");
}
/// Repopulate the trash, most recently deleted first: the order in which a user
/// looks for what they just deleted.
pub(crate) fn repaint_trash(ui: &Rc<Ui>, entries: &[DirEntry]) {
/// Go to the place `nav` now points at: read a trashed folder, or show
/// what the stored listing already holds.
fn show_trash_place(ui: &Rc<Ui>) {
if !ui.trash.search.text().is_empty() {
ui.trash.search.set_text("");
}
ui.trash.files.selection.unselect_all();
ui.trash.files.scroll_to_top();
if matches!(ui.trash.nav.borrow().last(), Some(TrashNav::Folder { .. })) {
load_trashed_folder(ui);
} else {
render_trash(ui);
}
}
/// Read what the trashed folder on screen holds, then show it.
fn load_trashed_folder(ui: &Rc<Ui>) {
let Some(TrashNav::Folder { uid, .. }) = ui.trash.nav.borrow().last().cloned() else {
return;
};
ui.trash.folder_rows.borrow_mut().take();
let ui_p = ui.clone();
let ticket = ui.trash.loader.replace(move || {
clear_trash(&ui_p);
trash_status(
&ui_p,
"folder-open-symbolic",
&gettext("Loading…"),
&gettext("Reading this folder."),
false,
);
});
ui.busy_begin();
let rx = spawn_request(
ui.dirs.control_socket(),
Request::ListTrashedFolder { uid: uid.clone() },
);
let ui = ui.clone();
glib::spawn_future_local(async move {
let result = rx.recv().await;
ui.busy_end();
if !ticket.is_current() {
return;
}
let still_here = matches!(
ui.trash.nav.borrow().last(),
Some(TrashNav::Folder { uid: on, .. }) if *on == uid
);
if !still_here {
return;
}
match result {
Ok(Ok(Response::Entries { entries })) => {
*ui.trash.folder_rows.borrow_mut() = Some(entries);
render_trash(&ui);
}
Ok(Ok(Response::Error { message, .. })) => {
clear_trash(&ui);
trash_status(
&ui,
"dialog-warning-symbolic",
&gettext("Couldn't open the folder"),
&message,
false,
);
}
Ok(Ok(_)) => {
clear_trash(&ui);
trash_status(
&ui,
"dialog-warning-symbolic",
&gettext("Couldn't open the folder"),
&gettext("Unexpected reply from the Proton Drive service."),
false,
);
}
Ok(Err(_)) | Err(_) => trash_unreachable(&ui),
}
});
}
/// After a new listing, step back out of places that are gone from it.
fn keep_trash_place(ui: &Rc<Ui>) {
let all = ui.trash.all.borrow();
let mut nav = ui.trash.nav.borrow_mut();
let keep = kept_steps(&nav, &all);
nav.truncate(keep);
}
/// How many steps of `nav` still lead somewhere in `all`. A location stays
/// while something deleted from it is listed, and the trashed folder opened
/// from it while that folder is; the folders below it went with it.
fn kept_steps(nav: &[TrashNav], all: &[DirEntry]) -> usize {
let mut inside = false;
for (i, step) in nav.iter().enumerate() {
let there = match step {
TrashNav::Location { key, .. } => all
.iter()
.any(|e| e.trashed_parent.is_none() && e.trashed_from == *key),
TrashNav::Folder { uid, .. } => inside || all.iter().any(|e| e.uid == *uid),
};
if !there {
return i;
}
inside |= matches!(step, TrashNav::Folder { .. });
}
nav.len()
}
/// Show the rows for the current place, search and grouping.
pub(crate) fn render_trash(ui: &Rc<Ui>) {
let all = ui.trash.all.borrow();
// An empty Trash has nothing to empty, so the button goes away rather than
// sitting there greyed out.
ui.trash.empty.set_sensitive(true);
ui.trash.empty.set_visible(!entries.is_empty());
if entries.is_empty() {
ui.trash.empty.set_visible(!all.is_empty());
repaint_trash_crumb(ui);
if all.is_empty() {
drop(all);
trash_status(
ui,
"user-trash-symbolic",
@@ -356,22 +597,198 @@ pub(crate) fn repaint_trash(ui: &Rc<Ui>, entries: &[DirEntry]) {
clear_trash(ui);
return;
}
ui.trash.content.set_visible_child_name("list");
ui.trash.subtitle.set_subtitle(&ngettext_f(
"{n} item",
"{n} items",
entries.len() as u64,
&[],
));
let subtitle = ngettext_f("{n} item", "{n} items", all.len() as u64, &[]);
let mut sorted = entries.to_vec();
sort_trash(&mut sorted);
let query = ui.trash.search.text().to_lowercase();
let nav = ui.trash.nav.borrow().clone();
let rows: Vec<DirEntry> = if !query.is_empty() {
all.iter()
.filter(|e| e.name.to_lowercase().contains(&query))
.cloned()
.collect()
} else if !ui.trash.grouped.is_active() {
all.clone()
} else {
match nav.last() {
None => trash_locations(&all),
Some(TrashNav::Location { key, .. }) => all
.iter()
.filter(|e| e.trashed_parent.is_none() && e.trashed_from == *key)
.cloned()
.collect(),
Some(TrashNav::Folder { .. }) => {
ui.trash.folder_rows.borrow().clone().unwrap_or_default()
}
}
};
drop(all);
if rows.is_empty() {
clear_trash(ui);
if query.is_empty() {
trash_status(
ui,
"folder-open-symbolic",
&gettext("This folder is empty"),
&gettext("Nothing else was in this folder when it was deleted."),
false,
);
} else {
trash_status(
ui,
"edit-find-symbolic",
&gettext("No results"),
&gettext("Nothing in the trash has that name."),
false,
);
}
ui.trash.subtitle.set_subtitle(&subtitle);
return;
}
ui.trash.content.set_visible_child_name("list");
ui.trash.subtitle.set_subtitle(&subtitle);
// Only the rows that changed are swapped, so a refresh keeps the
// selection and the scroll position.
replace_items(&ui.trash.files.model, &sorted);
replace_items(&ui.trash.files.model, &rows);
sync_trash_selection(ui);
}
/// One row per folder things were deleted from, the most recent first. Items
/// trashed inside a trashed folder are found by opening that folder.
fn trash_locations(all: &[DirEntry]) -> Vec<DirEntry> {
let mut rows: Vec<DirEntry> = Vec::new();
let mut index: HashMap<Option<String>, usize> = HashMap::new();
for entry in all.iter().filter(|e| e.trashed_parent.is_none()) {
let key = entry.trashed_from.clone();
let at = *index.entry(key.clone()).or_insert_with(|| {
rows.push(location_row(key));
rows.len() - 1
});
let row = &mut rows[at];
row.size += 1;
row.trashed_at = row.trashed_at.max(entry.trashed_at);
row.modified = row.modified.max(entry.modified);
}
sort_trash(&mut rows);
rows
}
/// The row that stands for the folder `key`, still holding nothing.
fn location_row(key: Option<String>) -> DirEntry {
let (uid, name) = match key.as_deref() {
None => (
format!("{LOCATION_UID}{UNKNOWN_LOCATION}"),
gettext("Unknown folder"),
),
Some("") => (LOCATION_UID.to_string(), gettext("My files")),
Some(path) => (
format!("{LOCATION_UID}{path}"),
path.rsplit('/').next().unwrap_or(path).to_string(),
),
};
DirEntry {
name,
is_dir: true,
size: 0,
modified: 0,
pinned: false,
pinned_by_folder: false,
cached: false,
uid,
path: String::new(),
role: String::new(),
shared_by: String::new(),
shared_at: 0,
shared_by_unverified: false,
trashed_at: 0,
trashed_from: key,
trashed_parent: None,
issue: None,
}
}
/// The folder a location row stands for, or `None` for any other row.
fn location_key(uid: &str) -> Option<Option<String>> {
let key = uid.strip_prefix(LOCATION_UID)?;
Some((key != UNKNOWN_LOCATION).then(|| key.to_string()))
}
/// Whether the stored listing holds `uid`, so it can be restored on its own.
fn in_trash(ui: &Ui, uid: &str) -> bool {
ui.trash.all.borrow().iter().any(|e| e.uid == uid)
}
/// The trashed folder the user opened from a location, when inside one.
fn outer_folder(ui: &Ui) -> Option<DirEntry> {
let nav = ui.trash.nav.borrow();
let uid = nav.iter().find_map(|step| match step {
TrashNav::Folder { uid, .. } => Some(uid.clone()),
TrashNav::Location { .. } => None,
})?;
ui.trash.all.borrow().iter().find(|e| e.uid == uid).cloned()
}
/// What acting on `entries` acts on: a location row stands for everything
/// deleted from that folder, and an item that went with its folder for the
/// folder. Each node once.
fn trashed_targets(ui: &Ui, entries: &[DirEntry]) -> Vec<DirEntry> {
let all = ui.trash.all.borrow();
let outer = outer_folder(ui);
let mut seen = HashSet::new();
let mut targets = Vec::new();
for entry in entries {
let picked: Vec<DirEntry> = if let Some(key) = location_key(&entry.uid) {
all.iter()
.filter(|e| e.trashed_parent.is_none() && e.trashed_from == key)
.cloned()
.collect()
} else if all.iter().any(|e| e.uid == entry.uid) {
vec![entry.clone()]
} else {
outer.clone().into_iter().collect()
};
for target in picked {
if seen.insert(target.uid.clone()) {
targets.push(target);
}
}
}
targets
}
/// Rebuild the path bar for `nav`: "Trash", then each place down to the
/// current one. Hidden at the top, where there is nowhere to go back to.
fn repaint_trash_crumb(ui: &Rc<Ui>) {
let nav = ui.trash.nav.borrow();
let crumb = &ui.trash.crumb;
while let Some(child) = crumb.first_child() {
crumb.remove(&child);
}
ui.trash.back.set_visible(!nav.is_empty());
crumb.append(&trash_crumb_node(ui, &gettext("Trash"), 0, nav.is_empty()));
for (i, step) in nav.iter().enumerate() {
let label = match step {
TrashNav::Location { label, .. } => label,
TrashNav::Folder { name, .. } => name,
};
crumb.append(&crumb_separator());
crumb.append(&trash_crumb_node(ui, label, i + 1, i + 1 == nav.len()));
}
}
fn trash_crumb_node(ui: &Rc<Ui>, label: &str, depth: usize, current: bool) -> gtk4::Widget {
if current {
return crumb_current(label);
}
let button = gtk4::Button::builder().label(label).build();
button.add_css_class("flat");
let ui = ui.clone();
button.connect_clicked(move |_| {
ui.trash.nav.borrow_mut().truncate(depth);
show_trash_place(&ui);
});
button.upcast()
}
/// Newest deletion first. Entries with no known deletion time go last, newest
/// modification first among themselves.
fn sort_trash(entries: &mut [DirEntry]) {
@@ -393,6 +810,10 @@ fn clear_trash(ui: &Rc<Ui>) {
/// Restore trashed entries to the folders they were trashed from. When they
/// all came from one known folder, the toast offers to show it.
pub(crate) fn restore_entries(ui: &Rc<Ui>, entries: &[DirEntry]) {
let entries = &trashed_targets(ui, entries)[..];
if entries.is_empty() {
return;
}
let message = match entries {
// Translators: {name} is a file or folder name.
[one] => gettext_f("Restored “{name}”", &[("name", &one.name)]),
@@ -430,6 +851,10 @@ fn common_origin(entries: &[DirEntry]) -> Option<String> {
/// Confirm, then permanently delete trashed entries. Irreversible, so it asks.
pub(crate) fn prompt_delete_forever(ui: &Rc<Ui>, entries: &[DirEntry]) {
let entries = &trashed_targets(ui, entries)[..];
if entries.is_empty() {
return;
}
let win = ui_window(ui);
let uids: Vec<String> = entries.iter().map(|e| e.uid.clone()).collect();
let count = entries.len() as u64;
@@ -485,7 +910,7 @@ pub(crate) fn prompt_delete_forever(ui: &Rc<Ui>, entries: &[DirEntry]) {
/// Confirm, then permanently delete everything in the trash.
pub(crate) fn prompt_empty_trash(ui: &Rc<Ui>) {
let win = ui_window(ui);
let count = ui.trash.files.model.n_items();
let count = ui.trash.all.borrow().len();
let dialog = adw::AlertDialog::builder()
.heading(gettext("Empty Trash?"))
.body(ngettext_f(
@@ -536,10 +961,64 @@ mod tests {
shared_by_unverified: false,
trashed_at,
trashed_from: from.map(str::to_string),
trashed_parent: None,
issue: None,
}
}
fn inside(name: &str, parent: &str) -> DirEntry {
DirEntry {
trashed_parent: Some(parent.into()),
..trashed(name, 5, 1, None)
}
}
#[test]
fn locations_group_top_level_items_by_folder() {
let all = vec![
trashed("a", 30, 1, Some("Photos/2019")),
trashed("b", 10, 1, Some("Photos/2019")),
trashed("c", 20, 1, Some("")),
trashed("d", 5, 1, None),
inside("e", "a"),
];
let rows = trash_locations(&all);
let summary: Vec<(&str, u64, i64)> = rows
.iter()
.map(|r| (r.name.as_str(), r.size, r.trashed_at))
.collect();
assert_eq!(
summary,
[
("2019", 2, 30),
("My files", 1, 20),
("Unknown folder", 1, 5)
]
);
assert_eq!(location_key(&rows[0].uid), Some(Some("Photos/2019".into())));
assert_eq!(location_key(&rows[1].uid), Some(Some(String::new())));
assert_eq!(location_key(&rows[2].uid), Some(None));
assert_eq!(location_key("vol~link"), None);
}
#[test]
fn a_place_stays_only_while_the_listing_still_leads_there() {
let all = vec![trashed("album", 1, 1, Some("Photos")), inside("x", "album")];
let location = TrashNav::Location {
key: Some("Photos".into()),
label: "Photos".into(),
};
let folder = |uid: &str| TrashNav::Folder {
uid: uid.into(),
name: uid.into(),
};
// Folders below the trashed one are not listed themselves.
let nav = [location.clone(), folder("album"), folder("child")];
assert_eq!(kept_steps(&nav, &all), 3);
assert_eq!(kept_steps(&[location.clone(), folder("gone")], &all), 1);
assert_eq!(kept_steps(&nav, &[]), 0);
}
#[test]
fn trash_lists_newest_deletion_first_and_undated_last() {
let mut entries = vec![