Compare commits

...
8 Commits
Author SHA1 Message Date
nvrl 61266fc9b1 chore(release): 2.5.0 2026-09-28 16:37:23 +02:00
nvrl d18655538e feat(core,fuse,gui): push daemon events, polish Photos, adopt newer widgets
The app and the tray stop polling. pdfs-core adds Request::Subscribe: the
connection stays open and carries Event lines (status, transfers, and
Changed with a Topic), with a heartbeat while quiet. In pdfs-fuse, an
EventHub gives each subscriber a mailbox, code that changes something
publishes its topic, and a sampler publishes the status, transfers and sync
progress when they differ. The app follows the feed on one thread, paints
status and transfers as they arrive, and reloads the page on screen when its
topic changes, including after changes made with the pdfs CLI. A hidden
window keeps the changes and catches up when focused. Front-ends fall back
to polling a daemon that predates subscriptions. Refresh buttons leave the
page headers; F5 and Ctrl+R still reload from the server.

Photos gets a scrubber overlaid on the right edge of the timeline in place
of the slider and scrollbar. It shows the years, appears when the pointer
comes near or the timeline scrolls, names the month under the pointer and
jumps to it on drag. Upload becomes a split button whose menu holds the
Google Photos import. Tiles are pooled per row and rebound instead of
rebuilt, hover scales the thumbnail to 1.02 without a shadow, and tiles
lose their tooltip.

On libadwaita 1.8 or newer the app uses AdwSpinner, AdwToggleGroup,
AdwButtonRow and AdwShortcutsDialog, and keeps look-alike stand-ins on
older releases (src/compat.rs, widgets/compat.rs). It still builds against
libadwaita 1.5 and picks at run time, creating the newer widgets by class
name through GtkBuilder, so every package gets them. PDFS_STAND_IN_WIDGETS
forces the stand-ins.

The Sync and share-link icons draw in full again: GTK drops group
transforms from symbolic icons, so their coordinates are baked into the
paths. All catalogs are updated and complete.
2026-09-28 16:37:23 +02:00
nvrl da7ea0ec56 feat(core,gui): split Sync into views, tidy Activity, rework Computers
The Sync page gets Overview, Folders and History views under a switcher in
the header. Overview holds the status card, conflicts, transfers and the
queue; Folders holds the folder list, with Add Folder and a popover that
explains the sync modes; History is the former Activity page, which leaves
the sidebar. A banner in Folders and History points back to Overview when
changes fail or conflict.

Activity hides save-by-rename temporaries (pdfs-core gains
syncignore::is_scratch_name), with a toggle to show them again. Runs of
similar events fold into one expandable row, "Show Older" pages further back
through what the daemon keeps, and titles and details are translated
sentences built from the daemon's targets instead of its raw text.
Conflict copies say when they were made.

Computers lists every device in one group, this computer first with a
"This computer" pill; its row opens Sync's folder list. Another computer's
row browses its backup read-only in the shared file list, and its menu
offers Browse Files, Restore, Rename, "Continue This Backup Here…" (the old
identity adoption, now explained in its dialog) and Remove. Subtitles read
"last backup" or "no backups yet", and an empty list links to the download
page. DirEntry derives Default for the browse view's synthesized entries.

The sidebar shows badges for sync problems and waiting invitations, polled
every five minutes away from their pages. All catalogs are updated and
complete.
2026-09-28 15:14:59 +02:00
nvrl 127b71efd0 feat(core,fuse,gui): rebuild Trash and shared pages on one file list
The list and grid view from My files moves into widgets/file_list.rs as
FileList, so Trash, Shared with me and Shared by me share its columns,
selection, context menus, keyboard handling and list/grid switch instead of
each drawing its own rows.

Trash shows where each item came from and when it was deleted. Proton does
not expose the trash time through the SDK yet, so the daemon records when it
first sees a node in the trash (migration V35, trash_seen) and reports that;
the date becomes exact once proton-sdk-rs exposes Node::trash_time. Restoring
offers a Show action, and opening a trashed item explains that it needs to be
restored first.

Shared with me splits files and saved links into two views. Files show who
shared them, with a warning pill for unverified senders, the access they give
and when they were shared. Pending invitations sit in a banner that opens a
dialog to accept or decline each one. Several items can be left at once.
Saved links get their own list with open, copy and remove actions.

Shared by me gains a filter (all, links, people, expired links) and columns
for location, people and link state, with a copy button for live links.
Several items can stop being shared at once, the page refreshes after the
share dialog closes, and a reload rebinds only the rows that changed so the
selection survives.

All catalogs are updated and complete.
2026-09-28 14:35:37 +02:00
nvrl 2339b17d97 feat(core,gui): keep pages up while they reload
Pages no longer swap their content for a "Loading…" status on every load.
A new Loader keeps the last rows on screen and only shows the loading
state if the reply takes longer than 300 ms; a newer load always
supersedes an older one, so a late reply is dropped instead of painted.
Reloading what is on screen keeps it usable; loading something else greys
the old rows out and clears the selection, since their paths would
resolve against the new folder.

My files, search results and Trash now swap only the rows that changed,
so selection, scroll position and thumbnails survive a refresh. Activity
is one sectioned ListView: open conflicts first, then a section per day,
with the filter bar pinned above the list.

Polls give up after 5 s instead of 120 s. A daemon that is running but
doesn't answer now reads as "Not responding" in the app and the tray
rather than as disconnected.
2026-09-28 13:51:28 +02:00
nvrl bd4f797d1f feat(gui): polish pass over wording, icons and responsiveness
The Sync page gives each folder one card with its state, a Synced /
Online only switch and a menu for the rest; switching either way asks
first and the download prompt shows the free space on the disk.

Enabling, disabling and restarting the Proton Drive service ran
systemctl on GTK's main thread and froze the window. They now run in
the background, and every Retry button goes through one shared restart
helper.

Ten icons are bundled under resources/icons for glyphs no stock theme
has or that read ambiguously (sync, share, people, link, menu, map and
so on). A new test fails when the app or search prompt asks for a
symbolic icon that is neither bundled nor on a list checked against
Adwaita 50, libadwaita and GTK, or when a bundled icon is missing from
the resource manifest. The tray's sync icon, which Adwaita 50 no longer
ships, is now view-refresh.

Wording follows one glossary, recorded in docs/TRANSLATING.md: "Proton
Drive service" instead of "mount service" or "daemon", "Online only"
instead of "On-demand", "Proton Drive folder" instead of "mountpoint".
Dialog headings and buttons use title case and page titles match the
sidebar. Dates go through one formatter (app/dates.rs) and sizes
through i18n::human_bytes, and the cache label is translated.

The status tick stops while the window is hidden or minimized and runs
every fifth tick while it is unfocused, refreshing as soon as it gains
focus. "Sync complete" is announced only for large batches and only
when the window isn't focused. Smaller fixes: Empty Trash hides when
there is nothing to empty, copy buttons confirm with a check mark, the
sidebar status spins until the first report, and Photos moves Import
and Find Duplicates into a menu beside a labelled Select toggle.

All catalogs are updated and complete.
2026-09-28 13:26:59 +02:00
nvrl e872cad058 ci: move to Node 24 versions of checkout, upload-artifact and action-gh-release
actions/checkout@v4, actions/upload-artifact@v4 and
softprops/action-gh-release@v2 still target Node.js 20, which the runners
now force onto Node.js 24 with a deprecation warning. Their current majors
(checkout v7, upload-artifact v7, action-gh-release v3) run on Node.js 24.
2026-09-28 12:16:54 +02:00
Nils Pukropp 081c8fb889 chore(aur): update packages to 2.4.0 2026-09-28 07:33:52 +00:00
88 changed files with 31230 additions and 18168 deletions

No files matched your search

+1 -1
View File
@@ -45,7 +45,7 @@ jobs:
run: pacman -Syu --noconfirm --needed git openssh pacman-contrib
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v7
with:
# The updated recipes are committed back to main, not to the tag.
ref: main
+1 -1
View File
@@ -13,7 +13,7 @@ jobs:
rust:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Install native dependencies
run: |
+3 -3
View File
@@ -17,7 +17,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v7
- name: Install system dependencies
run: |
@@ -181,7 +181,7 @@ jobs:
- name: Upload Workflow Artifacts
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: proton-drive-linux-builds
path: |
@@ -192,7 +192,7 @@ jobs:
- name: Create GitHub Release
if: startsWith(github.ref, 'refs/tags/')
uses: softprops/action-gh-release@v2
uses: softprops/action-gh-release@v3
with:
files: |
*.deb
Generated
+4 -4
View File
@@ -3474,7 +3474,7 @@ checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
[[package]]
name = "pdfs-cli"
version = "2.4.0"
version = "2.5.0"
dependencies = [
"anyhow",
"clap",
@@ -3489,7 +3489,7 @@ dependencies = [
[[package]]
name = "pdfs-core"
version = "2.4.0"
version = "2.5.0"
dependencies = [
"async-trait",
"dbus-secret-service-keyring-store",
@@ -3513,7 +3513,7 @@ dependencies = [
[[package]]
name = "pdfs-fuse"
version = "2.4.0"
version = "2.5.0"
dependencies = [
"base64 0.23.1",
"fuser",
@@ -3533,7 +3533,7 @@ dependencies = [
[[package]]
name = "pdfs-gui"
version = "2.4.0"
version = "2.5.0"
dependencies = [
"anyhow",
"async-channel",
+1 -1
View File
@@ -3,7 +3,7 @@ resolver = "2"
members = ["crates/pdfs-core", "crates/pdfs-fuse", "crates/pdfs-cli", "crates/pdfs-gui"]
[workspace.package]
version = "2.4.0"
version = "2.5.0"
edition = "2024"
license = "MIT"
authors = ["Nils Pukropp <contact@narl.io>"]
+2
View File
@@ -3364,6 +3364,8 @@ mod login_wait_tests {
shared_by: String::new(),
shared_at: 0,
shared_by_unverified: false,
trashed_at: 0,
trashed_from: None,
};
assert_eq!(shared_by_line(&entry), None, "no invitation, no line");
entry.shared_by = "alice@proton.me".into();
+361 -7
View File
@@ -31,6 +31,13 @@ const WRITE_TIMEOUT: Duration = Duration::from_secs(2);
/// answers.
const READ_TIMEOUT: Duration = Duration::from_secs(120);
/// Cap on the read half for the requests front ends poll ([`Request::is_poll`]).
/// The daemon answers those from memory or its database, so a reply that takes
/// longer than this means it is stuck. Waiting the full [`READ_TIMEOUT`] would
/// freeze the poller's read-out for two minutes; failing fast lets it say "not
/// responding" and ask again on its next tick.
const POLL_READ_TIMEOUT: Duration = Duration::from_secs(5);
/// A command sent from the CLI to the daemon.
#[derive(Serialize, Deserialize, Debug)]
pub enum Request {
@@ -672,8 +679,88 @@ pub enum Request {
/// passes, …), so a front-end can show a running "what happened" feed
/// without re-deriving it from anywhere.
ListActivity { limit: usize },
// ---- push -------------------------------------------------------------
/// Keep the connection open and stream [`Event`] lines instead of one
/// [`Response`]. See [`subscribe`] for the client side.
Subscribe,
}
/// Something a front-end shows that the daemon can say has changed, so the
/// front-end reads it again. Carried by [`Event::Changed`].
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(rename_all = "snake_case")]
pub enum Topic {
/// Folder listings in the mount: something was created, renamed, moved,
/// trashed or pinned, here or on another device.
Files,
/// The photos timeline or albums.
Photos,
Trash,
/// Shares, links, invitations and saved links, in either direction.
Shares,
/// The account's computers.
Devices,
/// Synced folders, their mode and their live progress.
Locations,
/// The pending-op queue ([`Request::ListPendingOps`]).
Queue,
Conflicts,
/// The activity log gained entries.
Activity,
/// A topic from a newer daemon, which this front-end cannot act on.
#[serde(other)]
Unknown,
}
impl Topic {
/// Every topic a front-end can act on. A new subscription is told all of
/// them have changed, so it catches up on whatever happened while it was
/// not connected.
pub const ALL: [Topic; 9] = [
Topic::Files,
Topic::Photos,
Topic::Trash,
Topic::Shares,
Topic::Devices,
Topic::Locations,
Topic::Queue,
Topic::Conflicts,
Topic::Activity,
];
}
/// One line on a [`Request::Subscribe`] connection.
///
/// The two things front ends show continuously, status and transfers, come
/// with their contents, so following them costs no requests. Everything else is
/// a [`Topic`] to re-read.
#[derive(Serialize, Deserialize, Debug)]
pub enum Event {
/// A fresh [`Response::Status`]. Sent when a subscription starts and
/// whenever any of its fields changes.
Status(Box<Response>),
/// A fresh [`Response::Transfers`] snapshot. Sent when a subscription
/// starts and whenever the snapshot changes, which is continuously while
/// something moves.
Transfers {
items: Vec<TransferItem>,
jobs: Vec<JobItem>,
},
/// These topics changed. Changes close together arrive as one event.
Changed { topics: Vec<Topic> },
/// Nothing happened. Sent every [`HEARTBEAT`] so a client can tell a quiet
/// daemon from a stuck one.
Heartbeat,
}
/// How often a quiet subscription sends [`Event::Heartbeat`].
pub const HEARTBEAT: Duration = Duration::from_secs(10);
/// How long [`Subscription::next_event`] waits for a line before it gives the
/// daemon up as stuck: a few missed heartbeats.
const SUBSCRIBE_READ_TIMEOUT: Duration = Duration::from_secs(25);
/// Which kind of share entry a [`ShareEntry`] is, and which collection an
/// [`Request::UpdateShareRole`]/[`Request::RemoveShareEntry`] targets.
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
@@ -739,7 +826,7 @@ pub struct DeviceInfo {
/// One `(sync-conflict …)` copy and the file it is a copy of (in
/// [`Response::Conflicts`]).
#[derive(Serialize, Deserialize, Debug, Clone)]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct ConflictInfo {
/// Mountpoint-relative path of the copy, or its absolute local path when it
/// sits in a synced folder.
@@ -898,7 +985,7 @@ pub struct ShareEntry {
}
/// A node's public link (in [`Response::Share`] / [`Response::PublicLink`]).
#[derive(Serialize, Deserialize, Debug, Clone)]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct PublicLinkInfo {
/// Public-link id — the handle for [`Request::RemovePublicLink`].
pub id: String,
@@ -911,6 +998,9 @@ pub struct PublicLinkInfo {
pub expires: Option<i64>,
/// Whether a custom password additionally protects the link.
pub has_password: bool,
/// When the link was made, epoch seconds; 0 when unknown.
#[serde(default)]
pub created: i64,
}
/// One invitation addressed to me (in [`Response::Invitations`]).
@@ -943,7 +1033,7 @@ pub struct BookmarkInfo {
/// the share's state so the "Shared" view renders in one pass: how many people
/// have access, how many invitations are still pending, and the public link if
/// the node has one.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct SharedItem {
/// Node uid in `volume~link` form — the handle for opening the node's share
/// (via its mount path) or its details.
@@ -1025,7 +1115,7 @@ pub enum ActivityKind {
/// One line in the daemon's activity log (in [`Response::Activity`]). Newest
/// first. Records a mutation or transfer the daemon performed, with enough
/// context to read as a sentence: "Uploaded report.pdf to /docs".
#[derive(Serialize, Deserialize, Debug, Clone)]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct ActivityEntry {
/// When it happened, epoch seconds.
pub time: i64,
@@ -1083,7 +1173,7 @@ pub struct TransferItem {
}
/// One entry in a [`Request::ListDir`] listing.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default)]
pub struct DirEntry {
/// Decrypted node name.
pub name: String,
@@ -1131,6 +1221,16 @@ pub struct DirEntry {
/// warning worth showing.
#[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.
#[serde(default)]
pub trashed_at: i64,
/// The folder a [`Request::ListTrash`] entry goes back to on restore, as a
/// mountpoint-relative path (`""` for the root). `None` when that folder is
/// not known, and for anything not in the trash.
#[serde(default)]
pub trashed_from: Option<String>,
}
/// One hit in a [`Request::Search`] result. Like [`DirEntry`] but carries the
@@ -2046,13 +2146,45 @@ impl ErrorKind {
}
}
impl Request {
/// Whether this is one of the cheap state reads that front ends repeat on a
/// timer. The daemon answers these without touching the network, so they
/// get the short [`POLL_READ_TIMEOUT`].
pub fn is_poll(&self) -> bool {
matches!(
self,
Request::Status
| Request::GetQueueStatus
| Request::ListLocations
| Request::ListPendingOps
| Request::ListConflicts
| Request::ListActivity { .. }
| Request::ThumbnailBuildStatus
| Request::PhotosRefreshStatus
| Request::RedateStatus
| Request::ImportStatus
)
}
/// How long to wait for the daemon's reply to this request.
pub fn read_timeout(&self) -> Duration {
if self.is_poll() {
POLL_READ_TIMEOUT
} else {
READ_TIMEOUT
}
}
}
/// Send one [`Request`] to the daemon listening on `socket` and read its
/// [`Response`]. Returns a crate [`crate::Error`] if no daemon is listening.
/// [`Response`]. Returns a crate [`crate::Error`] if no daemon is listening, and
/// one for which [`crate::Error::is_timeout`] holds if the daemon took longer
/// than [`Request::read_timeout`] to answer.
///
/// Shared by the CLI and GUI so both speak the wire format identically.
pub fn send(socket: &Path, req: &Request) -> Result<Response> {
let mut stream = UnixStream::connect(socket)?;
stream.set_read_timeout(Some(READ_TIMEOUT))?;
stream.set_read_timeout(Some(req.read_timeout()))?;
stream.set_write_timeout(Some(WRITE_TIMEOUT))?;
let mut line = serde_json::to_vec(req)?;
line.push(b'\n');
@@ -2064,10 +2196,232 @@ pub fn send(socket: &Path, req: &Request) -> Result<Response> {
Ok(serde_json::from_str(resp.trim())?)
}
/// An open [`Request::Subscribe`] connection. See [`subscribe`].
pub struct Subscription {
reader: BufReader<UnixStream>,
line: String,
}
/// Start following the daemon listening on `socket`. Fails if no daemon is
/// listening. A daemon too old to know [`Request::Subscribe`] answers it with an
/// error, which the first [`Subscription::next_event`] returns as
/// [`crate::Error::Other`].
pub fn subscribe(socket: &Path) -> Result<Subscription> {
let mut stream = UnixStream::connect(socket)?;
stream.set_read_timeout(Some(SUBSCRIBE_READ_TIMEOUT))?;
stream.set_write_timeout(Some(WRITE_TIMEOUT))?;
let mut line = serde_json::to_vec(&Request::Subscribe)?;
line.push(b'\n');
stream.write_all(&line)?;
stream.flush()?;
Ok(Subscription {
reader: BufReader::new(stream),
line: String::new(),
})
}
impl Subscription {
/// Wait for the next event. `Ok(None)` means the daemon closed the
/// connection; a timeout means it went [`SUBSCRIBE_READ_TIMEOUT`] without
/// even a heartbeat. A line from a newer daemon that this client cannot
/// read is skipped rather than ending the subscription.
pub fn next_event(&mut self) -> Result<Option<Event>> {
loop {
self.line.clear();
if self.reader.read_line(&mut self.line)? == 0 {
return Ok(None);
}
let line = self.line.trim();
if let Ok(event) = serde_json::from_str::<Event>(line) {
return Ok(Some(event));
}
if let Ok(Response::Error { message, .. }) = serde_json::from_str::<Response>(line) {
return Err(crate::Error::Other(message));
}
}
}
}
/// What [`follow`] reports.
#[derive(Debug)]
pub enum Feed {
/// A subscription started. The events after it describe the daemon's
/// current state, so a front-end catches up from them.
Connected,
Event(Event),
/// The subscription ended: the daemon stopped, or stopped answering.
Disconnected,
}
/// How often [`follow`] polls a daemon that cannot push events.
const LEGACY_POLL: Duration = Duration::from_secs(3);
/// The longest [`follow`] waits between attempts to reach a daemon.
const RECONNECT_MAX: Duration = Duration::from_secs(5);
/// Follow the daemon on `socket` for as long as `on` returns true, across
/// daemon restarts. Blocks, so run it on a thread of its own.
///
/// A daemon that predates [`Request::Subscribe`] (still running after an
/// upgrade, until its service restarts) is polled for its status and transfers
/// instead, so a front-end sees the same events either way, only later.
pub fn follow(socket: &Path, mut on: impl FnMut(Feed) -> bool) {
let mut connected = false;
let mut backoff = Duration::from_secs(1);
loop {
let ended = match subscribe(socket) {
Ok(mut subscription) => {
let mut first = true;
loop {
match subscription.next_event() {
Ok(Some(event)) => {
if first {
first = false;
connected = true;
backoff = Duration::from_secs(1);
if !on(Feed::Connected) {
return;
}
}
if !on(Feed::Event(event)) {
return;
}
}
Ok(None) => break Ok(()),
Err(e) => break Err(e),
}
}
}
Err(e) => Err(e),
};
if let Err(crate::Error::Other(_)) = ended {
if !connected {
connected = true;
if !on(Feed::Connected) {
return;
}
}
if !poll_legacy(socket, &mut on) {
return;
}
std::thread::sleep(LEGACY_POLL);
continue;
}
if connected {
connected = false;
if !on(Feed::Disconnected) {
return;
}
}
std::thread::sleep(backoff);
backoff = (backoff * 2).min(RECONNECT_MAX);
}
}
/// One round of [`follow`]'s fallback: the status and transfers a subscription
/// would have pushed. Returns what `on` returned.
fn poll_legacy(socket: &Path, on: &mut impl FnMut(Feed) -> bool) -> bool {
match send(socket, &Request::Status) {
Ok(status @ Response::Status { .. }) => {
if !on(Feed::Event(Event::Status(Box::new(status)))) {
return false;
}
}
_ => return true,
}
if let Ok(Response::Transfers { items, jobs }) = send(socket, &Request::GetQueueStatus) {
return on(Feed::Event(Event::Transfers { items, jobs }));
}
true
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn polls_wait_briefly_and_real_work_waits_long() {
assert_eq!(Request::Status.read_timeout(), POLL_READ_TIMEOUT);
assert_eq!(
Request::ListActivity { limit: 200 }.read_timeout(),
POLL_READ_TIMEOUT
);
assert_eq!(
Request::OpenFile {
path: "a.txt".into(),
uid: None,
}
.read_timeout(),
READ_TIMEOUT
);
}
/// A daemon on a fresh socket that reads the subscription request and
/// answers with `lines`, then hangs up.
fn fake_daemon(name: &str, lines: &'static str) -> std::path::PathBuf {
let socket = std::env::temp_dir().join(format!("pdfs-{name}-{}.sock", std::process::id()));
let _ = std::fs::remove_file(&socket);
let listener = std::os::unix::net::UnixListener::bind(&socket).unwrap();
std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
let mut reader = BufReader::new(stream);
let mut request = String::new();
reader.read_line(&mut request).unwrap();
assert!(matches!(
serde_json::from_str::<Request>(request.trim()),
Ok(Request::Subscribe)
));
reader.get_mut().write_all(lines.as_bytes()).unwrap();
});
socket
}
#[test]
fn a_subscription_skips_what_it_cannot_read() {
let socket = fake_daemon(
"subscribe",
"not json\n\
{\"Changed\":{\"topics\":[\"files\",\"from_a_newer_daemon\"]}}\n\
{\"NewEvent\":{}}\n\
\"Heartbeat\"\n",
);
let mut subscription = subscribe(&socket).unwrap();
let first = subscription.next_event().unwrap();
let second = subscription.next_event().unwrap();
let end = subscription.next_event().unwrap();
let _ = std::fs::remove_file(&socket);
match first {
Some(Event::Changed { topics }) => {
assert_eq!(topics, vec![Topic::Files, Topic::Unknown]);
}
other => panic!("expected a change, got {other:?}"),
}
assert!(matches!(second, Some(Event::Heartbeat)), "{second:?}");
assert!(end.is_none(), "{end:?}");
}
#[test]
fn a_daemon_without_subscriptions_is_told_apart_from_a_dead_one() {
let socket = fake_daemon("legacy", "{\"Error\":{\"message\":\"unknown request\"}}\n");
let mut subscription = subscribe(&socket).unwrap();
let answer = subscription.next_event();
let _ = std::fs::remove_file(&socket);
assert!(matches!(answer, Err(crate::Error::Other(_))), "{answer:?}");
}
#[test]
fn a_daemon_that_never_answers_times_out_as_not_responding() {
let socket = std::env::temp_dir().join(format!("pdfs-silent-{}.sock", std::process::id()));
let _ = std::fs::remove_file(&socket);
// Bound but never accepted: connect succeeds, no reply ever comes.
let _listener = std::os::unix::net::UnixListener::bind(&socket).unwrap();
let started = std::time::Instant::now();
let err = send(&socket, &Request::Status).unwrap_err();
let _ = std::fs::remove_file(&socket);
assert!(err.is_timeout(), "{err}");
assert!(started.elapsed() < READ_TIMEOUT);
}
#[test]
fn photo_kind_classifies_by_extension_then_mime() {
use PhotoKind::*;
+27 -1
View File
@@ -9,7 +9,7 @@ use super::Db;
use crate::Result;
/// Current schema version. Bump on every forward migration added below.
pub(super) const SCHEMA_VERSION: i64 = 34;
pub(super) const SCHEMA_VERSION: i64 = 35;
impl Db {
pub(super) fn migrate(&self) -> Result<()> {
@@ -316,6 +316,22 @@ impl Db {
tx.execute_batch(MIGRATION_V34)?;
}
}
if current < 35 {
// Same guards as V26-V34.
let has_column: bool = tx.query_row(
"SELECT COUNT(*) FROM pragma_table_info('trash') WHERE name = 'trashed_at'",
[],
|row| row.get::<_, i64>(0),
)? > 0;
let has_trash: bool = tx.query_row(
"SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'trash'",
[],
|row| row.get::<_, i64>(0),
)? > 0;
if has_trash && !has_column {
tx.execute_batch(MIGRATION_V35)?;
}
}
tx.execute(
"INSERT INTO sync_state (key, value) VALUES ('schema_version', ?1)
ON CONFLICT(key) DO UPDATE SET value = excluded.value",
@@ -1033,3 +1049,13 @@ UPDATE photos SET resolved_at = NULL;
const MIGRATION_V34: &str = "
ALTER TABLE photos ADD COLUMN similar_hash INTEGER;
";
/// Schema v35: when each trashed node went to the trash.
///
/// The API does not tell this client, so `trashed_at` is when the daemon first
/// saw the node in the trash, in epoch seconds. `NULL` when it cannot say: rows
/// from before this version, and nodes found by a refresh that did not follow a
/// complete one, which may have been in the trash for a long time already.
const MIGRATION_V35: &str = "
ALTER TABLE trash ADD COLUMN trashed_at INTEGER;
";
+11
View File
@@ -583,6 +583,7 @@ fn trash_replace_lists_folders_first() {
size: 10,
mtime: 1,
parent_uid: Some("t2".into()),
trashed_at: Some(100),
},
StoredTrash {
uid: "t2".into(),
@@ -591,6 +592,7 @@ fn trash_replace_lists_folders_first() {
size: 0,
mtime: 2,
parent_uid: None,
trashed_at: None,
},
])
.unwrap();
@@ -613,6 +615,15 @@ fn trash_replace_lists_folders_first() {
]
);
// The first-seen times round-trip, unknown ones included.
let mut seen: Vec<_> = db.trash_seen().unwrap().into_iter().collect();
seen.sort();
assert_eq!(
seen,
[("t1".to_string(), Some(100)), ("t2".to_string(), None)]
);
assert_eq!(items[1].trashed_at, Some(100));
// A replace is a replace: emptying the trash on the server empties it here.
db.trash_replace(&[]).unwrap();
assert!(db.trash_list().unwrap().is_empty());
+25 -4
View File
@@ -1,5 +1,7 @@
//! Trashed nodes, persisted so the trash view opens without a round-trip.
use std::collections::HashMap;
use rusqlite::params;
use super::Db;
@@ -15,6 +17,9 @@ pub struct StoredTrash {
/// row written before schema v29, and for a node whose parent the server
/// did not report.
pub parent_uid: Option<String>,
/// When the daemon first saw the node in the trash, epoch seconds. `None`
/// when it cannot say (see schema v35).
pub trashed_at: Option<i64>,
}
impl Db {
@@ -24,8 +29,8 @@ impl Db {
tx.execute("DELETE FROM trash", [])?;
{
let mut stmt = tx.prepare(
"INSERT INTO trash (uid, name, is_dir, size, mtime, parent_uid) \
VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
"INSERT INTO trash (uid, name, is_dir, size, mtime, parent_uid, trashed_at) \
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
)?;
for item in items {
stmt.execute(params![
@@ -34,7 +39,8 @@ impl Db {
item.is_dir as i64,
item.size,
item.mtime,
item.parent_uid
item.parent_uid,
item.trashed_at
])?;
}
}
@@ -47,7 +53,7 @@ impl Db {
pub fn trash_list(&self) -> Result<Vec<StoredTrash>> {
let conn = self.read();
let mut stmt = conn.prepare(
"SELECT uid, name, is_dir, size, mtime, parent_uid FROM trash
"SELECT uid, name, is_dir, size, mtime, parent_uid, trashed_at FROM trash
ORDER BY is_dir DESC, name COLLATE NOCASE",
)?;
let rows = stmt.query_map([], |r| {
@@ -58,6 +64,7 @@ impl Db {
size: r.get(3)?,
mtime: r.get(4)?,
parent_uid: r.get(5)?,
trashed_at: r.get(6)?,
})
})?;
let mut items = Vec::new();
@@ -81,5 +88,19 @@ impl Db {
Ok(pairs)
}
/// When each node now in the trash was first seen there, keyed by uid, so
/// a refresh can carry the times over into the listing it writes.
pub fn trash_seen(&self) -> Result<HashMap<String, Option<i64>>> {
let conn = self.read();
let mut stmt = conn.prepare("SELECT uid, trashed_at FROM trash")?;
let rows = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?;
let mut seen = HashMap::new();
for row in rows {
let (uid, at) = row?;
seen.insert(uid, at);
}
Ok(seen)
}
// ---- device sync (devices.md) -----------------------------------------
}
+14
View File
@@ -66,6 +66,20 @@ impl Error {
}
}
impl Error {
/// Whether a control-socket round-trip gave up waiting for the reply: the
/// daemon is running but stuck, as opposed to not running at all.
pub fn is_timeout(&self) -> bool {
matches!(
self,
Error::Io(e) if matches!(
e.kind(),
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
)
)
}
}
pub type Result<T> = std::result::Result<T, Error>;
/// A failure on its way to a front-end: prose for the user, plus the
+39
View File
@@ -96,6 +96,26 @@ pub fn is_transient_name(name: &str) -> bool {
false
}
/// Whether `name` is scratch another program writes and throws away: the
/// [`is_transient_name`] set, plus the save-by-rename temporaries of GTK, Qt,
/// Chromium and Electron, generic `.tmp` files and Emacs lock files. None of
/// them is a file the user made, so a front-end can hide them from a history
/// of what happened to the user's files.
pub fn is_scratch_name(name: &str) -> bool {
if is_transient_name(name) {
return true;
}
let lower = name.to_ascii_lowercase();
lower.ends_with(".tmp")
|| lower.ends_with(".temp")
|| name.starts_with(".goutputstream-")
|| name.starts_with(".org.chromium.")
|| name.starts_with(".com.google.chrome.")
|| name.starts_with(".#")
|| (name.starts_with('#') && name.ends_with('#') && name.len() > 1)
|| (name.starts_with('.') && name.contains(".tmp."))
}
/// Filenames accepted as a folder's ignore file, in precedence order.
const IGNORE_FILE_NAMES: &[&str] = &[".pdfsignore", ".protonignore"];
@@ -341,6 +361,25 @@ mod tests {
}
}
#[test]
fn save_by_rename_temporaries_are_scratch() {
for name in [
".goutputstream-4XK2B2",
".org.chromium.Chromium.aBc123",
"~$report.docx",
".~lock.budget.ods#",
".#notes.org",
"#notes.org#",
"cache.tmp",
"page.html.crdownload",
] {
assert!(is_scratch_name(name), "{name}");
}
for name in ["report.docx", "notes.org", "#1 hits.txt", ".bashrc"] {
assert!(!is_scratch_name(name), "{name}");
}
}
#[test]
fn finished_names_are_not_transient() {
for name in [
+6 -4
View File
@@ -15,7 +15,7 @@
use std::collections::{HashMap, HashSet};
use std::sync::atomic::Ordering;
use pdfs_core::control::{AlbumInfo, PhotoItem};
use pdfs_core::control::{AlbumInfo, PhotoItem, Topic};
use pdfs_core::db::StoredAlbum;
use pdfs_core::{CoreError, CoreResult};
@@ -137,10 +137,12 @@ impl Core {
}
let core = self.clone();
self.rt.spawn(async move {
if let Err(e) = core.refresh_albums().await {
warn!(error = %e, "background album refresh failed");
}
let refreshed = core.refresh_albums().await;
core.albums_refreshing.store(false, Ordering::SeqCst);
match refreshed {
Ok(_) => core.events.publish(&[Topic::Photos]),
Err(e) => warn!(error = %e, "background album refresh failed"),
}
});
}
+5
View File
@@ -422,6 +422,10 @@ pub(super) async fn run_event_sync(
cursor = Some(applied);
}
flush_dirty_parents(&core, &dirty);
// Another device changed the tree: whatever a front-end lists may have
// moved, including what is shared and what is in the trash.
core.events
.publish(&[Topic::Files, Topic::Trash, Topic::Shares, Topic::Conflicts]);
}
}
@@ -479,6 +483,7 @@ pub(super) async fn run_photos_event_sync(core: Core) {
continue;
};
apply_photo_events(&core, &events);
core.events.publish(&[Topic::Photos]);
// One cursor write per batch, after the batch is applied: a crash in
// between replays events whose effects are idempotent.
if let Err(error) = core.db.set_state_str(PHOTOS_EVENT_CURSOR, head.as_str()) {
+166 -25
View File
@@ -17,8 +17,8 @@ use std::time::{Duration, Instant};
use pdfs_core::config::AppDirs;
use pdfs_core::control::{
ActivityKind, PhotoMonth, RefreshScope, Request as CtlRequest, Response as CtlResponse,
TransferDirection, TrashFailure,
ActivityKind, Event, HEARTBEAT, PhotoMonth, RefreshScope, Request as CtlRequest,
Response as CtlResponse, Topic, TransferDirection, TrashFailure,
};
use pdfs_core::{CoreError, CoreResult};
use proton_drive_rs::proton_sdk::ids::NodeUid;
@@ -286,6 +286,155 @@ impl Drop for RefreshGuard {
}
}
/// The reply to [`CtlRequest::Status`], which subscriptions are also sent
/// whenever it changes.
pub(crate) fn status_response(core: &Core, username: &str, mountpoint: &Path) -> CtlResponse {
let pins = core.cache.list_pins();
let queued = core.db.pending_op_counts().unwrap_or_default();
let staging = core.cache.staging_usage();
CtlResponse::Status {
parked_uploads: queued.parked.max(0) as u64,
failing_ops: queued.failing.max(0) as u64,
failing_error: queued.last_error.clone(),
staged_bytes: staging.bytes,
staged_oldest_secs: staging.oldest_secs,
paused: core.sync_pause().is_some(),
paused_until: core.sync_pause().flatten(),
username: username.to_string(),
mountpoint: mountpoint.display().to_string(),
pinned: pins.len(),
used: core.cache.usage(),
budget: core.cache.budget(),
pins,
online: core.online.load(Ordering::Relaxed),
pending_uploads: queued.uploads.max(0) as u64,
pending_changes: queued.changes.max(0) as u64,
}
}
/// What a front-end shows that `request` changes when it succeeds. Requests
/// from the CLI publish the same way as the app's, so an open window follows
/// a change made in a terminal.
fn touched_topics(request: &CtlRequest) -> &'static [Topic] {
use CtlRequest as R;
match request {
R::Pin { .. } | R::Unpin { .. } => &[Topic::Files],
R::CreateAlbum { .. }
| R::RenameAlbum { .. }
| R::DeleteAlbum { .. }
| R::AddToAlbum { .. }
| R::RemoveFromAlbum { .. }
| R::SetPhotoFavorite { .. }
| R::UploadPhoto { .. } => &[Topic::Photos],
R::TrashNodes { .. } => &[Topic::Files, Topic::Photos, Topic::Trash, Topic::Conflicts],
R::Rename { .. } | R::Move { .. } | R::CreateFolder { .. } | R::UploadPaths { .. } => {
&[Topic::Files, Topic::Conflicts]
}
R::Delete { .. } => &[Topic::Files, Topic::Trash, Topic::Conflicts],
R::Restore { .. } | R::DeleteForever { .. } | R::EmptyTrash => {
&[Topic::Files, Topic::Photos, Topic::Trash, Topic::Conflicts]
}
R::Refresh { scope } => match scope {
RefreshScope::Dir { .. } => &[Topic::Files],
RefreshScope::Trash => &[Topic::Trash],
// A photos refresh answers once it has started; the timeline
// publishes again when it lands.
RefreshScope::Photos { .. } => &[],
},
R::RenameDevice { .. } | R::DeleteDevice { .. } => &[Topic::Devices],
R::AdoptDevice { .. } => &[Topic::Devices, Topic::Locations],
R::AddSyncFolder { .. }
| R::RemoveSyncFolder { .. }
| R::SetSyncFolderMode { .. }
| R::SetSyncFolderPaused { .. }
| R::RestoreSyncFolders { .. }
| R::RestoreDeviceFolders { .. } => &[Topic::Locations, Topic::Devices],
R::RetryPendingOp { .. } => &[Topic::Queue],
R::ResolveConflict { .. } => &[Topic::Files, Topic::Trash, Topic::Conflicts],
R::ShareNode { .. }
| R::ShareNodeByUid { .. }
| R::UpdateShareRole { .. }
| R::UpdateShareRoleByUid { .. }
| R::RemoveShareEntry { .. }
| R::RemoveShareEntryByUid { .. }
| R::CreatePublicLink { .. }
| R::CreatePublicLinkByUid { .. }
| R::RemovePublicLink { .. }
| R::RemovePublicLinkByUid { .. }
| R::StopSharing { .. }
| R::StopSharingByUid { .. } => &[Topic::Shares, Topic::Files],
R::LeaveShared { .. }
| R::AcceptInvitation { .. }
| R::RejectInvitation { .. }
| R::CreateBookmark { .. }
| R::DeleteBookmark { .. } => &[Topic::Shares],
R::RestoreRevision { .. }
| R::RestoreRevisionByUid { .. }
| R::SaveRevisionAs { .. }
| R::SaveRevisionAsByUid { .. } => &[Topic::Files],
_ => &[],
}
}
/// How long a subscription's writes may block. A client that stops reading
/// is dropped after this rather than holding its handler forever.
const SUBSCRIPTION_WRITE_TIMEOUT: Duration = Duration::from_secs(10);
/// Serve a [`CtlRequest::Subscribe`]: send the current status and transfers
/// and say every topic changed, so the client catches up, then send whatever
/// the [`EventHub`](super::events::EventHub) collects, with a heartbeat when
/// nothing does. Ends when the client goes away or the daemon stops.
fn serve_subscription(core: &Core, username: &str, mountpoint: &Path, mut stream: UnixStream) {
let Some(mailbox) = core.events.subscribe() else {
warn!("control: refusing a subscription at the limit");
if let Ok(mut out) = serde_json::to_vec(&CtlResponse::error(CoreError::remote(
"too many subscriptions",
))) {
out.push(b'\n');
let _ = stream.write_all(&out);
}
return;
};
struct Unsubscribe<'a>(&'a Core, std::sync::Arc<super::events::Mailbox>);
impl Drop for Unsubscribe<'_> {
fn drop(&mut self) {
self.0.events.unsubscribe(&self.1);
}
}
let _unsubscribe = Unsubscribe(core, mailbox.clone());
if let Err(e) = stream.set_write_timeout(Some(SUBSCRIPTION_WRITE_TIMEOUT)) {
warn!(error = %e, "control: could not set subscription timeout");
return;
}
let heartbeat = super::events::event_line(&Event::Heartbeat);
let mut lines: Vec<_> = [
super::events::event_line(&Event::Status(Box::new(status_response(
core, username, mountpoint,
)))),
super::events::transfers_line(core.transfers.snapshot(), core.jobs_snapshot()),
super::events::event_line(&Event::Changed {
topics: Topic::ALL.to_vec(),
}),
]
.into_iter()
.flatten()
.collect();
loop {
for line in &lines {
if stream.write_all(line.as_bytes()).is_err() {
return;
}
}
if core.shutdown.is_stopping() {
return;
}
lines = mailbox.take(HEARTBEAT);
if lines.is_empty() {
lines.extend(heartbeat.clone());
}
}
}
fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: UnixStream) {
if let Err(e) = stream.set_read_timeout(Some(CONTROL_READ_TIMEOUT)) {
warn!(error = %e, "control: could not set request timeout");
@@ -310,32 +459,21 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
return;
}
};
let request = serde_json::from_str::<CtlRequest>(line.trim());
// A subscription lasts as long as its client, so it is not a request in
// flight and stays out of the diagnostics' list of them.
if let Ok(CtlRequest::Subscribe) = request {
serve_subscription(core, username, mountpoint, stream);
return;
}
let touched = request.as_ref().map_or(&[][..], touched_topics);
// Registered before the request is even parsed, so a handler that wedges
// inside the daemon shows up by name in `pdfs diagnostics`.
let _inflight = super::diagnostics::InflightGuard::new(super::diagnostics::request_kind(&line));
let response = match serde_json::from_str::<CtlRequest>(line.trim()) {
Ok(CtlRequest::Status) => {
let pins = core.cache.list_pins();
let queued = core.db.pending_op_counts().unwrap_or_default();
let staging = core.cache.staging_usage();
CtlResponse::Status {
parked_uploads: queued.parked.max(0) as u64,
failing_ops: queued.failing.max(0) as u64,
failing_error: queued.last_error.clone(),
staged_bytes: staging.bytes,
staged_oldest_secs: staging.oldest_secs,
paused: core.sync_pause().is_some(),
paused_until: core.sync_pause().flatten(),
username: username.to_string(),
mountpoint: mountpoint.display().to_string(),
pinned: pins.len(),
used: core.cache.usage(),
budget: core.cache.budget(),
pins,
online: core.online.load(Ordering::Relaxed),
pending_uploads: queued.uploads.max(0) as u64,
pending_changes: queued.changes.max(0) as u64,
}
let response = match request {
Ok(CtlRequest::Status) => status_response(core, username, mountpoint),
Ok(CtlRequest::Subscribe) => {
CtlResponse::error(CoreError::invalid("a subscription is served on its own"))
}
Ok(CtlRequest::Pin { path }) => match rel_to_mount(mountpoint, &path) {
Ok(rel) => match core.pin(&rel) {
@@ -1584,6 +1722,9 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
// The request did not parse: the caller sent something malformed.
Err(e) => CtlResponse::error(CoreError::invalid(format!("bad request: {e}"))),
};
if !touched.is_empty() && !matches!(response, CtlResponse::Error { .. }) {
core.events.publish(touched);
}
let mut out = match serde_json::to_vec(&response) {
Ok(v) => v,
Err(e) => {
+4
View File
@@ -1184,6 +1184,10 @@ impl Core {
format!("{reason}; local changes uploaded as {alt}"),
false,
);
self.events.publish(&[
pdfs_core::control::Topic::Files,
pdfs_core::control::Topic::Conflicts,
]);
info!(%uid, name, alt, "queued write landed as a conflict copy");
Ok(())
}
+321
View File
@@ -0,0 +1,321 @@
//! Push notifications for front-ends: the daemon's side of
//! [`Request::Subscribe`](pdfs_core::control::Request::Subscribe).
//!
//! Front-ends used to poll. The app asked for the status every two seconds, the
//! tray every three, and pages re-read themselves on a timer, whether or not
//! anything had changed. Now each subscription owns a [`Mailbox`] in the
//! [`EventHub`]. Code that changes something publishes a [`Topic`], and
//! [`run_event_sampler`] watches the few things that change without passing
//! through one place (the status, transfers, sync progress) and publishes them
//! when they differ.
use std::collections::BTreeSet;
use std::sync::Arc;
use std::time::Duration;
use parking_lot::{Condvar, Mutex, MutexGuard};
use pdfs_core::control::{Event, JobItem, Response as CtlResponse, Topic, TransferItem};
use tracing::warn;
use super::Core;
/// Most subscriptions served at once. Each holds a control handler for as long
/// as it lasts; the app and the tray need one apiece, and the cap keeps a
/// misbehaving client from spending the handlers that requests need.
const MAX_SUBSCRIBERS: usize = 8;
/// How long a subscription waits after a change before it sends, so a burst
/// (a folder of files trashed at once) goes out as one event.
const COALESCE: Duration = Duration::from_millis(150);
/// How often [`run_event_sampler`] looks at transfers. Status and sync
/// progress are looked at every other time.
const SAMPLE_INTERVAL: Duration = Duration::from_millis(500);
/// Every open subscription's mailbox. Shared by every clone of [`Core`],
/// on-demand forks included, so a change in any mount reaches every client.
#[derive(Default)]
pub(crate) struct EventHub {
mailboxes: Mutex<Vec<Arc<Mailbox>>>,
}
/// What one subscription has yet to send.
#[derive(Default)]
pub(crate) struct Mailbox {
inbox: Mutex<Inbox>,
ready: Condvar,
}
#[derive(Default)]
struct Inbox {
topics: BTreeSet<Topic>,
/// The newest [`Event::Status`] line. A newer one replaces it unsent: a
/// client wants the current status, not every status in between.
status: Option<Arc<str>>,
/// The newest [`Event::Transfers`] line, replaced the same way.
transfers: Option<Arc<str>>,
}
impl Inbox {
fn is_empty(&self) -> bool {
self.topics.is_empty() && self.status.is_none() && self.transfers.is_none()
}
}
/// `event` as one line of the wire format, newline included.
pub(crate) fn event_line(event: &Event) -> Option<Arc<str>> {
match serde_json::to_string(event) {
Ok(mut line) => {
line.push('\n');
Some(line.into())
}
Err(e) => {
warn!(error = %e, "events: serialize event failed");
None
}
}
}
impl EventHub {
/// Tell every subscriber that `topics` changed.
pub(crate) fn publish(&self, topics: &[Topic]) {
self.deliver(|inbox| inbox.topics.extend(topics.iter().copied()));
}
/// Hand every subscriber a fresh status.
fn publish_status(&self, line: Arc<str>) {
self.deliver(|inbox| inbox.status = Some(line.clone()));
}
/// Hand every subscriber a fresh transfers snapshot.
fn publish_transfers(&self, line: Arc<str>) {
self.deliver(|inbox| inbox.transfers = Some(line.clone()));
}
fn deliver(&self, put: impl Fn(&mut Inbox)) {
for mailbox in self.mailboxes.lock().iter() {
put(&mut mailbox.inbox.lock());
mailbox.ready.notify_one();
}
}
/// Open a mailbox, or `None` at [`MAX_SUBSCRIBERS`].
pub(crate) fn subscribe(&self) -> Option<Arc<Mailbox>> {
let mut mailboxes = self.mailboxes.lock();
if mailboxes.len() >= MAX_SUBSCRIBERS {
return None;
}
let mailbox = Arc::new(Mailbox::default());
mailboxes.push(mailbox.clone());
Some(mailbox)
}
pub(crate) fn unsubscribe(&self, mailbox: &Arc<Mailbox>) {
self.mailboxes
.lock()
.retain(|other| !Arc::ptr_eq(other, mailbox));
}
fn has_subscribers(&self) -> bool {
!self.mailboxes.lock().is_empty()
}
}
impl Mailbox {
/// Wait up to `timeout` for something to send, then take it as wire lines:
/// the status first, then transfers, then the changed topics. Empty when
/// nothing arrived in time.
pub(crate) fn take(&self, timeout: Duration) -> Vec<Arc<str>> {
let mut inbox = self.inbox.lock();
if inbox.is_empty() {
self.ready.wait_for(&mut inbox, timeout);
if inbox.is_empty() {
return Vec::new();
}
// Let the rest of a burst arrive before sending the first of it.
MutexGuard::unlocked(&mut inbox, || std::thread::sleep(COALESCE));
}
let mut lines = Vec::new();
lines.extend(inbox.status.take());
lines.extend(inbox.transfers.take());
if !inbox.topics.is_empty() {
let topics = std::mem::take(&mut inbox.topics).into_iter().collect();
lines.extend(event_line(&Event::Changed { topics }));
}
lines
}
}
/// The [`Event::Transfers`] line for a snapshot.
pub(crate) fn transfers_line(items: Vec<TransferItem>, jobs: Vec<JobItem>) -> Option<Arc<str>> {
event_line(&Event::Transfers { items, jobs })
}
/// Watch what changes without a single place to publish it from, and publish it
/// when it differs from the last look: the status (queue counts, cache use,
/// online, pause), the transfers snapshot, and the synced folders with their
/// live progress. Looks only while someone is subscribed.
pub(crate) fn run_event_sampler(core: Core, username: String, mountpoint: std::path::PathBuf) {
let mut transfers: Option<Arc<str>> = None;
let mut status: Option<String> = None;
let mut queue: Option<String> = None;
let mut locations: Option<String> = None;
let mut tick = 0u32;
while core.shutdown.sleep(SAMPLE_INTERVAL) {
if !core.events.has_subscribers() {
// A new subscription starts from a snapshot of its own, so there is
// nothing to compare against until then.
transfers = None;
status = None;
queue = None;
locations = None;
continue;
}
let line = transfers_line(core.transfers.snapshot(), core.jobs_snapshot());
if line.is_some() && line != transfers {
transfers = line.clone();
if let Some(line) = line {
core.events.publish_transfers(line);
}
}
tick = tick.wrapping_add(1);
if !tick.is_multiple_of(2) {
continue;
}
let now = super::control::status_response(&core, &username, &mountpoint);
let (key, queue_key) = status_keys(&now);
if status.as_ref().is_some_and(|last| *last != key)
&& let Some(line) = event_line(&Event::Status(Box::new(now)))
{
core.events.publish_status(line);
}
status = Some(key);
if queue.as_ref().is_some_and(|last| *last != queue_key) {
core.events.publish(&[Topic::Queue]);
}
queue = Some(queue_key);
if let Ok(now) = core.list_locations() {
let key = serde_json::to_string(&now).unwrap_or_default();
if locations.as_ref().is_some_and(|last| *last != key) {
core.events.publish(&[Topic::Locations]);
}
locations = Some(key);
}
}
}
/// What makes two statuses different enough to send, and what makes their
/// queues different. The age of the oldest staged write is left out of both:
/// it grows every second while anything is staged, which is not news.
fn status_keys(status: &CtlResponse) -> (String, String) {
let CtlResponse::Status {
parked_uploads,
failing_ops,
failing_error,
staged_bytes,
paused,
paused_until,
username,
mountpoint,
pinned,
used,
budget,
online,
pending_uploads,
pending_changes,
..
} = status
else {
return (String::new(), String::new());
};
let queue = format!(
"{pending_uploads}/{pending_changes}/{parked_uploads}/{failing_ops}/{failing_error:?}"
);
let key = format!(
"{queue}/{staged_bytes}/{paused}/{paused_until:?}/{username}/{mountpoint}/{pinned}/\
{used}/{budget}/{online}"
);
(key, queue)
}
#[cfg(test)]
mod tests {
use super::*;
fn changed(line: &str) -> Vec<Topic> {
match serde_json::from_str::<Event>(line.trim()) {
Ok(Event::Changed { topics }) => topics,
other => panic!("not a change event: {other:?}"),
}
}
#[test]
fn a_burst_of_changes_arrives_as_one_event() {
let hub = EventHub::default();
let mailbox = hub.subscribe().expect("room for a subscriber");
hub.publish(&[Topic::Trash, Topic::Files]);
hub.publish(&[Topic::Files]);
let lines = mailbox.take(Duration::from_secs(1));
assert_eq!(lines.len(), 1);
assert_eq!(changed(&lines[0]), vec![Topic::Files, Topic::Trash]);
assert!(mailbox.take(Duration::from_millis(10)).is_empty());
}
#[test]
fn a_newer_status_replaces_one_not_yet_sent() {
let hub = EventHub::default();
let mailbox = hub.subscribe().expect("room for a subscriber");
hub.publish_status("first\n".into());
hub.publish_status("second\n".into());
assert_eq!(
mailbox.take(Duration::from_secs(1)),
vec![Arc::<str>::from("second\n")]
);
}
#[test]
fn a_closed_subscription_gets_nothing_more() {
let hub = EventHub::default();
let mailbox = hub.subscribe().expect("room for a subscriber");
hub.unsubscribe(&mailbox);
hub.publish(&[Topic::Files]);
assert!(mailbox.take(Duration::from_millis(10)).is_empty());
assert!(!hub.has_subscribers());
}
#[test]
fn subscriptions_are_capped() {
let hub = EventHub::default();
let open: Vec<_> = (0..MAX_SUBSCRIBERS)
.map(|_| hub.subscribe().expect("room for a subscriber"))
.collect();
assert!(hub.subscribe().is_none());
hub.unsubscribe(&open[0]);
assert!(hub.subscribe().is_some());
}
#[test]
fn the_age_of_a_staged_write_is_not_a_change() {
let status = |staged_oldest_secs| CtlResponse::Status {
parked_uploads: 0,
failing_ops: 0,
failing_error: None,
staged_bytes: 10,
staged_oldest_secs,
paused: false,
paused_until: None,
username: "u".into(),
mountpoint: "/m".into(),
pinned: 0,
used: 0,
budget: 0,
pins: Vec::new(),
online: true,
pending_uploads: 1,
pending_changes: 0,
};
assert_eq!(status_keys(&status(5)), status_keys(&status(6)));
}
}
+83 -6
View File
@@ -60,7 +60,7 @@ use pdfs_core::config::{AppDirs, SweepMode};
use pdfs_core::control::{
ActivityEntry, ActivityKind, DirEntry, ErrorKind, LocalHit, PhotoKind, PublicLinkInfo,
SearchFilters, SearchHit, SearchSource, SyncFolderInfo, SyncPhase, SyncProgress,
ThumbnailBuildStatus, TransferDirection,
ThumbnailBuildStatus, Topic, TransferDirection,
};
use pdfs_core::db::{
Db, LOCAL_VOLUME, OP_CREATE, OP_MKDIR, OP_RENAME, OP_REVISION, OP_TRASH, PARK_UNTIL, PendingOp,
@@ -86,6 +86,7 @@ use control::run_control_socket;
mod devices;
mod diagnostics;
mod drain;
mod events;
mod filesystem;
pub use filesystem::ProtonFs;
mod mount;
@@ -271,6 +272,12 @@ const PHOTOS_AVAILABLE: &str = "photos_available";
const ALBUMS_SYNCED_MS: &str = "albums_synced_ms";
const ALBUM_SYNCED_PREFIX: &str = "album_synced_ms:";
const TRASH_SYNCED_MS: &str = "trash_synced_ms";
/// Set when a trash refresh finishes and cleared when one starts, so it is only
/// present while the stored listing is the whole trash as of some moment. A node
/// that a refresh finds and that listing lacks went to the trash since then; one
/// found after an interrupted refresh may have been there all along. Unlike
/// [`TRASH_SYNCED_MS`], our own mutations leave it alone.
const TRASH_COMPLETE_MS: &str = "trash_complete_ms";
const SHARED_WITH_ME_NAME: &str = "shared_with_me_name";
const SHARED_WITH_ME_SYNCED_MS: &str = "shared_with_me_synced_ms";
const SHARED_FOLDER_SYNCED_PREFIX: &str = "shared_folder_synced_ms:";
@@ -659,6 +666,9 @@ struct Core {
/// In-flight upload/download progress, served to `GetQueueStatus`. Shared
/// across the FUSE session and the control-socket task.
transfers: Arc<TransferRegistry>,
/// Open [`Request::Subscribe`](pdfs_core::control::Request::Subscribe)
/// connections, which every change a front-end shows is published to.
events: Arc<events::EventHub>,
/// True while the background scanner is rebuilding the local-file index, so
/// `SearchLocal` can tell a front-end "still indexing" apart from "no match".
indexing: Arc<AtomicBool>,
@@ -3815,6 +3825,8 @@ impl Core {
shared_by: String::new(),
shared_at: 0,
shared_by_unverified: false,
trashed_at: 0,
trashed_from: None,
})
.collect())
}
@@ -4406,12 +4418,21 @@ impl Core {
self.await_trash_refresh(TRASH_FIRST_WAIT);
}
// 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)?
.into_iter()
.map(|item| 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_at: item.trashed_at.unwrap_or(0),
name: item.name,
is_dir: item.is_dir,
size: item.size.max(0) as u64,
@@ -4450,6 +4471,18 @@ 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
.state_i64(TRASH_COMPLETE_MS)
.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)?;
}
@@ -4470,6 +4503,7 @@ impl Core {
// 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.
@@ -4484,6 +4518,7 @@ 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(),
elapsed_ms = started.elapsed().as_millis() as u64,
@@ -4502,10 +4537,12 @@ impl Core {
}
let core = self.clone();
self.rt.spawn(async move {
if let Err(e) = core.refresh_trash().await {
warn!(error = %e, "background trash refresh failed");
}
let refreshed = core.refresh_trash().await;
core.trash_refreshing.store(false, Ordering::SeqCst);
match refreshed {
Ok(_) => core.events.publish(&[Topic::Trash]),
Err(e) => warn!(error = %e, "background trash refresh failed"),
}
// After the flag, so a waiter that wakes on this sees it cleared.
core.trash_progress.notify_waiters();
});
@@ -4796,6 +4833,14 @@ impl Core {
};
if let Err(e) = self.db.activity_add(&entry) {
warn!(error = ?e, "could not record activity");
return;
}
// A sync pass is how a conflict copy reaches the listing, and the sweep
// reports the ones it finds as conflicts.
if matches!(entry.kind, ActivityKind::Conflict | ActivityKind::Sync) {
self.events.publish(&[Topic::Activity, Topic::Conflicts]);
} else {
self.events.publish(&[Topic::Activity]);
}
}
@@ -4997,6 +5042,7 @@ fn public_link_info(link: proton_drive_rs::PublicLink) -> PublicLinkInfo {
role: role_to_str(link.role).to_string(),
expires: link.expiration_time,
has_password: link.has_custom_password,
created: link.creation_time,
}
}
@@ -5429,6 +5475,25 @@ fn node_size(node: &Node) -> u64 {
}
}
/// 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
/// refresh saw the whole trash (`complete`): after a first or interrupted one,
/// a node missing from the listing may be years old, and no date beats a wrong
/// one.
fn first_seen_in_trash(
seen: &HashMap<String, Option<i64>>,
uid: &str,
complete: bool,
now: i64,
) -> Option<i64> {
match seen.get(uid) {
Some(at) => *at,
None if complete => Some(now),
None => None,
}
}
/// Expand a restore request across the trashed tree, and order it so a parent is
/// always restored before its children.
///
@@ -6220,8 +6285,8 @@ mod tests {
Access, AccessFlags, Errno, HashMap, Intervals, PendingRevision, RootListingSnapshot,
SELF_CHANGE_TTL_MS, ShareId, SharedWithMeItem, StateRegistry, VirtualRootPlan,
accepted_share_provenance, conflict_name, copy_pending_for_truncate, expand_restore,
fuse_name, is_stale_mount, node_visible, note_self_change, orphan_past_retention,
parse_node_uid, prepare_shared_roots, preserve_on_access_denied,
first_seen_in_trash, fuse_name, is_stale_mount, node_visible, note_self_change,
orphan_past_retention, parse_node_uid, prepare_shared_roots, preserve_on_access_denied,
publish_virtual_root_in_listing, reconcile_virtual_root_in_listing,
release_can_discard_unlinked, release_must_retain_queued_trash, release_unlinked_entry,
rename_needs_queue, require_node_parent_access, require_rename_access,
@@ -6364,6 +6429,18 @@ mod tests {
);
}
/// A node keeps the time it was first seen in the trash; a new one is dated
/// now only when the previous refresh saw the whole trash.
#[test]
fn trash_dates_are_kept_and_only_guessed_after_a_complete_refresh() {
let seen = HashMap::from([("old".to_string(), Some(5)), ("unknown".to_string(), None)]);
assert_eq!(first_seen_in_trash(&seen, "old", true, 9), Some(5));
assert_eq!(first_seen_in_trash(&seen, "old", false, 9), Some(5));
assert_eq!(first_seen_in_trash(&seen, "unknown", true, 9), None);
assert_eq!(first_seen_in_trash(&seen, "new", true, 9), Some(9));
assert_eq!(first_seen_in_trash(&seen, "new", false, 9), None);
}
/// A parent chain that loops back on itself must terminate.
#[test]
fn a_cyclic_listing_terminates() {
+17
View File
@@ -416,6 +416,7 @@ pub fn mount(
notifier: Arc::new(OnceLock::new()),
session_live: Arc::new(AtomicBool::new(false)),
transfers: TransferRegistry::new(),
events: Arc::new(Default::default()),
indexing: Arc::new(AtomicBool::new(false)),
sync_progress: Arc::new(Mutex::new(HashMap::new())),
sync_tx,
@@ -568,6 +569,22 @@ pub fn mount(
}
}
}
// Publishes what changes without one place to publish it from (status,
// transfers, sync progress) to the front-ends subscribed on that socket.
{
let sampler_core = core.clone();
let username = username.clone();
let mountpoint = mountpoint.to_path_buf();
match std::thread::Builder::new()
.name("pdfs-events".into())
.spawn(move || events::run_event_sampler(sampler_core, username, mountpoint))
{
Ok(handle) => workers.push(handle),
// Not fatal: front-ends still get every published change, only
// not the sampled ones.
Err(error) => warn!(error = %error, "could not start the event sampler"),
}
}
// The supervisor watches the pool and answers the systemd watchdog. Started
// after the listener, because its liveness probe is a round trip over that
// socket.
+8 -4
View File
@@ -19,7 +19,7 @@ use std::time::{Duration, Instant};
use base64::Engine as _;
use pdfs_core::control::{
FileThumbRequest, MappingProgress, PhotoItem, PhotoKind, PhotoLocation, PhotoThumb, PlaceInfo,
ThumbnailBuildStatus, is_raw_image_name, is_thumbnail_image_name,
ThumbnailBuildStatus, Topic, is_raw_image_name, is_thumbnail_image_name,
};
use pdfs_core::db::{self, StoredPhoto};
use pdfs_core::{CoreError, CoreResult};
@@ -2041,10 +2041,14 @@ impl Core {
}
let core = self.clone();
self.rt.spawn(async move {
if let Err(e) = core.refresh_timeline().await {
warn!(error = %e, "background timeline refresh failed");
}
let refreshed = core.refresh_timeline().await;
core.timeline_refreshing.store(false, Ordering::SeqCst);
// Only a refresh that landed: a front-end re-reading after a failed
// one would find the timeline still stale and start another.
match refreshed {
Ok(_) => core.events.publish(&[Topic::Photos]),
Err(e) => warn!(error = %e, "background timeline refresh failed"),
}
});
}
+2
View File
@@ -73,6 +73,8 @@ fn shared_entry_of(core: &Core, n: Node) -> DirEntry {
shared_by,
shared_at,
shared_by_unverified,
trashed_at: 0,
trashed_from: None,
}
}
@@ -0,0 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<!-- A copy is on this computer: a check in an outlined circle. Adwaita 50
no longer ships emblem-ok-symbolic. -->
<path fill="#222222" fill-rule="evenodd" d="M 8,1 A 7,7 0 1 0 8,15 A 7,7 0 1 0 8,1 Z M 8,2.5 A 5.5,5.5 0 1 1 8,13.5 A 5.5,5.5 0 1 1 8,2.5 Z"/>
<path fill="#222222" d="M 4.1,8.6 L 5.2,7.5 L 7,9.3 L 10.8,5.4 L 11.9,6.5 L 7,11.5 Z"/>
</svg>

After

Width:  |  Height:  |  Size: 450 B

@@ -0,0 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<!-- Show or hide the details pane: a window with its right-hand pane
filled in. Some themes draw sidebar-show-right-symbolic as a solid block. -->
<path fill="#222222" fill-rule="evenodd" d="M 3,2 H 13 A 2,2 0 0 1 15,4 V 12 A 2,2 0 0 1 13,14 H 3 A 2,2 0 0 1 1,12 V 4 A 2,2 0 0 1 3,2 Z M 3,3.5 A 0.5,0.5 0 0 0 2.5,4 V 12 A 0.5,0.5 0 0 0 3,12.5 H 13 A 0.5,0.5 0 0 0 13.5,12 V 4 A 0.5,0.5 0 0 0 13,3.5 Z"/>
<path fill="#222222" d="M 9.5,5 H 12.5 V 11 H 9.5 Z"/>
</svg>

After

Width:  |  Height:  |  Size: 564 B

@@ -0,0 +1,8 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<!-- A share link: two open chain ends and the bar that joins them, laid
on the diagonal. Written out in plain coordinates: GTK's symbolic icon
renderer drops a transformed group. -->
<path fill="#222222" d="M 4.82,6.23 L 3.05,8 A 3.5,3.5 0 0 0 8,12.95 L 9.77,11.18 L 8.53,9.94 L 6.76,11.71 A 1.75,1.75 0 0 1 4.29,9.24 L 6.06,7.47 Z"/>
<path fill="#222222" d="M 6.23,4.82 L 8,3.05 A 3.5,3.5 0 0 1 12.95,8 L 11.18,9.77 L 9.94,8.53 L 11.71,6.76 A 1.75,1.75 0 0 0 9.24,4.29 L 7.47,6.06 Z"/>
<path fill="#222222" d="M 5.26,9.5 L 9.5,5.26 L 10.74,6.5 L 6.5,10.74 Z"/>
</svg>

After

Width:  |  Height:  |  Size: 676 B

@@ -0,0 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<!-- Show on map: a folded map in three panels. No stock theme has a
map-symbolic. -->
<path fill="#222222" d="M 1,3.2 L 5,1.5 V 12.8 L 1,14.5 Z M 11,3.2 L 15,1.5 V 12.8 L 11,14.5 Z"/>
<path fill="#222222" opacity="0.55" d="M 6,1.5 L 10,3.2 V 14.5 L 6,12.8 Z"/>
</svg>

After

Width:  |  Height:  |  Size: 366 B

@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<!-- Main menu: three bars. Bundled because themes such as Papirus draw
open-menu-symbolic as three dots, the same as every row's "more" menu. -->
<path fill="#222222" d="M 2,2.5 H 14 A 1,1 0 0 1 14,4.5 H 2 A 1,1 0 0 1 2,2.5 Z M 2,7 H 14 A 1,1 0 0 1 14,9 H 2 A 1,1 0 0 1 2,7 Z M 2,11.5 H 14 A 1,1 0 0 1 14,13.5 H 2 A 1,1 0 0 1 2,11.5 Z"/>
</svg>

After

Width:  |  Height:  |  Size: 441 B

@@ -0,0 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<!-- Shared with me: two people. system-users-symbolic survives only in
Adwaita's legacy folder. -->
<path fill="#222222" d="M 6,2.5 A 2.5,2.5 0 1 0 6,7.5 A 2.5,2.5 0 1 0 6,2.5 Z M 1.5,14.5 C 1.5,11 3.5,9 6,9 C 8.5,9 10.5,11 10.5,14.5 Z"/>
<path fill="#222222" d="M 11,2.4 A 2.1,2.1 0 1 0 11,6.6 A 2.1,2.1 0 1 0 11,2.4 Z M 9.8,8.4 C 10.2,8.3 10.6,8.25 11,8.25 C 13.3,8.25 15,10 15,13.5 H 11.8 C 11.7,11.5 11,9.7 9.8,8.4 Z"/>
</svg>

After

Width:  |  Height:  |  Size: 529 B

@@ -0,0 +1,8 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<!-- Shared by me: one node passing to two others. Adwaita 50 no longer
ships emblem-shared-symbolic. -->
<path fill="#222222" d="M 12,1.25 A 2.25,2.25 0 1 0 12,5.75 A 2.25,2.25 0 1 0 12,1.25 Z M 4,5.75 A 2.25,2.25 0 1 0 4,10.25 A 2.25,2.25 0 1 0 4,5.75 Z"/>
<path fill="#222222" d="M 4.37,8.65 L 12.37,4.15 L 11.63,2.85 L 3.63,7.35 Z"/>
<path fill="#222222" d="M 12,10.25 A 2.25,2.25 0 1 0 12,14.75 A 2.25,2.25 0 1 0 12,10.25 Z"/>
<path fill="#222222" d="M 3.63,8.65 L 11.63,13.15 L 12.37,11.85 L 4.37,7.35 Z"/>
</svg>

After

Width:  |  Height:  |  Size: 621 B

@@ -0,0 +1,10 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<!-- Syncing: two arrows chasing each other round a circle. Bundled because
Adwaita 50 no longer ships emblem-synchronizing-symbolic. The lower arrow
is the upper one turned half a circle, written out in plain coordinates:
GTK's symbolic icon renderer drops a transformed group. -->
<path fill="#222222" d="M 2,8 A 6,6 0 0 1 12.91,4.56 L 11.48,5.56 A 4.25,4.25 0 0 0 3.75,8 Z"/>
<path fill="#222222" d="M 14.23,3.64 L 14.03,7.68 L 10.17,6.48 Z"/>
<path fill="#222222" d="M 14,8 A 6,6 0 0 1 3.09,11.44 L 4.52,10.44 A 4.25,4.25 0 0 0 12.25,8 Z"/>
<path fill="#222222" d="M 1.77,12.36 L 1.97,8.32 L 5.83,9.52 Z"/>
</svg>

After

Width:  |  Height:  |  Size: 733 B

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<!-- Up to date: a check knocked out of a filled circle. -->
<path fill="#222222" fill-rule="evenodd" d="M 8,1 A 7,7 0 1 0 8,15 A 7,7 0 1 0 8,1 Z M 4.1,8.6 L 5.2,7.5 L 7,9.3 L 10.8,5.4 L 11.9,6.5 L 7,11.5 Z"/>
</svg>

After

Width:  |  Height:  |  Size: 305 B

@@ -0,0 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<!-- Sharing stopped: the share glyph with its last node crossed out. Not
a no-entry sign, which reads as an error. -->
<path fill="#222222" d="M 12,1.25 A 2.25,2.25 0 1 0 12,5.75 A 2.25,2.25 0 1 0 12,1.25 Z M 4,5.75 A 2.25,2.25 0 1 0 4,10.25 A 2.25,2.25 0 1 0 4,5.75 Z"/>
<path fill="#222222" d="M 4.37,8.65 L 12.37,4.15 L 11.63,2.85 L 3.63,7.35 Z"/>
<path fill="#222222" d="M 3.63,8.65 L 8.23,11.25 L 8.97,9.95 L 4.37,7.35 Z"/>
<path fill="#222222" d="M 9.28,11.02 L 13.48,15.22 L 14.72,13.98 L 10.52,9.78 Z"/>
<path fill="#222222" d="M 13.48,9.78 L 9.28,13.98 L 10.52,15.22 L 14.72,11.02 Z"/>
</svg>

After

Width:  |  Height:  |  Size: 706 B

@@ -10,6 +10,16 @@
<file preprocess="xml-stripblanks">scalable/actions/pdfs-filter-symbolic.svg</file>
<file preprocess="xml-stripblanks">scalable/actions/pdfs-offline-symbolic.svg</file>
<file preprocess="xml-stripblanks">scalable/actions/pdfs-online-only-symbolic.svg</file>
<file preprocess="xml-stripblanks">scalable/actions/pdfs-cached-symbolic.svg</file>
<file preprocess="xml-stripblanks">scalable/actions/pdfs-details-pane-symbolic.svg</file>
<file preprocess="xml-stripblanks">scalable/actions/pdfs-link-symbolic.svg</file>
<file preprocess="xml-stripblanks">scalable/actions/pdfs-map-symbolic.svg</file>
<file preprocess="xml-stripblanks">scalable/actions/pdfs-menu-symbolic.svg</file>
<file preprocess="xml-stripblanks">scalable/actions/pdfs-people-symbolic.svg</file>
<file preprocess="xml-stripblanks">scalable/actions/pdfs-share-symbolic.svg</file>
<file preprocess="xml-stripblanks">scalable/actions/pdfs-sync-symbolic.svg</file>
<file preprocess="xml-stripblanks">scalable/actions/pdfs-synced-symbolic.svg</file>
<file preprocess="xml-stripblanks">scalable/actions/pdfs-unshare-symbolic.svg</file>
<!-- The Proton theme's folder: a full-colour icon from the icon theme
can't be recoloured by CSS. -->
<file preprocess="xml-stripblanks">scalable/places/pdfs-proton-folder.svg</file>
+32 -10
View File
@@ -19,6 +19,22 @@
.sidebar-status image.error { color: var(--error-color); }
.sidebar-quota progressbar trough, .sidebar-quota progressbar progress { min-height: 4px; }
.sidebar-account { padding: 4px 4px 4px 8px; }
/* A count of what waits on a page, at the end of its sidebar row */
.sidebar-badge {
min-width: 10px;
padding: 0 7px;
border-radius: 999px;
background: alpha(currentColor, 0.15);
font-size: 0.8em;
font-weight: 700;
}
/* Sync page status card: the state is the headline, the detail explains it */
.sync-card { padding: 18px 24px; }
.sync-card-icon { padding: 6px; }
.sync-card-icon.success { color: var(--success-color); }
.sync-card-icon.warning { color: var(--warning-color); }
.sync-card-icon.error { color: var(--error-color); }
/* File browser */
.file-grid { padding: 6px; }
@@ -27,13 +43,11 @@
.file-tile:selected, .file-tile:hover:selected { background: color-mix(in srgb, var(--accent-bg-color) 20%, transparent); }
.file-thumbnail { border-radius: 7px; }
.file-badge { -gtk-icon-shadow: 0 1px 2px rgba(0, 0, 0, 0.5); }
.badge-pinned { color: var(--yellow-3); }
.badge-pinned { color: var(--success-color); }
.badge-cached { color: var(--success-color); }
.badge-cloud { color: color-mix(in srgb, currentColor 55%, transparent); }
.browser-statusbar { background-color: alpha(currentColor, 0.025); }
scale.browser-status-meter trough, progressbar.browser-status-meter trough { min-width: 104px; }
scale.browser-status-meter trough { min-height: 6px; }
progressbar.browser-status-meter trough, progressbar.browser-status-meter progress { min-height: 6px; }
scale.browser-status-meter trough { min-width: 104px; min-height: 6px; }
.bulk-bar { padding: 6px 8px; border-radius: 12px; background: color-mix(in srgb, var(--accent-bg-color) 12%, transparent); }
.dropzone { border: 2px dashed alpha(currentColor, 0.25); border-radius: 16px; padding: 28px 18px; transition: background 160ms ease, border-color 160ms ease; }
.dropzone-active { border-color: var(--accent-bg-color); background: color-mix(in srgb, var(--accent-bg-color) 10%, transparent); }
@@ -52,19 +66,19 @@ progressbar.browser-status-meter trough, progressbar.browser-status-meter progre
.viewer-nav-btn { background-color: rgba(0, 0, 0, 0.45); color: white; margin: 20px; min-width: 44px; min-height: 44px; border-radius: 50%; opacity: 0.7; transition: opacity 150ms ease, background-color 150ms ease; }
.viewer-nav-btn:hover { background-color: rgba(0, 0, 0, 0.85); color: white; opacity: 1; }
.viewer-nav-btn:disabled { opacity: 0; }
.photo-scrubber { min-width: 20px; padding: 0 2px; }
.photo-scrubber value { font-weight: 600; background-color: var(--popover-bg-color); border-radius: 6px; padding: 2px 8px; }
.photo-scrubber { background: linear-gradient(to left, alpha(var(--window-bg-color), 0.92) 40%, alpha(var(--window-bg-color), 0)); }
.photo-scrubber-knob { background-color: var(--accent-bg-color); border-radius: 2px; }
.photo-scrubber-bubble { font-weight: 600; background-color: var(--popover-bg-color); color: var(--popover-fg-color); border-radius: 999px; padding: 4px 12px; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3); }
.viewer-spinner { color: white; }
.viewer-status { color: white; font-size: 1rem; background-color: rgba(0, 0, 0, 0.75); padding: 12px 24px; border-radius: 12px; }
.viewer-info-panel { background-color: var(--window-bg-color); border-left: 1px solid alpha(currentColor, 0.12); }
/* Photos grid */
.gallery-day { font-size: 0.82rem; font-weight: 700; letter-spacing: 0.04em; text-transform: uppercase; color: alpha(currentColor, 0.65); padding: 2px 2px 6px 2px; }
.photo-tile { padding: 0; margin: 0; min-height: 0; min-width: 0; border: none; border-radius: 4px; background: none; box-shadow: none; transition: box-shadow 180ms ease; }
.photo-tile:hover { box-shadow: 0 8px 22px rgba(0, 0, 0, 0.45); }
.photo-tile { padding: 0; margin: 0; min-height: 0; min-width: 0; border: none; border-radius: 4px; background: none; box-shadow: none; }
.photo-tile:focus { outline: 2px solid var(--accent-color); outline-offset: -2px; }
.photo-thumb { transition: transform 220ms ease; }
.photo-tile:hover .photo-thumb { transform: scale(1.06); }
.photo-tile:hover .photo-thumb { transform: scale(1.02); }
.photo-check { color: white; background: rgba(0, 0, 0, 0.5); border-radius: 999px; padding: 3px; }
.photo-check-on { background: var(--accent-bg-color); color: var(--accent-fg-color); }
.photo-tile-selected { outline: 3px solid var(--accent-bg-color); outline-offset: -3px; }
@@ -83,10 +97,18 @@ progressbar.browser-status-meter trough, progressbar.browser-status-meter progre
.album-cover { border-radius: 16px; background: alpha(currentColor, 0.06); box-shadow: 0 4px 16px rgba(0, 0, 0, 0.32); transition: box-shadow 180ms ease; }
.album-card:hover .album-cover { box-shadow: 0 10px 26px rgba(0, 0, 0, 0.5); }
.album-card:hover .photo-thumb { transform: scale(1.05); }
.view-switch button { padding-left: 18px; padding-right: 18px; }
.view-switch button, .view-switch toggle { padding-left: 18px; padding-right: 18px; }
/* Shared with Me: what a share lets me do, as a tinted pill beside the name. */
.role-pill { padding: 2px 10px; border-radius: 999px; font-weight: 600; color: var(--accent-color); background-color: color-mix(in srgb, var(--accent-bg-color) 16%, transparent); }
.role-pill.warning-pill { color: var(--warning-color); background-color: color-mix(in srgb, var(--warning-bg-color) 20%, transparent); }
/* Activity: the feed sits on the window background as one card per row, under
* day headings, like a boxed list with its rows set apart. */
listview.activity-feed { background: none; color: inherit; padding: 0 12px 18px 12px; }
listview.activity-feed > row { padding: 0; margin-bottom: 6px; background: none; }
listview.activity-feed > header { padding: 18px 6px 6px 6px; background: none; }
listview.activity-feed row.card { border-radius: 12px; }
/* Photos: how many timeline filters are on, as a small badge on the Filters button. */
.filter-count { min-width: 18px; padding: 0 5px; border-radius: 999px; font-size: 0.8em; font-weight: 700; color: var(--accent-fg-color); background-color: var(--accent-bg-color); }
+139
View File
@@ -0,0 +1,139 @@
//! Dates and times as the app shows them, so every page words a moment the
//! same way.
//!
//! - [`relative`] for "when did this happen" in lists: "Just now", "5 min
//! ago", "Yesterday, 14:05", "Tuesday", then a date.
//! - [`short_date`] for date columns: "Sep 23", with the year only when it is
//! not this year.
//! - [`full`] for tooltips: the weekday, date, year and time.
//!
//! The formats are `strftime` patterns that go through gettext, so they follow
//! the language picked in Preferences, not only the system locale.
use gtk4::glib;
use crate::{gettext, gettext_f, ngettext_f};
/// Seconds in a day, for the "within the last week" checks.
const DAY: i64 = 86_400;
/// A past moment in epoch seconds, relative to now. Empty when the time can't
/// be read.
pub(crate) fn relative(secs: i64) -> String {
match (
glib::DateTime::from_unix_local(secs),
glib::DateTime::now_local(),
) {
(Ok(at), Ok(now)) => relative_to(&at, &now),
_ => String::new(),
}
}
/// [`relative`] for a fixed `now`, so it can be tested.
pub(crate) fn relative_to(at: &glib::DateTime, now: &glib::DateTime) -> String {
let ago = now.to_unix() - at.to_unix();
// A clock a little ahead of ours still reads as "just now".
if (-60..60).contains(&ago) {
return gettext("Just now");
}
if (60..3600).contains(&ago) {
let minutes = (ago / 60) as u64;
return ngettext_f("{n} min ago", "{n} min ago", minutes, &[]);
}
// Translators: strftime format for a time of day, such as "14:05".
let time = || format(at, &gettext("%H:%M"));
if at.ymd() == now.ymd() {
return time();
}
if now.add_days(-1).is_ok_and(|y| y.ymd() == at.ymd()) {
// Translators: {time} is a time of day, such as "14:05".
return gettext_f("Yesterday, {time}", &[("time", &time())]);
}
if (0..6 * DAY).contains(&ago) {
return format(at, "%A");
}
short_date_to(at, now)
}
/// A date in epoch seconds, without the time. Empty when the time can't be
/// read.
pub(crate) fn short_date(secs: i64) -> String {
match (
glib::DateTime::from_unix_local(secs),
glib::DateTime::now_local(),
) {
(Ok(at), Ok(now)) => short_date_to(&at, &now),
_ => String::new(),
}
}
/// [`short_date`] for a fixed `now`, so it can be tested.
pub(crate) fn short_date_to(at: &glib::DateTime, now: &glib::DateTime) -> String {
let pattern = if at.year() == now.year() {
// Translators: strftime format for a date in this year, such as "Sep 23".
gettext("%b %-d")
} else {
// Translators: strftime format for a date in another year, such as "Sep 23, 2025".
gettext("%b %-d, %Y")
};
format(at, &pattern)
}
/// The whole moment in epoch seconds, for a tooltip. Empty when the time
/// can't be read.
pub(crate) fn full(secs: i64) -> String {
glib::DateTime::from_unix_local(secs)
.map(|at| {
// Translators: strftime format for a full date and time, such as
// "Wednesday, September 23, 2026, 14:05".
format(&at, &gettext("%A, %B %-d, %Y, %H:%M"))
})
.unwrap_or_default()
}
fn format(at: &glib::DateTime, pattern: &str) -> String {
at.format(pattern)
.map(|s| s.trim().to_string())
.unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
fn at(y: i32, m: i32, d: i32, h: i32, min: i32) -> glib::DateTime {
glib::DateTime::from_local(y, m, d, h, min, 0.0).unwrap()
}
#[test]
fn relative_times_get_coarser_with_age() {
let now = at(2026, 9, 23, 15, 0);
assert_eq!(relative_to(&at(2026, 9, 23, 14, 59), &now), "1 min ago");
assert_eq!(relative_to(&at(2026, 9, 23, 14, 55), &now), "5 min ago");
assert_eq!(relative_to(&at(2026, 9, 23, 9, 5), &now), "09:05");
assert_eq!(
relative_to(&at(2026, 9, 22, 14, 5), &now),
"Yesterday, 14:05"
);
assert_eq!(relative_to(&at(2026, 9, 20, 10, 0), &now), "Sunday");
assert_eq!(relative_to(&at(2026, 9, 1, 10, 0), &now), "Sep 1");
assert_eq!(relative_to(&at(2024, 3, 5, 10, 0), &now), "Mar 5, 2024");
}
#[test]
fn a_moment_ago_or_slightly_ahead_is_just_now() {
let now = at(2026, 9, 23, 15, 0);
assert_eq!(relative_to(&now, &now), "Just now");
assert_eq!(
relative_to(&at(2026, 9, 23, 15, 0), &now.add_seconds(30.0).unwrap()),
"Just now"
);
}
#[test]
fn short_dates_show_the_year_only_when_it_differs() {
let now = at(2026, 9, 23, 15, 0);
assert_eq!(short_date_to(&at(2026, 1, 2, 8, 0), &now), "Jan 2");
assert_eq!(short_date_to(&at(2025, 12, 31, 8, 0), &now), "Dec 31, 2025");
}
}
+179
View File
@@ -0,0 +1,179 @@
//! The window's side of the daemon's event feed ([`Request::Subscribe`]).
//!
//! The window used to ask the daemon for its status every two seconds and let
//! pages re-read themselves on timers. Now one thread follows the feed and hands
//! each event to the main loop: a status or transfers snapshot is painted as it
//! comes, and a change reloads the page on screen if the page shows it. A
//! window nobody can see keeps its changes for later and catches up when it is
//! focused again.
use std::collections::BTreeSet;
use pdfs_core::control::{Event, Feed, follow};
use crate::*;
/// How long the conflict list waits after a change before it is read again.
/// Listing walks every node the daemon knows, and a sync pass can report
/// changes many times a second.
const CONFLICTS_DEBOUNCE: Duration = Duration::from_secs(3);
/// How long the import's state waits after its progress moved before it is
/// read again.
const TAKEOUT_DEBOUNCE: Duration = Duration::from_secs(2);
/// How old the invitations may be when the window is focused. Another person
/// inviting this account sends the daemon no event, so focus is when they are
/// looked for.
const INVITATIONS_ON_FOCUS: Duration = Duration::from_secs(60);
/// What the feed keeps between events.
#[derive(Default)]
struct FeedState {
/// What changed while the window was out of sight.
deferred: RefCell<BTreeSet<Topic>>,
/// Whether a conflict read is already waiting out [`CONFLICTS_DEBOUNCE`].
conflicts_pending: Rc<Cell<bool>>,
/// Whether an import read is already waiting out [`TAKEOUT_DEBOUNCE`].
takeout_pending: Rc<Cell<bool>>,
}
/// Follow the daemon for as long as `window` is open.
pub(crate) fn follow_daemon(ui: &Rc<Ui>, window: &adw::ApplicationWindow) {
let (tx, rx) = async_channel::bounded(64);
let socket = ui.dirs.control_socket();
let spawned = std::thread::Builder::new()
.name("pdfs-feed".into())
.spawn(move || follow(&socket, |feed| tx.send_blocking(feed).is_ok()));
if let Err(e) = spawned {
tracing::error!("cannot start the event feed: {e}");
return;
}
let state = Rc::new(FeedState::default());
let ui_feed = ui.clone();
let state_feed = state.clone();
let window_feed = window.downgrade();
let rx_feed = rx.clone();
glib::spawn_future_local(async move {
while let Ok(feed) = rx_feed.recv().await {
let hidden = window_feed.upgrade().is_none_or(|w| window_hidden(&w));
on_feed(&ui_feed, &state_feed, feed, hidden);
}
});
// Catch up as soon as the user comes back to the window.
let ui_focus = ui.clone();
window.connect_is_active_notify(move |window| {
if !window.is_active() {
return;
}
let topics: Vec<Topic> = state.deferred.take().into_iter().collect();
if !topics.is_empty() {
follow_changes(&ui_focus, &state, &topics);
}
refresh_quota(&ui_focus);
refresh_invitations_badge(&ui_focus, INVITATIONS_ON_FOCUS);
});
// Closing the channel ends the loop above, and the thread with the next
// event it tries to hand over.
window.connect_close_request(move |_| {
rx.close();
glib::Propagation::Proceed
});
}
fn on_feed(ui: &Rc<Ui>, state: &Rc<FeedState>, feed: Feed, hidden: bool) {
match feed {
// The daemon follows up with its whole state, so there is nothing to
// ask for here.
Feed::Connected | Feed::Event(Event::Heartbeat) => {}
Feed::Event(Event::Status(status)) => {
paint_status(ui, *status);
// Uploads are what move the quota, and they move the status too.
refresh_quota(ui);
}
// Painted even out of sight: the end of a batch is what sends the
// "Sync complete" notification.
Feed::Event(Event::Transfers { items, jobs }) => {
repaint_transfers(ui, &items, &jobs);
follow_takeout(ui, state, &jobs);
}
Feed::Event(Event::Changed { topics }) if hidden => {
state.deferred.borrow_mut().extend(topics);
}
Feed::Event(Event::Changed { topics }) => follow_changes(ui, state, &topics),
// Ask once, which paints "not connected" or "not responding", and clear
// progress that can no longer move.
Feed::Disconnected => {
refresh_status(ui);
repaint_transfers(ui, &[], &[]);
}
}
}
/// Reload what `topics` says changed: the sidebar badges wherever the user
/// is, and the page on screen if it shows one of them.
fn follow_changes(ui: &Rc<Ui>, state: &FeedState, topics: &[Topic]) {
let changed = |topic| topics.contains(&topic);
if changed(Topic::Conflicts) {
let ui = ui.clone();
debounce(&state.conflicts_pending, CONFLICTS_DEBOUNCE, move || {
refresh_conflicts(&ui);
if activity_visible(&ui) {
refresh_activity_conflicts(&ui, true);
}
});
}
if changed(Topic::Shares) {
refresh_invitations_badge(ui, Duration::ZERO);
}
match ui.stack.visible_child_name().as_deref() {
Some("browser") if changed(Topic::Files) => load_browser(ui),
// The timeline is left alone: reloading it would throw away the place
// the user scrolled to. F5 reloads it on request.
Some("gallery")
if changed(Topic::Photos)
&& ui.gallery.content.visible_child_name().as_deref() == Some("albums") =>
{
load_albums(ui)
}
Some("trash") if changed(Topic::Trash) => load_trash(ui),
Some("shared") if changed(Topic::Shares) => load_shared(ui),
Some("sharedbyme") if changed(Topic::Shares) || changed(Topic::Files) => {
load_shared_by_me(ui)
}
Some("devices") if changed(Topic::Devices) => load_devices(ui),
Some("locations") => follow_sync_view(ui, topics),
_ => {}
}
}
/// Read the import's state again while its progress moves, and once more after
/// it stops, which is how a finished import is noticed. Nothing is read while
/// no import runs and the page is elsewhere.
fn follow_takeout(ui: &Rc<Ui>, state: &FeedState, jobs: &[JobItem]) {
let importing = jobs.iter().any(|job| job.title == IMPORT_JOB);
if importing
|| ui.takeout.running.get()
|| ui.stack.visible_child_name().as_deref() == Some("takeout")
{
let ui = ui.clone();
debounce(&state.takeout_pending, TAKEOUT_DEBOUNCE, move || {
refresh_takeout(&ui)
});
}
}
/// Run `f` once `delay` has passed, unless a run is already waiting. The run
/// sees everything that happened up to it, so nothing is missed by skipping.
fn debounce(pending: &Rc<Cell<bool>>, delay: Duration, f: impl FnOnce() + 'static) {
if pending.replace(true) {
return;
}
let pending = pending.clone();
glib::timeout_add_local_once(delay, move || {
pending.set(false);
f();
});
}
+265 -258
View File
@@ -1,10 +1,17 @@
#[path = "../activation.rs"]
pub(crate) mod activation;
#[path = "../compat.rs"]
pub(crate) mod compat;
pub(crate) mod dates;
pub(crate) mod events;
#[path = "../i18n.rs"]
pub(crate) mod i18n;
pub(crate) mod pages;
pub(crate) mod reload;
pub(crate) mod widgets;
use compat::*;
use events::*;
use pages::activity::*;
use pages::albums::*;
use pages::browser::*;
@@ -22,13 +29,19 @@ use pages::status::*;
use pages::takeout::*;
use pages::trash::*;
use pages::verify::*;
use reload::{LoadTicket, Loader, replace_items};
use widgets::compat::*;
use widgets::details::*;
use widgets::file_list::*;
use widgets::menu::*;
use widgets::scrubber::*;
use widgets::share_dialog::*;
use widgets::thumbnails::*;
use widgets::versions_dialog::*;
pub(crate) use i18n::{country_name, gettext, gettext_f, gettext_noop, ngettext_f, pgettext};
pub(crate) use i18n::{
country_name, gettext, gettext_f, gettext_noop, human_bytes, ngettext_f, pgettext,
};
use std::cell::{Cell, RefCell};
@@ -59,8 +72,8 @@ use pdfs_core::control::{
DirEntry, ErrorKind, ImportSummary, InvitationInfo, JobItem, MappingProgress, PendingOpInfo,
PhotoItem, PhotoKind, PhotoMonth, PlaceInfo, PublicLinkInfo, RefreshScope, Request, Response,
RestorableFolder, RestoreItem, RevisionInfo, SearchHit, ShareEntry, ShareEntryKind, SharedItem,
SyncFolderInfo, SyncPhase, SyncProgress, ThumbnailBuildStatus, TransferDirection, TransferItem,
send,
SyncFolderInfo, SyncPhase, SyncProgress, ThumbnailBuildStatus, Topic, TransferDirection,
TransferItem, send,
};
use pdfs_core::mounts::{MountAccess, MountKind, MountMode, MountSpec};
@@ -69,20 +82,10 @@ use pdfs_core::service;
const APP_ID: &str = "io.narl.proton-drive-linux";
/// How often the window re-reads mount status, cache usage and the pin list.
const REFRESH_INTERVAL: Duration = Duration::from_secs(2);
/// Backoff between auto-retries of a Files/Photos load while the mount service
/// is still coming up (see [`load_browser`] / [`load_gallery`]).
const CONNECT_RETRY_INTERVAL: Duration = Duration::from_secs(2);
/// How long a network-backed page (Shared, Shared-by-me, Devices, Activity) is
/// considered fresh. Re-navigating to it within this window reuses the rows
/// already on screen instead of re-fetching and flashing the "Loading…"
/// placeholder. The Retry button and every mutation still force an immediate
/// reload by clearing the page's timestamp.
const PAGE_TTL: Duration = Duration::from_secs(30);
/// How often the gallery asks whether the timeline refresh it started has
/// finished.
const PHOTOS_REFRESH_POLL: Duration = Duration::from_secs(2);
@@ -454,8 +457,8 @@ fn build_window(app: &adw::Application) {
let (shared_page, shared_widgets) = build_shared_page();
let (shared_by_me_page, shared_by_me_widgets) = build_shared_by_me_page();
let (devices_page, devices_widgets) = build_devices_page();
let (locations_page, locations_widgets) = build_locations_page();
let (activity_page, activity_widgets) = build_activity_page();
let (locations_page, locations_widgets) = build_locations_page(&activity_page);
let (trash_page, trash_widgets) = build_trash_page();
let (takeout_page, takeout_widgets) = build_takeout_page();
// The login page has no title and no actions, but it still needs a header
@@ -474,7 +477,6 @@ fn build_window(app: &adw::Application) {
stack.add_named(&shared_page, Some("shared"));
stack.add_named(&devices_page, Some("devices"));
stack.add_named(&locations_page, Some("locations"));
stack.add_named(&activity_page, Some("activity"));
stack.add_named(&trash_page, Some("trash"));
stack.add_named(&takeout_page, Some("takeout"));
@@ -520,6 +522,7 @@ fn build_window(app: &adw::Application) {
account_name: main_widgets.account_name.clone(),
avatar: main_widgets.avatar.clone(),
status_icon: main_widgets.status_icon.clone(),
status_spinner: main_widgets.status_spinner.clone(),
status_title: main_widgets.status_title.clone(),
status_detail: main_widgets.status_detail.clone(),
transfer_rows: RefCell::new(Vec::new()),
@@ -549,9 +552,10 @@ fn build_window(app: &adw::Application) {
pins_state: RefCell::new(None),
notified_mounted: Cell::new(None),
active_transfers: Cell::new(0),
transfer_batch: RefCell::new(None),
},
browser: BrowserState {
model: browser_widgets.model.clone(),
files: browser_widgets.files.clone(),
history: RefCell::new(Vec::new()),
future: RefCell::new(Vec::new()),
crumb: browser_widgets.crumb.clone(),
@@ -574,9 +578,8 @@ fn build_window(app: &adw::Application) {
thumbnail_build_running: Cell::new(false),
thumbnail_cancel_pending: Cell::new(false),
search_source: RefCell::new(None),
load_generation: Cell::new(0),
views: browser_widgets.views.clone(),
column_view: browser_widgets.column_view.clone(),
loader: Loader::new(&browser_widgets.content),
listed: RefCell::new(None),
bulk: browser_widgets.bulk.clone(),
bulk_label: browser_widgets.bulk_label.clone(),
bulk_trash: browser_widgets.bulk_trash.clone(),
@@ -586,28 +589,23 @@ fn build_window(app: &adw::Application) {
empty_actions: browser_widgets.empty_actions.clone(),
summary: browser_widgets.summary.clone(),
zoom: browser_widgets.zoom.clone(),
grid_thumbnail_size: Cell::new(GRID_THUMB_DEFAULT),
grid_tiles: RefCell::new(Vec::new()),
quota_box: browser_widgets.quota_box.clone(),
quota: browser_widgets.quota.clone(),
quota_text: browser_widgets.quota_text.clone(),
},
details: DetailsState {
details: browser_widgets.details,
details_entry: RefCell::new(None),
details_suppress: Cell::new(false),
selection: browser_widgets.selection.clone(),
selection: browser_widgets.files.selection.clone(),
},
trash: TrashState {
model: trash_widgets.model.clone(),
files: trash_widgets.files.clone(),
content: trash_widgets.content.clone(),
status: trash_widgets.status.clone(),
retry: trash_widgets.retry.clone(),
empty: trash_widgets.empty.clone(),
subtitle: trash_widgets.subtitle.clone(),
selection: trash_widgets.selection.clone(),
selection_bar: trash_widgets.selection_bar.clone(),
selection_label: trash_widgets.selection_label.clone(),
loader: Loader::new(&trash_widgets.content),
},
gallery: GalleryState {
model: gallery_widgets.model.clone(),
@@ -621,33 +619,28 @@ fn build_window(app: &adw::Application) {
pager: gallery_widgets.pager.clone(),
scrubber: gallery_widgets.scrubber.clone(),
months: RefCell::new(Vec::new()),
scrubbing: Cell::new(false),
scrub_source: RefCell::new(None),
jump: Cell::new(None),
burst: Cell::new(false),
import_banner: gallery_widgets.import_banner.clone(),
upload: gallery_widgets.upload.clone(),
import: gallery_widgets.import.clone(),
empty_actions: gallery_widgets.empty_actions.clone(),
title: gallery_widgets.title.clone(),
albums: gallery_widgets.albums.clone(),
albums_stack: gallery_widgets.albums_stack.clone(),
albums_status: gallery_widgets.albums_status.clone(),
photos_btn: gallery_widgets.photos_btn.clone(),
albums_btn: gallery_widgets.albums_btn.clone(),
view_switch: gallery_widgets.view_switch.clone(),
albums_loading: Cell::new(false),
places: gallery_widgets.places.clone(),
places_stack: gallery_widgets.places_stack.clone(),
places_status: gallery_widgets.places_status.clone(),
places_btn: gallery_widgets.places_btn.clone(),
places_loading: Cell::new(false),
places_mapping: gallery_widgets.places_mapping.clone(),
places_mapping_label: gallery_widgets.places_mapping_label.clone(),
places_mapping_bar: gallery_widgets.places_mapping_bar.clone(),
places_poll: RefCell::new(None),
places_map: gallery_widgets.places_map.clone(),
places_map_btn: gallery_widgets.places_map_btn.clone(),
places_layout: gallery_widgets.places_layout.clone(),
place_count: Cell::new(0),
place: RefCell::new(None),
album: RefCell::new(None),
@@ -688,6 +681,7 @@ fn build_window(app: &adw::Application) {
thumb_source: RefCell::new(None),
relayout_source: RefCell::new(None),
bound: RefCell::new(BTreeMap::new()),
tile_pools: RefCell::new(HashMap::new()),
list: gallery_widgets.list.clone(),
selecting: Cell::new(false),
selected: RefCell::new(HashSet::new()),
@@ -698,43 +692,9 @@ fn build_window(app: &adw::Application) {
select_trash: gallery_widgets.select_trash.clone(),
select_album: gallery_widgets.select_album.clone(),
},
shared: SharedState {
content: shared_widgets.content.clone(),
status: shared_widgets.status.clone(),
retry: shared_widgets.retry.clone(),
with_me_group: shared_widgets.shared_with_me.clone(),
invitations_group: shared_widgets.invitations.clone(),
bookmarks_group: shared_widgets.bookmarks.clone(),
title: shared_widgets.title.clone(),
back: shared_widgets.back.clone(),
add_bookmark: shared_widgets.add_bookmark.clone(),
nav: RefCell::new(Vec::new()),
rows: RefCell::new(Vec::new()),
inflight: Cell::new(false),
loaded_at: Cell::new(None),
},
shared_by_me: SharedByMeState {
content: shared_by_me_widgets.content.clone(),
status: shared_by_me_widgets.status.clone(),
retry: shared_by_me_widgets.retry.clone(),
group: shared_by_me_widgets.group.clone(),
rows: RefCell::new(Vec::new()),
inflight: Cell::new(false),
loaded_at: Cell::new(None),
},
devices: DevicesState {
content: devices_widgets.content.clone(),
status: devices_widgets.status.clone(),
retry: devices_widgets.retry.clone(),
group: devices_widgets.group.clone(),
rows: RefCell::new(Vec::new()),
sync_group: devices_widgets.sync_group.clone(),
sync_rows: RefCell::new(Vec::new()),
rename_this: devices_widgets.rename_this.clone(),
this_device: RefCell::new(None),
inflight: Cell::new(false),
loaded_at: Cell::new(None),
},
shared: SharedState::new(&shared_widgets),
shared_by_me: SharedByMeState::new(&shared_by_me_widgets),
devices: DevicesState::new(&devices_widgets),
locations: LocationsState {
content: locations_widgets.content.clone(),
status: locations_widgets.status.clone(),
@@ -742,10 +702,11 @@ fn build_window(app: &adw::Application) {
group: locations_widgets.group.clone(),
rows: RefCell::new(Vec::new()),
inflight: Cell::new(false),
loaded_at: Cell::new(None),
loader: Loader::new(&locations_widgets.content),
card: SyncCard {
icon: locations_widgets.card_icon.clone(),
row: locations_widgets.card_row.clone(),
title: locations_widgets.card_title.clone(),
detail: locations_widgets.card_detail.clone(),
pause: locations_widgets.pause.clone(),
paused: Cell::new(false),
},
@@ -761,23 +722,26 @@ fn build_window(app: &adw::Application) {
rows: RefCell::new(Vec::new()),
painted: RefCell::new(Vec::new()),
inflight: Cell::new(false),
fetched_at: Cell::new(None),
},
views: locations_widgets.views.clone(),
banner: locations_widgets.banner.clone(),
failing: Cell::new(0),
},
activity: ActivityState {
content: activity_widgets.content.clone(),
status: activity_widgets.status.clone(),
retry: activity_widgets.retry.clone(),
attention: activity_widgets.attention.clone(),
attention_rows: RefCell::new(Vec::new()),
days: activity_widgets.days.clone(),
model: activity_widgets.model.clone(),
feed: activity_widgets.feed.clone(),
inflight: Cell::new(false),
key: RefCell::new(None),
loader: Loader::new(&activity_widgets.content),
items: RefCell::new(Vec::new()),
filter: Cell::new(ActivityFilter::All),
conflicts: RefCell::new(None),
conflicts_inflight: Cell::new(false),
conflicts_at: Cell::new(None),
show_scratch: Cell::new(false),
limit: Cell::new(ACTIVITY_PAGE),
},
takeout: TakeoutState {
archives: RefCell::new(Vec::new()),
@@ -809,7 +773,7 @@ fn build_window(app: &adw::Application) {
&main_widgets.mountpoint_button,
);
wire_sidebar(&ui);
wire_browser(&ui, &browser_widgets.grid, &browser_widgets.column_view);
wire_browser(&ui);
wire_bulk(
&ui,
&browser_widgets.bulk_clear,
@@ -830,32 +794,15 @@ fn build_window(app: &adw::Application) {
&gallery_widgets.empty_upload,
&gallery_widgets.empty_import,
);
let ui_duplicates = ui.clone();
gallery_widgets
.duplicates
.connect_clicked(move |_| show_duplicates(&ui_duplicates));
wire_albums(&ui);
wire_places(&ui);
wire_trash(&ui, &trash_widgets);
wire_shared(&ui, &shared_widgets.retry, &shared_widgets.add_bookmark);
wire_shared_by_me(&ui, &shared_by_me_widgets.retry);
wire_devices(&ui, &devices_widgets.retry);
wire_shared(&ui, &shared_widgets);
wire_shared_by_me(&ui, &shared_by_me_widgets);
wire_devices(&ui, &devices_widgets);
wire_locations(&ui, &locations_widgets.retry, &locations_widgets.add_folder);
wire_activity(&ui, &activity_widgets.retry, &activity_widgets.filters);
wire_activity(&ui, &activity_widgets);
wire_takeout(&ui, &takeout_widgets);
wire_refresh(
&ui,
&[
&browser_widgets.refresh,
&gallery_widgets.refresh,
&trash_widgets.refresh,
&shared_widgets.refresh,
&shared_by_me_widgets.refresh,
&devices_widgets.refresh,
&locations_widgets.refresh,
&activity_widgets.refresh,
],
);
wire_retry(&ui);
// Lazily load the Files / Photos pages the first time they're shown, so the
@@ -870,25 +817,12 @@ fn build_window(app: &adw::Application) {
match st.visible_child_name().as_deref() {
Some("browser") => load_browser(&ui_nav),
Some("gallery") => load_gallery(&ui_nav, false),
// Network-backed pages skip the fetch (and the "Loading…" flash) when
// the rows on screen are still fresh; the Retry button and mutations
// invalidate the timestamp to force a reload.
Some("sharedbyme") if page_fresh(&ui_nav.shared_by_me.loaded_at) => {}
// Every visit reads the page again. The rows already on screen stay
// up while it does, so arriving costs no "Loading…" flash.
Some("sharedbyme") => load_shared_by_me(&ui_nav),
Some("shared") if page_fresh(&ui_nav.shared.loaded_at) => {}
Some("shared") => load_shared(&ui_nav),
Some("devices") if page_fresh(&ui_nav.devices.loaded_at) => {}
Some("devices") => load_devices(&ui_nav),
Some("locations") => {
refresh_conflicts(&ui_nav, true);
if !page_fresh(&ui_nav.locations.loaded_at) {
load_locations(&ui_nav);
}
}
// Activity is intentionally not TTL-cached: it changes out from under
// the page as background uploads and edits complete, so it reloads on
// every visit to stay live.
Some("activity") => load_activity(&ui_nav),
Some("locations") => load_sync_view(&ui_nav),
Some("trash") => load_trash(&ui_nav),
// The import runs in the daemon and outlives this page, so arriving
// here asks straight away whether one is in flight.
@@ -918,29 +852,33 @@ fn build_window(app: &adw::Application) {
app.set_accels_for_action("win.shortcuts", &["<Control>question"]);
refresh(&ui);
// Periodic refresh while the window lives. The closure holds a strong `Rc`;
// it is dropped when the source is removed on window close.
let ui_tick = ui.clone();
let source = glib::timeout_add_local(REFRESH_INTERVAL, move || {
refresh(&ui_tick);
glib::ControlFlow::Continue
});
let cell = RefCell::new(Some(source));
window.connect_close_request(move |_| {
if let Some(id) = cell.borrow_mut().take() {
id.remove();
}
glib::Propagation::Proceed
});
// From here on the daemon says when something changed; nothing polls.
follow_daemon(&ui, &window);
window.present();
}
/// Whether `window` is minimised or otherwise out of sight (another workspace,
/// fully covered), as far as the compositor tells us.
fn window_hidden(window: &adw::ApplicationWindow) -> bool {
if !window.is_visible() {
return true;
}
window
.surface()
.and_downcast::<gtk4::gdk::Toplevel>()
.is_some_and(|toplevel| {
toplevel.state().intersects(
gtk4::gdk::ToplevelState::MINIMIZED | gtk4::gdk::ToplevelState::SUSPENDED,
)
})
}
/// The sidebar destinations, in order: the row index is the index into this table,
/// and each entry is `(stack page name, label, icon)`. The places in the account
/// come first; the rows from [`SIDEBAR_SYNC_SECTION`] on are about this computer's
/// sync, set off by a separator.
const DESTINATIONS: [(&str, &str, &str); 8] = [
const DESTINATIONS: [(&str, &str, &str); 7] = [
("browser", gettext_noop("My files"), "folder-symbolic"),
(
"gallery",
@@ -950,26 +888,17 @@ const DESTINATIONS: [(&str, &str, &str); 8] = [
(
"shared",
gettext_noop("Shared with me"),
"system-users-symbolic",
"pdfs-people-symbolic",
),
(
"sharedbyme",
gettext_noop("Shared by me"),
"emblem-shared-symbolic",
"pdfs-share-symbolic",
),
("devices", gettext_noop("Computers"), "computer-symbolic"),
("trash", gettext_noop("Trash"), "user-trash-symbolic"),
// Translators: sidebar entry for the page listing this computer's synced folders.
(
"locations",
gettext_noop("Sync"),
"emblem-synchronizing-symbolic",
),
(
"activity",
gettext_noop("Activity"),
"document-open-recent-symbolic",
),
("locations", gettext_noop("Sync"), "pdfs-sync-symbolic"),
];
/// Index of the first row in the sidebar's sync section.
@@ -985,7 +914,20 @@ fn build_sidebar(footer: &gtk4::Box) -> (adw::NavigationPage, gtk4::ListBox) {
for (_, label, icon) in DESTINATIONS {
let row_box = gtk4::Box::new(gtk4::Orientation::Horizontal, 12);
row_box.append(&gtk4::Image::from_icon_name(icon));
row_box.append(&gtk4::Label::new(Some(&gettext(label))));
let title = gtk4::Label::builder()
.label(gettext(label))
.xalign(0.0)
.hexpand(true)
.build();
row_box.append(&title);
// A count of what waits there; see `set_sidebar_badge`.
let badge = gtk4::Label::builder()
.visible(false)
.valign(gtk4::Align::Center)
.build();
badge.add_css_class("sidebar-badge");
badge.add_css_class("numeric");
row_box.append(&badge);
let row = gtk4::ListBoxRow::builder().child(&row_box).build();
list.append(&row);
}
@@ -1033,14 +975,13 @@ thread_local! {
/// Every page header's busy spinner. There is one per page because each
/// page has its own header bar; [`Ui::busy_begin`] shows them all, so the one
/// on screen is always the right one.
static BUSY_SPINNERS: RefCell<Vec<gtk4::Spinner>> = const { RefCell::new(Vec::new()) };
static BUSY_SPINNERS: RefCell<Vec<Spinner>> = const { RefCell::new(Vec::new()) };
}
fn set_busy_spinners(visible: bool) {
BUSY_SPINNERS.with(|spinners| {
for spinner in spinners.borrow().iter() {
spinner.set_visible(visible);
spinner.set_spinning(visible);
}
});
}
@@ -1054,11 +995,21 @@ fn page_frame(
content: &impl IsA<gtk4::Widget>,
) -> (adw::ToolbarView, adw::HeaderBar, adw::WindowTitle) {
let window_title = adw::WindowTitle::new(title, "");
let spinner = gtk4::Spinner::new();
let (toolbar, header) = page_frame_with(&window_title, content);
(toolbar, header, window_title)
}
/// [`page_frame`] with `title` in the header's title slot instead of a plain
/// title, such as a view switcher.
fn page_frame_with(
title: &impl IsA<gtk4::Widget>,
content: &impl IsA<gtk4::Widget>,
) -> (adw::ToolbarView, adw::HeaderBar) {
let spinner = spinner();
spinner.set_visible(false);
BUSY_SPINNERS.with(|spinners| spinners.borrow_mut().push(spinner.clone()));
let title_box = gtk4::Box::new(gtk4::Orientation::Horizontal, 6);
title_box.append(&window_title);
title_box.append(title);
title_box.append(&spinner);
let header = adw::HeaderBar::new();
@@ -1066,7 +1017,7 @@ fn page_frame(
let toolbar = adw::ToolbarView::new();
toolbar.add_top_bar(&header);
toolbar.set_content(Some(content));
(toolbar, header, window_title)
(toolbar, header)
}
/// The sidebar destination a page belongs under. Most pages are their own
@@ -1100,43 +1051,15 @@ fn wire_sidebar(ui: &Rc<Ui>) {
});
}
/// Whether a network-backed page painted good data within [`PAGE_TTL`] and so
/// can be reused without re-fetching. A `None` timestamp (never loaded, or
/// invalidated by a mutation) is always stale.
fn page_fresh(loaded_at: &Cell<Option<Instant>>) -> bool {
loaded_at.get().is_some_and(|t| t.elapsed() < PAGE_TTL)
}
/// A page header's Refresh button. Every page that can show stale rows carries
/// one, so the user never has to guess whether what they're looking at is
/// current or wait out a TTL they can't see.
fn refresh_button() -> gtk4::Button {
let button = gtk4::Button::builder()
.icon_name("view-refresh-symbolic")
.tooltip_text(gettext("Refresh (F5)"))
.valign(gtk4::Align::Center)
.build();
button.add_css_class("flat");
button
}
/// Point every page's Refresh button at the current page. One handler for all of
/// them: the button acts on whatever is on screen, so it can't refresh a page the
/// user has since navigated away from.
fn wire_refresh(ui: &Rc<Ui>, buttons: &[&gtk4::Button]) {
for button in buttons {
let ui = ui.clone();
button.connect_clicked(move |_| reload_current_page(&ui));
}
}
/// Re-fetch the visible page from the server, bypassing every layer of cache
/// between it and the account.
///
/// The two layers are separate: the daemon's own persisted listings (folders,
/// trash, photos) are dropped with [`Request::Refresh`] before re-asking, while
/// the pages the daemon always fetches live (sharing, devices, activity) only
/// need this front-end's [`PAGE_TTL`] stamp cleared.
/// The daemon keeps persisted listings (folders, trash, photos), and those are
/// dropped with [`Request::Refresh`] before re-asking. The pages the daemon
/// always fetches live (sharing, devices, activity) are simply loaded again.
///
/// The daemon's events keep every page current on their own. This is for F5,
/// when the account changed somewhere the daemon has not heard about yet.
fn reload_current_page(ui: &Rc<Ui>) {
match ui.stack.visible_child_name().as_deref() {
Some("browser") => {
@@ -1153,23 +1076,10 @@ fn reload_current_page(ui: &Rc<Ui>) {
}
}),
Some("trash") => refresh_then(ui, RefreshScope::Trash, load_trash),
Some("shared") => {
ui.shared.loaded_at.set(None);
load_shared(ui);
}
Some("sharedbyme") => {
ui.shared_by_me.loaded_at.set(None);
load_shared_by_me(ui);
}
Some("devices") => {
ui.devices.loaded_at.set(None);
load_devices(ui);
}
Some("locations") => {
ui.locations.loaded_at.set(None);
load_locations(ui);
}
Some("activity") => load_activity(ui),
Some("shared") => load_shared(ui),
Some("sharedbyme") => load_shared_by_me(ui),
Some("devices") => load_devices(ui),
Some("locations") => reload_sync_view(ui),
_ => {}
}
}
@@ -1253,6 +1163,24 @@ fn sync_sidebar(ui: &Rc<Ui>) {
}
}
/// Show `count` on the sidebar row of `page`, or nothing when it is 0.
pub(crate) fn set_sidebar_badge(ui: &Ui, page: &str, count: u64) {
let Some(index) = DESTINATIONS.iter().position(|(p, _, _)| *p == page) else {
return;
};
let Some(badge) = ui
.sidebar
.row_at_index(index as i32)
.and_then(|row| row.child())
.and_then(|row_box| row_box.last_child())
.and_downcast::<gtk4::Label>()
else {
return;
};
badge.set_visible(count > 0);
badge.set_label(&count.to_string());
}
/// Show a transient toast. Non-blocking by design: an action's outcome is
/// reported without stealing focus or forcing a click, so the user can keep
/// working while a slow upload lands.
@@ -1358,7 +1286,7 @@ fn build_primary_menu() -> gtk4::MenuButton {
Some("win.about"),
);
gtk4::MenuButton::builder()
.icon_name("open-menu-symbolic")
.icon_name("pdfs-menu-symbolic")
.tooltip_text(gettext("Main menu"))
.primary(true)
.menu_model(&menu)
@@ -1383,12 +1311,22 @@ fn install_window_actions(ui: &Rc<Ui>, window: &adw::ApplicationWindow) {
sign_out_action.connect_activate(move |_, _| sign_out(&ui_out));
window.add_action(&sign_out_action);
// The Photos page's import banner leads here.
// The Photos page's import banner and page menu lead here. The import is a
// staged, hours-long migration, so it gets its own page rather than a file
// chooser: the archives need reviewing before anything is sent, and the run
// needs somewhere to report.
let show_import = gio::SimpleAction::new("show-import", None);
let ui_import = ui.clone();
show_import.connect_activate(move |_, _| ui_import.stack.set_visible_child_name("takeout"));
window.add_action(&show_import);
// The Photos page menu's Find Duplicates. The finder opens over the page:
// a review, not a view of it.
let find_duplicates = gio::SimpleAction::new("find-duplicates", None);
let ui_duplicates = ui.clone();
find_duplicates.connect_activate(move |_, _| show_duplicates(&ui_duplicates));
window.add_action(&find_duplicates);
// The Albums view's New Album button.
let new_album = gio::SimpleAction::new("new-album", None);
let ui_album = ui.clone();
@@ -1489,7 +1427,14 @@ fn install_launch_actions(ui: &Rc<Ui>, app: &adw::Application, window: &adw::App
return;
};
// Signed out, the login page owns the window; unknown names are ignored.
if ui_page.session.borrow().is_some() && ui_page.stack.child_by_name(page).is_some() {
if ui_page.session.borrow().is_none() {
return;
}
// Activity lives on as the Sync page's History view.
if page == "activity" {
ui_page.locations.views.set_visible_child_name("history");
ui_page.stack.set_visible_child_name("locations");
} else if ui_page.stack.child_by_name(page).is_some() {
ui_page.stack.set_visible_child_name(page);
}
});
@@ -1502,7 +1447,7 @@ fn install_launch_actions(ui: &Rc<Ui>, app: &adw::Application, window: &adw::App
confirm_stop.connect_activate(move |_, _| {
let dialog = adw::AlertDialog::builder()
.heading(gettext("Stop Proton Drive?"))
.body(gettext("The drive unmounts and nothing syncs until you connect again. Proton Drive starts again at your next login."))
.body(gettext("My files goes offline and nothing syncs until you connect again. Proton Drive starts again at your next login."))
.build();
dialog.add_response("cancel", &gettext("Cancel"));
dialog.add_response("stop", &pgettext("verb", "Stop"));
@@ -1523,7 +1468,7 @@ fn install_launch_actions(ui: &Rc<Ui>, app: &adw::Application, window: &adw::App
toast_error(
&ui,
&gettext("Couldn't stop Proton Drive"),
&gettext("The mount service did not stop."),
&gettext("The Proton Drive service did not stop."),
);
}
});
@@ -1601,36 +1546,17 @@ fn show_shortcuts(window: &adw::ApplicationWindow) {
],
),
];
let page = adw::PreferencesPage::new();
for (title, keys) in GROUPS {
let group = adw::PreferencesGroup::builder()
.title(gettext(title))
.build();
for (accel, action) in keys {
let row = adw::ActionRow::builder().title(gettext(action)).build();
row.add_suffix(
&gtk4::ShortcutLabel::builder()
.accelerator(*accel)
.valign(gtk4::Align::Center)
.build(),
);
group.add(&row);
}
page.add(&group);
}
let dialog = adw::Dialog::builder()
.title(gettext("Keyboard Shortcuts"))
.content_width(460)
.content_height(620)
.child(&{
let toolbar = adw::ToolbarView::new();
toolbar.add_top_bar(&adw::HeaderBar::new());
toolbar.set_content(Some(&page));
toolbar
let groups: Vec<_> = GROUPS
.iter()
.map(|(title, keys)| {
let keys = keys
.iter()
.map(|(accel, action)| (*accel, gettext(action)))
.collect();
(gettext(title), keys)
})
.build();
dialog.present(Some(window));
.collect();
present_shortcuts(window, &groups);
}
/// Window-level keyboard shortcuts, so the browser is usable without the mouse:
@@ -1643,6 +1569,7 @@ fn install_shortcuts(ui: &Rc<Ui>, window: &adw::ApplicationWindow) {
let ctrl = state.contains(gtk4::gdk::ModifierType::CONTROL_MASK);
let alt = state.contains(gtk4::gdk::ModifierType::ALT_MASK);
let on_browser = ui.stack.visible_child_name().as_deref() == Some("browser");
let on_trash = ui.stack.visible_child_name().as_deref() == Some("trash");
match key {
// Refresh works on every page, so it is matched before the
// browser-only bindings.
@@ -1658,20 +1585,18 @@ fn install_shortcuts(ui: &Rc<Ui>, window: &adw::ApplicationWindow) {
ui.browser.search.grab_focus();
}
gtk4::gdk::Key::n | gtk4::gdk::Key::N if ctrl && on_browser => prompt_new_folder(&ui),
gtk4::gdk::Key::_1 if ctrl && on_browser => set_files_view(
gtk4::gdk::Key::_1 | gtk4::gdk::Key::_2 if ctrl && on_browser => set_files_view(
&ui,
FilesView {
list: false,
..ui.browser.view.get()
},
),
gtk4::gdk::Key::_2 if ctrl && on_browser => set_files_view(
&ui,
FilesView {
list: true,
list: key == gtk4::gdk::Key::_2,
..ui.browser.view.get()
},
),
gtk4::gdk::Key::_1 | gtk4::gdk::Key::_2 if ctrl && visible_file_list(&ui).is_some() => {
if let Some(list) = visible_file_list(&ui) {
list.show_list(key == gtk4::gdk::Key::_2);
}
}
gtk4::gdk::Key::Left if alt && on_browser => {
ui.browser.actions.activate_action("back", None)
}
@@ -1687,14 +1612,21 @@ fn install_shortcuts(ui: &Rc<Ui>, window: &adw::ApplicationWindow) {
ui.browser.actions.activate_action("back", None)
}
gtk4::gdk::Key::u | gtk4::gdk::Key::U if ctrl && on_browser => prompt_upload(&ui),
gtk4::gdk::Key::Menu if on_browser => popup_keyboard_context_menu(&ui),
gtk4::gdk::Key::Menu if visible_file_list(&ui).is_some() => {
if let Some(list) = visible_file_list(&ui) {
list.popup_keyboard_menu(&ui);
}
}
gtk4::gdk::Key::Return | gtk4::gdk::Key::KP_Enter if alt && on_browser => {
toggle_details(&ui)
}
gtk4::gdk::Key::F10
if on_browser && state.contains(gtk4::gdk::ModifierType::SHIFT_MASK) =>
if visible_file_list(&ui).is_some()
&& state.contains(gtk4::gdk::ModifierType::SHIFT_MASK) =>
{
popup_keyboard_context_menu(&ui)
if let Some(list) = visible_file_list(&ui) {
list.popup_keyboard_menu(&ui);
}
}
gtk4::gdk::Key::F2 if on_browser => {
// Renaming is one name at a time; saying so beats a key that
@@ -1714,6 +1646,12 @@ fn install_shortcuts(ui: &Rc<Ui>, window: &adw::ApplicationWindow) {
trash_entries(&ui, entries);
}
}
gtk4::gdk::Key::Delete if on_trash => {
let entries = ui.trash.files.selected();
if !entries.is_empty() {
prompt_delete_forever(&ui, &entries);
}
}
gtk4::gdk::Key::Escape
if on_browser
&& (ui.browser.split.shows_sidebar() || ui.browser.bulk.reveals_child()) =>
@@ -1723,6 +1661,15 @@ fn install_shortcuts(ui: &Rc<Ui>, window: &adw::ApplicationWindow) {
clear_details(&ui);
ui.details.details.toggle.set_active(false);
}
gtk4::gdk::Key::Escape
if !on_browser
&& visible_file_list(&ui)
.is_some_and(|list| list.selection.selection().size() > 0) =>
{
if let Some(list) = visible_file_list(&ui) {
list.selection.unselect_all();
}
}
_ => return glib::Propagation::Proceed,
}
glib::Propagation::Stop
@@ -1750,10 +1697,10 @@ fn notify(id: &str, title: &str, body: &str) {
fn spawn_request(
socket: PathBuf,
req: Request,
) -> async_channel::Receiver<Result<Response, String>> {
) -> async_channel::Receiver<Result<Response, pdfs_core::Error>> {
let (tx, rx) = async_channel::bounded(1);
std::thread::spawn(move || {
let result = send(&socket, &req).map_err(|e| e.to_string());
let result = send(&socket, &req);
let _ = tx.send_blocking(result);
});
rx
@@ -1810,6 +1757,77 @@ fn capitalize(s: &str) -> String {
}
}
/// Whether the Proton Drive service is down (failed, or not running at all).
/// Asks systemd on a worker thread: `systemctl` can take seconds to answer,
/// and the window must not freeze while it does.
pub(crate) async fn service_down() -> bool {
gio::spawn_blocking(|| service::is_failed() || !service::is_active())
.await
.unwrap_or(true)
}
/// Restart the Proton Drive service off the main thread, then run `then`.
pub(crate) fn restart_service_then(ui: &Rc<Ui>, then: impl FnOnce(&Rc<Ui>) + 'static) {
let ui = ui.clone();
glib::spawn_future_local(async move {
let _ = gio::spawn_blocking(service::restart).await;
then(&ui);
});
}
/// A page's answer to "the daemon didn't reply". It tells *still starting*
/// (poll again, no button) from *down* (an error with Retry, which restarts the
/// service), so a cold start heals itself but a real failure stays visible.
/// `status` paints the page's status view; `reload` loads the page again, and
/// runs only while `page` is still the one on screen.
pub(crate) fn service_unreachable(
ui: &Rc<Ui>,
page: &'static str,
status: impl Fn(&Rc<Ui>, &str, &str, &str, bool) + 'static,
reload: impl Fn(&Rc<Ui>) + 'static,
) {
let ui = ui.clone();
glib::spawn_future_local(async move {
if service_down().await {
status(
&ui,
"network-offline-symbolic",
&gettext("Not connected"),
&gettext("The Proton Drive service isn't running."),
true,
);
return;
}
status(
&ui,
"network-idle-symbolic",
&gettext("Connecting…"),
&gettext("Waiting for the Proton Drive service to start."),
false,
);
glib::timeout_add_local_once(CONNECT_RETRY_INTERVAL, move || {
if ui.stack.visible_child_name().as_deref() == Some(page) {
reload(&ui);
}
});
});
}
/// How long a copy button shows its check after copying.
const COPIED_FEEDBACK: Duration = Duration::from_millis(1500);
/// Confirm a copy on the button itself: its icon turns into a check for a
/// moment, then back to `icon`.
pub(crate) fn flash_copied(button: &gtk4::Button, icon: &'static str) {
button.set_icon_name("object-select-symbolic");
let button = button.downgrade();
glib::timeout_add_local_once(COPIED_FEEDBACK, move || {
if let Some(button) = button.upgrade() {
button.set_icon_name(icon);
}
});
}
/// Open a local path with the handler the user configured — `xdg-open` unless
/// `open_with` in `config.json` overrides it for this kind of file.
fn open_path(path: &str) {
@@ -1824,17 +1842,6 @@ pub(crate) fn open_named_path(path: &str, name: &str) {
pdfs_core::opener::open_default_named(Path::new(path), name, false);
}
/// Format a byte count as a short binary-unit string (e.g. `1.2 GiB`, or
/// `512 bytes` below one KiB).
///
/// GLib does the formatting, so the units, the plural of "bytes" and the
/// decimal separator follow the user's language from GLib's own catalog. GLib
/// separates number and unit with a no-break space; it is turned back into a
/// plain space so the text matches what the rest of the UI builds around it.
fn human_bytes(bytes: u64) -> String {
glib::format_size_full(bytes, glib::FormatSizeFlags::IEC_UNITS).replace('\u{a0}', " ")
}
#[cfg(test)]
mod tests {
use super::*;
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,609 @@
//! Activity entries as the feed words them.
//!
//! The daemon logs each entry in plain English for its own log and the CLI:
//! a target ("report.pdf", "3 item(s)", "sync conflict in Docs") and a detail
//! ("to /Documents", "was notes.txt", "2 uploaded, 1 deleted"). This module
//! reads the shapes the daemon writes and says them again in the user's
//! language. A shape it does not know, which is mostly an error message,
//! shows as the daemon wrote it.
use crate::*;
/// What a feed row says about one entry.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Described {
pub(crate) title: String,
/// Subtitle parts, shown joined by " · ".
pub(crate) details: Vec<String>,
}
/// The title and subtitle parts for `entry`.
pub(crate) fn describe(entry: &ActivityEntry) -> Described {
let title = entry_title(entry);
let mut details = Vec::new();
if entry.kind == ActivityKind::Conflict
&& let Some(stamp) = conflict_stamp(&entry.target)
{
let when = dates::relative(stamp);
if !when.is_empty() {
// Translators: {time} is when a conflicting copy was made, such as
// "Sep 21" or "5 min ago".
details.push(gettext_f("Made {time}", &[("time", &when)]));
}
}
if let Some(detail) = detail_label(entry) {
details.insert(0, detail);
}
Described { title, details }
}
/// The row title: what happened to what, one sentence per case so a
/// translator can place the name where their language needs it.
fn entry_title(entry: &ActivityEntry) -> String {
use ActivityKind::*;
let target = entry.target.as_str();
let ok = entry.ok;
// Entries whose target is a count or a fixed phrase rather than a name.
match (entry.kind, target) {
(Upload, "Google Photos import") => {
return if ok {
gettext("Imported from Google Photos")
} else {
gettext("Couldn't import from Google Photos")
};
}
(Upload, "bulk upload") => return gettext("Couldn't upload files"),
(Upload, "add sync folder") => return gettext("Couldn't add a sync folder"),
(Download, "restore folders") => return gettext("Couldn't restore folders"),
(Unshare, "shared item") => return gettext("Left a shared item"),
_ => {}
}
if matches!(entry.kind, Restore | DeleteForever | EmptyTrash)
&& let Some(n) = leading_count(target, &["item(s)", "item", "items"])
{
return match entry.kind {
Restore => ngettext_f("Restored {n} item", "Restored {n} items", n, &[]),
DeleteForever => ngettext_f(
"Deleted {n} item forever",
"Deleted {n} items forever",
n,
&[],
),
_ => ngettext_f(
"Emptied the Trash ({n} item)",
"Emptied the Trash ({n} items)",
n,
&[],
),
};
}
if entry.kind == Download
&& let Some(rest) = target.strip_prefix("restored ")
&& let Some(n) = leading_count(rest, &["folder(s)"])
{
return ngettext_f("Restored {n} folder", "Restored {n} folders", n, &[]);
}
if entry.kind == Sync
&& let Some(title) = sync_title(target)
{
return title;
}
let Some(name) = target_name(target) else {
return match entry.kind {
Share => gettext("Shared an item"),
PublicLink => gettext("Created a link to an item"),
Unshare if entry.detail == "link removed" => gettext("Removed a link to an item"),
Unshare => gettext("Stopped sharing an item"),
_ => activity_title(entry.kind, ok, target),
};
};
if entry.kind == Unshare && entry.detail == "link removed" {
// Translators: {name} is a file or folder name.
return gettext_f("Removed the link to {name}", &[("name", &name)]);
}
if entry.kind == Conflict
&& let Some(base) = conflict_base(&name)
{
// Translators: {name} is the file the conflicting copy was made from.
return gettext_f("Conflicting copy of {name}", &[("name", &base)]);
}
activity_title(entry.kind, ok, &name)
}
/// The title of a sync pass or mode switch, whose target is a phrase.
fn sync_title(target: &str) -> Option<String> {
if let Some(name) = target.strip_prefix("sync conflict in ") {
// Translators: {name} is a synced folder's name.
return Some(gettext_f(
"Conflicting changes in {name}",
&[("name", name)],
));
}
if let Some(name) = target.strip_prefix("sync incomplete for ") {
// Translators: {name} is a synced folder's name.
return Some(gettext_f(
"Some items in {name} didn't sync",
&[("name", name)],
));
}
if let Some(name) = target.strip_prefix("sync failed for ") {
// Translators: {name} is a synced folder's name.
return Some(gettext_f("Couldn't sync {name}", &[("name", name)]));
}
if let Some(name) = target.strip_prefix("couldn't switch ") {
// Translators: {name} is a synced folder's name.
return Some(gettext_f(
"Couldn't change how {name} syncs",
&[("name", name)],
));
}
if let Some(path) = target.strip_suffix(" is now on-demand") {
let name = file_name(path);
// Translators: {name} is a folder's name.
return Some(gettext_f("{name} is now online only", &[("name", name)]));
}
if let Some(path) = target.strip_suffix(" is mirroring again; downloading") {
let name = file_name(path);
// Translators: {name} is a folder's name.
return Some(gettext_f("{name} is synced again", &[("name", name)]));
}
if target.starts_with("already ") {
return Some(gettext("Sync mode was already set"));
}
None
}
/// The row title for an activity on a named item.
pub(crate) fn activity_title(kind: ActivityKind, ok: bool, name: &str) -> String {
let args = [("name", name)];
match (kind, ok) {
// Translators: {name} is a file or folder name.
(ActivityKind::Upload, true) => gettext_f("Uploaded {name}", &args),
// Translators: {name} is a file or folder name.
(ActivityKind::Upload, false) => gettext_f("Couldn't upload {name}", &args),
// Translators: {name} is a file or folder name.
(ActivityKind::Download, true) => gettext_f("Downloaded {name}", &args),
// Translators: {name} is a file or folder name.
(ActivityKind::Download, false) => gettext_f("Couldn't download {name}", &args),
// Translators: {name} is a file or folder name.
(ActivityKind::Sync, true) => gettext_f("Synced {name}", &args),
// Translators: {name} is a file or folder name.
(ActivityKind::Sync, false) => gettext_f("Couldn't sync {name}", &args),
// Translators: {name} is a file or folder name.
(ActivityKind::Rename, true) => gettext_f("Renamed {name}", &args),
// Translators: {name} is a file or folder name.
(ActivityKind::Rename, false) => gettext_f("Couldn't rename {name}", &args),
// Translators: {name} is a file or folder name.
(ActivityKind::Move, true) => gettext_f("Moved {name}", &args),
// Translators: {name} is a file or folder name.
(ActivityKind::Move, false) => gettext_f("Couldn't move {name}", &args),
// Translators: {name} is a folder name.
(ActivityKind::CreateFolder, true) => gettext_f("Created folder {name}", &args),
// Translators: {name} is a folder name.
(ActivityKind::CreateFolder, false) => gettext_f("Couldn't create folder {name}", &args),
// Translators: {name} is a file or folder name.
(ActivityKind::Trash, true) => gettext_f("Moved {name} to the Trash", &args),
// Translators: {name} is a file or folder name.
(ActivityKind::Trash, false) => gettext_f("Couldn't move {name} to the Trash", &args),
// Translators: {name} is a file or folder name.
(ActivityKind::Restore, true) => gettext_f("Restored {name}", &args),
// Translators: {name} is a file or folder name.
(ActivityKind::Restore, false) => gettext_f("Couldn't restore {name}", &args),
// Translators: {name} is a file or folder name.
(ActivityKind::DeleteForever, true) => gettext_f("Deleted {name} forever", &args),
// Translators: {name} is a file or folder name.
(ActivityKind::DeleteForever, false) => gettext_f("Couldn't delete {name}", &args),
(ActivityKind::EmptyTrash, true) => gettext("Emptied the Trash"),
(ActivityKind::EmptyTrash, false) => gettext("Couldn't empty the Trash"),
// Translators: {name} is a file or folder name.
(ActivityKind::Share, true) => gettext_f("Shared {name}", &args),
// Translators: {name} is a file or folder name.
(ActivityKind::Share, false) => gettext_f("Couldn't share {name}", &args),
// Translators: {name} is a file or folder name.
(ActivityKind::PublicLink, true) => gettext_f("Created a link to {name}", &args),
// Translators: {name} is a file or folder name.
(ActivityKind::PublicLink, false) => gettext_f("Couldn't create a link to {name}", &args),
// Translators: {name} is a file or folder name.
(ActivityKind::Unshare, true) => gettext_f("Stopped sharing {name}", &args),
// Translators: {name} is a file or folder name.
(ActivityKind::Unshare, false) => gettext_f("Couldn't stop sharing {name}", &args),
// Translators: {name} is the name of the conflicting copy.
(ActivityKind::Conflict, _) => gettext_f("Conflicting copy {name}", &args),
}
}
/// The subtitle's first part: the daemon's detail in the user's language, or
/// `None` when it only repeats the title.
fn detail_label(entry: &ActivityEntry) -> Option<String> {
let detail = entry.detail.trim();
let name = |s: &str| file_name(s).to_string();
match detail {
""
| "uploaded"
| "created"
| "trashed"
| "trashed from the mount"
| "stopped sharing"
| "left"
| "link created"
| "link removed"
| "access removed"
| "removed" => {
return None;
}
"removed on Drive" => return Some(gettext("Removed on Proton Drive")),
"removed locally" => return Some(gettext("Removed on this computer")),
"replaced by a rename from the mount" => {
return Some(gettext("Replaced by a renamed file"));
}
"destination folder no longer exists; the file was left in place" => {
return Some(gettext(
"The destination folder no longer exists, so the file stayed where it was",
));
}
_ => {}
}
if entry.kind == ActivityKind::Upload
&& entry.target == "Google Photos import"
&& entry.ok
&& let Some(summary) = import_summary(detail)
{
return Some(summary);
}
if entry.kind == ActivityKind::Sync
&& let Some(summary) = sync_summary(detail)
{
return Some(summary);
}
if let Some(dest) = detail.strip_prefix("to ") {
// Translators: {name} is the folder an item was moved into.
return Some(gettext_f("To {name}", &[("name", &folder_name(dest))]));
}
if let Some(old) = detail.strip_prefix("was ") {
// Translators: {name} is an item's previous name.
return Some(gettext_f("Previously {name}", &[("name", &name(old))]));
}
if detail.starts_with("restored version ") {
return Some(gettext("Restored an earlier version"));
}
if detail.starts_with("deleted version ") {
return Some(gettext("Deleted an earlier version"));
}
if let Some(rest) = detail.strip_prefix("saved version ")
&& let Some((_, path)) = rest.split_once(" to ")
{
// Translators: {path} is where an earlier version was saved.
return Some(gettext_f(
"Saved an earlier version to {path}",
&[("path", &tilde_path(path))],
));
}
if let Some(copy) = detail.strip_prefix("kept both; the copy is now ") {
// Translators: {name} is the new name of the conflicting copy.
return Some(gettext_f(
"Kept both; the copy is now {name}",
&[("name", copy)],
));
}
if let Some(base) = detail
.strip_prefix("kept ")
.and_then(|rest| rest.strip_suffix("; the copy is in Trash"))
{
// Translators: {name} is the file that was kept.
return Some(gettext_f(
"Kept {name}; the copy is in the Trash",
&[("name", base)],
));
}
if detail.starts_with("kept the conflict copy ") {
return Some(gettext("Kept the conflicting copy"));
}
if let Some(base) = detail.strip_prefix("kept ") {
// Translators: {name} is the file that was kept.
return Some(gettext_f("Kept {name}", &[("name", base)]));
}
if let Some(base) = detail.strip_prefix("auto-removed duplicate of ") {
// Translators: {name} is the file the removed copy was identical to.
return Some(gettext_f(
"Same as {name}, so it was removed",
&[("name", base)],
));
}
if let Some(alt) = detail.strip_prefix("destination already had that name; moved as ") {
// Translators: {name} is the name the item was given instead.
return Some(gettext_f(
"The name was taken, so it was moved as {name}",
&[("name", alt)],
));
}
if let Some(alt) = detail.strip_prefix("name was taken remotely; renamed to ") {
// Translators: {name} is the name the item was given instead.
return Some(gettext_f(
"The name was taken on Proton Drive, so it was renamed to {name}",
&[("name", alt)],
));
}
if let Some(alt) = detail.strip_prefix("name was taken remotely; created as ") {
// Translators: {name} is the name the item was given instead.
return Some(gettext_f(
"The name was taken on Proton Drive, so it was created as {name}",
&[("name", alt)],
));
}
if let Some(alt) =
detail.strip_prefix("its folder was trashed remotely; created in the root as ")
{
// Translators: {name} is the name the item was given.
return Some(gettext_f(
"Its folder was moved to the Trash on Proton Drive, so it was created at the top as {name}",
&[("name", alt)],
));
}
if let Some(base) = detail.strip_prefix("differs from ") {
// Translators: {name} is the file the conflicting copy was made from.
return Some(gettext_f("Differs from {name}", &[("name", base)]));
}
if let Some(base) = detail
.strip_prefix("no original ")
.and_then(|rest| rest.strip_suffix(" to reconcile against"))
{
// Translators: {name} is the file the conflicting copy was made from.
return Some(gettext_f("{name} no longer exists", &[("name", base)]));
}
if let Some(base) = detail
.strip_prefix("identical to ")
.and_then(|rest| rest.split_once(';').map(|(base, _)| base))
{
// Translators: {name} is the file the conflicting copy was made from.
return Some(gettext_f("Same as {name}", &[("name", base)]));
}
if let Some((n, role)) = detail
.split_once(" recipient(s) as ")
.and_then(|(n, role)| Some((n.parse::<u64>().ok()?, role)))
{
return Some(match role {
"viewer" => ngettext_f("{n} person can view", "{n} people can view", n, &[]),
"editor" => ngettext_f("{n} person can edit", "{n} people can edit", n, &[]),
_ => ngettext_f("{n} person invited", "{n} people invited", n, &[]),
});
}
if let Some(n) = leading_count(detail, &["file(s) kept as conflict copies"]) {
return Some(ngettext_f(
"{n} file kept as a conflicting copy",
"{n} files kept as conflicting copies",
n,
&[],
));
}
if let Some(n) = leading_count(detail, &["item(s) failed; will retry"]) {
return Some(ngettext_f(
"{n} item failed and will be tried again",
"{n} items failed and will be tried again",
n,
&[],
));
}
Some(capitalize(detail))
}
/// A sync pass summary such as "2 uploaded, 1 folder(s) created", as a
/// list of counts. `None` when a part is not one the daemon writes.
fn sync_summary(detail: &str) -> Option<String> {
let mut parts = Vec::new();
for part in detail.split(", ") {
let (n, label) = part.split_once(' ')?;
let n = n.parse::<u64>().ok()?;
parts.push(match label {
// Translators: part of a list summing up a sync pass.
"uploaded" => ngettext_f("{n} uploaded", "{n} uploaded", n, &[]),
// Translators: part of a list summing up a sync pass.
"downloaded" => ngettext_f("{n} downloaded", "{n} downloaded", n, &[]),
// Translators: part of a list summing up a sync pass.
"folder(s) created" => ngettext_f("{n} folder created", "{n} folders created", n, &[]),
// Translators: part of a list summing up a sync pass.
"deleted" => ngettext_f("{n} deleted", "{n} deleted", n, &[]),
// Translators: part of a list summing up a sync pass.
"conflicted" => ngettext_f("{n} in conflict", "{n} in conflict", n, &[]),
// Translators: part of a list summing up a sync pass; the files are
// still open in another app.
"deferred (open for write)" => ngettext_f("{n} still open", "{n} still open", n, &[]),
// Translators: part of a list summing up a sync pass.
"failed" => ngettext_f("{n} failed", "{n} failed", n, &[]),
_ => return None,
});
}
Some(parts.join(", "))
}
/// A Google Photos import summary such as "40 uploaded · 2 already there".
fn import_summary(detail: &str) -> Option<String> {
let mut parts = Vec::new();
for part in detail.split(" · ") {
if part == "cancelled" {
parts.push(gettext("Cancelled"));
continue;
}
let (n, label) = part.split_once(' ')?;
let n = n.parse::<u64>().ok()?;
parts.push(match label {
"uploaded" => ngettext_f("{n} uploaded", "{n} uploaded", n, &[]),
// Translators: photos an import skipped because they were already
// in Proton Drive.
"already there" => ngettext_f("{n} already there", "{n} already there", n, &[]),
"albums" => ngettext_f("{n} album", "{n} albums", n, &[]),
"failed" => ngettext_f("{n} failed", "{n} failed", n, &[]),
_ => return None,
});
}
Some(parts.join(" · "))
}
/// The number in front of `text` when the rest is one of `units`, as in
/// "3 item(s)".
fn leading_count(text: &str, units: &[&str]) -> Option<u64> {
let (n, unit) = text.split_once(' ')?;
units.contains(&unit).then_some(())?;
n.parse().ok()
}
/// The name to show for a target: the last part of a path, or `None` when
/// the daemon logged a node id because it had no path.
fn target_name(target: &str) -> Option<String> {
let looks_like_uid =
target.len() >= 40 && target.matches('~').count() == 1 && !target.contains(['/', ' ', '.']);
if target.is_empty() || looks_like_uid {
return None;
}
Some(file_name(target).to_string())
}
/// The folder a destination path names, with the root read as "My files".
fn folder_name(dest: &str) -> String {
let name = file_name(dest.trim_end_matches('/'));
if name.is_empty() {
gettext("My files")
} else {
name.to_string()
}
}
/// The file a `name (sync-conflict <stamp>).ext` copy was made from.
pub(crate) fn conflict_base(name: &str) -> Option<String> {
let (start, close) = conflict_marker(name)?;
Some(format!("{}{}", &name[..start], &name[close + 1..]))
}
/// When a conflicting copy was made, from the stamp in its name.
fn conflict_stamp(name: &str) -> Option<i64> {
let (start, close) = conflict_marker(name)?;
let inner = &name[start + MARKER.len()..close];
inner.split('-').next()?.parse().ok()
}
const MARKER: &str = " (sync-conflict ";
/// Where the ` (sync-conflict <stamp>[-<n>])` marker starts and where its
/// closing parenthesis is. The same shape the daemon reads back.
fn conflict_marker(name: &str) -> Option<(usize, usize)> {
let start = name.find(MARKER)?;
let after = start + MARKER.len();
let close = after + name[after..].find(')')?;
let inner = &name[after..close];
let mut parts = inner.splitn(2, '-');
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
if !digits(parts.next()?) || parts.next().is_some_and(|s| !digits(s)) {
return None;
}
Some((start, close))
}
#[cfg(test)]
mod tests {
use super::*;
fn entry(kind: ActivityKind, target: &str, detail: &str, ok: bool) -> ActivityEntry {
ActivityEntry {
time: 0,
kind,
target: target.into(),
detail: detail.into(),
ok,
}
}
#[test]
fn details_that_repeat_the_title_are_dropped() {
let d = describe(&entry(ActivityKind::Upload, "a.txt", "uploaded", true));
assert_eq!(d.title, "Uploaded a.txt");
assert!(d.details.is_empty());
}
#[test]
fn paths_and_counts_read_as_names_and_numbers() {
let d = describe(&entry(
ActivityKind::Move,
"/mnt/a.txt",
"to /mnt/Docs",
true,
));
assert_eq!(d.title, "Moved a.txt");
assert_eq!(d.details, vec!["To Docs"]);
let d = describe(&entry(ActivityKind::Restore, "3 item(s)", "", true));
assert_eq!(d.title, "Restored 3 items");
let d = describe(&entry(ActivityKind::EmptyTrash, "1 item", "", true));
assert_eq!(d.title, "Emptied the Trash (1 item)");
}
#[test]
fn failures_say_what_could_not_happen() {
let d = describe(&entry(
ActivityKind::Upload,
"a.txt",
"quota exceeded",
false,
));
assert_eq!(d.title, "Couldn't upload a.txt");
assert_eq!(d.details, vec!["Quota exceeded"]);
}
#[test]
fn sync_passes_are_summed_up() {
let d = describe(&entry(
ActivityKind::Sync,
"Docs",
"2 uploaded, 1 folder(s) created",
true,
));
assert_eq!(d.title, "Synced Docs");
assert_eq!(d.details, vec!["2 uploaded, 1 folder created"]);
let d = describe(&entry(
ActivityKind::Sync,
"sync incomplete for Docs",
"2 item(s) failed; will retry",
false,
));
assert_eq!(d.title, "Some items in Docs didn't sync");
assert_eq!(d.details, vec!["2 items failed and will be tried again"]);
}
#[test]
fn a_conflicting_copy_names_its_original() {
let d = describe(&entry(
ActivityKind::Conflict,
"notes (sync-conflict 1700000000).txt",
"differs from notes.txt",
false,
));
assert_eq!(d.title, "Conflicting copy of notes.txt");
assert_eq!(d.details[0], "Differs from notes.txt");
assert_eq!(d.details.len(), 2);
assert_eq!(conflict_base("a (sync-conflict 12-2)"), Some("a".into()));
assert_eq!(conflict_base("a (sync-conflict x).txt"), None);
}
#[test]
fn node_ids_are_not_shown_as_names() {
let uid = format!("{}~{}", "A".repeat(30), "B".repeat(30));
let d = describe(&entry(
ActivityKind::Share,
&uid,
"1 recipient(s) as viewer",
true,
));
assert_eq!(d.title, "Shared an item");
assert_eq!(d.details, vec!["1 person can view"]);
}
#[test]
fn unknown_details_show_as_written() {
let d = describe(&entry(
ActivityKind::Download,
"a.txt",
"network timeout",
false,
));
assert_eq!(d.details, vec!["Network timeout"]);
}
}
+16 -14
View File
@@ -83,7 +83,7 @@ pub(crate) fn load_albums(ui: &Rc<Ui>) {
&ui,
"network-offline-symbolic",
&gettext("Not connected"),
&gettext("The Proton Drive mount service didn't respond."),
&gettext("The Proton Drive service didn't respond."),
),
}
});
@@ -286,7 +286,7 @@ pub(crate) fn prompt_new_album(ui: &Rc<Ui>, photos: Vec<String>) {
_ => toast_error(
&ui,
&gettext("Couldn't create the album"),
&gettext("The mount service didn't respond."),
&gettext("The Proton Drive service didn't respond."),
),
}
});
@@ -351,7 +351,11 @@ fn run_album_request(ui: &Rc<Ui>, request: Request, done: String, failed: String
Ok(Ok(Response::Error { message, kind })) => {
toast_failure(&ui, &failed, &message, kind)
}
_ => toast_error(&ui, &failed, &gettext("The mount service didn't respond.")),
_ => toast_error(
&ui,
&failed,
&gettext("The Proton Drive service didn't respond."),
),
}
});
}
@@ -380,7 +384,7 @@ pub(crate) fn prompt_add_to_album(ui: &Rc<Ui>, photos: Vec<String>) {
toast_error(
&ui,
&gettext("Couldn't load albums"),
&gettext("The mount service didn't respond."),
&gettext("The Proton Drive service didn't respond."),
);
return;
}
@@ -487,7 +491,7 @@ fn add_to_album(ui: &Rc<Ui>, album: String, photos: Vec<String>) {
_ => toast_error(
&ui,
&gettext("Couldn't add to the album"),
&gettext("The mount service didn't respond."),
&gettext("The Proton Drive service didn't respond."),
),
}
});
@@ -559,7 +563,7 @@ pub(crate) fn remove_from_album(ui: &Rc<Ui>, album: &AlbumInfo, photos: Vec<Stri
toast_error(
&ui,
&gettext("Couldn't remove from the album"),
&gettext("The mount service didn't respond."),
&gettext("The Proton Drive service didn't respond."),
)
}
}
@@ -614,7 +618,7 @@ pub(crate) fn open_album(ui: &Rc<Ui>, album: AlbumInfo) {
// would silently do something else. The Photos/Albums switcher goes too: an
// album is a level below it, and back is the way out.
ui.gallery.filters.set_visible(false);
ui.gallery.view_switch.set_visible(false);
ui.gallery.view_switch.widget().set_visible(false);
ui.gallery.upload.set_visible(false);
ui.gallery.back.set_visible(true);
// A stale kind/date filter would otherwise be sent with the album request.
@@ -632,7 +636,7 @@ pub(crate) fn close_album(ui: &Rc<Ui>) {
return;
}
ui.gallery.title.set_title(&gettext("Photos"));
ui.gallery.view_switch.set_visible(true);
ui.gallery.view_switch.widget().set_visible(true);
ui.gallery.upload.set_visible(true);
ui.gallery.back.set_visible(false);
}
@@ -649,17 +653,15 @@ fn albums_status(ui: &Rc<Ui>, icon: &str, title: &str, description: &str) {
/// whole content area; back leaves an open album for the grid it came from.
pub(crate) fn wire_albums(ui: &Rc<Ui>) {
let ui_albums = ui.clone();
ui.gallery.albums_btn.clone().connect_toggled(move |btn| {
if btn.is_active() {
ui.gallery.view_switch.connect_changed(move |view| {
if view == VIEW_ALBUMS {
show_albums(&ui_albums);
}
});
// Only the button being switched *on* acts: the group fires `toggled` for
// the one going off too, and acting on both would load twice.
let ui_photos = ui.clone();
ui.gallery.photos_btn.clone().connect_toggled(move |btn| {
if !btn.is_active() {
ui.gallery.view_switch.connect_changed(move |view| {
if view != VIEW_TIMELINE {
return;
}
close_album(&ui_photos);
File diff suppressed because it is too large. Load diff
+506 -276
View File
@@ -1,85 +1,115 @@
use crate::*;
pub(crate) struct DevicesState {
// Devices page: two sections (synced folders + other devices), rebuilt
// wholesale on each load.
// Computers page: one list of the account's computers, this one first, and
// a read-only browser over another computer's backup.
/// "list", "browse", or "status" while the page loads or can't be read.
pub(crate) content: gtk4::Stack,
pub(crate) status: adw::StatusPage,
pub(crate) retry: gtk4::Button,
pub(crate) group: adw::PreferencesGroup,
/// Rows added last time, removed before the next paint (adw groups have no
/// clear-all).
pub(crate) rows: RefCell<Vec<gtk4::Widget>>,
pub(crate) sync_group: adw::PreferencesGroup,
/// The single "This computer" summary row. The per-folder rows moved to the
/// Locations page, which owns every local path.
pub(crate) sync_rows: RefCell<Vec<gtk4::Widget>>,
/// "Rename" action in the "This computer" header. Insensitive until the
/// device list identifies this machine's own device.
pub(crate) rename_this: gtk4::Button,
/// This machine's own device `(uid, name)`, from the last device list. The
/// current device is filtered out of the "Other computers" rows, so this is
/// where its rename target lives. `None` until identified.
pub(crate) this_device: RefCell<Option<(String, String)>>,
pub(crate) inflight: Cell<bool>,
pub(crate) loaded_at: Cell<Option<Instant>>,
/// The browse view's files.
pub(crate) files: FileList,
/// The browse view: "list", or "empty".
pub(crate) files_content: gtk4::Stack,
/// The breadcrumb trail from "Computers" down to the current folder.
pub(crate) crumb: gtk4::Box,
/// Grid or list for the browse view; hidden on the device list.
pub(crate) layout: gtk4::Button,
/// Where the browse view is, as `(uid, name)`: the computer first, then each
/// folder below it. Empty = the device list. A backup has no path in the
/// mount, so descending is uid-addressed and the stack is the breadcrumb.
pub(crate) nav: RefCell<Vec<(String, String)>>,
/// The [`DevicesState::nav`] the page on screen was painted for, or `None`
/// before the first paint.
pub(crate) listed: RefCell<Option<Vec<(String, String)>>>,
/// Runs the loads; the rows stay up while one runs.
pub(crate) loader: Rc<Loader>,
}
impl DevicesState {
pub(crate) fn new(widgets: &DevicesWidgets) -> Self {
DevicesState {
content: widgets.content.clone(),
status: widgets.status.clone(),
retry: widgets.retry.clone(),
group: widgets.group.clone(),
rows: RefCell::new(Vec::new()),
files: widgets.files.clone(),
files_content: widgets.files_content.clone(),
crumb: widgets.crumb.clone(),
layout: widgets.layout.clone(),
nav: RefCell::new(Vec::new()),
listed: RefCell::new(None),
loader: Loader::new(&widgets.content),
}
}
}
/// Widgets the Devices page's load/repaint touch.
pub(crate) struct DevicesWidgets {
pub(crate) content: gtk4::Stack,
pub(crate) status: adw::StatusPage,
/// "This computer" — this machine's device identity and a pointer to its
/// folders on the Locations page.
pub(crate) sync_group: adw::PreferencesGroup,
/// "Rename" in the "This computer" header — renames this machine's device.
pub(crate) rename_this: gtk4::Button,
/// "Other computers" — the account's *other* registered devices. This
/// machine's own device is deliberately not among them; see
/// [`repaint_devices`].
/// Every computer on the account, this one first.
pub(crate) group: adw::PreferencesGroup,
pub(crate) files: FileList,
pub(crate) files_content: gtk4::Stack,
/// Goes up one folder, and from a computer's top level back to the list.
pub(crate) back: gtk4::Button,
pub(crate) crumb: gtk4::Box,
pub(crate) layout: gtk4::Button,
pub(crate) retry: gtk4::Button,
pub(crate) refresh: gtk4::Button,
}
/// The Computers page: a "This computer" section naming the device this machine
/// backs up to (renamable from its header), plus an "Other computers" section
/// listing the account's other registered devices. The synced folders
/// themselves live on the Sync page.
/// The Computers page: every computer backing up to the account, with this one
/// first. This computer's row leads to its folders on the Sync page; another
/// computer's row opens its backup read-only, in the same list as My files.
pub(crate) fn build_devices_page() -> (gtk4::Widget, DevicesWidgets) {
let refresh = refresh_button();
// This page is about device *identity* — which computer this is, which other
// computers back up to the account, and how to adopt one. The folders
// themselves are local paths, so they live on the Sync page; keeping a
// second copy of that list here would be two places to change the same mode.
let sync_group = adw::PreferencesGroup::builder()
.title(gettext("This computer"))
.description(gettext("The computer this machine backs up as."))
.build();
// Rename control for *this* machine's device, in the section header. The
// current device is filtered out of "Other computers", so this is the only
// place it can be renamed; insensitive until the device list identifies it.
let rename_this = gtk4::Button::builder()
.icon_name("document-edit-symbolic")
.tooltip_text(gettext("Rename this computer"))
.valign(gtk4::Align::Center)
.sensitive(false)
.build();
rename_this.add_css_class("flat");
sync_group.set_header_suffix(Some(&rename_this));
let group = adw::PreferencesGroup::builder()
.title(gettext("Other computers"))
.description(gettext("Other computers backing up to this account."))
.build();
let groups = gtk4::Box::new(gtk4::Orientation::Vertical, 18);
groups.append(&sync_group);
groups.append(&group);
let clamp = adw::Clamp::builder().child(&groups).build();
let group = adw::PreferencesGroup::new();
let clamp = adw::Clamp::builder().child(&group).build();
let scroll = gtk4::ScrolledWindow::builder()
.vexpand(true)
.child(&clamp)
.build();
// Browse: a path bar over the list, as on Shared with me.
let files = FileList::new();
files.show_list(true);
let layout = layout_button(&files);
layout.set_visible(false);
let back = gtk4::Button::builder()
.icon_name("go-previous-symbolic")
.tooltip_text(gettext("Back"))
.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 path_bar = gtk4::Box::new(gtk4::Orientation::Horizontal, 8);
path_bar.append(&back);
path_bar.append(&crumb_scroll);
let files_empty = adw::StatusPage::builder()
.icon_name("folder-open-symbolic")
.title(gettext("This folder is empty"))
.description(gettext("Nothing in this folder has been backed up."))
.vexpand(true)
.build();
files_empty.add_css_class("compact");
let files_content = gtk4::Stack::new();
files_content.add_named(&files.views, Some("list"));
files_content.add_named(&files_empty, Some("empty"));
let browse = gtk4::Box::new(gtk4::Orientation::Vertical, 12);
browse.append(&path_bar);
browse.append(&files_content);
let retry = gtk4::Button::builder()
.label(gettext("Retry"))
.halign(gtk4::Align::Center)
@@ -98,6 +128,7 @@ pub(crate) fn build_devices_page() -> (gtk4::Widget, DevicesWidgets) {
content.set_vexpand(true);
content.set_transition_type(gtk4::StackTransitionType::Crossfade);
content.add_named(&scroll, Some("list"));
content.add_named(&browse, Some("browse"));
content.add_named(&status, Some("status"));
let inner = gtk4::Box::new(gtk4::Orientation::Vertical, 12);
@@ -107,35 +138,66 @@ pub(crate) fn build_devices_page() -> (gtk4::Widget, DevicesWidgets) {
inner.set_margin_end(18);
inner.append(&content);
let (frame, header, _) = page_frame(&gettext("Computers"), &inner);
header.pack_end(&refresh);
header.pack_end(&layout);
(
frame.upcast(),
DevicesWidgets {
content,
status,
sync_group,
rename_this,
group,
files,
files_content,
back,
crumb,
layout,
retry,
refresh,
},
)
}
/// Install the Devices page's retry button and the Rename action.
pub(crate) fn wire_devices(ui: &Rc<Ui>, retry: &gtk4::Button) {
/// Install the browse view's file list and the page's buttons.
pub(crate) fn wire_devices(ui: &Rc<Ui>, widgets: &DevicesWidgets) {
let files = &ui.devices.files;
files.wire(
ui,
FileListBehavior {
activate: open_device_entry,
entry_menu: device_entry_menu,
bulk_menu: device_bulk_menu,
background_menu: device_background_menu,
badges: false,
drag_and_drop: false,
},
);
files
.column_view
.append_column(&text_column(&pgettext("column", "Modified"), |e| {
if e.modified > 0 {
dates::short_date(e.modified)
} else {
"—".to_string()
}
}));
files
.column_view
.append_column(&text_column(&pgettext("column", "Size"), |e| {
if e.is_dir {
"—".to_string()
} else {
human_bytes(e.size)
}
}));
let ui_back = ui.clone();
widgets.back.connect_clicked(move |_| {
ui_back.devices.nav.borrow_mut().pop();
load_devices(&ui_back);
});
let ui_retry = ui.clone();
retry.connect_clicked(move |_| {
service::restart();
load_devices(&ui_retry);
});
let ui_ren = ui.clone();
ui.devices.rename_this.connect_clicked(move |_| {
if let Some((uid, name)) = ui_ren.devices.this_device.borrow().clone() {
prompt_rename_device(&ui_ren, &uid, &name);
}
});
widgets
.retry
.connect_clicked(move |_| restart_service_then(&ui_retry, load_devices));
}
/// Show a status page in place of the Devices list.
@@ -147,21 +209,17 @@ pub(crate) fn devices_status(ui: &Rc<Ui>, icon: &str, title: &str, description:
ui.devices.content.set_visible_child_name("status");
}
/// Fetch this machine's synced folders and the account's other devices, then
/// repaint both sections. The two requests are chained so a single unreachable
/// daemon collapses the whole page to a status view.
/// Load the view [`DevicesState::nav`] points at: the device list, or a folder
/// of another computer's backup.
pub(crate) fn load_devices(ui: &Rc<Ui>) {
if ui.devices.inflight.get() {
cancel_file_thumbnails(ui);
let nav = ui.devices.nav.borrow().clone();
ui.devices.layout.set_visible(!nav.is_empty());
if !nav.is_empty() {
load_device_folder(ui, &nav);
return;
}
ui.devices.inflight.set(true);
devices_status(
ui,
"computer-symbolic",
&gettext("Loading…"),
&gettext("Reading your computers."),
false,
);
let ticket = begin_devices_load(ui, "computer-symbolic", gettext("Reading your computers."));
ui.busy_begin();
// The two lists are independent and the daemon serves requests concurrently,
// so fire both up front and collect them, rather than paying two round trips
@@ -172,213 +230,361 @@ pub(crate) fn load_devices(ui: &Rc<Ui>) {
glib::spawn_future_local(async move {
let sync = rx.recv().await;
let devices_reply = rx2.recv().await;
ui.busy_end();
if !ticket.is_current() {
return;
}
let folders = match sync {
Ok(Ok(Response::SyncFolders { items })) => items,
// The daemon answered but not as expected — treat as empty and carry
// on to the devices list rather than failing the whole page.
Ok(Ok(_)) => Vec::new(),
Ok(Err(_)) | Err(_) => {
ui.busy_end();
ui.devices.inflight.set(false);
ui.devices.loaded_at.set(None);
devices_unreachable(&ui);
return;
}
};
// Daemon reachable: show the list and paint the "This computer" section.
ui.devices.content.set_visible_child_name("list");
repaint_this_computer(&ui, &folders);
let devices = match devices_reply {
Ok(Ok(Response::Devices { items })) => items,
_ => Vec::new(),
};
ui.busy_end();
ui.devices.inflight.set(false);
repaint_devices(&ui, &devices);
ui.devices.loaded_at.set(Some(Instant::now()));
ui.devices.content.set_visible_child_name("list");
repaint_devices(&ui, &devices, &folders);
repaint_device_crumb(&ui, &[]);
*ui.devices.listed.borrow_mut() = Some(Vec::new());
});
}
/// List one folder of another computer's backup. The computer's own top level
/// is its restorable folders; below that, any folder lists by uid.
fn load_device_folder(ui: &Rc<Ui>, nav: &[(String, String)]) {
let ticket = begin_devices_load(ui, "folder-symbolic", gettext("Reading this folder."));
ui.busy_begin();
let (uid, _) = nav.last().cloned().unwrap_or_default();
let request = if nav.len() == 1 {
Request::ListDeviceRestorableFolders { device: uid }
} else {
Request::ListSharedFolder { uid }
};
let rx = spawn_request(ui.dirs.control_socket(), request);
let ui = ui.clone();
let nav = nav.to_vec();
glib::spawn_future_local(async move {
let result = rx.recv().await;
ui.busy_end();
if !ticket.is_current() {
return;
}
let entries = match result {
Ok(Ok(Response::Entries { entries })) => entries,
Ok(Ok(Response::RestorableFolders { items })) => {
items.into_iter().map(restorable_entry).collect()
}
Ok(Ok(Response::Error { message, kind })) => {
// The folder or the computer is gone: fall back a level rather
// than stranding the page on a dead uid.
ui.devices.nav.borrow_mut().pop();
toast_failure(&ui, &gettext("Couldn't open folder"), &message, kind);
load_devices(&ui);
return;
}
_ => {
devices_unreachable(&ui);
return;
}
};
ui.devices.content.set_visible_child_name("browse");
repaint_device_crumb(&ui, &nav);
*ui.devices.listed.borrow_mut() = Some(nav);
if entries.is_empty() {
ui.devices.files.model.remove_all();
ui.devices.files_content.set_visible_child_name("empty");
} else {
ui.devices.files_content.set_visible_child_name("list");
replace_items(&ui.devices.files.model, &entries);
}
});
}
/// A computer's top-level folder as a browsable entry.
fn restorable_entry(folder: RestorableFolder) -> DirEntry {
DirEntry {
name: folder.name,
is_dir: true,
uid: folder.remote_uid,
..DirEntry::default()
}
}
/// Start a load of the view [`DevicesState::nav`] points at. A reload of the
/// view on screen keeps it up and usable; moving elsewhere greys it out until
/// the new view arrives.
fn begin_devices_load(ui: &Rc<Ui>, icon: &'static str, description: String) -> LoadTicket {
let ui_p = ui.clone();
let placeholder = move || {
devices_status(&ui_p, icon, &gettext("Loading…"), &description, false);
};
if *ui.devices.listed.borrow() == Some(ui.devices.nav.borrow().clone()) {
ui.devices.loader.refresh(placeholder)
} else {
ui.devices.listed.borrow_mut().take();
ui.devices.loader.replace(placeholder)
}
}
/// The daemon didn't answer the Devices page.
pub(crate) fn devices_unreachable(ui: &Rc<Ui>) {
if service::is_failed() || !service::is_active() {
devices_status(
ui,
"network-offline-symbolic",
&gettext("Not connected"),
&gettext("The Proton Drive mount service isn't running."),
true,
);
return;
}
devices_status(
ui,
"folder-remote-symbolic",
&gettext("Connecting…"),
&gettext("Waiting for the Proton Drive mount service to come up."),
false,
);
let ui = ui.clone();
glib::timeout_add_local_once(CONNECT_RETRY_INTERVAL, move || {
if ui.stack.visible_child_name().as_deref() == Some("devices") {
load_devices(&ui);
}
});
service_unreachable(ui, "devices", devices_status, load_devices);
}
/// Rebuild the "Other computers" section from a fresh listing. Empty is a normal
/// state (this machine may be the only device), so it shows a placeholder row
/// rather than collapsing the page.
/// Rebuild the device list: this computer first, then the others.
///
/// This machine's own device is filtered out. Deleting a device deletes its root
/// folder — every file backed up from it — and for *this* machine that would also
/// pull the ground out from under the synced folders listed directly above, so it
/// is not offered as a peer of "remove some other laptop". Removing this
/// computer's backup means removing its folders, each of which asks about its
/// cloud copy on its own terms.
pub(crate) fn repaint_devices(ui: &Rc<Ui>, devices: &[DeviceInfo]) {
/// This computer's row offers no Remove. Deleting a device deletes its root
/// folder — every file backed up from it — and for this machine that would also
/// pull the ground out from under its synced folders, so it is not offered as a
/// peer of "remove some other laptop". Removing this computer's backup means
/// removing its folders, each of which asks about its cloud copy on its own
/// terms.
pub(crate) fn repaint_devices(ui: &Rc<Ui>, devices: &[DeviceInfo], folders: &[SyncFolderInfo]) {
for row in ui.devices.rows.borrow_mut().drain(..) {
ui.devices.group.remove(&row);
}
// Identify this machine's own device so the "This computer" header's Rename
// action has a target. It never appears in the rows below, so this is the
// only place its name/uid is captured.
match devices.iter().find(|d| d.this_device) {
Some(me) => {
*ui.devices.this_device.borrow_mut() = Some((me.uid.clone(), me.name.clone()));
ui.devices
.sync_group
// Translators: {name} is the name of this computer's device.
.set_description(Some(&gettext_f(
"Backing up as “{name}”.",
&[("name", &me.name)],
)));
ui.devices.rename_this.set_sensitive(true);
ui.devices
.rename_this
// Translators: {name} is the name of this computer's device.
.set_tooltip_text(Some(&gettext_f(
"Rename this computer ({name})",
&[("name", &me.name)],
)));
}
None => {
*ui.devices.this_device.borrow_mut() = None;
ui.devices.rename_this.set_sensitive(false);
}
}
let mut rows: Vec<gtk4::Widget> = Vec::new();
let me = devices.iter().find(|d| d.this_device);
rows.push(this_computer_row(ui, me, folders).upcast());
let others: Vec<&DeviceInfo> = devices.iter().filter(|d| !d.this_device).collect();
for dev in &others {
rows.push(other_computer_row(ui, dev).upcast());
}
if others.is_empty() {
let row = adw::ActionRow::builder()
.title(gettext("No other computers"))
.subtitle(gettext("Desktop apps syncing to this account appear here."))
.subtitle(gettext(
"Install Proton Drive on another computer to see it here.",
))
.build();
row.add_prefix(&gtk4::Image::from_icon_name("computer-symbolic"));
ui.devices.group.add(&row);
*ui.devices.rows.borrow_mut() = vec![row.upcast()];
return;
}
let mut rows: Vec<gtk4::Widget> = Vec::new();
for dev in others {
let row = adw::ActionRow::builder()
.title(&dev.name)
.subtitle(device_subtitle(dev))
.build();
row.add_prefix(&gtk4::Image::from_icon_name("computer-symbolic"));
// Adoption is how a reinstalled or renamed machine re-attaches to the
// device it used to be, instead of registering a duplicate. It only
// makes sense on *another* computer's row, which is the only place this
// loop paints.
let (ui_ren, uid_ren, name_ren) = (ui.clone(), dev.uid.clone(), dev.name.clone());
let (ui_ad, uid_ad, name_ad) = (ui.clone(), dev.uid.clone(), dev.name.clone());
let (ui_rm, uid_rm, name_rm) = (ui.clone(), dev.uid.clone(), dev.name.clone());
let (ui_rs, uid_rs, name_rs) = (ui.clone(), dev.uid.clone(), dev.name.clone());
row.add_suffix(&more_menu_button(vec![
(
&gettext("Restore to This Computer…"),
Box::new(move || {
prompt_restore_folders(&ui_rs, Some((uid_rs.clone(), name_rs.clone())))
}),
),
(
&gettext("Rename…"),
Box::new(move || prompt_rename_device(&ui_ren, &uid_ren, &name_ren)),
),
(
&gettext("Use This Computer's Identity…"),
Box::new(move || prompt_adopt_device(&ui_ad, &uid_ad, &name_ad)),
),
(
&gettext("Remove Computer…"),
Box::new(move || prompt_remove_device(&ui_rm, &uid_rm, &name_rm)),
),
]));
ui.devices.group.add(&row);
let get = gtk4::LinkButton::with_label(PROTON_DRIVE_DOWNLOAD, &gettext("Get Proton Drive"));
get.set_valign(gtk4::Align::Center);
row.add_suffix(&get);
rows.push(row.upcast());
}
for row in &rows {
ui.devices.group.add(row);
}
*ui.devices.rows.borrow_mut() = rows;
}
/// A device row's subtitle: its platform, and when it last synced. A device that
/// has never synced says so — an unexplained missing date reads as a bug, and
/// "never" is the fact that tells the user this computer isn't backing anything up.
pub(crate) fn device_subtitle(dev: &DeviceInfo) -> String {
match dev.last_sync {
// Translators: {platform} is the device's platform (such as "Linux"), {time} a date and time.
Some(secs) if secs > 0 => gettext_f(
"{platform} · last synced {time}",
&[
("platform", &dev.device_type),
("time", &activity_time(secs)),
],
),
// Translators: {platform} is the device's platform, such as "Linux".
_ => gettext_f(
"{platform} · never synced",
&[("platform", &dev.device_type)],
),
/// Where the Proton Drive apps for other systems are.
const PROTON_DRIVE_DOWNLOAD: &str = "https://proton.me/drive/download";
/// This computer's row: its device name with a "This computer" pill, and how
/// many folders it backs up. It leads to those folders on the Sync page, which
/// owns every local path. `me` is `None` until the daemon has registered this
/// machine as a device.
fn this_computer_row(
ui: &Rc<Ui>,
me: Option<&DeviceInfo>,
folders: &[SyncFolderInfo],
) -> adw::ActionRow {
let row = adw::ActionRow::builder()
.title(me.map_or_else(|| gettext("This computer"), |d| d.name.clone()))
.subtitle(this_computer_subtitle(folders))
.activatable(true)
.build();
row.add_prefix(&gtk4::Image::from_icon_name("computer-symbolic"));
if me.is_some() {
let pill = gtk4::Label::new(Some(&gettext("This computer")));
pill.add_css_class("role-pill");
pill.add_css_class("caption");
pill.set_valign(gtk4::Align::Center);
row.add_suffix(&pill);
}
let mut menu = ActionMenu::new();
if let Some(me) = me {
let (ui_c, uid, name) = (ui.clone(), me.uid.clone(), me.name.clone());
menu.item(&gettext("Rename…"), move || {
prompt_rename_device(&ui_c, &uid, &name)
});
}
let ui_c = ui.clone();
menu.item(&gettext("Restore Folders…"), move || {
prompt_restore_folders(&ui_c, None)
});
row.add_suffix(&menu.button());
row.add_suffix(&gtk4::Image::from_icon_name("go-next-symbolic"));
let ui_c = ui.clone();
row.connect_activated(move |_| {
ui_c.locations.views.set_visible_child_name("folders");
ui_c.stack.set_visible_child_name("locations");
});
row
}
/// Another computer's row. Opening it browses that computer's backup.
fn other_computer_row(ui: &Rc<Ui>, dev: &DeviceInfo) -> adw::ActionRow {
let row = adw::ActionRow::builder()
.title(&dev.name)
.subtitle(device_subtitle(dev))
.activatable(true)
.build();
row.add_prefix(&gtk4::Image::from_icon_name("computer-symbolic"));
let (uid, name) = (dev.uid.clone(), dev.name.clone());
let mut menu = ActionMenu::new();
let (ui_c, uid_c, name_c) = (ui.clone(), uid.clone(), name.clone());
menu.item(&gettext("Browse Files"), move || {
browse_device(&ui_c, &uid_c, &name_c)
});
let (ui_c, uid_c, name_c) = (ui.clone(), uid.clone(), name.clone());
menu.item(&gettext("Restore to This Computer…"), move || {
prompt_restore_folders(&ui_c, Some((uid_c.clone(), name_c.clone())))
});
menu.section();
let (ui_c, uid_c, name_c) = (ui.clone(), uid.clone(), name.clone());
menu.item(&gettext("Rename…"), move || {
prompt_rename_device(&ui_c, &uid_c, &name_c)
});
// Adoption is how a reinstalled or renamed machine re-attaches to the device
// it used to be, instead of registering a duplicate. It only makes sense on
// another computer's row.
let (ui_c, uid_c, name_c) = (ui.clone(), uid.clone(), name.clone());
menu.item(&gettext("Continue This Backup Here…"), move || {
prompt_adopt_device(&ui_c, &uid_c, &name_c)
});
menu.section();
let (ui_c, uid_c, name_c) = (ui.clone(), uid.clone(), name.clone());
menu.item(&gettext("Remove…"), move || {
prompt_remove_device(&ui_c, &uid_c, &name_c)
});
row.add_suffix(&menu.button());
row.add_suffix(&gtk4::Image::from_icon_name("go-next-symbolic"));
let ui_c = ui.clone();
row.connect_activated(move |_| browse_device(&ui_c, &uid, &name));
row
}
/// Open another computer's backup at its top level.
fn browse_device(ui: &Rc<Ui>, uid: &str, name: &str) {
*ui.devices.nav.borrow_mut() = vec![(uid.to_string(), name.to_string())];
load_devices(ui);
}
/// Rebuild the breadcrumb trail for `nav`: "Computers", then the computer and
/// each folder down to the current one, which is a plain heading.
fn repaint_device_crumb(ui: &Rc<Ui>, nav: &[(String, String)]) {
let crumb = &ui.devices.crumb;
while let Some(child) = crumb.first_child() {
crumb.remove(&child);
}
crumb.append(&device_crumb_node(
ui,
&gettext("Computers"),
0,
nav.is_empty(),
));
for (i, (_, name)) in nav.iter().enumerate() {
let sep = gtk4::Label::new(Some("›"));
sep.add_css_class("dim-label");
crumb.append(&sep);
crumb.append(&device_crumb_node(ui, name, i + 1, i + 1 == nav.len()));
}
}
/// Rebuild the "This computer" section: one row naming the device this machine
/// backs up to, and how many folders it carries.
///
/// The per-folder rows (mode switch, sync now, remove) live on the Locations
/// page. They are local paths, and Locations is the one page that owns those;
/// two lists of the same folders would be two places to flip the same switch.
pub(crate) fn repaint_this_computer(ui: &Rc<Ui>, folders: &[SyncFolderInfo]) {
for row in ui.devices.sync_rows.borrow_mut().drain(..) {
ui.devices.sync_group.remove(&row);
/// One breadcrumb segment: a heading for the current folder, or a flat button
/// that goes back up to `depth` levels below the device list.
fn device_crumb_node(ui: &Rc<Ui>, label: &str, depth: usize, current: bool) -> gtk4::Widget {
if current {
let l = gtk4::Label::builder()
.label(label)
.ellipsize(gtk4::pango::EllipsizeMode::Start)
.build();
l.add_css_class("heading");
return l.upcast();
}
let button = gtk4::Button::builder().label(label).build();
button.add_css_class("flat");
let ui = ui.clone();
button.connect_clicked(move |_| {
ui.devices.nav.borrow_mut().truncate(depth);
load_devices(&ui);
});
button.upcast()
}
/// Folders open in place; files download and open with the default app.
fn open_device_entry(ui: &Rc<Ui>, entry: &DirEntry) {
if entry.is_dir {
ui.devices
.nav
.borrow_mut()
.push((entry.uid.clone(), entry.name.clone()));
load_devices(ui);
} else {
open_shared_file(ui, &entry.uid, &entry.name);
}
}
fn device_entry_menu(ui: &Rc<Ui>, entry: &DirEntry) -> ActionMenu {
let mut menu = ActionMenu::new();
let (ui_c, entry_c) = (ui.clone(), entry.clone());
menu.item(&pgettext("verb", "Open"), move || {
open_device_entry(&ui_c, &entry_c)
});
menu
}
fn device_bulk_menu(_ui: &Rc<Ui>, entries: Vec<DirEntry>) -> ActionMenu {
let mut menu = ActionMenu::new();
menu.labelled_section(&ngettext_f(
"{n} selected",
"{n} selected",
entries.len() as u64,
&[],
));
menu
}
fn device_background_menu(ui: &Rc<Ui>) -> ActionMenu {
let mut menu = ActionMenu::new();
let ui_c = ui.clone();
menu.item(&gettext("Select All"), move || {
ui_c.devices.files.selection.select_all();
});
let ui_c = ui.clone();
menu.item(&gettext("Refresh"), move || reload_current_page(&ui_c));
menu
}
/// A device row's subtitle: its platform, and when it last backed up. A device
/// that never did says so — an unexplained missing date reads as a bug, and
/// "no backups yet" is the fact that tells the user this computer isn't backing
/// anything up.
pub(crate) fn device_subtitle(dev: &DeviceInfo) -> String {
let platform = platform_label(&dev.device_type);
match dev.last_sync {
// Translators: {platform} is the device's platform (such as "Linux"), {time} a relative time such as "5 minutes ago".
Some(secs) if secs > 0 => gettext_f(
"{platform} · last backup {time}",
&[("platform", platform), ("time", &dates::relative(secs))],
),
// Translators: {platform} is the device's platform, such as "Linux".
_ => gettext_f("{platform} · no backups yet", &[("platform", platform)]),
}
}
/// The platform as its maker spells it. The API's names are enum variants.
fn platform_label(device_type: &str) -> &str {
match device_type {
"MacOs" => "macOS",
other => other,
}
let row = adw::ActionRow::builder()
.title(gettext("This computer"))
.subtitle(this_computer_subtitle(folders))
.build();
row.add_prefix(&gtk4::Image::from_icon_name("computer-symbolic"));
let manage = gtk4::Button::builder()
.label(gettext("Open Sync"))
.tooltip_text(gettext("Manage this computer's folders and mountpoint"))
.valign(gtk4::Align::Center)
.build();
manage.add_css_class("flat");
let ui_go = ui.clone();
manage.connect_clicked(move |_| ui_go.stack.set_visible_child_name("locations"));
row.add_suffix(&manage);
let ui_rs = ui.clone();
row.add_suffix(&more_menu_button(vec![(
&gettext("Restore Folders…"),
Box::new(move || prompt_restore_folders(&ui_rs, None)),
)]));
ui.devices.sync_group.add(&row);
*ui.devices.sync_rows.borrow_mut() = vec![row.upcast()];
}
/// How many folders this machine backs up, and whether any of them needs
/// attention — the one fact worth surfacing away from the folder list itself.
pub(crate) fn this_computer_subtitle(folders: &[SyncFolderInfo]) -> String {
if folders.is_empty() {
return gettext("No folders backed up yet — add one on the Sync page.");
return gettext("No folders backed up yet");
}
let count = ngettext_f(
"{n} folder backed up",
@@ -391,11 +597,7 @@ pub(crate) fn this_computer_subtitle(folders: &[SyncFolderInfo]) -> String {
.filter(|f| f.state == "error" || f.state == "conflict")
.count();
match attention {
// Translators: {folders} is "N folders backed up".
0 => gettext_f(
"{folders} · manage them on the Sync page",
&[("folders", &count)],
),
0 => count,
// Translators: {folders} is "N folders backed up"; {n} counts the folders with a problem.
n => ngettext_f(
"{folders} · {n} needs attention",
@@ -489,7 +691,7 @@ pub(crate) fn prompt_add_sync_folder(ui: &Rc<Ui>) {
_ => toast_error(
&ui,
&gettext("Couldn't add folder"),
&gettext("The mount service didn't respond."),
&gettext("The Proton Drive service didn't respond."),
),
}
});
@@ -529,7 +731,7 @@ pub(crate) fn prompt_restore_folders(ui: &Rc<Ui>, device: Option<(String, String
_ => toast_error(
&ui,
&gettext("Couldn't list folders to restore"),
&gettext("The mount service didn't respond."),
&gettext("The Proton Drive service didn't respond."),
),
}
});
@@ -577,7 +779,7 @@ fn show_restore_picker(
.child(&group)
.build();
let dialog = adw::AlertDialog::builder()
.heading(gettext("Restore folders"))
.heading(gettext("Restore Folders"))
.body(restore_picker_body(
device.as_ref().map(|(_, n)| n.as_str()),
))
@@ -668,7 +870,7 @@ pub(crate) fn set_sync_folder_mode(ui: &Rc<Ui>, id: i64, mode: &'static str) {
Ok(Ok(Response::Ok { .. })) => toast(
&ui,
&if mode == "ondemand" {
gettext("Folder will switch to on-demand")
gettext("Folder will switch to online only")
} else {
gettext("Folder will download and stay synced")
},
@@ -679,7 +881,7 @@ pub(crate) fn set_sync_folder_mode(ui: &Rc<Ui>, id: i64, mode: &'static str) {
_ => toast_error(
&ui,
&gettext("Couldn't change mode"),
&gettext("The mount service didn't respond."),
&gettext("The Proton Drive service didn't respond."),
),
}
reload_sync_pages(&ui);
@@ -710,7 +912,7 @@ pub(crate) fn prompt_remove_sync_folder(ui: &Rc<Ui>, id: i64, path: &str, ondema
let body = if ondemand {
// Translators: {path} is a local folder path.
gettext_f(
"Stop syncing “{path}”?\n\nThis folder is on-demand: its files live in Proton Drive, not on this disk, so the folder will be empty once it is unmounted. To keep a local copy, cancel, turn off On-demand, and wait for the download to finish before removing it.",
"Stop syncing “{path}”?\n\nThis folder is online only: its files live in Proton Drive, not on this disk, so the folder will be empty once it stops syncing. To keep a local copy, cancel, switch the folder to Synced, and wait for the download to finish before removing it.",
&[("path", path)],
)
} else {
@@ -721,7 +923,7 @@ pub(crate) fn prompt_remove_sync_folder(ui: &Rc<Ui>, id: i64, path: &str, ondema
)
};
let dialog = adw::AlertDialog::builder()
.heading(gettext("Stop syncing folder"))
.heading(gettext("Stop Syncing Folder?"))
.body(body)
.build();
let group = adw::PreferencesGroup::new();
@@ -818,7 +1020,7 @@ pub(crate) fn prompt_remove_device(ui: &Rc<Ui>, uid: &str, name: &str) {
let group = adw::PreferencesGroup::new();
group.add(&confirm);
let dialog = adw::AlertDialog::builder()
.heading(gettext("Remove Computer"))
.heading(gettext("Remove Computer?"))
// Translators: {name} is the name of the computer being removed.
.body(gettext_f(
"Remove “{name}” from this account?\n\nEverything it backed up to Proton Drive is deleted along with it. The files on that computer itself are not touched — but this cannot be undone from here.",
@@ -852,7 +1054,8 @@ pub(crate) fn prompt_remove_device(ui: &Rc<Ui>, uid: &str, name: &str) {
dialog.present(win.as_ref());
}
/// Confirm, then adopt another device as this machine's identity.
/// Confirm, then continue another computer's backup on this machine (adopt its
/// device).
///
/// Worth a confirmation rather than a plain click: adoption re-points this
/// machine's syncing at another computer's device folder, and the folders
@@ -862,20 +1065,22 @@ pub(crate) fn prompt_remove_device(ui: &Rc<Ui>, uid: &str, name: &str) {
pub(crate) fn prompt_adopt_device(ui: &Rc<Ui>, uid: &str, name: &str) {
let win = ui_window(ui);
let dialog = adw::AlertDialog::builder()
.heading(gettext("Use this computer's identity"))
// Translators: {name} is the name of the other computer whose identity is adopted.
.heading(gettext("Continue This Backup Here?"))
// Translators: {name} is the name of the other computer whose backup this one takes over.
.body(gettext_f(
"Treat this machine as “{name}”?\n\nNew synced folders are created under that computer in Proton Drive, and this machine keeps that identity even if its hostname changes. Folders already synced here are not moved.\n\nUse “Restore folders” afterwards to bring back what “{name}” was syncing.",
"This computer takes over the backup of “{name}”, for example after a reinstall.\n\nNew synced folders go under “{name}” in Proton Drive, even if this computer's name changes. Folders already synced here are not moved. Use “Restore to This Computer” afterwards to bring back what “{name}” was syncing.",
&[("name", name)],
))
.build();
dialog.add_response("cancel", &gettext("Cancel"));
dialog.add_response("adopt", &gettext("Use identity"));
dialog.add_response("adopt", &gettext("Continue Here"));
dialog.set_response_appearance("adopt", adw::ResponseAppearance::Suggested);
dialog.set_default_response(Some("cancel"));
dialog.set_close_response("cancel");
let ui = ui.clone();
let uid = uid.to_string();
// Translators: {name} is the name of the computer whose backup this one took over.
let done = gettext_f("Now backing up as “{name}”", &[("name", name)]);
dialog.connect_response(None, move |_, resp| {
if resp == "adopt" {
run_devices_mutation(
@@ -883,8 +1088,8 @@ pub(crate) fn prompt_adopt_device(ui: &Rc<Ui>, uid: &str, name: &str) {
Request::AdoptDevice {
uid: Some(uid.clone()),
},
&gettext("Identity adopted"),
&gettext("Couldn't adopt that computer"),
&done,
&gettext("Couldn't continue that backup here"),
);
}
});
@@ -909,7 +1114,11 @@ pub(crate) fn run_devices_mutation(ui: &Rc<Ui>, req: Request, done: &str, failed
Ok(Ok(Response::Error { message, kind })) => {
toast_failure(&ui, &failed, &message, kind)
}
_ => toast_error(&ui, &failed, &gettext("The mount service didn't respond.")),
_ => toast_error(
&ui,
&failed,
&gettext("The Proton Drive service didn't respond."),
),
}
});
}
@@ -933,20 +1142,17 @@ mod tests {
}
#[test]
fn a_machine_with_no_folders_is_told_where_to_add_one() {
assert_eq!(
this_computer_subtitle(&[]),
"No folders backed up yet — add one on the Sync page."
);
fn a_machine_with_no_folders_says_so() {
assert_eq!(this_computer_subtitle(&[]), "No folders backed up yet");
}
#[test]
fn folders_needing_attention_are_counted_not_hidden() {
// The per-folder rows moved to Locations, so this row is the only place
// the Computers page can surface that something is wrong.
// The per-folder rows live on the Sync page, so this row is the only
// place the Computers page can surface that something is wrong.
assert_eq!(
this_computer_subtitle(&[folder("idle"), folder("idle")]),
"2 folders backed up · manage them on the Sync page"
"2 folders backed up"
);
assert_eq!(
this_computer_subtitle(&[folder("idle"), folder("error")]),
@@ -964,4 +1170,28 @@ mod tests {
assert!(restore_picker_body(None).contains("this computer"));
assert!(nothing_to_restore(Some("laptop")).contains("“laptop”"));
}
fn device(device_type: &str, last_sync: Option<i64>) -> DeviceInfo {
DeviceInfo {
uid: "dev".into(),
name: "laptop".into(),
device_type: device_type.into(),
last_sync,
this_device: false,
adopted: false,
}
}
#[test]
fn a_computer_that_never_backed_up_says_no_backups_yet() {
assert_eq!(
device_subtitle(&device("Linux", None)),
"Linux · no backups yet"
);
assert_eq!(
device_subtitle(&device("Linux", Some(0))),
"Linux · no backups yet"
);
assert!(device_subtitle(&device("MacOs", Some(1))).starts_with("macOS · last backup "));
}
}
+16 -19
View File
@@ -75,22 +75,19 @@ pub(crate) fn show_duplicates(ui: &Rc<Ui>) {
bottom.set_halign(gtk4::Align::End);
bottom.append(&trash);
let exact = gtk4::ToggleButton::builder()
.label(pgettext("duplicates", "Exact"))
.tooltip_text(gettext("Photos stored more than once"))
.active(true)
.build();
let similar = gtk4::ToggleButton::builder()
.label(pgettext("duplicates", "Similar"))
.tooltip_text(gettext("Photos that look alike"))
.group(&exact)
.build();
let switch = gtk4::Box::new(gtk4::Orientation::Horizontal, 0);
switch.add_css_class("linked");
switch.append(&exact);
switch.append(&similar);
// Exact first, then Similar: the index is the finder.
let switch = ToggleGroup::new(&[
(
&pgettext("duplicates", "Exact"),
Some(&gettext("Photos stored more than once")),
),
(
&pgettext("duplicates", "Similar"),
Some(&gettext("Photos that look alike")),
),
]);
let header = adw::HeaderBar::new();
header.set_title_widget(Some(&switch));
header.set_title_widget(Some(&switch.widget()));
let toolbar = adw::ToolbarView::new();
toolbar.add_top_bar(&header);
@@ -124,8 +121,8 @@ pub(crate) fn show_duplicates(ui: &Rc<Ui>) {
.set(view_closed.generation.get().wrapping_add(1));
});
let view_switch = view.clone();
similar.connect_toggled(move |similar| {
let finder = if similar.is_active() {
switch.connect_changed(move |index| {
let finder = if index == 1 {
Finder::Similar
} else {
Finder::Exact
@@ -220,14 +217,14 @@ fn ask(view: &Rc<FinderView>, finder: Finder, generation: u32) {
view.status.set_icon_name(Some("dialog-warning-symbolic"));
view.status.set_title(&failed);
view.status
.set_description(Some(&gettext("The mount service didn't respond.")));
.set_description(Some(&gettext("The Proton Drive service didn't respond.")));
view.progress.set_visible(false);
return;
}
};
view.progress.set_visible(false);
if sets.is_empty() {
view.status.set_icon_name(Some("emblem-ok-symbolic"));
view.status.set_icon_name(Some("pdfs-synced-symbolic"));
match finder {
Finder::Exact => {
view.status.set_title(&gettext("No duplicates"));
File diff suppressed because it is too large. Load diff
+19 -11
View File
@@ -7,7 +7,7 @@ pub(crate) struct LoginState {
pub(crate) password: adw::PasswordEntryRow,
pub(crate) login_button: gtk4::Button,
/// Spins inside the Sign in button while a sign-in is running.
pub(crate) login_spinner: gtk4::Spinner,
pub(crate) login_spinner: Spinner,
pub(crate) login_status: gtk4::Label,
}
@@ -34,7 +34,8 @@ pub(crate) fn build_login_page() -> (gtk4::Widget, LoginState) {
group.add(&email);
group.add(&password);
let login_spinner = gtk4::Spinner::builder().visible(false).build();
let login_spinner = spinner();
login_spinner.set_visible(false);
let button_content = gtk4::Box::new(gtk4::Orientation::Horizontal, 8);
button_content.append(&login_spinner);
button_content.append(&gtk4::Label::new(Some(&gettext("Sign in"))));
@@ -170,7 +171,7 @@ pub(crate) fn wire_login(ui: &Rc<Ui>) {
// Cache the new identity so `refresh` never hits the keyring.
*ui.session.borrow_mut() = auth::load().ok();
// Enable+start the mount service now that we have a session.
service::enable_start();
let _ = gio::spawn_blocking(service::enable_start).await;
refresh(&ui);
}
Err(e) => ui.login.login_status.set_text(&e),
@@ -185,7 +186,6 @@ fn set_signing_in(ui: &Rc<Ui>, running: bool) {
ui.login.email.set_sensitive(!running);
ui.login.password.set_sensitive(!running);
ui.login.login_spinner.set_visible(running);
ui.login.login_spinner.set_spinning(running);
}
/// What to tell the person when sign-in fails. Proton's own API messages are
@@ -295,7 +295,7 @@ pub(crate) fn spawn_login(
/// the worker reads as a cancelled login.
pub(crate) fn prompt_2fa(ui: &Rc<Ui>, code_tx: std::sync::mpsc::Sender<String>) {
let dialog = adw::AlertDialog::builder()
.heading(gettext("Two-factor authentication"))
.heading(gettext("Two-Factor Authentication"))
.body(gettext(
"Enter the code from your authenticator app, or one of your recovery codes.",
))
@@ -344,12 +344,20 @@ pub(crate) fn sign_out(ui: &Rc<Ui>) {
),
&gettext("Sign Out"),
move || {
service::disable_stop();
if let Err(e) = auth::logout() {
tracing::error!("logout failed: {e}");
}
*ui.session.borrow_mut() = None;
refresh(&ui);
// systemctl and the keyring both block, so run them on a worker.
let ui = ui.clone();
glib::spawn_future_local(async move {
let result = gio::spawn_blocking(|| {
service::disable_stop();
auth::logout().map_err(|e| e.to_string())
})
.await;
if let Ok(Err(e)) = result {
tracing::error!("logout failed: {e}");
}
*ui.session.borrow_mut() = None;
refresh(&ui);
});
},
);
}
+1
View File
@@ -1,4 +1,5 @@
pub(crate) mod activity;
pub(crate) mod activity_text;
pub(crate) mod albums;
pub(crate) mod browser;
pub(crate) mod devices;
+8 -12
View File
@@ -31,7 +31,7 @@ pub(crate) struct Viewer {
pub(crate) scroller: gtk4::ScrolledWindow,
pub(crate) picture: gtk4::Picture,
pub(crate) video: gtk4::Video,
pub(crate) spinner: gtk4::Spinner,
pub(crate) spinner: Spinner,
pub(crate) status: gtk4::Label,
pub(crate) title: gtk4::Label,
pub(crate) counter: gtk4::Label,
@@ -224,7 +224,6 @@ fn viewer_item(ui: &Rc<Ui>, viewer: &Rc<Viewer>, uid: &str) -> Option<PhotoItem>
/// plays in place once its file is down.
pub(crate) fn load_photo(ui: &Rc<Ui>, viewer: &Rc<Viewer>, uid: String) {
viewer.spinner.set_visible(true);
viewer.spinner.start();
viewer.status.set_visible(false);
viewer.loading.set(true);
*viewer.path.borrow_mut() = None;
@@ -266,7 +265,6 @@ pub(crate) fn load_photo(ui: &Rc<Ui>, viewer: &Rc<Viewer>, uid: String) {
if *viewer.uid.borrow() != uid {
return;
}
viewer.spinner.stop();
viewer.spinner.set_visible(false);
viewer.loading.set(false);
// Armed whether or not the photo rendered: a slideshow steps past a
@@ -307,7 +305,7 @@ pub(crate) fn load_photo(ui: &Rc<Ui>, viewer: &Rc<Viewer>, uid: String) {
}
},
Ok(Ok(Response::Error { message, .. })) => fail(&message),
Ok(Ok(_)) => fail(&gettext("Unexpected reply from the mount service.")),
Ok(Ok(_)) => fail(&gettext("Unexpected reply from the Proton Drive service.")),
Ok(Err(_)) | Err(_) => fail(&gettext("Couldn't reach Proton Drive.")),
}
});
@@ -1136,7 +1134,7 @@ pub(crate) fn open_photo_viewer(ui: &Rc<Ui>, initial_uid: String) {
.child(
&adw::ButtonContent::builder()
.label(gettext("Show on map"))
.icon_name("map-symbolic")
.icon_name("pdfs-map-symbolic")
.build(),
)
.halign(gtk4::Align::Start)
@@ -1192,12 +1190,10 @@ pub(crate) fn open_photo_viewer(ui: &Rc<Ui>, initial_uid: String) {
.child(&info_panel)
.build();
let spinner = gtk4::Spinner::builder()
.halign(gtk4::Align::Center)
.valign(gtk4::Align::Center)
.width_request(48)
.height_request(48)
.build();
let spinner = spinner();
spinner.set_halign(gtk4::Align::Center);
spinner.set_valign(gtk4::Align::Center);
spinner.set_size_request(48, 48);
spinner.add_css_class("viewer-spinner");
overlay.add_overlay(&spinner);
@@ -1426,7 +1422,7 @@ pub(crate) fn open_photo_viewer(ui: &Rc<Ui>, initial_uid: String) {
None
}
Ok(Ok(Response::Error { message, .. })) => Some(message),
_ => Some(gettext("The mount service didn't respond.")),
_ => Some(gettext("The Proton Drive service didn't respond.")),
};
if let Some(detail) = failed {
toast_error(
File diff suppressed because it is too large. Load diff
+10 -10
View File
@@ -102,7 +102,7 @@ pub(crate) fn load_places(ui: &Rc<Ui>) {
&ui,
"network-offline-symbolic",
&gettext("Not connected"),
&gettext("The Proton Drive mount service didn't respond."),
&gettext("The Proton Drive service didn't respond."),
),
}
});
@@ -422,7 +422,7 @@ fn open_place(ui: &Rc<Ui>, place: PlaceInfo) {
// As in an album: no filters, no Upload, no view switch — back leads out.
ui.gallery.filters.set_visible(false);
ui.gallery.view_switch.set_visible(false);
ui.gallery.view_switch.widget().set_visible(false);
ui.gallery.upload.set_visible(false);
ui.gallery.back.set_visible(true);
ui.gallery.kind.set(None);
@@ -439,7 +439,7 @@ pub(crate) fn close_place(ui: &Rc<Ui>) {
return;
}
ui.gallery.title.set_title(&gettext("Photos"));
ui.gallery.view_switch.set_visible(true);
ui.gallery.view_switch.widget().set_visible(true);
ui.gallery.upload.set_visible(true);
ui.gallery.back.set_visible(false);
}
@@ -455,14 +455,14 @@ fn places_status(ui: &Rc<Ui>, icon: &str, title: &str, description: &str) {
/// Wire the Places toggle of the view switcher.
pub(crate) fn wire_places(ui: &Rc<Ui>) {
let ui_places = ui.clone();
ui.gallery.places_btn.clone().connect_toggled(move |btn| {
if btn.is_active() {
ui.gallery.view_switch.connect_changed(move |view| {
if view == VIEW_PLACES {
show_places(&ui_places);
}
});
let ui_layout = ui.clone();
ui.gallery.places_map_btn.connect_toggled(move |_| {
ui.gallery.places_layout.connect_changed(move |_| {
// A status page (loading, empty, an error) stays until a listing
// replaces it; only the grid and the map swap.
if ui_layout
@@ -493,19 +493,19 @@ pub(crate) fn wire_places(ui: &Rc<Ui>) {
/// Switch to the Places map and zoom in on `(latitude, longitude)`, where a
/// photo in the viewer was taken.
pub(crate) fn show_on_map(ui: &Rc<Ui>, latitude: f64, longitude: f64) {
ui.gallery.places_map_btn.set_active(true);
if ui.gallery.places_btn.is_active() {
ui.gallery.places_layout.set_active(PLACES_MAP);
if ui.gallery.view_switch.active() == VIEW_PLACES {
// Already in Places, perhaps inside a town: back out to the listing.
show_places(ui);
} else {
ui.gallery.places_btn.set_active(true);
ui.gallery.view_switch.set_active(VIEW_PLACES);
}
ui.gallery.places_map.show_spot(latitude, longitude);
}
/// Show the places as cards or on the map, as the Grid/Map toggle says.
fn show_places_layout(ui: &Rc<Ui>) {
let layout = if ui.gallery.places_map_btn.is_active() {
let layout = if ui.gallery.places_layout.active() == PLACES_MAP {
"map"
} else {
"grid"
File diff suppressed because it is too large. Load diff
+590 -268
View File
@@ -1,38 +1,94 @@
use crate::*;
pub(crate) struct SharedByMeState {
// Shared (by me) page: one section listing the items I've shared, each with a
// copy-link / manage affordance. Rebuilt wholesale on each load.
// Shared by me page: the items I have shared, as a file list whose columns
// say where each lives, who has it and what its public link is doing.
pub(crate) files: FileList,
/// "list", or "status" while the page loads, is empty or can't be read.
pub(crate) content: gtk4::Stack,
pub(crate) status: adw::StatusPage,
pub(crate) retry: gtk4::Button,
pub(crate) group: adw::PreferencesGroup,
pub(crate) rows: RefCell<Vec<gtk4::Widget>>,
pub(crate) inflight: Cell<bool>,
pub(crate) loaded_at: Cell<Option<Instant>>,
/// "12 items" under the page title.
pub(crate) subtitle: adw::WindowTitle,
/// Which items to show, indexed like [`SHARE_FILTERS`].
pub(crate) filter: gtk4::DropDown,
/// The last listing, unfiltered. The list holds [`DirEntry`]s; the columns
/// and menus look a row's people and link up here by uid.
pub(crate) items: Rc<RefCell<Vec<SharedItem>>>,
/// Runs the loads; the rows stay up while one runs.
pub(crate) loader: Rc<Loader>,
}
impl SharedByMeState {
pub(crate) fn new(widgets: &SharedByMeWidgets) -> Self {
SharedByMeState {
files: widgets.files.clone(),
content: widgets.content.clone(),
status: widgets.status.clone(),
retry: widgets.retry.clone(),
subtitle: widgets.subtitle.clone(),
filter: widgets.filter.clone(),
items: Rc::new(RefCell::new(Vec::new())),
loader: Loader::new(&widgets.content),
}
}
}
/// Widgets the Shared (by-me) page's load/repaint touch.
pub(crate) struct SharedByMeWidgets {
pub(crate) files: FileList,
pub(crate) content: gtk4::Stack,
pub(crate) status: adw::StatusPage,
pub(crate) group: adw::PreferencesGroup,
pub(crate) retry: gtk4::Button,
pub(crate) refresh: gtk4::Button,
pub(crate) subtitle: adw::WindowTitle,
pub(crate) filter: gtk4::DropDown,
}
/// The Shared page: one section listing the items I have shared with others —
/// each row summarizing who has access, opening the item when activated, with
/// Copy link and a menu for the link and the per-node Share dialog.
pub(crate) fn build_shared_by_me_page() -> (gtk4::Widget, SharedByMeWidgets) {
let refresh = refresh_button();
/// Which shared items the page shows.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum ShareFilter {
All,
/// Items with a public link.
Links,
/// Items shared with people, invited or already in.
People,
/// Items whose public link has expired.
Expired,
}
let group = adw::PreferencesGroup::new();
let clamp = adw::Clamp::builder().child(&group).build();
let scroll = gtk4::ScrolledWindow::builder()
.vexpand(true)
.child(&clamp)
.build();
/// The filters in the order the header's drop-down lists them.
const SHARE_FILTERS: [ShareFilter; 4] = [
ShareFilter::All,
ShareFilter::Links,
ShareFilter::People,
ShareFilter::Expired,
];
fn share_filter_label(filter: ShareFilter) -> String {
match filter {
ShareFilter::All => gettext("All Shared Items"),
ShareFilter::Links => gettext("Links Only"),
ShareFilter::People => gettext("People Only"),
ShareFilter::Expired => gettext("Expired Links"),
}
}
/// The Shared by me page: every item I have shared with people or by link.
/// Activating one opens its Share dialog, since managing access is what this
/// page is for; opening the item itself is in the menu.
pub(crate) fn build_shared_by_me_page() -> (gtk4::Widget, SharedByMeWidgets) {
let files = FileList::new();
files.show_list(true);
let layout = layout_button(&files);
let labels: Vec<String> = SHARE_FILTERS
.iter()
.copied()
.map(share_filter_label)
.collect();
let filter =
gtk4::DropDown::from_strings(&labels.iter().map(String::as_str).collect::<Vec<_>>());
filter.set_valign(gtk4::Align::Center);
filter.set_tooltip_text(Some(&gettext("Show only some shared items")));
let retry = gtk4::Button::builder()
.label(gettext("Retry"))
@@ -42,7 +98,7 @@ pub(crate) fn build_shared_by_me_page() -> (gtk4::Widget, SharedByMeWidgets) {
retry.add_css_class("suggested-action");
retry.set_visible(false);
let status = adw::StatusPage::builder()
.icon_name("emblem-shared-symbolic")
.icon_name("pdfs-share-symbolic")
.vexpand(true)
.child(&retry)
.build();
@@ -51,277 +107,154 @@ pub(crate) fn build_shared_by_me_page() -> (gtk4::Widget, SharedByMeWidgets) {
let content = gtk4::Stack::new();
content.set_vexpand(true);
content.set_transition_type(gtk4::StackTransitionType::Crossfade);
content.add_named(&scroll, Some("list"));
content.add_named(&files.views, Some("list"));
content.add_named(&status, Some("status"));
let inner = gtk4::Box::new(gtk4::Orientation::Vertical, 12);
inner.set_margin_top(18);
inner.set_margin_bottom(18);
inner.set_margin_start(18);
inner.set_margin_end(18);
inner.set_margin_top(12);
inner.set_margin_bottom(12);
inner.set_margin_start(12);
inner.set_margin_end(12);
inner.append(&content);
let (frame, header, _) = page_frame(&gettext("Shared by Me"), &inner);
header.pack_end(&refresh);
let (frame, header, subtitle) = page_frame(&gettext("Shared by me"), &inner);
header.pack_start(&filter);
header.pack_end(&layout);
(
frame.upcast(),
SharedByMeWidgets {
files,
content,
status,
group,
retry,
refresh,
subtitle,
filter,
},
)
}
/// Install the Shared (by-me) page's retry button.
pub(crate) fn wire_shared_by_me(ui: &Rc<Ui>, retry: &gtk4::Button) {
/// Install the file list, its columns, the filter and the retry button.
pub(crate) fn wire_shared_by_me(ui: &Rc<Ui>, widgets: &SharedByMeWidgets) {
let files = &ui.shared_by_me.files;
files.wire(
ui,
FileListBehavior {
activate: open_share_dialog,
entry_menu: shared_by_me_menu,
bulk_menu: shared_by_me_bulk_menu,
background_menu: shared_by_me_background_menu,
badges: false,
drag_and_drop: false,
},
);
let items = &ui.shared_by_me.items;
files
.column_view
.append_column(&text_column(&gettext("Location"), |e| {
location_label(&e.path)
}));
let people = items.clone();
files
.column_view
.append_column(&text_column(&pgettext("column", "People"), move |e| {
find_item(&people, &e.uid)
.map(|item| people_label(&item))
.unwrap_or_else(|| "—".to_string())
}));
files.column_view.append_column(&link_column(ui));
let ui_retry = ui.clone();
retry.connect_clicked(move |_| {
service::restart();
load_shared_by_me(&ui_retry);
widgets
.retry
.connect_clicked(move |_| restart_service_then(&ui_retry, load_shared_by_me));
let ui_filter = ui.clone();
widgets.filter.connect_selected_notify(move |_| {
let items = ui_filter.shared_by_me.items.borrow().clone();
repaint_shared_by_me(&ui_filter, &items);
});
}
/// Show a status page in place of the Shared (by-me) list.
pub(crate) fn shared_by_me_status(
ui: &Rc<Ui>,
icon: &str,
title: &str,
description: &str,
retry: bool,
) {
ui.shared_by_me.status.set_icon_name(Some(icon));
ui.shared_by_me.status.set_title(title);
ui.shared_by_me.status.set_description(Some(description));
ui.shared_by_me.retry.set_visible(retry);
ui.shared_by_me.content.set_visible_child_name("status");
/// The shared item a row stands for.
fn find_item(items: &RefCell<Vec<SharedItem>>, uid: &str) -> Option<SharedItem> {
items.borrow().iter().find(|item| item.uid == uid).cloned()
}
/// Fetch the shared-by-me listing and repaint the page.
pub(crate) fn load_shared_by_me(ui: &Rc<Ui>) {
if ui.shared_by_me.inflight.get() {
return;
}
cancel_file_thumbnails(ui);
ui.shared_by_me.inflight.set(true);
shared_by_me_status(
ui,
"emblem-shared-symbolic",
&gettext("Loading…"),
&gettext("Reading what you've shared."),
false,
);
ui.busy_begin();
let rx = spawn_request(ui.dirs.control_socket(), Request::ListSharedByMe);
let ui = ui.clone();
glib::spawn_future_local(async move {
let result = rx.recv().await;
ui.busy_end();
ui.shared_by_me.inflight.set(false);
match result {
Ok(Ok(Response::SharedByMe { items })) => {
repaint_shared_by_me(&ui, &items);
ui.shared_by_me.loaded_at.set(Some(Instant::now()));
}
Ok(Ok(Response::Error { message, .. })) => shared_by_me_status(
&ui,
"dialog-warning-symbolic",
&gettext("Couldn't read your shares"),
&message,
false,
),
Ok(Ok(_)) => shared_by_me_status(
&ui,
"dialog-warning-symbolic",
&gettext("Couldn't read your shares"),
&gettext("Unexpected reply from the mount service."),
false,
),
Ok(Err(_)) | Err(_) => {
ui.shared_by_me.loaded_at.set(None);
shared_by_me_unreachable(&ui);
}
}
});
}
/// The daemon didn't answer the Shared (by-me) page.
pub(crate) fn shared_by_me_unreachable(ui: &Rc<Ui>) {
if service::is_failed() || !service::is_active() {
shared_by_me_status(
ui,
"network-offline-symbolic",
&gettext("Not connected"),
&gettext("The Proton Drive mount service isn't running."),
true,
);
return;
}
shared_by_me_status(
ui,
"folder-remote-symbolic",
&gettext("Connecting…"),
&gettext("Waiting for the Proton Drive mount service to come up."),
false,
);
let ui = ui.clone();
glib::timeout_add_local_once(CONNECT_RETRY_INTERVAL, move || {
if ui.stack.visible_child_name().as_deref() == Some("sharedbyme") {
load_shared_by_me(&ui);
}
});
}
/// Rebuild the Shared (by-me) section from a fresh listing.
pub(crate) fn repaint_shared_by_me(ui: &Rc<Ui>, items: &[SharedItem]) {
for row in ui.shared_by_me.rows.borrow_mut().drain(..) {
ui.shared_by_me.group.remove(&row);
}
if items.is_empty() {
shared_by_me_status(
ui,
"emblem-shared-symbolic",
&gettext("Nothing shared yet"),
&gettext("Items you share with people or by link show up here."),
false,
);
return;
}
ui.shared_by_me.content.set_visible_child_name("list");
let mut rows: Vec<gtk4::Widget> = Vec::new();
for item in items {
let entry = shared_item_as_entry(item);
let row = adw::ActionRow::builder()
.title(&item.name)
.subtitle(shared_item_summary(item))
/// The Link column: what the public link is doing, and a button that copies
/// it while it works.
fn link_column(ui: &Rc<Ui>) -> gtk4::ColumnViewColumn {
let factory = gtk4::SignalListItemFactory::new();
let ui_setup = ui.clone();
factory.connect_setup(move |_, item| {
let item = item.downcast_ref::<gtk4::ListItem>().unwrap();
let label = gtk4::Label::builder()
.halign(gtk4::Align::Start)
.hexpand(true)
.ellipsize(gtk4::pango::EllipsizeMode::End)
.build();
row.add_prefix(&file_thumbnail(ui, &entry, 40, 24, true));
// A node the daemon can place in my tree opens like it would in My Files.
if !item.path.is_empty() {
row.set_activatable(true);
let ui_open = ui.clone();
let entry_open = entry.clone();
row.connect_activated(move |_| open_shared_by_me(&ui_open, &entry_open));
}
let url = item.link.as_ref().and_then(|l| l.url.clone());
// The one action people come here for most gets its own button.
if let Some(url) = url.clone() {
let copy = gtk4::Button::builder()
.icon_name("edit-copy-symbolic")
.tooltip_text(gettext("Copy link"))
.valign(gtk4::Align::Center)
.build();
copy.add_css_class("flat");
let ui_copy = ui.clone();
copy.connect_clicked(move |btn| {
label.add_css_class("dim-label");
let copy = gtk4::Button::builder()
.icon_name("pdfs-link-symbolic")
.tooltip_text(gettext("Copy link"))
.valign(gtk4::Align::Center)
.build();
copy.add_css_class("flat");
// Read at click time: the view recycles this cell for other rows.
let (ui, item_c) = (ui_setup.clone(), item.clone());
copy.connect_clicked(move |btn| {
let Some(obj) = item_c.item().and_downcast::<BoxedAnyObject>() else {
return;
};
let uid = obj.borrow::<DirEntry>().uid.clone();
if let Some(url) = find_item(&ui.shared_by_me.items, &uid)
.and_then(|item| item.link)
.and_then(|link| link.url)
{
btn.clipboard().set_text(&url);
toast(&ui_copy, &gettext("Link copied"));
});
row.add_suffix(&copy);
}
row.add_suffix(&shared_by_me_menu(ui, &entry, url));
ui.shared_by_me.group.add(&row);
rows.push(row.upcast());
}
*ui.shared_by_me.rows.borrow_mut() = rows;
}
/// The ⋮ menu on a shared item: open it, the link, the Share dialog, and
/// Stop Sharing.
///
/// Manage access opens the per-node Share dialog, which addresses a pathless
/// node by uid, so every shared item can be managed from here.
fn shared_by_me_menu(ui: &Rc<Ui>, entry: &DirEntry, url: Option<String>) -> gtk4::MenuButton {
let mut items: Vec<(String, MenuAction)> = Vec::new();
if !entry.path.is_empty() {
let (ui_c, entry_c) = (ui.clone(), entry.clone());
items.push((
pgettext("verb", "Open"),
Box::new(move || open_shared_by_me(&ui_c, &entry_c)),
));
let (ui_c, entry_c) = (ui.clone(), entry.clone());
items.push((
gettext("Show in My Files"),
Box::new(move || show_in_my_files(&ui_c, &entry_c)),
));
}
if let Some(url) = url {
items.push((gettext("Open Link"), Box::new(move || open_uri(&url))));
}
let (ui_c, entry_c) = (ui.clone(), entry.clone());
items.push((
gettext("Manage Access…"),
Box::new(move || open_share_dialog(&ui_c, &entry_c)),
));
let (ui_c, entry_c) = (ui.clone(), entry.clone());
items.push((
gettext("Stop Sharing…"),
Box::new(move || prompt_stop_sharing(&ui_c, &entry_c)),
));
let (labels, actions): (Vec<String>, Vec<MenuAction>) = items.into_iter().unzip();
more_menu_button(labels.iter().map(String::as_str).zip(actions).collect())
}
/// Confirm, then remove every member, invitation and the public link.
pub(crate) fn prompt_stop_sharing(ui: &Rc<Ui>, entry: &DirEntry) {
let dialog = adw::AlertDialog::builder()
.heading(gettext("Stop sharing?"))
// Translators: {name} is the shared item's name.
.body(gettext_f(
"Everyone you invited loses access to “{name}”, pending invitations are withdrawn and its public link stops working.",
&[("name", &entry.name)],
))
.build();
dialog.add_response("cancel", &gettext("Cancel"));
dialog.add_response("stop", &gettext("Stop Sharing"));
dialog.set_response_appearance("stop", adw::ResponseAppearance::Destructive);
dialog.set_default_response(Some("cancel"));
dialog.set_close_response("cancel");
let ui_c = ui.clone();
let uid = entry.uid.clone();
let name = entry.name.clone();
dialog.connect_response(Some("stop"), move |_, _| {
run_mutation(
&ui_c,
Request::StopSharingByUid { uid: uid.clone() },
// Translators: {name} is the item's name.
gettext_f("Stopped sharing {name}", &[("name", &name)]),
gettext_noop("Couldn't stop sharing"),
flash_copied(btn, "pdfs-link-symbolic");
toast(&ui, &gettext("Link copied"));
}
});
let cell = gtk4::Box::new(gtk4::Orientation::Horizontal, 6);
cell.append(&label);
cell.append(&copy);
item.set_child(Some(&cell));
});
let items = ui.shared_by_me.items.clone();
factory.connect_bind(move |_, item| {
let item = item.downcast_ref::<gtk4::ListItem>().unwrap();
let cell = item.child().and_downcast::<gtk4::Box>().unwrap();
let label = cell.first_child().and_downcast::<gtk4::Label>().unwrap();
let copy = cell.last_child().unwrap();
let obj = item.item().and_downcast::<BoxedAnyObject>().unwrap();
let uid = obj.borrow::<DirEntry>().uid.clone();
let link = find_item(&items, &uid).and_then(|item| item.link);
let now = glib::real_time() / 1_000_000;
let text = link_label(link.as_ref(), now);
label.set_label(&text);
label.set_tooltip_text(Some(&text));
copy.set_visible(
link.as_ref()
.is_some_and(|l| l.url.is_some() && !link_expired(l, now)),
);
});
dialog.present(ui_window(ui).as_ref());
let column = gtk4::ColumnViewColumn::new(Some(&pgettext("column", "Link")), Some(factory));
column.set_resizable(true);
column
}
/// Open a shared item: a folder in My Files, a file the way My Files would.
fn open_shared_by_me(ui: &Rc<Ui>, entry: &DirEntry) {
if entry.is_dir {
ui.stack.set_visible_child_name("browser");
ui.browser.search.set_text("");
browse_to(ui, entry.path.clone());
} else {
activate_entry(ui, entry);
/// Where a shared item lives in My files: its folder, "My files" at the top,
/// or a dash when the daemon can't place it.
pub(crate) fn location_label(path: &str) -> String {
match path.rsplit_once('/') {
Some((parent, _)) => parent.to_string(),
None if path.is_empty() => "—".to_string(),
None => gettext("My files"),
}
}
/// Go to the folder holding a shared item in My Files.
pub(crate) fn show_in_my_files(ui: &Rc<Ui>, entry: &DirEntry) {
let parent = entry
.path
.rsplit_once('/')
.map(|(parent, _)| parent.to_string())
.unwrap_or_default();
ui.stack.set_visible_child_name("browser");
ui.browser.search.set_text("");
browse_to(ui, parent);
}
/// A one-line summary of who can reach a shared item, for its row subtitle.
pub(crate) fn shared_item_summary(item: &SharedItem) -> String {
/// Who can reach a shared item through an invitation.
pub(crate) fn people_label(item: &SharedItem) -> String {
let mut parts = Vec::new();
if item.member_count > 0 {
// Translators: how many people have access to a shared item.
@@ -341,19 +274,333 @@ pub(crate) fn shared_item_summary(item: &SharedItem) -> String {
&[],
));
}
if item.link.is_some() {
parts.push(gettext("Public link"));
}
if parts.is_empty() {
// Translators: a shared item's summary when no people or link can be counted.
pgettext("state", "Shared")
"—".to_string()
} else {
parts.join(" · ")
}
}
/// Build a [`DirEntry`] from a [`SharedItem`] so the path-keyed Share dialog can
/// open on it. Only used when the item's path is known.
fn link_expired(link: &PublicLinkInfo, now: i64) -> bool {
link.expires.is_some_and(|at| at <= now)
}
/// What a public link is doing at `now` (epoch seconds): working, working
/// until a date, or expired, and whether a password guards it.
pub(crate) fn link_label(link: Option<&PublicLinkInfo>, now: i64) -> String {
let Some(link) = link else {
return "—".to_string();
};
let state = match link.expires {
Some(at) if at <= now => pgettext("link", "Expired"),
// Translators: {date} is when a public link stops working.
Some(at) => gettext_f("Expires {date}", &[("date", &dates::short_date(at))]),
None if link.created > 0 => gettext_f(
// Translators: {date} is when the public link was created.
"Active since {date}",
&[("date", &dates::short_date(link.created))],
),
None => pgettext("link", "Active"),
};
if link.has_password {
[state, gettext("Password protected")].join(" · ")
} else {
state
}
}
/// Whether `item` passes `filter` at `now` (epoch seconds).
pub(crate) fn matches_filter(item: &SharedItem, filter: ShareFilter, now: i64) -> bool {
match filter {
ShareFilter::All => true,
ShareFilter::Links => item.link.is_some(),
ShareFilter::People => item.member_count + item.invite_count > 0,
ShareFilter::Expired => item.link.as_ref().is_some_and(|l| link_expired(l, now)),
}
}
/// Show a status page in place of the Shared (by-me) list.
pub(crate) fn shared_by_me_status(
ui: &Rc<Ui>,
icon: &str,
title: &str,
description: &str,
retry: bool,
) {
ui.shared_by_me.status.set_icon_name(Some(icon));
ui.shared_by_me.status.set_title(title);
ui.shared_by_me.status.set_description(Some(description));
ui.shared_by_me.retry.set_visible(retry);
ui.shared_by_me.content.set_visible_child_name("status");
ui.shared_by_me.subtitle.set_subtitle("");
}
/// Fetch the shared-by-me listing and repaint the page.
pub(crate) fn load_shared_by_me(ui: &Rc<Ui>) {
cancel_file_thumbnails(ui);
let ui_p = ui.clone();
let ticket = ui.shared_by_me.loader.refresh(move || {
ui_p.shared_by_me.files.model.remove_all();
shared_by_me_status(
&ui_p,
"pdfs-share-symbolic",
&gettext("Loading…"),
&gettext("Reading what you've shared."),
false,
);
});
ui.busy_begin();
let rx = spawn_request(ui.dirs.control_socket(), Request::ListSharedByMe);
let ui = ui.clone();
glib::spawn_future_local(async move {
let result = rx.recv().await;
ui.busy_end();
if !ticket.is_current() {
return;
}
if !matches!(result, Ok(Ok(Response::SharedByMe { .. }))) {
ui.shared_by_me.files.model.remove_all();
}
match result {
Ok(Ok(Response::SharedByMe { items })) => {
let changed = changed_items(&ui.shared_by_me.items.borrow(), &items);
*ui.shared_by_me.items.borrow_mut() = items.clone();
repaint_shared_by_me(&ui, &items);
rebind_rows(&ui, &changed);
}
Ok(Ok(Response::Error { message, .. })) => shared_by_me_status(
&ui,
"dialog-warning-symbolic",
&gettext("Couldn't read your shares"),
&message,
false,
),
Ok(Ok(_)) => shared_by_me_status(
&ui,
"dialog-warning-symbolic",
&gettext("Couldn't read your shares"),
&gettext("Unexpected reply from the Proton Drive service."),
false,
),
Ok(Err(_)) | Err(_) => {
shared_by_me_unreachable(&ui);
}
}
});
}
/// The daemon didn't answer the Shared (by-me) page.
pub(crate) fn shared_by_me_unreachable(ui: &Rc<Ui>) {
service_unreachable(ui, "sharedbyme", shared_by_me_status, load_shared_by_me);
}
/// Show the items that pass the header's filter.
pub(crate) fn repaint_shared_by_me(ui: &Rc<Ui>, items: &[SharedItem]) {
if items.is_empty() {
shared_by_me_status(
ui,
"pdfs-share-symbolic",
&gettext("Nothing shared yet"),
&gettext("Items you share with people or by link show up here."),
false,
);
ui.shared_by_me.files.model.remove_all();
return;
}
let filter = SHARE_FILTERS
.get(ui.shared_by_me.filter.selected() as usize)
.copied()
.unwrap_or(ShareFilter::All);
let now = glib::real_time() / 1_000_000;
let shown: Vec<DirEntry> = items
.iter()
.filter(|item| matches_filter(item, filter, now))
.map(shared_item_as_entry)
.collect();
if shown.is_empty() {
shared_by_me_status(
ui,
"pdfs-share-symbolic",
&gettext("No Matching Items"),
&gettext("None of your shared items match this filter."),
false,
);
ui.shared_by_me.files.model.remove_all();
return;
}
ui.shared_by_me.content.set_visible_child_name("list");
ui.shared_by_me.subtitle.set_subtitle(&ngettext_f(
"{n} item",
"{n} items",
shown.len() as u64,
&[],
));
// Only the rows that changed are swapped, so a refresh keeps the selection
// and the scroll position.
replace_items(&ui.shared_by_me.files.model, &shown);
}
/// The uids in `new` whose people or link differ from `old`. Their rows show
/// the same [`DirEntry`] as before, so the list would not repaint them.
fn changed_items(old: &[SharedItem], new: &[SharedItem]) -> HashSet<String> {
new.iter()
.filter(|item| old.iter().find(|o| o.uid == item.uid) != Some(*item))
.map(|item| item.uid.clone())
.collect()
}
/// Have the list bind the rows of `uids` again, to repaint their columns.
fn rebind_rows(ui: &Rc<Ui>, uids: &HashSet<String>) {
let model = &ui.shared_by_me.files.model;
for pos in 0..model.n_items() {
if entry_at(Some(model), pos).is_some_and(|e| uids.contains(&e.uid)) {
model.items_changed(pos, 1, 1);
}
}
}
/// A shared item's right-click menu: manage it, open it, its link, and Stop
/// Sharing. Manage Access opens the Share dialog, which addresses a pathless
/// node by uid, so every shared item can be managed from here.
fn shared_by_me_menu(ui: &Rc<Ui>, entry: &DirEntry) -> ActionMenu {
let mut menu = ActionMenu::new();
let (ui_c, entry_c) = (ui.clone(), entry.clone());
menu.item(&gettext("Manage Access…"), move || {
open_share_dialog(&ui_c, &entry_c)
});
// A node the daemon can place in my tree opens like it would in My Files.
if !entry.path.is_empty() {
let (ui_c, entry_c) = (ui.clone(), entry.clone());
menu.item(&pgettext("verb", "Open"), move || {
open_shared_by_me(&ui_c, &entry_c)
});
let (ui_c, entry_c) = (ui.clone(), entry.clone());
menu.item(&gettext("Show in My Files"), move || {
show_in_my_files(&ui_c, &entry_c)
});
}
let now = glib::real_time() / 1_000_000;
let url = find_item(&ui.shared_by_me.items, &entry.uid)
.and_then(|item| item.link)
.filter(|link| !link_expired(link, now))
.and_then(|link| link.url);
if let Some(url) = url {
menu.section();
let (ui_c, url_c) = (ui.clone(), url.clone());
menu.item(&gettext("Copy Link"), move || {
ui_c.stack.clipboard().set_text(&url_c);
toast(&ui_c, &gettext("Link copied"));
});
menu.item(&gettext("Open Link"), move || open_uri(&url));
}
menu.section();
let (ui_c, entry_c) = (ui.clone(), entry.clone());
menu.item(&gettext("Stop Sharing…"), move || {
prompt_stop_sharing(&ui_c, std::slice::from_ref(&entry_c))
});
menu
}
fn shared_by_me_bulk_menu(ui: &Rc<Ui>, entries: Vec<DirEntry>) -> ActionMenu {
let mut menu = ActionMenu::new();
menu.labelled_section(&ngettext_f(
"{n} selected",
"{n} selected",
entries.len() as u64,
&[],
));
let ui_c = ui.clone();
menu.item(&gettext("Stop Sharing…"), move || {
prompt_stop_sharing(&ui_c, &entries)
});
menu
}
fn shared_by_me_background_menu(ui: &Rc<Ui>) -> ActionMenu {
let mut menu = ActionMenu::new();
let ui_c = ui.clone();
menu.item(&gettext("Select All"), move || {
ui_c.shared_by_me.files.selection.select_all();
});
let ui_c = ui.clone();
menu.item(&gettext("Refresh"), move || reload_current_page(&ui_c));
menu
}
/// Confirm, then remove every member, invitation and the public link.
pub(crate) fn prompt_stop_sharing(ui: &Rc<Ui>, entries: &[DirEntry]) {
let body = match entries {
// Translators: {name} is the shared item's name.
[one] => gettext_f(
"Everyone you invited loses access to “{name}”, pending invitations are withdrawn and its public link stops working.",
&[("name", &one.name)],
),
_ => ngettext_f(
"Everyone you invited loses access to {n} item, pending invitations are withdrawn and its public link stops working.",
"Everyone you invited loses access to {n} items, pending invitations are withdrawn and their public links stop working.",
entries.len() as u64,
&[],
),
};
let dialog = adw::AlertDialog::builder()
.heading(gettext("Stop Sharing?"))
.body(body)
.build();
dialog.add_response("cancel", &gettext("Cancel"));
dialog.add_response("stop", &gettext("Stop Sharing"));
dialog.set_response_appearance("stop", adw::ResponseAppearance::Destructive);
dialog.set_default_response(Some("cancel"));
dialog.set_close_response("cancel");
let ui_c = ui.clone();
let done = match entries {
// Translators: {name} is the item's name.
[one] => gettext_f("Stopped sharing {name}", &[("name", &one.name)]),
_ => ngettext_f(
"Stopped sharing {n} item",
"Stopped sharing {n} items",
entries.len() as u64,
&[],
),
};
let uids: Vec<String> = entries.iter().map(|e| e.uid.clone()).collect();
dialog.connect_response(Some("stop"), move |_, _| {
let done = done.clone();
run_requests(
&ui_c,
uids.iter()
.map(|uid| Request::StopSharingByUid { uid: uid.clone() })
.collect(),
gettext_noop("Couldn't stop sharing"),
move |ui| {
reload_listing(ui);
toast(ui, &done);
},
);
});
dialog.present(ui_window(ui).as_ref());
}
/// Open a shared item: a folder in My Files, a file the way My Files would.
fn open_shared_by_me(ui: &Rc<Ui>, entry: &DirEntry) {
if entry.is_dir {
open_in_my_files(ui, entry.path.clone());
} else {
activate_entry(ui, entry);
}
}
/// Go to the folder holding a shared item in My Files.
pub(crate) fn show_in_my_files(ui: &Rc<Ui>, entry: &DirEntry) {
let parent = entry
.path
.rsplit_once('/')
.map(|(parent, _)| parent.to_string())
.unwrap_or_default();
open_in_my_files(ui, parent);
}
/// Build a [`DirEntry`] from a [`SharedItem`], for the file list and the
/// Share dialog, which addresses a pathless node by uid.
pub(crate) fn shared_item_as_entry(item: &SharedItem) -> DirEntry {
DirEntry {
name: item.name.clone(),
@@ -369,5 +616,80 @@ pub(crate) fn shared_item_as_entry(item: &SharedItem) -> DirEntry {
shared_by: String::new(),
shared_at: 0,
shared_by_unverified: false,
trashed_at: 0,
trashed_from: None,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn item(members: usize, invites: usize, link: Option<PublicLinkInfo>) -> SharedItem {
SharedItem {
uid: "vol~link".into(),
name: "Budget.ods".into(),
is_dir: false,
modified: 0,
path: "Work/Budget.ods".into(),
member_count: members,
invite_count: invites,
link,
}
}
fn link(expires: Option<i64>, has_password: bool) -> PublicLinkInfo {
PublicLinkInfo {
id: "l".into(),
url: Some("https://drive.proton.me/urls/X#y".into()),
role: "viewer".into(),
expires,
has_password,
created: 0,
}
}
#[test]
fn a_link_says_whether_it_still_works() {
assert_eq!(link_label(None, 100), "—");
assert_eq!(link_label(Some(&link(None, false)), 100), "Active");
assert_eq!(link_label(Some(&link(Some(100), false)), 100), "Expired");
assert!(link_label(Some(&link(Some(200), false)), 100).starts_with("Expires "));
assert_eq!(
link_label(Some(&link(None, true)), 100),
"Active · Password protected"
);
}
#[test]
fn the_filters_pick_links_people_and_expired_links() {
let people = item(2, 0, None);
let invited = item(0, 1, None);
let live = item(0, 0, Some(link(None, false)));
let expired = item(0, 0, Some(link(Some(50), false)));
let pick = |filter| {
[&people, &invited, &live, &expired]
.iter()
.map(|i| matches_filter(i, filter, 100))
.collect::<Vec<_>>()
};
assert_eq!(pick(ShareFilter::All), [true, true, true, true]);
assert_eq!(pick(ShareFilter::Links), [false, false, true, true]);
assert_eq!(pick(ShareFilter::People), [true, true, false, false]);
assert_eq!(pick(ShareFilter::Expired), [false, false, false, true]);
}
#[test]
fn the_location_is_the_folder_in_my_files() {
assert_eq!(location_label("Work/Budget.ods"), "Work");
assert_eq!(location_label("Budget.ods"), "My files");
assert_eq!(location_label(""), "—");
}
#[test]
fn people_counts_members_and_pending_invitations() {
assert_eq!(people_label(&item(0, 0, None)), "—");
assert_eq!(people_label(&item(1, 0, None)), "1 person");
assert_eq!(people_label(&item(2, 3, None)), "2 people · 3 pending");
}
}
+248 -229
View File
@@ -19,6 +19,8 @@ pub(crate) struct StatusState {
/// Sidebar footer: the one-line sync state. The mount is driven by the
/// systemd user service, not by the user — so this only reports.
pub(crate) status_icon: gtk4::Image,
/// Stands in for [`Self::status_icon`] until the first status arrives.
pub(crate) status_spinner: Spinner,
pub(crate) status_title: gtk4::Label,
pub(crate) status_detail: gtk4::Label,
pub(crate) cache_bar: gtk4::ProgressBar,
@@ -82,12 +84,29 @@ pub(crate) struct StatusState {
/// How many transfers were in flight on the previous poll. A drop to zero is
/// what "sync complete" means; there's no completion event on the wire.
pub(crate) active_transfers: Cell<usize>,
/// The run of transfers since the count last left zero, for deciding
/// whether its end is worth a "Sync complete" notification.
pub(crate) transfer_batch: RefCell<Option<TransferBatch>>,
}
/// One run of transfers, from the first file to the count falling back to 0.
pub(crate) struct TransferBatch {
started: Instant,
/// Every file seen in flight during the run, so the notification can count
/// files rather than the handful still moving on the last poll.
names: HashSet<String>,
}
/// A run of transfers earns a "Sync complete" notification only when it moved
/// at least this many files or lasted at least [`SYNC_NOTIFY_MIN_DURATION`].
/// Saving one document at a time would otherwise notify on every save.
const SYNC_NOTIFY_MIN_FILES: usize = 5;
const SYNC_NOTIFY_MIN_DURATION: Duration = Duration::from_secs(30);
/// One rendered pin row, retained so [`repaint_pins`] can flip the unpin button's
/// `sensitive` in place (when the pin set is unchanged) instead of rebuilding.
pub(crate) struct PinRow {
pub(crate) row: adw::ActionRow,
pub(crate) row: gtk4::ListBoxRow,
/// The unpin button, absent on the placeholder row.
pub(crate) unpin: Option<gtk4::Button>,
}
@@ -121,6 +140,7 @@ pub(crate) struct MainWidgets {
pub(crate) account_name: gtk4::Label,
pub(crate) avatar: adw::Avatar,
pub(crate) status_icon: gtk4::Image,
pub(crate) status_spinner: Spinner,
pub(crate) status_title: gtk4::Label,
pub(crate) status_detail: gtk4::Label,
pub(crate) quota_box: gtk4::Box,
@@ -178,9 +198,7 @@ pub(crate) fn build_main_page() -> MainWidgets {
mountpoint_row.add_css_class("property");
let mountpoint_button = gtk4::Button::builder()
.label(gettext("Change…"))
.tooltip_text(gettext(
"Choose a different folder for the Proton Drive mount",
))
.tooltip_text(gettext("Choose where My files appears on this computer"))
.valign(gtk4::Align::Center)
.build();
mountpoint_button.add_css_class("flat");
@@ -310,7 +328,10 @@ pub(crate) fn build_main_page() -> MainWidgets {
prefs.add(&storage);
// ---- Sidebar footer
let status_icon = gtk4::Image::from_icon_name("content-loading-symbolic");
// Until the first status arrives there is no state to show, only that the
// app is still asking.
let status_icon = gtk4::Image::builder().visible(false).build();
let status_spinner = spinner();
let status_title = gtk4::Label::builder()
.label(gettext("Connecting…"))
.halign(gtk4::Align::Start)
@@ -329,6 +350,7 @@ pub(crate) fn build_main_page() -> MainWidgets {
status_text.append(&status_title);
status_text.append(&status_detail);
let status_content = gtk4::Box::new(gtk4::Orientation::Horizontal, 10);
status_content.append(&status_spinner);
status_content.append(&status_icon);
status_content.append(&status_text);
let status_button = gtk4::Button::builder()
@@ -390,6 +412,7 @@ pub(crate) fn build_main_page() -> MainWidgets {
account_name,
avatar,
status_icon,
status_spinner,
status_title,
status_detail,
quota_box,
@@ -491,7 +514,17 @@ pub(crate) fn wire_settings(
ui.status
.mountpoint_row
.set_subtitle(&ui.dirs.resolved_mountpoint(&config).display().to_string());
ui.status.autostart_row.set_active(service::is_enabled());
// systemctl can take a while, so ask off the main thread and fill the
// switch in when it answers, without firing its change handler.
let ui_auto = ui.clone();
glib::spawn_future_local(async move {
let enabled = gio::spawn_blocking(service::is_enabled)
.await
.unwrap_or(false);
let suppress = ui_auto.status.settings_suppress.replace(true);
ui_auto.status.autostart_row.set_active(enabled);
ui_auto.status.settings_suppress.set(suppress);
});
ui.status
.theme_row
.set_active(config.proton_theme.unwrap_or(false));
@@ -587,11 +620,14 @@ pub(crate) fn wire_settings(
if ui_auto.status.settings_suppress.get() {
return;
}
if row.is_active() {
service::enable();
} else {
service::disable();
}
let enable = row.is_active();
gio::spawn_blocking(move || {
if enable {
service::enable();
} else {
service::disable();
}
});
});
let ui_mp = ui.clone();
@@ -606,8 +642,10 @@ pub(crate) fn wire_settings(
let on = row.is_active();
set_proton_theme(on);
// Folders swap their icon with the theme; have every row bound again.
let rows = ui_theme.browser.model.n_items();
ui_theme.browser.model.items_changed(0, rows, rows);
for list in file_lists(&ui_theme) {
let rows = list.model.n_items();
list.model.items_changed(0, rows, rows);
}
let mut config = ui_theme.dirs.load_config();
config.proton_theme = Some(on);
if let Err(e) = ui_theme.dirs.save_config(&config) {
@@ -706,7 +744,11 @@ pub(crate) fn settings_request(ui: &Rc<Ui>, req: Request, done: String, failed:
Ok(Ok(Response::Error { message, kind })) => {
toast_failure(&ui, &failed, &message, kind)
}
_ => toast_error(&ui, &failed, &gettext("The mount service didn't respond.")),
_ => toast_error(
&ui,
&failed,
&gettext("The Proton Drive service didn't respond."),
),
}
});
}
@@ -716,7 +758,7 @@ pub(crate) fn settings_request(ui: &Rc<Ui>, req: Request, done: String, failed:
pub(crate) fn prompt_mountpoint(ui: &Rc<Ui>) {
let win = ui_window(ui);
let dialog = gtk4::FileDialog::builder()
.title(gettext("Choose mountpoint folder"))
.title(gettext("Choose Proton Drive Folder"))
.build();
let ui = ui.clone();
dialog.select_folder(win.as_ref(), gio::Cancellable::NONE, move |res| {
@@ -728,34 +770,34 @@ pub(crate) fn prompt_mountpoint(ui: &Rc<Ui>) {
let mut config = ui.dirs.load_config();
config.mountpoint = Some(path_str.clone());
if let Err(e) = ui.dirs.save_config(&config) {
toast_error(&ui, &gettext("Couldn't save mountpoint"), &e.to_string());
toast_error(&ui, &gettext("Couldn't save the folder"), &e.to_string());
return;
}
ui.status.mountpoint_row.set_subtitle(&path_str);
// The Locations page shows the same path as a row title; its cached rows
// are now stale whether or not it is the visible page.
ui.locations.loaded_at.set(None);
// The Locations page shows the same path as a row title. Any other page
// reads it again on the next visit.
if ui.stack.visible_child_name().as_deref() == Some("locations") {
load_locations(&ui);
}
// The daemon only reads the mountpoint at mount time, so offer a restart.
let confirm = adw::AlertDialog::builder()
.heading(gettext("Restart to apply"))
.heading(gettext("Restart Proton Drive?"))
// Translators: {path} is the folder the drive is mounted at.
.body(gettext_f(
"The mountpoint is now “{path}”. Restart the Drive mount to use it?",
"My files now appears in “{path}” after Proton Drive restarts.",
&[("path", &path_str)],
))
.build();
confirm.add_response("later", &gettext("Later"));
confirm.add_response("restart", &gettext("Restart now"));
confirm.add_response("restart", &gettext("Restart Now"));
confirm.set_response_appearance("restart", adw::ResponseAppearance::Suggested);
confirm.set_default_response(Some("restart"));
confirm.set_close_response("later");
confirm.connect_response(None, |_, resp| {
let ui_restart = ui.clone();
confirm.connect_response(None, move |_, resp| {
if resp == "restart" {
service::restart();
restart_service_then(&ui_restart, |_| {});
}
});
confirm.present(ui_window(&ui).as_ref());
@@ -767,26 +809,27 @@ pub(crate) fn prompt_mountpoint(ui: &Rc<Ui>) {
/// reload the page.
pub(crate) fn wire_retry(ui: &Rc<Ui>) {
let ui_browser = ui.clone();
ui.browser.retry.clone().connect_clicked(move |_| {
service::restart();
load_browser(&ui_browser);
});
ui.browser
.retry
.clone()
.connect_clicked(move |_| restart_service_then(&ui_browser, load_browser));
let ui_gallery = ui.clone();
ui.gallery.retry.clone().connect_clicked(move |_| {
service::restart();
load_gallery(&ui_gallery, false);
});
ui.gallery
.retry
.clone()
.connect_clicked(move |_| restart_service_then(&ui_gallery, |ui| load_gallery(ui, false)));
let ui_trash = ui.clone();
ui.trash.retry.clone().connect_clicked(move |_| {
service::restart();
load_trash(&ui_trash);
});
ui.trash
.retry
.clone()
.connect_clicked(move |_| restart_service_then(&ui_trash, load_trash));
}
/// Repaint the window from the cached login identity, then kick an async mount-
/// status fetch. Runs on the 2s tick: the identity check is instant (no keyring),
/// and the status round-trip is offloaded to a worker so the main loop never
/// blocks on a slow or wedged daemon.
/// Repaint the window from the cached login identity, then ask the daemon for
/// its status and transfers. Runs at startup, after a login and after a service
/// restart; the daemon's event feed keeps both current in between. The identity
/// check is instant (no keyring), and the round-trips run on workers so the
/// main loop never blocks on a slow or wedged daemon.
pub(crate) fn refresh(ui: &Rc<Ui>) {
// Login identity decides which page is shown. Read the cached session — set
// at startup and on login/logout — never the keyring.
@@ -819,38 +862,14 @@ pub(crate) fn refresh(ui: &Rc<Ui>) {
refresh_status(ui);
refresh_transfers(ui);
// Both of these pages show work as it happens, so they follow the tick while
// they are on screen. Every other page loads on navigation only.
// A Takeout import outlives the page that started it, so it is polled
// wherever the user has navigated to — otherwise leaving the page means
// never being told it finished.
ui.gallery
.import_banner
.set_revealed(ui.takeout.running.get());
if ui.stack.visible_child_name().as_deref() == Some("takeout") || ui.takeout.running.get() {
refresh_takeout(ui);
}
// The quota sits in the sidebar footer, visible on every page; its TTL
// keeps this from asking more than once a minute.
refresh_quota(ui);
match ui.stack.visible_child_name().as_deref() {
Some("locations") => {
refresh_locations(ui);
refresh_queue(ui);
refresh_conflicts(ui, false);
}
Some("activity") => refresh_activity(ui),
_ => {}
}
}
/// How long a quota reading stays fresh. Account storage barely moves, so the
/// active-page tick refetches it only this often rather than every 2s.
/// How long a quota reading stays fresh. Account storage barely moves, so a
/// status change reads it again only this often.
const QUOTA_TTL: Duration = Duration::from_secs(60);
/// Fetch the account quota (if the last reading is stale) and paint both the
/// sidebar footer and Files status bar. A failed fetch leaves the last
/// good reading in place.
/// Fetch the account quota (if the last reading is stale) and paint the
/// sidebar footer. A failed fetch leaves the last good reading in place.
pub(crate) fn refresh_quota(ui: &Rc<Ui>) {
if ui.status.quota_inflight.get() {
return;
@@ -874,10 +893,6 @@ pub(crate) fn refresh_quota(ui: &Rc<Ui>) {
ui.status.quota_checked_at.set(Some(Instant::now()));
paint_account_quota(&ui, max_space, used_space);
ui.status.quota_box.set_visible(true);
} else if ui.status.quota_checked_at.get().is_none() {
// Match Dolphin: capacity information does not occupy the bar until
// the backing observer has real figures.
ui.browser.quota_box.set_visible(false);
}
});
}
@@ -886,15 +901,6 @@ fn paint_account_quota(ui: &Rc<Ui>, max_space: i64, used_space: i64) {
let (fraction, text) = quota_display(max_space, used_space);
ui.status.quota_bar.set_fraction(fraction);
ui.status.quota_label.set_text(&text);
if let Some((fraction, free_text, tooltip)) = quota_status_display(max_space, used_space) {
ui.browser.quota.set_fraction(fraction);
ui.browser.quota.set_tooltip_text(Some(&tooltip));
ui.browser.quota_text.set_label(&free_text);
ui.browser.quota_text.set_tooltip_text(Some(&tooltip));
ui.browser.quota_box.set_visible(true);
} else {
ui.browser.quota_box.set_visible(false);
}
}
fn quota_display(max_space: i64, used_space: i64) -> (f64, String) {
@@ -924,34 +930,6 @@ fn quota_display(max_space: i64, used_space: i64) -> (f64, String) {
)
}
/// Dolphin's status bar shows a bare capacity bar followed by “X free”; the
/// full free/total/percentage sentence is a tooltip rather than inline bar text.
fn quota_status_display(max_space: i64, used_space: i64) -> Option<(f64, String, String)> {
if max_space <= 0 {
return None;
}
let total = max_space as u64;
let used = (used_space.max(0) as u64).min(total);
let free = total.saturating_sub(used);
let fraction = used as f64 / total as f64;
let pct = (fraction * 100.0).round() as u64;
Some((
fraction,
// Translators: {size} is an amount of storage, such as "1.2 GiB".
gettext_f("{size} free", &[("size", &human_bytes(free))]),
// Translators: account storage. {free} and {total} are sizes such as
// "1.2 GiB"; {percent} is a whole number, followed by the percent sign.
gettext_f(
"{free} free out of {total} ({percent}% used)",
&[
("free", &human_bytes(free)),
("total", &human_bytes(total)),
("percent", &pct.to_string()),
],
),
))
}
/// Record the mount state seen by the last status poll: gate every control that
/// needs a live daemon, and notify the desktop when the state actually flips.
///
@@ -981,20 +959,20 @@ pub(crate) fn set_mounted(ui: &Rc<Ui>, mounted: bool) {
notify(
"mount-state",
&gettext("Proton Drive connected"),
&gettext("Your Drive is mounted and available."),
&gettext("Your files are available."),
);
} else {
notify(
"mount-state",
&gettext("Proton Drive disconnected"),
&gettext("The mount service stopped. Files aren't available until it restarts."),
&gettext("The Proton Drive service stopped. Files aren't available until it restarts."),
);
}
}
/// Poll the daemon's in-flight transfers on a worker thread and repaint the
/// Ask the daemon for its in-flight transfers on a worker thread and repaint the
/// Activity group. Independently inflight-guarded from [`refresh_status`] so the
/// two cheap polls on the 2s tick don't gate each other. The group hides itself
/// two requests don't gate each other; the event feed pushes later snapshots. The group hides itself
/// when nothing is moving, so an idle account shows no Activity section.
pub(crate) fn refresh_transfers(ui: &Rc<Ui>) {
if ui.status.transfers_inflight.get() {
@@ -1036,17 +1014,35 @@ pub(crate) fn repaint_transfers(ui: &Rc<Ui>, items: &[TransferItem], jobs: &[Job
takeout_progress(ui, jobs);
let previous = ui.status.active_transfers.replace(items.len());
if !items.is_empty() {
let mut batch = ui.status.transfer_batch.borrow_mut();
let batch = batch.get_or_insert_with(|| TransferBatch {
started: Instant::now(),
names: HashSet::new(),
});
batch
.names
.extend(items.iter().map(|item| item.name.clone()));
}
if items.is_empty() && previous > 0 {
notify(
"sync-complete",
&gettext("Sync complete"),
&ngettext_f(
"{n} file finished transferring.",
"{n} files finished transferring.",
previous as u64,
&[],
),
);
// Nobody needs a notification for what they are watching happen.
let watching = ui_window(ui).is_some_and(|window| window.is_active());
if let Some(batch) = ui.status.transfer_batch.take()
&& !watching
&& (batch.names.len() >= SYNC_NOTIFY_MIN_FILES
|| batch.started.elapsed() >= SYNC_NOTIFY_MIN_DURATION)
{
notify(
"sync-complete",
&gettext("Sync complete"),
&ngettext_f(
"{n} file finished transferring.",
"{n} files finished transferring.",
batch.names.len() as u64,
&[],
),
);
}
// A just-finished batch may have added files (bulk upload) the current
// listing doesn't show yet; refresh whichever listing is on screen.
reload_listing(ui);
@@ -1169,7 +1165,10 @@ pub(crate) fn transfer_line(t: &TransferItem) -> ActivityLine {
/// the mount line, cache bar and pin list on the reply. The daemon owns the cache
/// stats now (`used`/`budget`/`pins` ride along on [`Response::Status`]), so the
/// GUI never opens the on-disk cache itself. Skipped while a fetch is in flight so
/// the tick can't stack threads on a stalled daemon.
/// a stalled daemon can't pile up threads.
///
/// The event feed pushes every later change through [`paint_status`]; this asks
/// only when the feed (re)connects or loses the daemon.
pub(crate) fn refresh_status(ui: &Rc<Ui>) {
if ui.status.status_inflight.get() {
return;
@@ -1181,75 +1180,102 @@ pub(crate) fn refresh_status(ui: &Rc<Ui>) {
let result = rx.recv().await;
ui.status.status_inflight.set(false);
match result {
Ok(Ok(Response::Status {
mountpoint,
used,
budget,
pins,
online,
pending_uploads,
pending_changes,
failing_ops,
failing_error,
paused,
paused_until,
..
})) => {
set_mounted(&ui, true);
// The queue is the more useful thing to say when it has anything
// in it: it is why a file that looks saved is not on the remote
// yet, and offline is usually the reason it is still queued.
let queued = i18n::pending_summary(pending_uploads, pending_changes);
let state = if paused {
SyncState::Paused {
until: paused_until,
queued,
}
} else if failing_ops > 0 {
SyncState::Attention {
count: failing_ops,
error: failing_error,
}
} else if !online {
SyncState::Offline { queued }
} else if let Some(queued) = queued {
SyncState::Syncing { queued }
} else {
SyncState::UpToDate { mountpoint }
};
paint_sync_status(&ui, state);
let fraction = if budget == 0 {
0.0
} else {
(used as f64 / budget as f64).min(1.0)
};
ui.status.cache_bar.set_fraction(fraction);
// A 0 budget means *unlimited*, not a zero-byte cap — "of 0 B
// used" reads as a broken read-out, and there is no fraction to
// draw against no limit.
ui.status.cache_label.set_text(&if budget == 0 {
format!("{} cached — no limit set", human_bytes(used))
} else {
format!("{} of {} used", human_bytes(used), human_bytes(budget))
});
repaint_pins(&ui, &pins, true);
}
// Daemon unreachable (still starting, or down): report not-mounted and
// grey out the unpin buttons in place, but leave the last-known pin
// rows and cache read-out so the page doesn't flicker on a blip.
_ => {
set_mounted(&ui, false);
paint_sync_status(&ui, SyncState::Disconnected);
for r in ui.status.pin_rows.borrow().iter() {
if let Some(b) = &r.unpin {
b.set_sensitive(false);
}
}
}
Ok(Ok(status @ Response::Status { .. })) => paint_status(&ui, status),
// The daemon is up but stuck. Say so, and keep the mount state:
// announcing "disconnected" for a slow reply would be wrong, and
// the feed asks again when it reconnects.
Ok(Err(e)) if e.is_timeout() => paint_sync_status(&ui, SyncState::NotResponding),
_ => paint_disconnected(&ui),
}
});
}
/// Paint a [`Response::Status`], fetched or pushed: the mount state, the sync
/// status, the cache bar and the pin list.
pub(crate) fn paint_status(ui: &Rc<Ui>, status: Response) {
let Response::Status {
mountpoint,
used,
budget,
pins,
online,
pending_uploads,
pending_changes,
failing_ops,
failing_error,
paused,
paused_until,
..
} = status
else {
return;
};
set_mounted(ui, true);
// The queue is the more useful thing to say when it has anything
// in it: it is why a file that looks saved is not on the remote
// yet, and offline is usually the reason it is still queued.
let queued = i18n::pending_summary(pending_uploads, pending_changes);
let state = if paused {
SyncState::Paused {
until: paused_until,
queued,
}
} else if failing_ops > 0 {
SyncState::Attention {
count: failing_ops,
error: failing_error,
}
} else if !online {
SyncState::Offline { queued }
} else if let Some(queued) = queued {
SyncState::Syncing { queued }
} else {
SyncState::UpToDate { mountpoint }
};
paint_sync_status(ui, state);
ui.locations.failing.set(failing_ops);
paint_sync_banner(ui);
let fraction = if budget == 0 {
0.0
} else {
(used as f64 / budget as f64).min(1.0)
};
ui.status.cache_bar.set_fraction(fraction);
// A 0 budget means *unlimited*, not a zero-byte cap — "of 0 B
// used" reads as a broken read-out, and there is no fraction to
// draw against no limit.
ui.status.cache_label.set_text(&if budget == 0 {
// Translators: {used} is a size such as "1.2 GiB".
gettext_f(
"{used} cached — no limit set",
&[("used", &human_bytes(used))],
)
} else {
// Translators: {used} and {limit} are sizes such as "1.2 GiB".
gettext_f(
"{used} of {limit} used",
&[
("used", &human_bytes(used)),
("limit", &human_bytes(budget)),
],
)
});
repaint_pins(ui, &pins, true);
}
/// Daemon unreachable (still starting, or down): report not-mounted and grey
/// out the unpin buttons in place, but leave the last-known pin rows and cache
/// read-out so the page doesn't flicker on a blip.
pub(crate) fn paint_disconnected(ui: &Rc<Ui>) {
set_mounted(ui, false);
paint_sync_status(ui, SyncState::Disconnected);
for r in ui.status.pin_rows.borrow().iter() {
if let Some(b) = &r.unpin {
b.set_sensitive(false);
}
}
}
/// What the sidebar's status strip reports, most urgent first.
pub(crate) enum SyncState {
/// The user paused syncing; nothing goes up until it resumes. Outranks
@@ -1277,13 +1303,15 @@ pub(crate) enum SyncState {
},
/// No mount daemon answered: still starting, or the service is down.
Disconnected,
/// The daemon is running but didn't answer in time.
NotResponding,
}
/// Paint the sidebar status strip and the Sync page's status card: icon,
/// one-line state, and a detail line.
fn paint_sync_status(ui: &Rc<Ui>, state: SyncState) {
let paused = matches!(state, SyncState::Paused { .. });
let connected = !matches!(state, SyncState::Disconnected);
let connected = !matches!(state, SyncState::Disconnected | SyncState::NotResponding);
let (icon, class, title, detail) = match state {
SyncState::Paused { until, queued } => (
"media-playback-pause-symbolic",
@@ -1321,13 +1349,13 @@ fn paint_sync_status(ui: &Rc<Ui>, state: SyncState) {
Some(queued.unwrap_or_else(|| gettext("Cached files only"))),
),
SyncState::Syncing { queued } => (
"emblem-synchronizing-symbolic",
"pdfs-sync-symbolic",
None,
pgettext("state", "Syncing"),
Some(queued),
),
SyncState::UpToDate { mountpoint } => (
"emblem-ok-symbolic",
"pdfs-synced-symbolic",
Some("success"),
gettext("Up to date"),
Some(mountpoint),
@@ -1338,9 +1366,17 @@ fn paint_sync_status(ui: &Rc<Ui>, state: SyncState) {
gettext("Not connected"),
Some(gettext("Proton Drive isn't running")),
),
SyncState::NotResponding => (
"dialog-warning-symbolic",
Some("warning"),
gettext("Not responding"),
Some(gettext("Proton Drive is taking too long to answer")),
),
};
let image = &ui.status.status_icon;
image.set_icon_name(Some(icon));
image.set_visible(true);
ui.status.status_spinner.set_visible(false);
for c in ["success", "warning", "error"] {
image.remove_css_class(c);
}
@@ -1419,10 +1455,10 @@ pub(crate) fn repaint_pins(ui: &Rc<Ui>, pins: &[pdfs_core::cache::Pin], mounted:
))
.build();
ui.status.pins_group.add(&row);
ui.status
.pin_rows
.borrow_mut()
.push(PinRow { row, unpin: None });
ui.status.pin_rows.borrow_mut().push(PinRow {
row: row.upcast(),
unpin: None,
});
return;
}
@@ -1474,7 +1510,7 @@ pub(crate) fn repaint_pins(ui: &Rc<Ui>, pins: &[pdfs_core::cache::Pin], mounted:
_ => toast_error(
&ui,
&gettext("Couldn't make it online only"),
&gettext("The mount service didn't respond."),
&gettext("The Proton Drive service didn't respond."),
),
}
});
@@ -1483,32 +1519,29 @@ pub(crate) fn repaint_pins(ui: &Rc<Ui>, pins: &[pdfs_core::cache::Pin], mounted:
ui.status.pins_group.add(&row);
ui.status.pin_rows.borrow_mut().push(PinRow {
row,
row: row.upcast(),
unpin: Some(unpin),
});
}
if pins.len() > PINS_COLLAPSED {
let row = adw::ActionRow::builder()
.title(if expanded {
gettext("Show fewer")
} else {
ngettext_f(
"Show all {n} file",
"Show all {n} files",
pins.len() as u64,
&[],
)
})
.activatable(true)
.build();
row.add_suffix(&gtk4::Image::from_icon_name(if expanded {
let title = if expanded {
gettext("Show fewer")
} else {
ngettext_f(
"Show all {n} file",
"Show all {n} files",
pins.len() as u64,
&[],
)
};
let icon = if expanded {
"go-up-symbolic"
} else {
"go-down-symbolic"
}));
};
let ui_more = ui.clone();
row.connect_activated(move |_| {
let row = button_row(&title, icon, move || {
ui_more
.status
.pins_expanded
@@ -1529,7 +1562,7 @@ pub(crate) fn repaint_pins(ui: &Rc<Ui>, pins: &[pdfs_core::cache::Pin], mounted:
#[cfg(test)]
mod tests {
use super::{quota_display, quota_status_display};
use super::quota_display;
#[test]
fn quota_display_reports_used_total_and_percentage() {
@@ -1544,18 +1577,4 @@ mod tests {
assert_eq!(quota_display(0, -1), (0.0, "0 bytes used".to_string()));
assert_eq!(quota_display(100, 150).0, 1.0);
}
#[test]
fn quota_status_display_matches_dolphin_wording() {
let gib = 1024_i64.pow(3);
assert_eq!(
quota_status_display(4 * gib, gib),
Some((
0.25,
"3.0 GiB free".to_string(),
"3.0 GiB free out of 4.0 GiB (25% used)".to_string()
))
);
assert_eq!(quota_status_display(0, 0), None);
}
}
+15 -13
View File
@@ -15,16 +15,16 @@
//! Import — staging is local, so a mis-drop costs nothing.
//!
//! The daemon owns the run itself ([`Request::ImportTakeout`]): this page only
//! stages paths, launches, polls [`Request::ImportStatus`] for the final report,
//! stages paths, launches, asks [`Request::ImportStatus`] for the final report,
//! and reads live progress off the import's job in the transfer snapshot the
//! status tick already fetches (see [`takeout_progress`]).
//! daemon already pushes (see [`takeout_progress`]).
use crate::*;
/// The title the daemon gives the import's job in [`Request::GetQueueStatus`].
/// Matching on it is how this page borrows the progress the status tick is
/// already polling instead of adding a second poll of its own.
const IMPORT_JOB: &str = "Importing Google Photos";
/// Matching on it is how this page borrows the progress the daemon already
/// pushes instead of asking for it separately.
pub(crate) const IMPORT_JOB: &str = "Importing Google Photos";
/// What the archive list says before anything is staged. `repaint_archives`
/// swaps in the count and total once there is something to report, and swaps
@@ -384,7 +384,7 @@ pub(crate) fn wire_takeout(ui: &Rc<Ui>, widgets: &TakeoutWidgets) {
let count = ui_import.takeout.archives.borrow().len();
let ui = ui_import.clone();
let dialog = adw::AlertDialog::builder()
.heading(gettext("Import this export?"))
.heading(gettext("Import This Export?"))
.body(ngettext_f(
"{n} archive will be uploaded to Proton Photos, creating albums as they appear in the export. This can take hours; you can stop it at any point and what has been uploaded stays. Photos you already have are skipped.",
"{n} archives will be uploaded to Proton Photos, creating albums as they appear in the export. This can take hours; you can stop it at any point and what has been uploaded stays. Photos you already have are skipped.",
@@ -421,7 +421,7 @@ pub(crate) fn wire_takeout(ui: &Rc<Ui>, widgets: &TakeoutWidgets) {
_ => toast_error(
&ui,
&gettext("Couldn't stop the import"),
&gettext("The mount service didn't respond."),
&gettext("The Proton Drive service didn't respond."),
),
}
});
@@ -589,6 +589,7 @@ fn start_import(ui: &Rc<Ui>, dry_run: bool) {
match result {
Ok(Ok(Response::Ok { .. })) => {
ui.takeout.running.set(true);
ui.gallery.import_banner.set_revealed(true);
ui.takeout.summary_group.set_visible(false);
ui.takeout.progress_group.set_visible(true);
ui.takeout.progress_bar.set_fraction(0.0);
@@ -613,15 +614,15 @@ fn start_import(ui: &Rc<Ui>, dry_run: bool) {
_ => toast_error(
&ui,
&gettext("Couldn't start the import"),
&gettext("The mount service didn't respond."),
&gettext("The Proton Drive service didn't respond."),
),
}
});
}
/// Poll the daemon for the import's state while the page is on screen, and paint
/// the report once a run has finished. Cheap and inflight-guarded, like the other
/// tick polls.
/// Ask the daemon for the import's state, and paint the report once a run has
/// finished. Asked on arrival and while import progress keeps arriving. Cheap
/// and inflight-guarded.
pub(crate) fn refresh_takeout(ui: &Rc<Ui>) {
if ui.takeout.inflight.get() {
return;
@@ -636,6 +637,7 @@ pub(crate) fn refresh_takeout(ui: &Rc<Ui>) {
return;
};
let was_running = ui.takeout.running.replace(running);
ui.gallery.import_banner.set_revealed(running);
if running {
ui.takeout.progress_group.set_visible(true);
} else {
@@ -776,8 +778,8 @@ fn repaint_summary(ui: &Rc<Ui>, summary: &ImportSummary) {
ui.takeout.summary_group.set_visible(true);
}
/// Paint the import's progress from the transfer snapshot the status tick
/// already fetched, so this page costs no extra poll. A job with no known total
/// Paint the import's progress from the transfer snapshot the daemon pushed,
/// so this page costs no extra request. A job with no known total
/// pulses instead of showing a fraction, the same as the Activity list.
pub(crate) fn takeout_progress(ui: &Rc<Ui>, jobs: &[JobItem]) {
let Some(job) = jobs.iter().find(|job| job.title == IMPORT_JOB) else {
+279 -217
View File
@@ -3,55 +3,51 @@ use crate::*;
pub(crate) struct TrashState {
// Trash page. Trashed nodes are addressed by uid, not by path, so this page
// keeps no current-directory state — it re-lists from the daemon on show.
pub(crate) model: gio::ListStore,
pub(crate) files: FileList,
pub(crate) content: gtk4::Stack,
pub(crate) status: adw::StatusPage,
pub(crate) retry: gtk4::Button,
/// Empties the trash; insensitive while it is empty (or unread).
/// Empties the trash; hidden while it is empty (or unread).
pub(crate) empty: gtk4::Button,
/// "12 items" under the page title.
pub(crate) subtitle: adw::WindowTitle,
pub(crate) selection: gtk4::MultiSelection,
/// The bottom bar acting on the selection; revealed while anything is selected.
pub(crate) selection_bar: gtk4::Revealer,
pub(crate) selection_label: gtk4::Label,
/// Runs the loads; the rows stay up while one runs.
pub(crate) loader: Rc<Loader>,
}
/// The widgets of the Trash page that a load repaints.
pub(crate) struct TrashWidgets {
pub(crate) model: gio::ListStore,
pub(crate) list: gtk4::ListView,
pub(crate) files: FileList,
pub(crate) content: gtk4::Stack,
pub(crate) status: adw::StatusPage,
pub(crate) retry: gtk4::Button,
pub(crate) empty: gtk4::Button,
pub(crate) refresh: gtk4::Button,
pub(crate) subtitle: adw::WindowTitle,
pub(crate) selection: gtk4::MultiSelection,
pub(crate) selection_bar: gtk4::Revealer,
pub(crate) selection_label: gtk4::Label,
pub(crate) restore_selected: gtk4::Button,
pub(crate) delete_selected: gtk4::Button,
}
/// The Trash page: a flat list of everything Drive is holding in the trash, each
/// row offering Restore and Delete Forever, with Empty Trash in the header. A
/// selection (click, Shift/Ctrl+click, Ctrl+A) gets the same two actions in a
/// bottom bar.
/// 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
/// right-click menu and, for a selection, in a bottom bar; Empty Trash is in
/// the header while there is something to empty.
///
/// A trashed node has no path inside the mount — the daemon forgets it when it is
/// trashed — so unlike the Files page this one addresses entries by uid and always
/// re-lists from the server rather than from a cached listing. Row rendering needs
/// the [`Ui`] handle for its buttons, so the factory is installed in [`wire_trash`].
/// A trashed node has no path inside the mount — the daemon forgets it when it
/// is trashed — so unlike the Files page this one addresses entries by uid. The
/// list's factories need the [`Ui`] handle, so they are installed in
/// [`wire_trash`].
pub(crate) fn build_trash_page() -> (gtk4::Widget, TrashWidgets) {
let model = gio::ListStore::new::<BoxedAnyObject>();
let empty = gtk4::Button::builder()
.label(gettext("Empty Trash…"))
.tooltip_text(gettext("Permanently delete everything in the Trash"))
.sensitive(false)
.visible(false)
.build();
let refresh = refresh_button();
let retry = gtk4::Button::builder()
.label(gettext("Retry"))
@@ -67,28 +63,27 @@ pub(crate) fn build_trash_page() -> (gtk4::Widget, TrashWidgets) {
.build();
status.add_css_class("compact");
// Bulk Delete Forever always confirms with the count, so a stale selection
// can't delete anything silently.
let selection = gtk4::MultiSelection::new(Some(model.clone()));
let list = gtk4::ListView::builder().model(&selection).build();
let scroll = gtk4::ScrolledWindow::builder()
.vexpand(true)
.child(&list)
.build();
// The list first: where an item came from and when it went are what tell
// two copies of a file apart here.
let files = FileList::new();
files.show_list(true);
let layout = layout_button(&files);
let content = gtk4::Stack::new();
content.set_vexpand(true);
content.set_transition_type(gtk4::StackTransitionType::Crossfade);
content.add_named(&scroll, Some("list"));
content.add_named(&files.views, Some("list"));
content.add_named(&status, Some("status"));
let inner = gtk4::Box::new(gtk4::Orientation::Vertical, 12);
inner.set_margin_top(18);
inner.set_margin_bottom(18);
inner.set_margin_start(18);
inner.set_margin_end(18);
inner.set_margin_top(12);
inner.set_margin_bottom(12);
inner.set_margin_start(12);
inner.set_margin_end(12);
inner.append(&content);
// Bulk Delete Permanently always confirms with the count, so a stale
// selection can't delete anything silently.
let selection_label = gtk4::Label::new(None);
let restore_selected = gtk4::Button::with_label(&pgettext("verb", "Restore"));
let delete_selected = gtk4::Button::with_label(&gettext("Delete Permanently…"));
@@ -105,20 +100,17 @@ 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(&refresh);
header.pack_end(&layout);
(
frame.upcast(),
TrashWidgets {
model,
list,
files,
content,
status,
retry,
empty,
refresh,
subtitle,
selection,
selection_bar,
selection_label,
restore_selected,
@@ -127,142 +119,144 @@ pub(crate) fn build_trash_page() -> (gtk4::Widget, TrashWidgets) {
)
}
/// Install the row factory and the Empty Trash button. The row's two buttons read
/// the entry off the [`gtk4::ListItem`] they were clicked on rather than a
/// captured copy, so a recycled row always acts on the item it currently shows.
/// Install the list's factories and columns, the Empty Trash button and the
/// selection bar.
pub(crate) fn wire_trash(ui: &Rc<Ui>, widgets: &TrashWidgets) {
let list = &widgets.list;
let empty = &widgets.empty;
let factory = gtk4::SignalListItemFactory::new();
let ui_setup = ui.clone();
factory.connect_setup(move |_, item| {
let item = item.downcast_ref::<gtk4::ListItem>().unwrap();
let thumbnail = file_thumbnail_widget(40, 32);
let name = gtk4::Label::builder()
.halign(gtk4::Align::Start)
.ellipsize(gtk4::pango::EllipsizeMode::Middle)
.build();
let meta = gtk4::Label::builder().halign(gtk4::Align::Start).build();
meta.add_css_class("dim-label");
meta.add_css_class("caption");
let text = gtk4::Box::new(gtk4::Orientation::Vertical, 2);
text.set_hexpand(true);
text.set_valign(gtk4::Align::Center);
text.append(&name);
text.append(&meta);
let restore = gtk4::Button::builder()
.icon_name("edit-undo-symbolic")
.tooltip_text(gettext("Restore to its original folder"))
.valign(gtk4::Align::Center)
.build();
restore.add_css_class("flat");
let purge = gtk4::Button::builder()
.icon_name("edit-delete-symbolic")
.tooltip_text(gettext("Delete permanently"))
.valign(gtk4::Align::Center)
.build();
purge.add_css_class("flat");
let ui_restore = ui_setup.clone();
let item_restore = item.clone();
restore.connect_clicked(move |_| {
if let Some(entry) = bound_entry(&item_restore) {
restore_entry(&ui_restore, &entry);
let files = &ui.trash.files;
files.wire(
ui,
FileListBehavior {
activate: activate_trashed,
entry_menu: trash_entry_menu,
bulk_menu: trash_bulk_menu,
background_menu: trash_background_menu,
badges: false,
drag_and_drop: false,
},
);
files
.column_view
.append_column(&text_column(&gettext("Original Location"), |e| {
trashed_from_label(e)
}));
files
.column_view
.append_column(&text_column(&pgettext("column", "Deleted"), |e| {
if e.trashed_at > 0 {
dates::relative(e.trashed_at)
} else {
"—".to_string()
}
});
let ui_purge = ui_setup.clone();
let item_purge = item.clone();
purge.connect_clicked(move |_| {
if let Some(entry) = bound_entry(&item_purge) {
prompt_delete_forever(&ui_purge, std::slice::from_ref(&entry));
}));
files
.column_view
.append_column(&text_column(&pgettext("column", "Size"), |e| {
if e.is_dir {
"—".to_string()
} else {
human_bytes(e.size)
}
});
let row = gtk4::Box::new(gtk4::Orientation::Horizontal, 12);
row.set_margin_top(6);
row.set_margin_bottom(6);
row.set_margin_start(6);
row.set_margin_end(6);
row.append(&thumbnail);
row.append(&text);
row.append(&restore);
row.append(&purge);
item.set_child(Some(&row));
});
factory.connect_bind({
let ui = ui.clone();
move |_, item| {
let item = item.downcast_ref::<gtk4::ListItem>().unwrap();
let Some(entry) = bound_entry(item) else {
return;
};
let row = item.child().and_downcast::<gtk4::Box>().unwrap();
let Some(thumbnail) = row.first_child().and_downcast::<gtk4::Overlay>() else {
return;
};
bind_file_thumbnail(&ui, &thumbnail, &entry, true);
let Some(text) = thumbnail.next_sibling().and_downcast::<gtk4::Box>() else {
return;
};
if let Some(name) = text.first_child().and_downcast::<gtk4::Label>() {
name.set_label(&entry.name);
}
if let Some(meta) = text.last_child().and_downcast::<gtk4::Label>() {
let kind = if entry.is_dir {
gettext("Folder")
} else {
human_bytes(entry.size)
};
let modified = format_modified(entry.modified);
// Translators: {kind} is "Folder" or a file size; {modified} is a date.
let text = gettext_f(
"{kind} · {modified}",
&[("kind", &kind), ("modified", &modified)],
);
meta.set_label(&text);
}
}
});
list.set_factory(Some(&factory));
}));
let ui_empty = ui.clone();
empty.connect_clicked(move |_| prompt_empty_trash(&ui_empty));
widgets
.empty
.connect_clicked(move |_| prompt_empty_trash(&ui_empty));
let ui_sel = ui.clone();
widgets
files
.selection
.connect_selection_changed(move |_, _, _| sync_trash_selection(&ui_sel));
let ui_restore = ui.clone();
widgets.restore_selected.connect_clicked(move |_| {
let entries = selected_trash(&ui_restore);
let entries = ui_restore.trash.files.selected();
if !entries.is_empty() {
restore_entries(&ui_restore, &entries);
}
});
let ui_delete = ui.clone();
widgets.delete_selected.connect_clicked(move |_| {
let entries = selected_trash(&ui_delete);
let entries = ui_delete.trash.files.selected();
if !entries.is_empty() {
prompt_delete_forever(&ui_delete, &entries);
}
});
}
/// The trashed entries currently selected, in list order.
fn selected_trash(ui: &Rc<Ui>) -> Vec<DirEntry> {
let selected = ui.trash.selection.selection();
(0..selected.size())
.filter_map(|i| ui.trash.model.item(selected.nth(i as u32)))
.filter_map(|obj| obj.downcast::<BoxedAnyObject>().ok())
.map(|obj| obj.borrow::<DirEntry>().clone())
.collect()
/// Where a trashed entry goes back to on restore, for the Original Location
/// column.
fn trashed_from_label(entry: &DirEntry) -> String {
match entry.trashed_from.as_deref() {
None => "—".to_string(),
Some("") => gettext("My files"),
Some(path) => path.to_string(),
}
}
/// A trashed file can't be opened; say what would let it be.
fn activate_trashed(ui: &Rc<Ui>, entry: &DirEntry) {
toast(
ui,
// Translators: {name} is a file or folder name.
&gettext_f("Restore “{name}” to open it", &[("name", &entry.name)]),
);
}
fn trash_entry_menu(ui: &Rc<Ui>, entry: &DirEntry) -> ActionMenu {
let mut menu = ActionMenu::new();
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))
});
menu.section();
let (ui_c, entry_c) = (ui.clone(), entry.clone());
menu.item(&gettext("Delete Permanently…"), move || {
prompt_delete_forever(&ui_c, std::slice::from_ref(&entry_c))
});
menu
}
fn trash_bulk_menu(ui: &Rc<Ui>, entries: Vec<DirEntry>) -> ActionMenu {
let mut menu = ActionMenu::new();
menu.labelled_section(&ngettext_f(
"{n} selected",
"{n} selected",
entries.len() as u64,
&[],
));
let (ui_c, batch) = (ui.clone(), entries.clone());
menu.item(&pgettext("verb", "Restore"), move || {
restore_entries(&ui_c, &batch)
});
menu.section();
let ui_c = ui.clone();
menu.item(&gettext("Delete Permanently…"), move || {
prompt_delete_forever(&ui_c, &entries)
});
menu
}
fn trash_background_menu(ui: &Rc<Ui>) -> ActionMenu {
let mut menu = ActionMenu::new();
let ui_c = ui.clone();
menu.item(&gettext("Select All"), move || {
ui_c.trash.files.selection.select_all();
});
let ui_c = ui.clone();
menu.item(&gettext("Refresh"), move || reload_current_page(&ui_c));
if ui.trash.files.model.n_items() > 0 {
menu.section();
let ui_c = ui.clone();
menu.item(&gettext("Empty Trash…"), move || {
prompt_empty_trash(&ui_c)
});
}
menu
}
/// Reveal the selection bar while anything is selected and count what is.
fn sync_trash_selection(ui: &Rc<Ui>) {
let count = ui.trash.selection.selection().size() as usize;
let count = ui.trash.files.selection.selection().size() as usize;
ui.trash.selection_bar.set_reveal_child(count > 0);
if count > 0 {
ui.trash.selection_label.set_label(&ngettext_f(
@@ -274,29 +268,24 @@ fn sync_trash_selection(ui: &Rc<Ui>) {
}
}
/// The [`DirEntry`] a list item is currently bound to, or `None` for an unbound
/// (recycled) row.
pub(crate) fn bound_entry(item: &gtk4::ListItem) -> Option<DirEntry> {
let obj = item.item().and_downcast::<BoxedAnyObject>()?;
let entry = obj.borrow::<DirEntry>().clone();
Some(entry)
}
/// Fetch the trash listing and repaint the page.
pub(crate) fn load_trash(ui: &Rc<Ui>) {
cancel_file_thumbnails(ui);
// Drop the old rows first: a stale row here would offer Restore on something
// that may already be gone.
ui.trash.model.remove_all();
ui.trash.empty.set_sensitive(false);
sync_trash_selection(ui);
trash_status(
ui,
"user-trash-symbolic",
&gettext("Loading…"),
&gettext("Reading the trash."),
false,
);
// The rows stay up while the trash is read again. Trashed items are
// addressed by uid, so acting on one that has gone meanwhile fails
// cleanly rather than hitting something else.
let ui_p = ui.clone();
let ticket = ui.trash.loader.refresh(move || {
clear_trash(&ui_p);
ui_p.trash.empty.set_sensitive(false);
trash_status(
&ui_p,
"user-trash-symbolic",
&gettext("Loading…"),
&gettext("Reading the trash."),
false,
);
});
ui.busy_begin();
let rx = spawn_request(ui.dirs.control_socket(), Request::ListTrash);
@@ -304,6 +293,12 @@ pub(crate) fn load_trash(ui: &Rc<Ui>) {
glib::spawn_future_local(async move {
let result = rx.recv().await;
ui.busy_end();
if !ticket.is_current() {
return;
}
if !matches!(result, Ok(Ok(Response::Entries { .. }))) {
clear_trash(&ui);
}
match result {
Ok(Ok(Response::Entries { entries })) => repaint_trash(&ui, &entries),
Ok(Ok(Response::Error { message, .. })) => trash_status(
@@ -317,7 +312,7 @@ pub(crate) fn load_trash(ui: &Rc<Ui>) {
&ui,
"dialog-warning-symbolic",
&gettext("Couldn't read the trash"),
&gettext("Unexpected reply from the mount service."),
&gettext("Unexpected reply from the Proton Drive service."),
false,
),
Ok(Err(_)) | Err(_) => trash_unreachable(&ui),
@@ -328,29 +323,7 @@ pub(crate) fn load_trash(ui: &Rc<Ui>) {
/// The daemon didn't answer. Same split as the Files page: still starting (poll
/// again, no button) versus actually down (Retry, which restarts the service).
pub(crate) fn trash_unreachable(ui: &Rc<Ui>) {
if service::is_failed() || !service::is_active() {
trash_status(
ui,
"network-offline-symbolic",
&gettext("Not connected"),
&gettext("The Proton Drive mount service isn't running."),
true,
);
return;
}
trash_status(
ui,
"folder-remote-symbolic",
&gettext("Connecting…"),
&gettext("Waiting for the Proton Drive mount service to come up."),
false,
);
let ui = ui.clone();
glib::timeout_add_local_once(CONNECT_RETRY_INTERVAL, move || {
if ui.stack.visible_child_name().as_deref() == Some("trash") {
load_trash(&ui);
}
});
service_unreachable(ui, "trash", trash_status, load_trash);
}
/// Show a status page in place of the trash list.
@@ -363,12 +336,13 @@ pub(crate) fn trash_status(ui: &Rc<Ui>, icon: &str, title: &str, description: &s
ui.trash.subtitle.set_subtitle("");
}
/// Repopulate the trash list, most recently modified first — the order in which a
/// user looks for what they just deleted.
/// 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]) {
ui.trash.model.remove_all();
sync_trash_selection(ui);
ui.trash.empty.set_sensitive(!entries.is_empty());
// 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() {
trash_status(
ui,
@@ -377,6 +351,7 @@ pub(crate) fn repaint_trash(ui: &Rc<Ui>, entries: &[DirEntry]) {
&gettext("Items you delete from Proton Drive show up here."),
false,
);
clear_trash(ui);
return;
}
ui.trash.content.set_visible_child_name("list");
@@ -388,38 +363,69 @@ pub(crate) fn repaint_trash(ui: &Rc<Ui>, entries: &[DirEntry]) {
));
let mut sorted = entries.to_vec();
sorted.sort_by_key(|e| std::cmp::Reverse(e.modified));
for entry in sorted {
ui.trash.model.append(&BoxedAnyObject::new(entry));
}
sort_trash(&mut sorted);
// Only the rows that changed are swapped, so a refresh keeps the
// selection and the scroll position.
replace_items(&ui.trash.files.model, &sorted);
sync_trash_selection(ui);
}
/// Restore one trashed entry to the folder it was trashed from.
pub(crate) fn restore_entry(ui: &Rc<Ui>, entry: &DirEntry) {
restore_entries(ui, std::slice::from_ref(entry));
/// Newest deletion first. Entries with no known deletion time go last, newest
/// modification first among themselves.
fn sort_trash(entries: &mut [DirEntry]) {
entries.sort_by_key(|e| {
(
e.trashed_at == 0,
std::cmp::Reverse(e.trashed_at),
std::cmp::Reverse(e.modified),
)
});
}
/// Restore trashed entries to the folders they were trashed from.
/// Drop every row, and with them the selection and its bar.
fn clear_trash(ui: &Rc<Ui>) {
ui.trash.files.model.remove_all();
sync_trash_selection(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]) {
run_mutation(
let message = match entries {
// Translators: {name} is a file or folder name.
[one] => gettext_f("Restored “{name}”", &[("name", &one.name)]),
_ => ngettext_f(
"Restored {n} item",
"Restored {n} items",
entries.len() as u64,
&[],
),
};
let folder = common_origin(entries);
run_mutation_then(
ui,
Request::Restore {
uids: entries.iter().map(|e| e.uid.clone()).collect(),
},
match entries {
// Translators: {name} is a file or folder name.
[one] => gettext_f("Restored “{name}”", &[("name", &one.name)]),
_ => ngettext_f(
"Restored {n} item",
"Restored {n} items",
entries.len() as u64,
&[],
),
},
gettext_noop("Couldn't restore"),
move |ui| match folder {
Some(folder) => toast_action(ui, &message, &gettext("Show"), move |ui| {
open_in_my_files(ui, folder.clone())
}),
None => toast(ui, &message),
},
);
}
/// The folder every entry goes back to, when that is one known folder.
fn common_origin(entries: &[DirEntry]) -> Option<String> {
let first = entries.first()?.trashed_from.clone()?;
entries
.iter()
.all(|e| e.trashed_from.as_deref() == Some(first.as_str()))
.then_some(first)
}
/// Confirm, then permanently delete trashed entries. Irreversible, so it asks.
pub(crate) fn prompt_delete_forever(ui: &Rc<Ui>, entries: &[DirEntry]) {
let win = ui_window(ui);
@@ -451,7 +457,7 @@ pub(crate) fn prompt_delete_forever(ui: &Rc<Ui>, entries: &[DirEntry]) {
),
};
let dialog = adw::AlertDialog::builder()
.heading(gettext("Delete Permanently"))
.heading(gettext("Delete Permanently?"))
.body(body)
.build();
dialog.add_response("cancel", &gettext("Cancel"));
@@ -477,9 +483,9 @@ 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.model.n_items();
let count = ui.trash.files.model.n_items();
let dialog = adw::AlertDialog::builder()
.heading(gettext("Empty Trash"))
.heading(gettext("Empty Trash?"))
.body(ngettext_f(
"Permanently delete all {n} item in the trash? This cannot be undone.",
"Permanently delete all {n} items in the trash? This cannot be undone.",
@@ -506,3 +512,59 @@ pub(crate) fn prompt_empty_trash(ui: &Rc<Ui>) {
});
dialog.present(win.as_ref());
}
#[cfg(test)]
mod tests {
use super::*;
fn trashed(name: &str, trashed_at: i64, modified: i64, from: Option<&str>) -> DirEntry {
DirEntry {
name: name.into(),
is_dir: false,
size: 0,
modified,
pinned: false,
cached: false,
uid: name.into(),
path: String::new(),
role: String::new(),
shared_by: String::new(),
shared_at: 0,
shared_by_unverified: false,
trashed_at,
trashed_from: from.map(str::to_string),
}
}
#[test]
fn trash_lists_newest_deletion_first_and_undated_last() {
let mut entries = vec![
trashed("undated-old", 0, 1, None),
trashed("older", 10, 50, None),
trashed("undated-new", 0, 9, None),
trashed("newest", 20, 5, None),
];
sort_trash(&mut entries);
let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
assert_eq!(names, ["newest", "older", "undated-new", "undated-old"]);
}
#[test]
fn restore_offers_a_folder_only_when_all_share_one() {
let docs = trashed("a", 1, 1, Some("Documents"));
let docs2 = trashed("b", 1, 1, Some("Documents"));
let root = trashed("c", 1, 1, Some(""));
let unknown = trashed("d", 1, 1, None);
assert_eq!(
common_origin(&[docs.clone(), docs2]).as_deref(),
Some("Documents")
);
assert_eq!(
common_origin(std::slice::from_ref(&root)).as_deref(),
Some("")
);
assert_eq!(common_origin(&[docs.clone(), root]), None);
assert_eq!(common_origin(&[docs, unknown]), None);
assert_eq!(common_origin(&[]), None);
}
}
+188
View File
@@ -0,0 +1,188 @@
//! Reloading a page without flashing it.
//!
//! Pages used to swap their content for a "Loading…" status page on every
//! load, so every sidebar click and every folder change blinked. A [`Loader`]
//! keeps the last content on screen while the request runs and shows the
//! loading state only if the reply is slow. [`replace_items`] then swaps in the
//! new rows by changing only the ones that differ, so selection and scroll
//! position survive a refresh.
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::time::Duration;
use gtk4::gio;
use gtk4::glib;
use gtk4::glib::BoxedAnyObject;
use gtk4::glib::object::Cast;
use gtk4::prelude::*;
/// How long a load may run before the page gives up its old content for a
/// loading state. Most replies arrive well within this, so the page updates in
/// place.
const LOADING_GRACE: Duration = Duration::from_millis(300);
/// One page's loads. Each [`Loader::refresh`] or [`Loader::replace`]
/// supersedes the one before it.
pub(crate) struct Loader {
content: gtk4::Widget,
generation: Cell<u64>,
placeholder: RefCell<Option<glib::SourceId>>,
}
impl Loader {
/// A loader for the page whose content is `content`.
pub(crate) fn new(content: &impl IsA<gtk4::Widget>) -> Rc<Self> {
Rc::new(Loader {
content: content.clone().upcast(),
generation: Cell::new(0),
placeholder: RefCell::new(None),
})
}
/// Start a load of what the page already shows. The content stays up and
/// usable; `placeholder` runs if the load is still going after
/// [`LOADING_GRACE`].
pub(crate) fn refresh(self: &Rc<Self>, placeholder: impl FnOnce() + 'static) -> LoadTicket {
self.begin(false, placeholder)
}
/// Start a load of something else, such as another folder. The old
/// content stays up but insensitive, since acting on it would act on the
/// wrong thing; `placeholder` runs if the load is still going after
/// [`LOADING_GRACE`].
pub(crate) fn replace(self: &Rc<Self>, placeholder: impl FnOnce() + 'static) -> LoadTicket {
self.begin(true, placeholder)
}
fn begin(self: &Rc<Self>, stale: bool, placeholder: impl FnOnce() + 'static) -> LoadTicket {
let generation = self.generation.get().wrapping_add(1);
self.generation.set(generation);
self.cancel_placeholder();
self.content.set_sensitive(!stale);
let loader = Rc::downgrade(self);
let source = glib::timeout_add_local_once(LOADING_GRACE, move || {
let Some(loader) = loader.upgrade() else {
return;
};
loader.placeholder.borrow_mut().take();
loader.content.set_sensitive(true);
placeholder();
});
*self.placeholder.borrow_mut() = Some(source);
LoadTicket {
loader: self.clone(),
generation,
}
}
fn cancel_placeholder(&self) {
if let Some(source) = self.placeholder.borrow_mut().take() {
source.remove();
}
}
}
/// A load in flight. Dropping it ends the load: the pending loading state is
/// cancelled and the content is usable again, unless a newer load has taken
/// over in the meantime.
pub(crate) struct LoadTicket {
loader: Rc<Loader>,
generation: u64,
}
impl LoadTicket {
/// Whether no newer load has started since this one. A superseded load's
/// reply is stale and must not be painted.
pub(crate) fn is_current(&self) -> bool {
self.loader.generation.get() == self.generation
}
}
impl Drop for LoadTicket {
fn drop(&mut self) {
if self.is_current() {
self.loader.cancel_placeholder();
self.loader.content.set_sensitive(true);
}
}
}
/// Make `model`, a list of [`BoxedAnyObject`]s holding `T`, hold `items`,
/// replacing only the run of items that changed, in one `items-changed`
/// signal. Rows before and after that run keep their objects, so the views
/// keep their widgets, the selection and the scroll position.
pub(crate) fn replace_items<T: Clone + PartialEq + 'static>(model: &gio::ListStore, items: &[T]) {
let held = |i: usize, item: &T| {
model
.item(i as u32)
.and_downcast::<BoxedAnyObject>()
.is_some_and(|object| *object.borrow::<T>() == *item)
};
let Some((start, removed, added)) = changed_run(model.n_items() as usize, items, held) else {
return;
};
let added: Vec<BoxedAnyObject> = items[added]
.iter()
.cloned()
.map(BoxedAnyObject::new)
.collect();
model.splice(start as u32, removed as u32, &added);
}
/// The one run that differs between an old list of `old_len` items and `new`:
/// where it starts, how many old items it covers, and which new items replace
/// them. `held(i, item)` says whether old item `i` equals `item`. `None` when
/// the lists are equal.
fn changed_run<T>(
old_len: usize,
new: &[T],
held: impl Fn(usize, &T) -> bool,
) -> Option<(usize, usize, std::ops::Range<usize>)> {
let shared = old_len.min(new.len());
let prefix = (0..shared).take_while(|&i| held(i, &new[i])).count();
let suffix = (0..shared - prefix)
.take_while(|&k| held(old_len - 1 - k, &new[new.len() - 1 - k]))
.count();
let removed = old_len - prefix - suffix;
let added = prefix..new.len() - suffix;
(removed > 0 || !added.is_empty()).then_some((prefix, removed, added))
}
#[cfg(test)]
mod tests {
use super::changed_run;
fn run(old: &[u32], new: &[u32]) -> Option<(usize, usize, Vec<u32>)> {
changed_run(old.len(), new, |i, item| old[i] == *item)
.map(|(start, removed, added)| (start, removed, new[added].to_vec()))
}
#[test]
fn equal_lists_change_nothing() {
assert_eq!(run(&[1, 2, 3], &[1, 2, 3]), None);
assert_eq!(run(&[], &[]), None);
}
#[test]
fn only_the_differing_middle_is_replaced() {
assert_eq!(run(&[1, 2, 3, 4], &[1, 9, 4]), Some((1, 2, vec![9])));
assert_eq!(run(&[1, 2, 3], &[1, 2, 5, 3]), Some((2, 0, vec![5])));
assert_eq!(run(&[1, 2, 3], &[1, 3]), Some((1, 1, vec![])));
}
#[test]
fn growing_or_shrinking_at_either_end() {
assert_eq!(run(&[1, 2], &[0, 1, 2]), Some((0, 0, vec![0])));
assert_eq!(run(&[1, 2], &[1, 2, 3]), Some((2, 0, vec![3])));
assert_eq!(run(&[1, 2, 3], &[]), Some((0, 3, vec![])));
assert_eq!(run(&[], &[1]), Some((0, 0, vec![1])));
}
#[test]
fn repeated_items_are_not_counted_twice() {
// The prefix takes both 1s; the suffix must not reuse them.
assert_eq!(run(&[1, 1], &[1, 1, 1]), Some((2, 0, vec![1])));
assert_eq!(run(&[1, 1, 1], &[1, 1]), Some((2, 1, vec![])));
}
}
+311
View File
@@ -0,0 +1,311 @@
//! The app's side of `src/compat.rs`: widgets libadwaita 1.6–1.8 brought, with
//! a stand-in for 1.5. [`has_adw_1_8`] picks the real ones at run time.
use crate::*;
/// A segmented control: a row of options of which exactly one is on, told
/// apart by index in the order they were given. `AdwToggleGroup` on
/// libadwaita 1.8, linked toggle buttons before.
#[derive(Clone)]
pub(crate) struct ToggleGroup {
widget: gtk4::Widget,
options: Options,
}
#[derive(Clone)]
enum Options {
/// The group's `AdwToggle`s, reached by property name.
Toggles(Rc<[glib::Object]>),
Buttons(Rc<[gtk4::ToggleButton]>),
}
impl ToggleGroup {
/// A group of `(label, tooltip)` options, with the first one on.
pub(crate) fn new(options: &[(&str, Option<&str>)]) -> Self {
if has_adw_1_8() {
let children: String = (0..options.len())
.map(|i| format!(r#"<child><object class="AdwToggle" id="toggle{i}"/></child>"#))
.collect();
let builder = build_ui(&format!(
r#"<object class="AdwToggleGroup" id="group">{children}</object>"#
));
let toggles = options
.iter()
.enumerate()
.map(|(i, (label, tooltip))| {
let toggle: glib::Object = built(&builder, &format!("toggle{i}"));
toggle.set_property("label", *label);
if let Some(tooltip) = tooltip {
toggle.set_property("tooltip", *tooltip);
}
toggle
})
.collect();
let widget: gtk4::Widget = built(&builder, "group");
// A toggle group starts with nothing on.
widget.set_property("active", 0u32);
Self {
widget,
options: Options::Toggles(toggles),
}
} else {
let bar = gtk4::Box::new(gtk4::Orientation::Horizontal, 0);
bar.add_css_class("linked");
let buttons: Rc<[gtk4::ToggleButton]> = options
.iter()
.map(|(label, tooltip)| {
let button = gtk4::ToggleButton::with_label(label);
button.set_tooltip_text(*tooltip);
bar.append(&button);
button
})
.collect();
if let Some((first, rest)) = buttons.split_first() {
first.set_active(true);
// Chaining each to the first is what GTK turns into mutual
// exclusion.
for button in rest {
button.set_group(Some(first));
}
}
Self {
widget: bar.upcast(),
options: Options::Buttons(buttons),
}
}
}
/// The widget to pack.
pub(crate) fn widget(&self) -> gtk4::Widget {
self.widget.clone()
}
/// Give the options pill-shaped ends.
pub(crate) fn set_round(&self) {
match &self.options {
Options::Toggles(_) => self.widget.add_css_class("round"),
Options::Buttons(buttons) => {
for button in buttons.iter() {
button.add_css_class("pill");
}
}
}
}
/// The option that is on.
pub(crate) fn active(&self) -> u32 {
match &self.options {
Options::Toggles(_) => self.widget.property("active"),
Options::Buttons(buttons) => {
buttons.iter().position(|b| b.is_active()).unwrap_or(0) as u32
}
}
}
/// Turn option `index` on, which turns the one that was on off.
pub(crate) fn set_active(&self, index: u32) {
match &self.options {
Options::Toggles(_) => self.widget.set_property("active", index),
Options::Buttons(buttons) => {
if let Some(button) = buttons.get(index as usize) {
button.set_active(true);
}
}
}
}
pub(crate) fn set_label(&self, index: u32, label: &str) {
match &self.options {
Options::Toggles(toggles) => {
if let Some(toggle) = toggles.get(index as usize) {
toggle.set_property("label", label);
}
}
Options::Buttons(buttons) => {
if let Some(button) = buttons.get(index as usize) {
button.set_label(label);
}
}
}
}
/// Let option `index` be picked, or not.
pub(crate) fn set_enabled(&self, index: u32, enabled: bool) {
match &self.options {
Options::Toggles(toggles) => {
if let Some(toggle) = toggles.get(index as usize) {
toggle.set_property("enabled", enabled);
}
}
Options::Buttons(buttons) => {
if let Some(button) = buttons.get(index as usize) {
button.set_sensitive(enabled);
}
}
}
}
/// Call `f` with the option that has just come on, whether the user or
/// [`Self::set_active`] turned it on.
pub(crate) fn connect_changed(&self, f: impl Fn(u32) + 'static) {
match &self.options {
Options::Toggles(_) => {
self.widget
.connect_notify_local(Some("active"), move |group, _| {
f(group.property("active"))
});
}
Options::Buttons(buttons) => {
let f = Rc::new(f);
for (index, button) in buttons.iter().enumerate() {
let f = f.clone();
// The group also fires `toggled` for the button going off;
// only the one coming on counts.
button.connect_toggled(move |button| {
if button.is_active() {
f(index as u32);
}
});
}
}
}
}
}
/// A list row that is a button: a centred title and an icon after it.
/// `AdwButtonRow` on libadwaita 1.8, an activatable `adw::ActionRow` before.
pub(crate) fn button_row(
title: &str,
end_icon: &str,
on_activated: impl Fn() + 'static,
) -> gtk4::ListBoxRow {
if has_adw_1_8() {
let builder = build_ui(r#"<object class="AdwButtonRow" id="row"/>"#);
let row: adw::PreferencesRow = built(&builder, "row");
row.set_title(title);
row.set_property("end-icon-name", end_icon);
row.connect_local("activated", false, move |_| {
on_activated();
None
});
row.upcast()
} else {
let row = adw::ActionRow::builder()
.title(title)
.activatable(true)
.build();
row.add_suffix(&gtk4::Image::from_icon_name(end_icon));
row.connect_activated(move |_| on_activated());
row.upcast()
}
}
/// Show the keyboard shortcuts window over `window`. See [`shortcuts_dialog`].
pub(crate) fn present_shortcuts(
window: &impl IsA<gtk4::Widget>,
groups: &[(String, Vec<(&str, String)>)],
) {
shortcuts_dialog(groups).present(Some(window));
}
/// The keyboard shortcuts window: `groups` of `(accelerator, what it does)`
/// under a heading each, all already translated. `AdwShortcutsDialog` on
/// libadwaita 1.8, a preferences page of rows before.
fn shortcuts_dialog(groups: &[(String, Vec<(&str, String)>)]) -> adw::Dialog {
if has_adw_1_8() {
let sections: String = groups
.iter()
.enumerate()
.map(|(s, (_, keys))| {
let items: String = (0..keys.len())
.map(|k| {
format!(r#"<child><object class="AdwShortcutsItem" id="item{s}_{k}"/></child>"#)
})
.collect();
format!(
r#"<child><object class="AdwShortcutsSection" id="section{s}">{items}</object></child>"#
)
})
.collect();
let builder = build_ui(&format!(
r#"<object class="AdwShortcutsDialog" id="dialog">{sections}</object>"#
));
for (s, (title, keys)) in groups.iter().enumerate() {
let section: glib::Object = built(&builder, &format!("section{s}"));
section.set_property("title", title.as_str());
for (k, (accel, action)) in keys.iter().enumerate() {
let item: glib::Object = built(&builder, &format!("item{s}_{k}"));
item.set_property("title", action.as_str());
item.set_property("accelerator", *accel);
}
}
return built(&builder, "dialog");
}
let page = adw::PreferencesPage::new();
for (title, keys) in groups {
let group = adw::PreferencesGroup::builder().title(title).build();
for (accel, action) in keys {
let row = adw::ActionRow::builder().title(action).build();
row.add_suffix(
&gtk4::ShortcutLabel::builder()
.accelerator(*accel)
.valign(gtk4::Align::Center)
.build(),
);
group.add(&row);
}
page.add(&group);
}
adw::Dialog::builder()
.title(gettext("Keyboard Shortcuts"))
.content_width(460)
.content_height(620)
.child(&{
let toolbar = adw::ToolbarView::new();
toolbar.add_top_bar(&adw::HeaderBar::new());
toolbar.set_content(Some(&page));
toolbar
})
.build()
}
#[cfg(test)]
mod tests {
use super::*;
/// The newer widgets are made by class name and set up by property and
/// signal name, so a typo in any of those only shows when they are built.
/// Needs a display and libadwaita 1.8; passes trivially without either.
#[test]
fn newer_widgets_build_by_class_name() {
if adw::init().is_err() || !has_adw_1_8() {
return;
}
let group = ToggleGroup::new(&[("One", None), ("Two", Some("The second"))]);
group.set_round();
group.set_label(1, "Deux");
group.set_enabled(1, true);
assert_eq!(group.widget().type_().name(), "AdwToggleGroup");
assert_eq!(group.active(), 0);
let changed = Rc::new(Cell::new(None));
group.connect_changed({
let changed = changed.clone();
move |index| changed.set(Some(index))
});
group.set_active(1);
assert_eq!((group.active(), changed.get()), (1, Some(1)));
let row = button_row("Row", "go-down-symbolic", || {});
assert_eq!(row.type_().name(), "AdwButtonRow");
assert_eq!(spinner().type_().name(), "AdwSpinner");
let dialog = shortcuts_dialog(&[(
"General".to_owned(),
vec![("<Control>q", "Quit".to_owned())],
)]);
assert_eq!(dialog.type_().name(), "AdwShortcutsDialog");
}
}
+5 -5
View File
@@ -49,7 +49,7 @@ pub(crate) struct DetailsWidgets {
/// [`DirEntry`] and [`wire_details`] connects the buttons.
pub(crate) fn build_details_pane() -> (gtk4::Widget, DetailsWidgets) {
let toggle = gtk4::ToggleButton::builder()
.icon_name("sidebar-show-right-symbolic")
.icon_name("pdfs-details-pane-symbolic")
.tooltip_text(gettext("Details (Alt+Enter)"))
.build();
@@ -202,7 +202,7 @@ pub(crate) fn build_details_pane() -> (gtk4::Widget, DetailsWidgets) {
let toggle_off = toggle.clone();
empty_close.connect_clicked(move |_| toggle_off.set_active(false));
let empty_status = adw::StatusPage::builder()
.icon_name("sidebar-show-right-symbolic")
.icon_name("pdfs-details-pane-symbolic")
.title(gettext("No item selected"))
.description(gettext("Select a file or folder to see its details."))
.vexpand(true)
@@ -373,7 +373,7 @@ pub(crate) fn show_details(ui: &Rc<Ui>, entry: &DirEntry) {
});
d.size_row.set_visible(!entry.is_dir);
d.modified_row
.set_subtitle(&format_modified(entry.modified));
.set_subtitle(&dates::short_date(entry.modified));
let rel = entry_rel(ui, entry);
let parent = match rel.rfind('/') {
Some(i) => &rel[..i],
@@ -494,13 +494,13 @@ pub(crate) fn versions_summary(items: &[RevisionInfo]) -> String {
match (items.len(), latest) {
(0, _) | (_, None) => gettext("No earlier versions"),
// Translators: {date} is the date of the only version.
(1, Some(t)) => gettext_f("1 version · {date}", &[("date", &format_modified(t))]),
(1, Some(t)) => gettext_f("1 version · {date}", &[("date", &dates::short_date(t))]),
// Translators: {date} is the date of the newest version.
(n, Some(t)) => ngettext_f(
"{n} version · latest {date}",
"{n} versions · latest {date}",
n as u64,
&[("date", &format_modified(t))],
&[("date", &dates::short_date(t))],
),
}
}
@@ -0,0 +1,522 @@
//! The file list every file page shows: an icon grid and a column list over one
//! model and one selection, with thumbnails, context menus, rubberband selection
//! and click-to-deselect. My files, Trash, Shared with me and Shared by me build
//! one each and differ only in their columns, menus and what activating an entry
//! does (see [`FileListBehavior`]).
use crate::*;
/// Where a page's entries go when the user acts on them. Plain function pointers:
/// each page has one of these, fixed for the life of the window.
#[derive(Clone, Copy)]
pub(crate) struct FileListBehavior {
/// Double-click or Enter on an entry.
pub(crate) activate: fn(&Rc<Ui>, &DirEntry),
/// The right-click menu for one entry.
pub(crate) entry_menu: fn(&Rc<Ui>, &DirEntry) -> ActionMenu,
/// The right-click menu for a multi-selection the clicked entry is part of.
pub(crate) bulk_menu: fn(&Rc<Ui>, Vec<DirEntry>) -> ActionMenu,
/// The right-click menu on empty space.
pub(crate) background_menu: fn(&Rc<Ui>) -> ActionMenu,
/// Paint the offline/cached/online-only badge. Only entries in the mounted
/// tree have a local state worth showing.
pub(crate) badges: bool,
/// Entries can be dragged onto folders to move them.
pub(crate) drag_and_drop: bool,
}
/// A realised grid cell's thumbnail and name label.
type GridTile = (glib::WeakRef<gtk4::Overlay>, glib::WeakRef<gtk4::Label>);
/// One page's grid and list. Cheap to clone: every field is a GObject or an
/// `Rc`, so a clone is the same list.
#[derive(Clone)]
pub(crate) struct FileList {
/// The entries, as [`BoxedAnyObject`]-wrapped [`DirEntry`]s.
pub(crate) model: gio::ListStore,
/// One selection for both views: switching layout keeps what is selected.
pub(crate) selection: gtk4::MultiSelection,
pub(crate) grid: gtk4::GridView,
pub(crate) column_view: gtk4::ColumnView,
/// The two views, named "grid" and "list".
pub(crate) views: gtk4::Stack,
thumbnail_size: Rc<Cell<i32>>,
/// Weak references to realised grid cells. A new thumbnail size resizes only
/// these visible, recycled surfaces instead of invalidating the whole model.
tiles: Rc<RefCell<Vec<GridTile>>>,
behavior: Rc<Cell<Option<FileListBehavior>>>,
}
impl FileList {
/// Assemble the empty views. The factories need the [`Ui`] handle, so they
/// are installed later by [`FileList::wire`].
pub(crate) fn new() -> Self {
let model = gio::ListStore::new::<BoxedAnyObject>();
// Multi-select: acting on a batch is the common case, and doing it one
// confirmation dialog at a time is not a workflow. Rubberband drags a
// selection box from empty space, as a file manager does.
let selection = gtk4::MultiSelection::new(Some(model.clone()));
let grid = gtk4::GridView::builder()
.model(&selection)
.min_columns(2)
.max_columns(32)
.enable_rubberband(true)
.build();
grid.add_css_class("file-grid");
let grid_scroll = gtk4::ScrolledWindow::builder()
.vexpand(true)
.child(&grid)
.build();
let column_view = gtk4::ColumnView::builder()
.model(&selection)
.enable_rubberband(true)
.build();
column_view.add_css_class("data-table");
let column_scroll = gtk4::ScrolledWindow::builder()
.vexpand(true)
.child(&column_view)
.build();
let views = gtk4::Stack::new();
views.set_vexpand(true);
views.add_named(&grid_scroll, Some("grid"));
views.add_named(&column_scroll, Some("list"));
FileList {
model,
selection,
grid,
column_view,
views,
thumbnail_size: Rc::new(Cell::new(GRID_THUMB_DEFAULT)),
tiles: Rc::new(RefCell::new(Vec::new())),
behavior: Rc::new(Cell::new(None)),
}
}
/// Install the grid tiles, the Name column, activation, the context menus
/// and click-to-deselect. The page appends its other columns afterwards.
pub(crate) fn wire(&self, ui: &Rc<Ui>, behavior: FileListBehavior) {
self.behavior.set(Some(behavior));
for view in [
self.grid.clone().upcast::<gtk4::Widget>(),
self.column_view.clone().upcast(),
] {
self.attach_background_menu(ui, &view, behavior);
self.attach_background_deselect(&view);
}
let factory = gtk4::SignalListItemFactory::new();
factory.connect_setup({
let (ui, list) = (ui.clone(), self.clone());
move |_, item| {
let item = item.downcast_ref::<gtk4::ListItem>().unwrap();
let size = list.thumbnail_size.get();
let thumbnail = file_thumbnail_widget(size, grid_fallback_size(size));
// Keep the sync-state badge inside the thumbnail surface.
let badge = gtk4::Image::builder()
.pixel_size(18)
.halign(gtk4::Align::End)
.valign(gtk4::Align::Start)
.margin_top(2)
.margin_end(2)
.visible(false)
.build();
badge.add_css_class("file-badge");
thumbnail.add_overlay(&badge);
// `WordChar` rather than the default `Word`: a name with no
// spaces offers no word-break opportunity, so word wrapping
// cannot break it at all and the label asks for its full natural
// width instead — one tile stretches to the width of the window
// and the grid collapses to a single column. Allowing a mid-word
// break is what keeps the two-line-then-ellipsis budget below
// enforceable for *every* name rather than only the ones that
// happen to have spaces.
let label = gtk4::Label::builder()
.ellipsize(gtk4::pango::EllipsizeMode::End)
.justify(gtk4::Justification::Center)
.max_width_chars(13)
.width_chars(13)
.wrap(true)
.wrap_mode(gtk4::pango::WrapMode::WordChar)
.lines(2)
.build();
list.tiles
.borrow_mut()
.push((thumbnail.downgrade(), label.downgrade()));
let tile = gtk4::Box::new(gtk4::Orientation::Vertical, 4);
tile.add_css_class("file-tile");
tile.append(&thumbnail);
tile.append(&label);
list.attach_context_menu(&ui, item, &tile, behavior);
if behavior.drag_and_drop {
attach_drag(&ui, item, &tile);
attach_drop(&ui, item, &tile);
}
item.set_child(Some(&tile));
}
});
factory.connect_bind({
let (ui, list) = (ui.clone(), self.clone());
move |_, item| {
let item = item.downcast_ref::<gtk4::ListItem>().unwrap();
let tile = item.child().and_downcast::<gtk4::Box>().unwrap();
let thumbnail = tile.first_child().and_downcast::<gtk4::Overlay>().unwrap();
let badge = thumbnail
.last_child()
.and_downcast::<gtk4::Image>()
.unwrap();
let label = thumbnail
.next_sibling()
.and_downcast::<gtk4::Label>()
.unwrap();
let obj = item.item().and_downcast::<BoxedAnyObject>().unwrap();
let entry = obj.borrow::<DirEntry>();
resize_grid_tile(&thumbnail, &label, list.thumbnail_size.get());
bind_file_thumbnail(&ui, &thumbnail, &entry, false);
label.set_label(&entry.name);
label.set_tooltip_text(Some(&entry.name));
if behavior.badges {
apply_badge(&badge, &entry);
}
}
});
self.grid.set_factory(Some(&factory));
let ui_grid = ui.clone();
self.grid.connect_activate(move |grid, pos| {
if let Some(entry) = entry_at(grid.model().as_ref(), pos) {
(behavior.activate)(&ui_grid, &entry);
}
});
self.column_view
.append_column(&self.name_column(ui, behavior));
let ui_col = ui.clone();
self.column_view.connect_activate(move |view, pos| {
if let Some(entry) = entry_at(view.model().as_ref(), pos) {
(behavior.activate)(&ui_col, &entry);
}
});
}
/// Every highlighted entry, in model order.
///
/// Walks the model rather than the selection bitset: a listing is at most a
/// few thousand rows, and asking each position whether it is selected keeps
/// this free of bitset-iterator lifetimes for no measurable cost.
pub(crate) fn selected(&self) -> Vec<DirEntry> {
(0..self.selection.n_items())
.filter(|i| self.selection.is_selected(*i))
.filter_map(|i| entry_at(Some(&self.selection), i))
.collect()
}
/// Show the grid, or the list.
pub(crate) fn show_list(&self, list: bool) {
self.views
.set_visible_child_name(if list { "list" } else { "grid" });
}
/// Whether the list, rather than the grid, is on screen.
pub(crate) fn shows_list(&self) -> bool {
self.views.visible_child_name().as_deref() == Some("list")
}
/// Resize the grid's thumbnails. Only realised cells are touched; the rest
/// pick the size up when they are bound.
pub(crate) fn set_thumbnail_size(&self, size: i32) {
if self.thumbnail_size.replace(size) == size {
return;
}
self.tiles
.borrow_mut()
.retain(|(thumbnail_ref, label_ref)| {
let (Some(thumbnail), Some(label)) = (thumbnail_ref.upgrade(), label_ref.upgrade())
else {
return false;
};
resize_grid_tile(&thumbnail, &label, size);
true
});
self.grid.queue_resize();
}
/// The Menu key or Shift+F10: the menu for the selection, or the background
/// menu when nothing is selected, opened at the focused item.
pub(crate) fn popup_keyboard_menu(&self, ui: &Rc<Ui>) {
let Some(behavior) = self.behavior.get() else {
return;
};
let view = self
.views
.visible_child()
.unwrap_or_else(|| self.views.clone().upcast());
// The focused cell is where the eye is; without one, the middle of the view.
let (x, y) = view
.root()
.and_then(|root| root.focus())
.filter(|focus| focus.is_ancestor(&view))
.and_then(|focus| focus.compute_bounds(&view))
.map(|b| {
(
(b.x() + b.width() / 2.0) as f64,
(b.y() + b.height() / 2.0) as f64,
)
})
.unwrap_or((view.width() as f64 / 2.0, view.height() as f64 / 2.0));
let selected = self.selected();
let menu = match selected.len() {
0 => (behavior.background_menu)(ui),
1 => (behavior.entry_menu)(ui, &selected[0]),
_ => (behavior.bulk_menu)(ui, selected),
};
menu.popup_at(&view, x, y);
}
/// The Name column: a small thumbnail with its local-state badge overlaid,
/// followed by the name and the same right-click menu the grid tiles carry.
fn name_column(&self, ui: &Rc<Ui>, behavior: FileListBehavior) -> gtk4::ColumnViewColumn {
let factory = gtk4::SignalListItemFactory::new();
factory.connect_setup({
let (ui, list) = (ui.clone(), self.clone());
move |_, item| {
let item = item.downcast_ref::<gtk4::ListItem>().unwrap();
let thumbnail = file_thumbnail_widget(28, 16);
let badge = gtk4::Image::builder()
.pixel_size(14)
.halign(gtk4::Align::End)
.valign(gtk4::Align::Start)
.visible(false)
.build();
badge.add_css_class("file-badge");
thumbnail.add_overlay(&badge);
// Ellipsized so the Name column can be *narrower* than its
// longest name. Without it the label's minimum width is the whole
// string, the column inherits that minimum, and one long name
// pushes the other columns off the right edge of the window for
// every row.
let label = gtk4::Label::builder()
.halign(gtk4::Align::Start)
.ellipsize(gtk4::pango::EllipsizeMode::End)
.build();
let cell = gtk4::Box::new(gtk4::Orientation::Horizontal, 8);
cell.append(&thumbnail);
cell.append(&label);
list.attach_context_menu(&ui, item, &cell, behavior);
if behavior.drag_and_drop {
attach_drag(&ui, item, &cell);
attach_drop(&ui, item, &cell);
}
item.set_child(Some(&cell));
}
});
factory.connect_bind({
let ui = ui.clone();
move |_, item| {
let item = item.downcast_ref::<gtk4::ListItem>().unwrap();
let cell = item.child().and_downcast::<gtk4::Box>().unwrap();
let thumbnail = cell.first_child().and_downcast::<gtk4::Overlay>().unwrap();
let badge = thumbnail
.last_child()
.and_downcast::<gtk4::Image>()
.unwrap();
let label = thumbnail
.next_sibling()
.and_downcast::<gtk4::Label>()
.unwrap();
let obj = item.item().and_downcast::<BoxedAnyObject>().unwrap();
let entry = obj.borrow::<DirEntry>();
bind_file_thumbnail(&ui, &thumbnail, &entry, true);
label.set_label(&entry.name);
label.set_tooltip_text(Some(&entry.name));
if behavior.badges {
apply_badge(&badge, &entry);
}
}
});
let column = gtk4::ColumnViewColumn::new(Some(&pgettext("column", "Name")), Some(factory));
column.set_expand(true);
column
}
/// Pop the menu for whatever entry `item` is bound to when a cell is
/// right-clicked. Capturing the [`gtk4::ListItem`] rather than a snapshot of
/// the entry keeps the menu right as the view recycles cells while
/// scrolling. The click is claimed, so the background menu does not open on
/// top of it.
fn attach_context_menu(
&self,
ui: &Rc<Ui>,
item: &gtk4::ListItem,
anchor: &gtk4::Box,
behavior: FileListBehavior,
) {
let gesture = gtk4::GestureClick::new();
gesture.set_button(gtk4::gdk::BUTTON_SECONDARY);
let (ui, list, item, target) = (ui.clone(), self.clone(), item.clone(), anchor.clone());
gesture.connect_pressed(move |gesture, _, x, y| {
gesture.set_state(gtk4::EventSequenceState::Claimed);
if let Some(obj) = item.item().and_downcast::<BoxedAnyObject>() {
let entry = obj.borrow::<DirEntry>().clone();
// Right-clicking a row that is part of a multi-selection acts on
// the batch; right-clicking outside one acts on the row.
let selected = list.selected();
if selected.len() > 1 && selected.iter().any(|e| e.uid == entry.uid) {
(behavior.bulk_menu)(&ui, selected).popup_at(&target, x, y);
} else {
(behavior.entry_menu)(&ui, &entry).popup_at(&target, x, y);
}
}
});
anchor.add_controller(gesture);
}
/// Right-clicking the empty space of a view offers the page's own actions.
fn attach_background_menu(&self, ui: &Rc<Ui>, view: &gtk4::Widget, behavior: FileListBehavior) {
let gesture = gtk4::GestureClick::new();
gesture.set_button(gtk4::gdk::BUTTON_SECONDARY);
let (ui, target) = (ui.clone(), view.clone());
gesture.connect_pressed(move |_, _, x, y| {
(behavior.background_menu)(&ui).popup_at(&target, x, y);
});
view.add_controller(gesture);
}
/// Clicking the empty space of a view drops the selection, as in a file
/// manager. GTK's list views leave it alone, so a stray highlight otherwise
/// sticks around until another item is clicked.
fn attach_background_deselect(&self, view: &gtk4::Widget) {
let gesture = gtk4::GestureClick::new();
gesture.set_button(gtk4::gdk::BUTTON_PRIMARY);
// Capture sees the press before an item's own gesture claims it; this
// only looks, so the item still gets its click.
gesture.set_propagation_phase(gtk4::PropagationPhase::Capture);
let (selection, target) = (self.selection.clone(), view.clone());
gesture.connect_pressed(move |gesture, _, x, y| {
let modifiers = gesture.current_event_state();
if modifiers.intersects(
gtk4::gdk::ModifierType::CONTROL_MASK | gtk4::gdk::ModifierType::SHIFT_MASK,
) {
return;
}
if !on_item(&target, x, y) {
selection.unselect_all();
}
});
view.add_controller(gesture);
}
}
/// A header button that switches `list` between grid and list. It offers the
/// other layout, the way a toggle reads.
pub(crate) fn layout_button(list: &FileList) -> gtk4::Button {
let button = gtk4::Button::builder().valign(gtk4::Align::Center).build();
let sync = |button: &gtk4::Button, list: bool| {
button.set_icon_name(if list {
"view-grid-symbolic"
} else {
"view-list-symbolic"
});
button.set_tooltip_text(Some(&if list {
gettext("Show as grid (Ctrl+1)")
} else {
gettext("Show as list (Ctrl+2)")
}));
};
sync(&button, list.shows_list());
let weak = button.downgrade();
list.views.connect_visible_child_name_notify(move |views| {
if let Some(button) = weak.upgrade() {
sync(
&button,
views.visible_child_name().as_deref() == Some("list"),
);
}
});
let views = list.views.clone();
button.connect_clicked(move |_| {
let to_list = views.visible_child_name().as_deref() != Some("list");
views.set_visible_child_name(if to_list { "list" } else { "grid" });
});
button
}
/// Build a trailing text column whose cell text is derived from each [`DirEntry`]
/// by `render`.
pub(crate) fn text_column(
title: &str,
render: impl Fn(&DirEntry) -> String + 'static,
) -> gtk4::ColumnViewColumn {
let factory = gtk4::SignalListItemFactory::new();
factory.connect_setup(|_, item| {
let item = item.downcast_ref::<gtk4::ListItem>().unwrap();
let label = gtk4::Label::builder()
.halign(gtk4::Align::Start)
.ellipsize(gtk4::pango::EllipsizeMode::End)
.build();
label.add_css_class("dim-label");
item.set_child(Some(&label));
});
factory.connect_bind(move |_, item| {
let item = item.downcast_ref::<gtk4::ListItem>().unwrap();
let label = item.child().and_downcast::<gtk4::Label>().unwrap();
let obj = item.item().and_downcast::<BoxedAnyObject>().unwrap();
let entry = obj.borrow::<DirEntry>();
let text = render(&entry);
label.set_tooltip_text(Some(&text));
label.set_label(&text);
});
gtk4::ColumnViewColumn::new(Some(title), Some(factory))
}
fn resize_grid_tile(thumbnail: &gtk4::Overlay, label: &gtk4::Label, size: i32) {
resize_file_thumbnail(thumbnail, size, grid_fallback_size(size));
let name_width = (size / 6 + 1).clamp(8, 24);
label.set_width_chars(name_width);
label.set_max_width_chars(name_width);
}
fn grid_fallback_size(thumbnail_size: i32) -> i32 {
(thumbnail_size * 8 / 9).clamp(24, thumbnail_size)
}
/// Whether `(x, y)` in `view` lands on an item: a grid tile ("child"), a list
/// row ("row"), or a column header ("header"), which has clicks of its own.
fn on_item(view: &gtk4::Widget, x: f64, y: f64) -> bool {
let mut widget = view.pick(x, y, gtk4::PickFlags::DEFAULT);
while let Some(w) = widget {
if &w == view {
return false;
}
if matches!(w.css_name().as_str(), "child" | "row" | "header") {
return true;
}
widget = w.parent();
}
false
}
/// Every page's file list.
pub(crate) fn file_lists(ui: &Ui) -> [&FileList; 4] {
[
&ui.browser.files,
&ui.trash.files,
&ui.shared.files,
&ui.shared_by_me.files,
]
}
/// The file list of the page on screen, if it has one.
pub(crate) fn visible_file_list(ui: &Ui) -> Option<&FileList> {
match ui.stack.visible_child_name()?.as_str() {
"browser" => Some(&ui.browser.files),
"trash" => Some(&ui.trash.files),
"sharedbyme" => Some(&ui.shared_by_me.files),
"shared" if ui.shared.views.visible_child_name().as_deref() == Some("files") => {
Some(&ui.shared.files)
}
_ => None,
}
}
-12
View File
@@ -1,8 +1,5 @@
use crate::*;
/// An action run by an [`ActionMenu`] item.
pub(crate) type MenuAction = Box<dyn Fn()>;
/// A `gio::Menu` whose items run closures, for menus whose contents depend on
/// what they were opened for (a row, a selection, a photo). Each item gets its
/// own action in a private `menu` group, installed on whatever hosts the
@@ -148,12 +145,3 @@ fn popover_host(anchor: &gtk4::Widget) -> gtk4::Widget {
}
host
}
/// A flat ⋮ button whose menu lists `items` as (label, action).
pub(crate) fn more_menu_button(items: Vec<(&str, MenuAction)>) -> gtk4::MenuButton {
let mut menu = ActionMenu::new();
for (label, run) in items {
menu.item(label, run);
}
menu.button()
}
+3
View File
@@ -1,5 +1,8 @@
pub(crate) mod compat;
pub(crate) mod details;
pub(crate) mod file_list;
pub(crate) mod menu;
pub(crate) mod scrubber;
pub(crate) mod share_dialog;
pub(crate) mod thumbnails;
pub(crate) mod versions_dialog;
+403
View File
@@ -0,0 +1,403 @@
//! The Photos timeline's month scrubber, laid over the grid's right edge as in
//! Google Photos: a thin tick where each year starts, a knob at the month on
//! screen, and a bubble naming the month under the pointer. It stays out of
//! the way until the pointer nears the edge or the timeline scrolls.
use crate::*;
use gtk4::cairo;
/// Width of the strip the scrubber draws in, in px.
const STRIP_WIDTH: i32 = 72;
/// How close to the right edge the pointer has to come to show the scrubber.
const EDGE: f64 = 96.0;
/// Space kept free above the first and below the last month, in px.
const PAD: f64 = 16.0;
/// How long the scrubber stays up after the timeline stops scrolling.
const LINGER: Duration = Duration::from_millis(1500);
#[derive(Default)]
struct State {
/// How many months the strip spans, newest at the top.
months: usize,
/// Where each year starts, as `(month index, label)`.
years: Vec<(usize, String)>,
/// The month the knob marks.
value: usize,
/// Whether the timeline has months to move between at all.
available: bool,
/// The pointer is near the right edge.
near: bool,
/// The month under the pointer while it is on the strip.
hover: Option<usize>,
/// Where the running drag started, in the strip's coordinates.
drag_from: Option<f64>,
/// Keeps the scrubber up for a moment after a scroll.
linger: Option<glib::SourceId>,
label: Option<Rc<dyn Fn(usize) -> String>>,
on_pick: Option<Rc<dyn Fn(usize)>>,
}
/// The scrubber's widgets and state. Cheap to clone: every clone is the same
/// scrubber.
#[derive(Clone)]
pub(crate) struct Scrubber {
revealer: gtk4::Revealer,
area: gtk4::DrawingArea,
knob: gtk4::Box,
bubble: gtk4::Label,
/// The timeline the scrubber lies over.
scroll: Option<gtk4::ScrolledWindow>,
state: Rc<RefCell<State>>,
}
impl Scrubber {
/// Build the scrubber over `host`, whose child is the scrolled timeline.
pub(crate) fn new(host: &gtk4::Overlay) -> Self {
let scroll = host.child().and_downcast::<gtk4::ScrolledWindow>();
let area = gtk4::DrawingArea::builder()
.width_request(STRIP_WIDTH)
.vexpand(true)
.build();
area.add_css_class("photo-scrubber");
let knob = gtk4::Box::builder()
.width_request(24)
.height_request(4)
.halign(gtk4::Align::End)
.valign(gtk4::Align::Start)
.margin_end(4)
.can_target(false)
.build();
knob.add_css_class("photo-scrubber-knob");
let strip = gtk4::Overlay::new();
strip.set_child(Some(&area));
strip.add_overlay(&knob);
let revealer = gtk4::Revealer::builder()
.transition_type(gtk4::RevealerTransitionType::Crossfade)
.transition_duration(150)
.halign(gtk4::Align::End)
.valign(gtk4::Align::Fill)
.can_target(false)
.child(&strip)
.build();
let bubble = gtk4::Label::builder()
.halign(gtk4::Align::End)
.valign(gtk4::Align::Start)
.margin_end(STRIP_WIDTH)
.can_target(false)
.visible(false)
.build();
bubble.add_css_class("photo-scrubber-bubble");
host.add_overlay(&revealer);
host.add_overlay(&bubble);
let scrubber = Self {
revealer,
area,
knob,
bubble,
scroll,
state: Rc::default(),
};
scrubber.wire(host);
scrubber
}
fn wire(&self, host: &gtk4::Overlay) {
let this = self.clone();
self.area.set_draw_func(move |area, cr, width, height| {
this.draw(area, cr, width, height);
});
let this = self.clone();
self.area.connect_resize(move |_, _, _| this.place_knob());
// Near the edge is judged on the whole timeline, not the strip: the
// strip takes no input while it is hidden.
let edge = gtk4::EventControllerMotion::new();
let this = self.clone();
let host_motion = host.clone();
edge.connect_motion(move |_, x, _| {
let near = x >= f64::from(host_motion.width()) - EDGE;
if this.state.borrow().near != near {
this.state.borrow_mut().near = near;
this.sync_reveal();
}
});
let this = self.clone();
edge.connect_leave(move |_| {
this.state.borrow_mut().near = false;
this.sync_reveal();
});
host.add_controller(edge);
let hover = gtk4::EventControllerMotion::new();
let this = self.clone();
hover.connect_motion(move |_, _, y| {
let index = this.index_at(y);
this.state.borrow_mut().hover = index;
this.sync_bubble();
});
let this = self.clone();
hover.connect_leave(move |_| {
this.state.borrow_mut().hover = None;
this.sync_bubble();
});
self.area.add_controller(hover);
// A click is a drag that goes nowhere, so this covers both.
let drag = gtk4::GestureDrag::new();
let this = self.clone();
drag.connect_drag_begin(move |_, _, y| {
this.state.borrow_mut().drag_from = Some(y);
this.pick(y, true);
});
let this = self.clone();
drag.connect_drag_update(move |_, _, dy| {
let from = this.state.borrow().drag_from;
if let Some(from) = from {
this.pick(from + dy, false);
}
});
let this = self.clone();
drag.connect_drag_end(move |_, _, _| {
this.state.borrow_mut().drag_from = None;
this.sync_reveal();
this.sync_bubble();
});
self.area.add_controller(drag);
}
/// Span `months` months, newest first, with a tick and a label where each
/// of `years` starts. Moves the knob back to the top.
pub(crate) fn set_months(&self, months: usize, years: Vec<(usize, String)>) {
{
let mut state = self.state.borrow_mut();
state.months = months;
state.years = years;
state.value = 0;
}
self.area.queue_draw();
self.place_knob();
}
/// Whether there is anything to scrub through. The scrubber never shows
/// while there is not.
pub(crate) fn set_available(&self, available: bool) {
self.state.borrow_mut().available = available;
// The scrubber takes the scrollbar's place at the edge; both at once
// would fight over the same strip.
if let Some(scroll) = &self.scroll {
scroll.set_vscrollbar_policy(if available {
gtk4::PolicyType::External
} else {
gtk4::PolicyType::Automatic
});
}
self.sync_reveal();
}
pub(crate) fn is_available(&self) -> bool {
self.state.borrow().available
}
/// Mark month `index`, unless the user has the scrubber in hand: the
/// timeline's scroll position must not move the knob out from under them.
pub(crate) fn set_value(&self, index: usize) {
{
let mut state = self.state.borrow_mut();
if state.drag_from.is_some() || state.hover.is_some() || state.value == index {
return;
}
state.value = index;
}
self.place_knob();
}
/// How a month index reads in the bubble, such as "March 2024".
pub(crate) fn set_label_func(&self, label: impl Fn(usize) -> String + 'static) {
self.state.borrow_mut().label = Some(Rc::new(label));
}
/// Call `f` with the month the user points the scrubber at.
pub(crate) fn connect_pick(&self, f: impl Fn(usize) + 'static) {
self.state.borrow_mut().on_pick = Some(Rc::new(f));
}
/// Show the scrubber for a moment, as the timeline scrolls, so it can be
/// found without hunting for the edge — and on a touch screen at all.
pub(crate) fn flash(&self) {
if !self.is_available() {
return;
}
if let Some(source) = self.state.borrow_mut().linger.take() {
source.remove();
}
let this = self.clone();
let source = glib::timeout_add_local_once(LINGER, move || {
this.state.borrow_mut().linger = None;
this.sync_reveal();
});
self.state.borrow_mut().linger = Some(source);
self.sync_reveal();
}
fn sync_reveal(&self) {
let show = {
let state = self.state.borrow();
state.available && (state.near || state.drag_from.is_some() || state.linger.is_some())
};
self.revealer.set_reveal_child(show);
// A hidden revealer still claims its strip of the grid; let the clicks
// through to the tiles underneath.
self.revealer.set_can_target(show);
if !show {
self.state.borrow_mut().hover = None;
self.bubble.set_visible(false);
}
}
/// The bubble names the month being dragged to, or else the one under
/// the pointer.
fn sync_bubble(&self) {
let (index, label) = {
let state = self.state.borrow();
let index = if state.drag_from.is_some() {
Some(state.value)
} else {
state.hover
};
(index, state.label.clone())
};
let (Some(index), Some(label)) = (index, label) else {
self.bubble.set_visible(false);
return;
};
self.bubble.set_label(&label(index));
let (_, height, _, _) = self.bubble.measure(gtk4::Orientation::Vertical, -1);
let y = self.y_of(index) - f64::from(height) / 2.0;
self.bubble.set_margin_top(y.max(0.0) as i32);
self.bubble.set_visible(true);
}
/// Move the knob to month `y` points at, and tell the page when that is a
/// different month — or when a new drag starts, so a click jumps even to
/// the month already marked.
fn pick(&self, y: f64, starting: bool) {
let Some(index) = self.index_at(y) else {
return;
};
let (changed, on_pick) = {
let mut state = self.state.borrow_mut();
let changed = state.value != index;
state.value = index;
(changed, state.on_pick.clone())
};
self.place_knob();
self.sync_bubble();
if let (true, Some(on_pick)) = (changed || starting, on_pick) {
on_pick(index);
}
}
fn place_knob(&self) {
let value = self.state.borrow().value;
let y = self.y_of(value) - 2.0;
self.knob.set_margin_top(y.max(0.0) as i32);
}
/// Where month `index` sits on the strip.
fn y_of(&self, index: usize) -> f64 {
let months = self.state.borrow().months;
month_y(index, months, f64::from(self.area.height()))
}
/// The month at height `y` on the strip, if it spans any.
fn index_at(&self, y: f64) -> Option<usize> {
let months = self.state.borrow().months;
month_at(y, months, f64::from(self.area.height()))
}
fn draw(&self, area: &gtk4::DrawingArea, cr: &cairo::Context, width: i32, height: i32) {
let state = self.state.borrow();
let color = area.color();
let (width, height) = (f64::from(width), f64::from(height));
let attrs = gtk4::pango::AttrList::new();
attrs.insert(gtk4::pango::AttrFloat::new_scale(0.8));
attrs.insert(gtk4::pango::AttrInt::new_weight(gtk4::pango::Weight::Bold));
// The bottom of the last label drawn: a year crowded against the one
// above it keeps its tick but not its label.
let mut clear_below = f64::NEG_INFINITY;
for (index, year) in &state.years {
let y = month_y(*index, state.months, height);
cr.set_source_rgba(
f64::from(color.red()),
f64::from(color.green()),
f64::from(color.blue()),
0.5,
);
cr.rectangle(width - 12.0, y.round() - 0.5, 8.0, 1.0);
let _ = cr.fill();
let layout = area.create_pango_layout(Some(year));
layout.set_attributes(Some(&attrs));
let (_, logical) = layout.pixel_extents();
let (w, h) = (f64::from(logical.width()), f64::from(logical.height()));
let top = y - h / 2.0;
if top < clear_below {
continue;
}
clear_below = top + h + 2.0;
cr.set_source_rgba(
f64::from(color.red()),
f64::from(color.green()),
f64::from(color.blue()),
0.8,
);
cr.move_to(width - 16.0 - w, top);
pangocairo::functions::show_layout(cr, &layout);
}
}
}
/// Where month `index` of `months` sits on a strip `height` px tall: evenly
/// spaced, newest at the top.
fn month_y(index: usize, months: usize, height: f64) -> f64 {
let span = (height - 2.0 * PAD).max(0.0);
if months < 2 {
return PAD;
}
PAD + span * index as f64 / (months - 1) as f64
}
/// The month nearest height `y` on a strip `height` px tall.
fn month_at(y: f64, months: usize, height: f64) -> Option<usize> {
let last = months.checked_sub(1)?;
let span = height - 2.0 * PAD;
if span <= 0.0 {
return Some(0);
}
let fraction = ((y - PAD) / span).clamp(0.0, 1.0);
Some((fraction * last as f64).round() as usize)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_scrubber_maps_heights_back_to_their_months() {
let height = 432.0;
for index in 0..12 {
assert_eq!(
month_at(month_y(index, 12, height), 12, height),
Some(index)
);
}
}
#[test]
fn the_scrubber_clamps_past_either_end() {
assert_eq!(month_at(-50.0, 12, 432.0), Some(0));
assert_eq!(month_at(900.0, 12, 432.0), Some(11));
assert_eq!(month_at(10.0, 0, 432.0), None);
}
}
@@ -97,7 +97,7 @@ impl Busy {
pub(crate) fn start(button: &gtk4::Button) -> Self {
let label = button.label();
let icon = button.icon_name();
let spinner = gtk4::Spinner::builder().spinning(true).build();
let spinner = spinner();
match &label {
Some(text) => {
let content = gtk4::Box::new(gtk4::Orientation::Horizontal, 6);
@@ -407,6 +407,14 @@ pub(crate) fn open_share_dialog(ui: &Rc<Ui>, entry: &DirEntry) {
);
});
// Shared by me lists what this dialog changes: reload it when it is the
// page underneath. Any other page reads it again on the next visit.
let ui_closed = ui.clone();
dialog.connect_closed(move |_| {
if ui_closed.stack.visible_child_name().as_deref() == Some("sharedbyme") {
load_shared_by_me(&ui_closed);
}
});
share_dialog_reload(&state);
dialog.present(ui_window(ui).as_ref());
}
@@ -427,7 +435,7 @@ pub(crate) fn share_dialog_reload(state: &Rc<ShareDialog>) {
_ => toast_error(
&state.ui,
&gettext("Couldn't load sharing"),
&gettext("The mount service didn't respond."),
&gettext("The Proton Drive service didn't respond."),
),
}
});
@@ -582,6 +590,7 @@ pub(crate) fn repaint_share_link(state: &Rc<ShareDialog>, link: Option<&PublicLi
let url_copy = url.clone();
copy.connect_clicked(move |btn| {
btn.clipboard().set_text(&url_copy);
flash_copied(btn, "edit-copy-symbolic");
toast(&state_copy.ui, &gettext("Link copied"));
});
row.add_suffix(&copy);
@@ -718,7 +727,7 @@ pub(crate) fn share_dialog_create_link(
_ => toast_error(
&state.ui,
&gettext("Couldn't create the link"),
&gettext("The mount service didn't respond."),
&gettext("The Proton Drive service didn't respond."),
),
}
});
@@ -756,7 +765,7 @@ pub(crate) fn share_dialog_op(
toast_error(
&state.ui,
&failed,
&gettext("The mount service didn't respond."),
&gettext("The Proton Drive service didn't respond."),
);
share_dialog_reload(&state);
}
@@ -214,19 +214,6 @@ pub(crate) fn bind_file_thumbnail(
schedule_file_thumbs(ui);
}
/// Create and immediately bind a thumbnail for a non-recycled row.
pub(crate) fn file_thumbnail(
ui: &Rc<Ui>,
entry: &DirEntry,
size: i32,
fallback_size: i32,
symbolic_fallback: bool,
) -> gtk4::Overlay {
let widget = file_thumbnail_widget(size, fallback_size);
bind_file_thumbnail(ui, &widget, entry, symbolic_fallback);
widget
}
/// Whether the file name denotes an image format for which Proton or the local
/// decoder can reasonably provide a thumbnail.
pub(crate) fn is_image_name(name: &str) -> bool {
@@ -167,7 +167,7 @@ pub(crate) fn versions_dialog_reload(state: &Rc<VersionsDialog>) {
_ => toast_error(
&state.ui,
&gettext("Couldn't load versions"),
&gettext("The mount service didn't respond."),
&gettext("The Proton Drive service didn't respond."),
),
}
});
@@ -204,13 +204,13 @@ fn repaint_versions(state: &Rc<VersionsDialog>, items: &[RevisionInfo]) {
gettext_f(
"{time} · {size}",
&[
("time", &activity_time(item.created)),
("time", &dates::relative(item.created)),
("size", &human_bytes(size)),
],
),
)
} else {
(activity_time(item.created), human_bytes(size))
(dates::relative(item.created), human_bytes(size))
};
if let Some(email) = &item.signed_by {
subtitle.push_str(" · ");
@@ -266,7 +266,7 @@ fn repaint_versions(state: &Rc<VersionsDialog>, items: &[RevisionInfo]) {
/// every device on the account, not only this one.
fn prompt_restore_version(state: &Rc<VersionsDialog>, revision_id: &str) {
let dialog = adw::AlertDialog::builder()
.heading(gettext("Restore version"))
.heading(gettext("Restore Version?"))
// Translators: {name} is a file name.
.body(gettext_f(
"Make this version the current content of “{name}”? The version it replaces stays in the history.",
@@ -301,7 +301,7 @@ fn prompt_restore_version(state: &Rc<VersionsDialog>, revision_id: &str) {
/// Confirm, then permanently delete one revision.
fn prompt_delete_version(state: &Rc<VersionsDialog>, revision_id: &str) {
let dialog = adw::AlertDialog::builder()
.heading(gettext("Delete version"))
.heading(gettext("Delete Version?"))
.body(gettext(
"Delete this version permanently? Its content can't be recovered.",
))
@@ -377,7 +377,7 @@ fn versions_dialog_op(state: &Rc<VersionsDialog>, request: Request, done: &str,
_ => toast_error(
&state.ui,
&failed,
&gettext("The mount service didn't respond."),
&gettext("The Proton Drive service didn't respond."),
),
}
});
+55
View File
@@ -0,0 +1,55 @@
//! Widgets that newer libadwaita releases bring, with a stand-in built from
//! what the oldest supported release (1.5, as on Ubuntu 24.04) has.
//!
//! The app builds against 1.5 and picks at run time: when the libadwaita it
//! runs with is 1.8 or newer, the real widgets are made by class name through
//! a `gtk4::Builder`, since the 1.5 bindings have no types for them. Their
//! properties and signals are then reached by name. Call sites never care
//! which one they got.
use std::sync::OnceLock;
use gtk4::prelude::*;
/// Set to anything to use the stand-ins even on a new libadwaita, to see the
/// app as it looks on the oldest supported release.
const STAND_INS_ENV: &str = "PDFS_STAND_IN_WIDGETS";
/// Whether the libadwaita the app runs with has the 1.8 widgets.
pub(crate) fn has_adw_1_8() -> bool {
static HAS: OnceLock<bool> = OnceLock::new();
*HAS.get_or_init(|| {
std::env::var_os(STAND_INS_ENV).is_none()
&& (adw::major_version(), adw::minor_version()) >= (1, 8)
})
}
/// Build `xml`, a GtkBuilder interface naming classes the bindings lack. It
/// is only ever one this module wrote, so a failure is a bug here.
pub(crate) fn build_ui(xml: &str) -> gtk4::Builder {
gtk4::Builder::from_string(&format!("<interface>{xml}</interface>"))
}
/// The object `id` from a builder [`build_ui`] made.
pub(crate) fn built<T: IsA<gtk4::glib::Object>>(builder: &gtk4::Builder, id: &str) -> T {
builder
.object(id)
.unwrap_or_else(|| panic!("the compat UI has no object {id}"))
}
/// A busy spinner. It spins whenever it is shown: show and hide it with
/// `set_visible` rather than starting and stopping it.
pub(crate) type Spinner = gtk4::Widget;
/// A new [`Spinner`], shown: `AdwSpinner` on libadwaita 1.8, a spinning
/// `gtk4::Spinner` before.
pub(crate) fn spinner() -> Spinner {
if has_adw_1_8() {
let builder = build_ui(r#"<object class="AdwSpinner" id="spinner"/>"#);
built(&builder, "spinner")
} else {
// Spinning costs nothing while hidden: an unmapped widget draws no
// frames.
gtk4::Spinner::builder().spinning(true).build().upcast()
}
}
+12
View File
@@ -198,6 +198,18 @@ pub(crate) fn pending_summary(uploads: u64, changes: u64) -> Option<String> {
}
}
/// Format a byte count as a short binary-unit string (e.g. `1.2 GiB`, or
/// `512 bytes` below one KiB).
///
/// GLib does the formatting, so the units, the plural of "bytes" and the
/// decimal separator follow the user's language from GLib's own catalog. GLib
/// separates number and unit with a no-break space; it is turned back into a
/// plain space so the text matches what the rest of the UI builds around it.
pub(crate) fn human_bytes(bytes: u64) -> String {
gtk4::glib::format_size_full(bytes, gtk4::glib::FormatSizeFlags::IEC_UNITS)
.replace('\u{a0}', " ")
}
/// gettext takes the count as `u32`. Counts past that pick the same form as
/// the largest one, which is the plural in every shipped language.
fn plural_count(n: u64) -> u32 {
+141 -70
View File
@@ -13,7 +13,7 @@
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;
use std::time::{Duration, Instant};
use anyhow::{Context, Result};
use ksni::blocking::TrayMethods;
@@ -21,14 +21,17 @@ use ksni::menu::StandardItem;
use ksni::{MenuItem, Status, ToolTip, Tray};
use pdfs_core::auth;
use pdfs_core::config::AppDirs;
use pdfs_core::control::{JobItem, Request, Response, TransferDirection, TransferItem, send};
use pdfs_core::control::{
Event, Feed, JobItem, Request, Response, TransferDirection, TransferItem, follow, send,
};
use pdfs_core::service;
mod i18n;
use i18n::{gettext, gettext_f, ngettext_f};
/// How often the tray re-polls the daemon to refresh its menu.
const POLL_INTERVAL: Duration = Duration::from_secs(3);
/// How long the tray lets a burst of events arrive before it repaints. Progress
/// moves several times a second, which is more than a tray menu can show.
const COALESCE: Duration = Duration::from_secs(1);
/// The one word the icon says about the drive, derived from each poll.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -53,7 +56,7 @@ impl Phase {
fn icon(self) -> &'static str {
match self {
Phase::Synced => "folder-remote-symbolic",
Phase::Syncing => "emblem-synchronizing-symbolic",
Phase::Syncing => "view-refresh-symbolic",
Phase::Paused => "media-playback-pause-symbolic",
Phase::Offline => "network-offline-symbolic",
Phase::Attention => "dialog-warning-symbolic",
@@ -139,72 +142,20 @@ struct DriveTray {
/// menu can still say "Logged in …" / "Not logged in" when no mount is running.
fn poll_state(socket: &Path, default_mountpoint: &Path) -> DriveState {
match send(socket, &Request::Status) {
Ok(Response::Status {
mountpoint,
pinned,
online,
pending_uploads,
pending_changes,
failing_ops,
paused,
..
}) => {
// Same daemon is up, so a cheap follow-up poll gives the sync line.
Ok(status @ Response::Status { .. }) => {
// Same daemon is up, so a cheap follow-up request gives the sync line.
let sync = match send(socket, &Request::GetQueueStatus) {
Ok(Response::Transfers { items, jobs }) => sync_line(&items, &jobs),
_ => String::new(),
};
let queued = i18n::pending_summary(pending_uploads, pending_changes);
let phase = phase_of(
paused,
failing_ops,
online,
queued.is_some() || !sync.is_empty(),
);
DriveState {
line: match (online, queued) {
_ if paused => gettext("Sync paused"),
_ if failing_ops > 0 => ngettext_f(
"{n} change needs attention",
"{n} changes need attention",
failing_ops,
&[],
),
// Translators: {mountpoint} is a folder path; {n} is the number of pinned items.
(true, None) => ngettext_f(
"Mounted at {mountpoint} ({n} pinned)",
"Mounted at {mountpoint} ({n} pinned)",
pinned as u64,
&[("mountpoint", &mountpoint)],
),
// Translators: {queued} is a queue summary such as "3 uploads queued"; {n} is the number of pinned items.
(true, Some(q)) => ngettext_f(
"Syncing — {queued} ({n} pinned)",
"Syncing — {queued} ({n} pinned)",
pinned as u64,
&[("queued", &q)],
),
// Translators: {n} is the number of pinned items.
(false, None) => ngettext_f(
"Offline — cached files only ({n} pinned)",
"Offline — cached files only ({n} pinned)",
pinned as u64,
&[],
),
// Translators: {queued} is a queue summary such as "3 uploads queued".
(false, Some(q)) => gettext_f("Offline — {queued}", &[("queued", &q)]),
},
phase,
mounted: true,
paused,
mountpoint: PathBuf::from(mountpoint),
sync,
failing: failing_ops,
}
status_state(&status, sync, default_mountpoint)
}
// Socket answered but with something unexpected — treat as up but odd.
Ok(_) => DriveState {
line: gettext("Mount: unexpected daemon response"),
Ok(_) => unexpected_reply(default_mountpoint),
// The daemon is up but stuck: say so rather than "not connected", and
// keep the mount actions, which still work on the folder itself.
Err(e) if e.is_timeout() => DriveState {
line: gettext("Proton Drive isn't responding"),
phase: Phase::Attention,
mounted: true,
mountpoint: default_mountpoint.to_path_buf(),
@@ -218,7 +169,7 @@ fn poll_state(socket: &Path, default_mountpoint: &Path) -> DriveState {
Ok(s) => (
// Translators: {username} is the Proton account name.
gettext_f(
"Logged in as {username} — not mounted",
"Signed in as {username} — not connected",
&[("username", &s.username)],
),
Phase::Disconnected,
@@ -243,6 +194,86 @@ fn poll_state(socket: &Path, default_mountpoint: &Path) -> DriveState {
}
}
/// What the tray says when the daemon answers with something it did not ask
/// for: up, but odd.
fn unexpected_reply(default_mountpoint: &Path) -> DriveState {
DriveState {
line: gettext("Proton Drive sent an unexpected reply"),
phase: Phase::Attention,
mounted: true,
mountpoint: default_mountpoint.to_path_buf(),
sync: String::new(),
paused: false,
failing: 0,
}
}
/// The state a running daemon's [`Response::Status`] describes, with `sync`
/// saying what it is moving right now.
fn status_state(status: &Response, sync: String, default_mountpoint: &Path) -> DriveState {
let Response::Status {
mountpoint,
pinned,
online,
pending_uploads,
pending_changes,
failing_ops,
paused,
..
} = status
else {
return unexpected_reply(default_mountpoint);
};
let (pinned, online, failing_ops, paused) = (*pinned, *online, *failing_ops, *paused);
let queued = i18n::pending_summary(*pending_uploads, *pending_changes);
let phase = phase_of(
paused,
failing_ops,
online,
queued.is_some() || !sync.is_empty(),
);
DriveState {
line: match (online, queued) {
_ if paused => gettext("Sync paused"),
_ if failing_ops > 0 => ngettext_f(
"{n} change needs attention",
"{n} changes need attention",
failing_ops,
&[],
),
// Translators: {mountpoint} is a folder path; {n} is the number of pinned items.
(true, None) => ngettext_f(
"Up to date in {mountpoint} ({n} pinned)",
"Up to date in {mountpoint} ({n} pinned)",
pinned as u64,
&[("mountpoint", mountpoint)],
),
// Translators: {queued} is a queue summary such as "3 uploads queued"; {n} is the number of pinned items.
(true, Some(q)) => ngettext_f(
"Syncing — {queued} ({n} pinned)",
"Syncing — {queued} ({n} pinned)",
pinned as u64,
&[("queued", &q)],
),
// Translators: {n} is the number of pinned items.
(false, None) => ngettext_f(
"Offline — cached files only ({n} pinned)",
"Offline — cached files only ({n} pinned)",
pinned as u64,
&[],
),
// Translators: {queued} is a queue summary such as "3 uploads queued".
(false, Some(q)) => gettext_f("Offline — {queued}", &[("queued", &q)]),
},
phase,
mounted: true,
paused,
mountpoint: PathBuf::from(mountpoint),
sync,
failing: failing_ops,
}
}
/// The phase a running mount is in. A pause is the user's own doing and says
/// so first; failures outrank everything else the daemon reports.
fn phase_of(paused: bool, failing: u64, online: bool, busy: bool) -> Phase {
@@ -490,13 +521,53 @@ fn main() -> Result<()> {
.spawn()
.context("start tray service")?;
// Poll the daemon forever, pushing each fresh snapshot into the tray so the
// Follow the daemon forever, pushing each fresh state into the tray so the
// menu reflects mount/login changes made elsewhere (e.g. via the CLI).
loop {
std::thread::sleep(POLL_INTERVAL);
let st = poll_state(&socket, &default_mountpoint);
let (tx, rx) = std::sync::mpsc::channel();
let feed_socket = socket.clone();
std::thread::spawn(move || follow(&feed_socket, |feed| tx.send(feed).is_ok()));
let mut heard = Heard::default();
while let Ok(feed) = rx.recv() {
heard.take(feed);
let until = Instant::now() + COALESCE;
while let Ok(feed) = rx.recv_timeout(until.saturating_duration_since(Instant::now())) {
heard.take(feed);
}
let st = match &heard.status {
Some(status) => status_state(
status,
sync_line(&heard.items, &heard.jobs),
&default_mountpoint,
),
// Lost the daemon: ask once, which describes the sign-in instead.
None => poll_state(&socket, &default_mountpoint),
};
handle.update(move |t: &mut DriveTray| t.state = st);
}
Ok(())
}
/// What the tray has heard from the daemon's event feed.
#[derive(Default)]
struct Heard {
/// The last status, or `None` once the daemon has gone.
status: Option<Response>,
items: Vec<TransferItem>,
jobs: Vec<JobItem>,
}
impl Heard {
fn take(&mut self, feed: Feed) {
match feed {
Feed::Event(Event::Status(status)) => self.status = Some(*status),
Feed::Event(Event::Transfers { items, jobs }) => {
self.items = items;
self.jobs = jobs;
}
Feed::Disconnected => *self = Self::default(),
Feed::Connected | Feed::Event(Event::Changed { .. } | Event::Heartbeat) => {}
}
}
}
#[cfg(test)]
+10 -33
View File
@@ -23,8 +23,10 @@ use pdfs_core::menu::PromptMode;
use pdfs_core::opener::{self, OpenWith};
mod activation;
mod compat;
mod i18n;
use i18n::{gettext, gettext_f, gettext_noop, ngettext_f, pgettext};
use compat::{Spinner, spinner};
use i18n::{gettext, gettext_f, gettext_noop, human_bytes, ngettext_f, pgettext};
mod dmenu;
mod fzf;
mod query;
@@ -235,7 +237,7 @@ struct Ui {
opener: OpenWith,
entry: gtk4::Entry,
spinner: gtk4::Spinner,
spinner: Spinner,
stack: gtk4::Stack,
scroller: gtk4::ScrolledWindow,
results: gtk4::Box,
@@ -542,7 +544,7 @@ fn build_window(app: &adw::Application) -> Option<Rc<Ui>> {
entry.add_css_class("search-entry");
search_bar.append(&entry);
let spinner = gtk4::Spinner::new();
let spinner = spinner();
spinner.set_visible(false);
search_bar.append(&spinner);
@@ -586,7 +588,7 @@ fn build_window(app: &adw::Application) -> Option<Rc<Ui>> {
let offline = adw::StatusPage::builder()
.icon_name("network-offline-symbolic")
.title(gettext("Proton Drive is not running"))
.description(gettext("Start the mount daemon to search your Drive."))
.description(gettext("Start Proton Drive to search your files."))
.build();
offline.add_css_class("compact");
let retry = gtk4::Button::builder()
@@ -824,7 +826,6 @@ impl Ui {
self.query_id.set(self.query_id.get() + 1);
self.pending.set(0);
self.open_pending.set(false);
self.spinner.stop();
self.spinner.set_visible(false);
self.suppress_entry_change.set(true);
self.entry.set_text("");
@@ -876,7 +877,7 @@ impl Ui {
}
_ => {
ui.entry.set_sensitive(false);
ui.hint.set_label(&gettext("Daemon offline"));
ui.hint.set_label(&gettext("Proton Drive isn't running"));
ui.stack.set_visible_child_name("offline");
}
}
@@ -887,10 +888,9 @@ impl Ui {
/// the offline page and lock the entry; the retry button re-runs `connect`.
fn go_offline(self: &Rc<Self>) {
self.pending.set(0);
self.spinner.stop();
self.spinner.set_visible(false);
self.entry.set_sensitive(false);
self.hint.set_label(&gettext("Daemon offline"));
self.hint.set_label(&gettext("Proton Drive isn't running"));
self.stack.set_visible_child_name("offline");
}
@@ -990,7 +990,6 @@ impl Ui {
self.query_id.set(id);
self.pending.set(requests);
self.spinner.set_visible(true);
self.spinner.start();
id
}
@@ -1003,7 +1002,6 @@ impl Ui {
let left = self.pending.get().saturating_sub(1);
self.pending.set(left);
if left == 0 {
self.spinner.stop();
self.spinner.set_visible(false);
}
true
@@ -1292,7 +1290,6 @@ impl Ui {
self.opening.set(true);
self.spinner.set_visible(true);
self.spinner.start();
// Translators: {name} is a file name.
let opening = gettext_f("Opening {name}…", &[("name", &drive.name)]);
self.hint.set_label(&opening);
@@ -1307,7 +1304,6 @@ impl Ui {
let ui = self.clone();
glib::spawn_future_local(async move {
let reply = rx.recv().await;
ui.spinner.stop();
ui.spinner.set_visible(false);
ui.opening.set(false);
match reply {
@@ -1322,7 +1318,7 @@ impl Ui {
&[("message", &message)],
));
}
_ => ui.hint.set_label(&gettext("Could not reach the daemon")),
_ => ui.hint.set_label(&gettext("Couldn't reach Proton Drive")),
}
});
}
@@ -1370,7 +1366,7 @@ fn build_row(hit: &Hit) -> gtk4::ListBoxRow {
meta.append(&pin);
}
if !hit.is_dir() && hit.size() > 0 {
let size = gtk4::Label::new(Some(&format_size(hit.size())));
let size = gtk4::Label::new(Some(&human_bytes(hit.size())));
size.add_css_class("result-meta");
meta.append(&size);
}
@@ -1445,25 +1441,6 @@ fn parent_of(path: &str) -> String {
.unwrap_or_default()
}
fn format_size(bytes: u64) -> String {
const UNITS: [(u64, &str); 3] = [
// Translators: a file size in gigabytes; {size} is a number such as "4.2".
(1024 * 1024 * 1024, gettext_noop("{size} GB")),
// Translators: a file size in megabytes; {size} is a number such as "4.2".
(1024 * 1024, gettext_noop("{size} MB")),
// Translators: a file size in kilobytes; {size} is a number such as "4.2".
(1024, gettext_noop("{size} KB")),
];
for (scale, unit) in UNITS {
if bytes >= scale {
let size = format!("{:.1}", bytes as f64 / scale as f64);
return gettext_f(unit, &[("size", &size)]);
}
}
// Translators: a file size in bytes; {size} is a whole number.
gettext_f("{size} B", &[("size", &bytes.to_string())])
}
/// Coarse relative age, in the granularity a launcher row has room for.
fn format_age(epoch_secs: i64) -> String {
let now = std::time::SystemTime::now()
+160
View File
@@ -0,0 +1,160 @@
//! Every symbolic icon the app window and the search prompt ask for must
//! exist on a stock GNOME desktop.
//!
//! An icon name that no theme ships shows up as a missing-image glyph, and
//! nothing fails until someone looks. So each `"…-symbolic"` literal in the
//! sources has to be either one of the `pdfs-*` icons bundled in
//! `resources/icons` (and listed in the gresource manifest), or on
//! [`STOCK`], a list of names checked against Adwaita 50, libadwaita and
//! GTK's own built-in icons.
//!
//! The tray is left out: its icons are drawn by the panel, from the panel's
//! theme, not from our resources.
use std::collections::BTreeSet;
use std::fs;
use std::path::{Path, PathBuf};
/// Stock symbolic icons the app may use. Before adding a name, check that
/// Adwaita has it outside its `legacy` folder, or that libadwaita or GTK
/// ship it themselves.
const STOCK: &[&str] = &[
// libadwaita
"adw-external-link-symbolic",
// GTK's built-in icons
"info-outline-symbolic",
// Adwaita
"checkbox-checked-symbolic",
"checkbox-symbolic",
"computer-symbolic",
"dialog-error-symbolic",
"dialog-warning-symbolic",
"document-edit-symbolic",
"document-open-recent-symbolic",
"document-open-symbolic",
"document-save-symbolic",
"drive-harddisk-symbolic",
"edit-copy-symbolic",
"edit-delete-symbolic",
"edit-find-symbolic",
"edit-undo-symbolic",
"folder-download-symbolic",
"folder-new-symbolic",
"folder-open-symbolic",
"folder-remote-symbolic",
"folder-symbolic",
"go-down-symbolic",
"go-jump-symbolic",
"go-next-symbolic",
"go-previous-symbolic",
"go-up-symbolic",
"image-missing-symbolic",
"image-x-generic-symbolic",
"list-add-symbolic",
"mark-location-symbolic",
"media-playback-pause-symbolic",
"media-playback-start-symbolic",
"network-idle-symbolic",
"network-offline-symbolic",
"non-starred-symbolic",
"object-select-symbolic",
"preferences-system-symbolic",
"process-stop-symbolic",
"starred-symbolic",
"system-search-symbolic",
"text-x-generic-symbolic",
"user-trash-symbolic",
"view-grid-symbolic",
"view-list-symbolic",
"view-more-symbolic",
"view-paged-symbolic",
"view-pin-symbolic",
"view-refresh-symbolic",
"window-close-symbolic",
"zoom-fit-best-symbolic",
"zoom-in-symbolic",
"zoom-out-symbolic",
];
fn crate_dir() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
}
fn rust_files(dir: &Path, out: &mut Vec<PathBuf>) {
for entry in fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
rust_files(&path, out);
} else if path.extension().is_some_and(|e| e == "rs") {
out.push(path);
}
}
}
/// Every `"name-symbolic"` string literal in `source`. Found by suffix rather
/// than by pairing quotes, so an escaped quote or a `'"'` elsewhere in the
/// file can't hide one.
fn symbolic_literals(source: &str) -> Vec<String> {
const SUFFIX: &str = "-symbolic\"";
let is_name = |c: char| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-';
source
.match_indices(SUFFIX)
.filter_map(|(at, _)| {
let head = &source[..at];
let start = head.trim_end_matches(is_name).len();
(start > 0 && head[..start].ends_with('"'))
.then(|| format!("{}-symbolic", &head[start..]))
})
.collect()
}
/// The `pdfs-*` icons in `resources/icons`, by name.
fn bundled() -> BTreeSet<String> {
let mut names = BTreeSet::new();
let root = crate_dir().join("resources/icons/scalable");
for context in fs::read_dir(root).unwrap() {
for icon in fs::read_dir(context.unwrap().path()).unwrap() {
let path = icon.unwrap().path();
if let Some(name) = path.file_stem().and_then(|s| s.to_str()) {
names.insert(name.to_string());
}
}
}
names
}
#[test]
fn every_symbolic_icon_exists_on_a_stock_desktop() {
let mut files = vec![crate_dir().join("src/prompt.rs")];
rust_files(&crate_dir().join("src/app"), &mut files);
let bundled = bundled();
let mut unknown = BTreeSet::new();
for file in files {
let source = fs::read_to_string(&file).unwrap();
for name in symbolic_literals(&source) {
if !bundled.contains(&name) && !STOCK.contains(&name.as_str()) {
let file = file
.strip_prefix(crate_dir())
.unwrap()
.display()
.to_string();
unknown.insert(format!("{name} ({file})"));
}
}
}
assert!(
unknown.is_empty(),
"icons that are neither bundled nor on the stock list:\n {}",
unknown.into_iter().collect::<Vec<_>>().join("\n ")
);
}
#[test]
fn every_bundled_icon_is_in_the_resource_manifest() {
let manifest = fs::read_to_string(crate_dir().join("resources/pdfs.gresource.xml")).unwrap();
let missing: Vec<String> = bundled()
.into_iter()
.filter(|name| name.starts_with("pdfs-") && !manifest.contains(&format!("/{name}.svg<")))
.collect();
assert!(missing.is_empty(), "not in pdfs.gresource.xml: {missing:?}");
}
+67
View File
@@ -11,6 +11,73 @@ scratch (user data in `staging/` and `recovery/` is never touched by this).
## [Unreleased]
## [2.5.0] — 2026-09-28
A polish pass over the desktop app: the daemon pushes changes instead of being polled, pages
stay up while they reload, Trash and the shared pages use the same file list as My files, the
Sync page is split into views, the Computers page can browse another computer's backup, and
Photos gains a timeline scrubber.
Schema: **35**. The daemon notes when it first sees an item in the trash, since Proton does not
report the trash time to this client yet.
### Added
- **Browse other computers.** Opening another computer on the Computers page shows its backup
read-only, in the same list and grid as My files, and files open with a double-click.
- **Trash shows where items came from and when they were deleted.** The date is when this client
first saw the item in the trash until Proton reports the exact time. Restoring offers a Show
action, and opening a trashed item explains that it must be restored first.
- **Shared with me** shows who shared each item, with a warning for unverified senders, the
access it gives and when it was shared. Pending invitations wait in a banner, several items can
be left at once, and saved links have their own view.
- **Shared by me** gains a filter (links, people, expired links), columns for location, people
and link state, a copy button for live links, and stopping several shares at once.
- **Sidebar badges** count sync problems and waiting invitations.
### Changed
- **The app and the tray no longer poll.** The daemon pushes its status, its transfers and what
changed over one control connection (`Request::Subscribe`), and the window reloads the page on
screen when that page's data changes, including changes made with the `pdfs` CLI. A hidden
window keeps the changes and catches up when it is focused. Front-ends fall back to polling a
daemon that predates subscriptions until its service restarts.
- **Refresh buttons are gone** from the page headers now that pages follow the daemon. F5 and
Ctrl+R still reload the page from the server.
- **Photos timeline scrubber.** A strip along the right edge of the timeline shows the years
and appears when the pointer comes near or the timeline scrolls. Hovering names the month
under the pointer, and dragging jumps to it. It replaces the slider above the grid and the
scrollbar.
- **Upload is a split button** on the Photos page. Its menu holds "Import from Google Photos…",
and the page menu keeps "Find Duplicates…".
- **Quieter photo tiles.** Hovering enlarges the thumbnail slightly instead of lifting the tile
with a shadow, and tiles no longer show a tooltip. Tiles are reused while scrolling rather than
rebuilt for every row.
- **Newer libadwaita widgets where available.** On libadwaita 1.8 or newer the app uses its
spinner, toggle groups, button rows and shortcuts dialog, and on older releases it keeps
look-alike stand-ins. The choice is made at run time, so every package gets them and the app
still builds and runs on libadwaita 1.5. Set `PDFS_STAND_IN_WIDGETS=1` to see the stand-ins
on a newer system.
- **Sync page views.** Overview holds the status, conflicts, transfers and queue; Folders holds
the folder list, with a short explanation of the sync modes; History is the former Activity
page. A banner points back to Overview when changes fail or conflict. Each folder is one card
with a Synced / Online only switch, and switching either way asks first.
- **Activity reads better.** Temporary files that editors save through are hidden (a menu shows
them again), runs of similar events fold into one expandable row, entries are full translated
sentences, and "Show Older" reaches further back.
- **Computers** lists every computer in one group, this one first. "Use This Computer's
Identity" is now "Continue This Backup Here", with an explanation in its dialog, and "never
synced" reads "no backups yet".
- **Pages stay up while they reload.** A loading state shows only when a reply takes longer than
300 ms, and a refresh keeps the selection, scroll position and thumbnails.
- **One glossary.** "Proton Drive service" replaces "mount service" and "daemon", and "Online
only" replaces "On-demand"; dialogs use title case, and dates and sizes are formatted one way.
- **Bundled icons** replace glyphs that stock icon themes lack or draw ambiguously.
### Fixed
- **Enabling, disabling or restarting the service no longer freezes the window.**
- **A daemon that runs but doesn't answer** reads as "Not responding" instead of disconnected,
and requests to it give up after 5 s instead of 120 s.
- The Sync and share-link icons drew only half of themselves on recent GTK versions.
## [2.4.0] — 2026-09-28
Schema: **34**. Photos gain a `similar_hash` column for the similar-photo finder. It stays
+13
View File
@@ -63,6 +63,19 @@ stored as `language` in `config.json` and takes effect the next time they start.
- Keep product names as they are: Proton Drive, Proton, Google Takeout.
- Use the same term for the same thing across the catalog, and follow the terminology of your
desktop (GNOME or KDE) for common actions such as Trash, Preferences and Cancel.
- The English UI uses one term per concept. Pick one translation for each and keep it:
| Concept | English term |
|---|---|
| The root of the user's Drive | My files |
| The background service | Proton Drive service (never "daemon" or "mount") |
| A folder with a full copy on this computer | Synced folder |
| A folder whose files download when opened | Online-only folder |
| A single file kept on this computer | Available offline |
| A single file that is not on this computer | Online only |
| Where My files appears on disk | Proton Drive folder |
| Stop syncing a folder | Stop syncing |
| Two versions of one file | Conflict |
## Rules for developers
+2 -1
View File
@@ -283,7 +283,8 @@ Header: `[‹ ›] Path bar (breadcrumbs, scroll to end, Ctrl+L to edit) … [
| Cloud-only file | Online only | none / `cloud-outline` |
| Pinned file | Available offline | pin/download-filled custom icon, not stars |
| Upload | Upload files / Upload folder | `document-upload`-style arrow up, custom pair |
| Folder sync mode | Synced / On-demand | — |
| Folder sync mode | Synced / Online only | — |
| Where My files appears on disk | Proton Drive folder — never "mountpoint" in UI | — |
| Stop syncing a folder | Stop syncing… | `media-playback-stop-symbolic` in a menu, not trash |
| Remove a computer | Remove computer… | destructive, in menu |
| Conflict copy | Conflict | `dialog-warning-symbolic` + warning colour |
+1 -1
View File
@@ -9,7 +9,7 @@
# Build + install: cd packaging && makepkg -fi
pkgname=proton-drive-linux
pkgver=2.4.0
pkgver=2.5.0
pkgrel=1
pkgdesc="Unofficial Proton Drive client for Linux: files-on-demand FUSE mount, CLI, GTK4 app + tray"
arch=('x86_64')
@@ -1,6 +1,6 @@
pkgbase = proton-drive-for-linux-bin
pkgdesc = Unofficial Proton Drive client: FUSE files-on-demand mount, CLI, GTK4 app, tray (binaries)
pkgver = 2.3.0
pkgver = 2.4.0
pkgrel = 1
url = https://github.com/narrrl/proton-drive-linux
arch = x86_64
@@ -21,21 +21,21 @@ pkgbase = proton-drive-for-linux-bin
optdepends = xdg-utils: "Open folder" action in the tray menu
optdepends = fzf: search-as-you-type launcher (pdfs-prompt --fzf)
optdepends = foot: terminal that hosts pdfs-prompt --fzf when started from a keybinding
provides = proton-drive-for-linux=2.3.0
provides = proton-drive-linux=2.3.0
provides = proton-drive-for-linux=2.4.0
provides = proton-drive-linux=2.4.0
provides = pdfs
conflicts = proton-drive-linux
conflicts = proton-drive-for-linux
conflicts = proton-drive-for-linux-git
options = !strip
options = !debug
source = proton-drive-linux-2.3.0-x86_64.tar.gz::https://github.com/narrrl/proton-drive-linux/releases/download/v2.3.0/proton-drive-linux-2.3.0-x86_64.tar.gz
source = io.narl.proton-drive-linux.desktop::https://raw.githubusercontent.com/narrrl/proton-drive-linux/v2.3.0/packaging/io.narl.proton-drive-linux.desktop
source = io.narl.proton-drive-linux-tray.desktop::https://raw.githubusercontent.com/narrrl/proton-drive-linux/v2.3.0/packaging/io.narl.proton-drive-linux-tray.desktop
source = io.narl.proton-drive-linux.svg::https://raw.githubusercontent.com/narrrl/proton-drive-linux/v2.3.0/packaging/io.narl.proton-drive-linux.svg
source = proton-drive.service::https://raw.githubusercontent.com/narrrl/proton-drive-linux/v2.3.0/packaging/proton-drive.service
source = LICENSE-2.3.0::https://raw.githubusercontent.com/narrrl/proton-drive-linux/v2.3.0/LICENSE
sha256sums = 1d313f30a6f1bc7c2089f3233c7ffcec32daaf17c2b6710e481d73f2f15f82f4
source = proton-drive-linux-2.4.0-x86_64.tar.gz::https://github.com/narrrl/proton-drive-linux/releases/download/v2.4.0/proton-drive-linux-2.4.0-x86_64.tar.gz
source = io.narl.proton-drive-linux.desktop::https://raw.githubusercontent.com/narrrl/proton-drive-linux/v2.4.0/packaging/io.narl.proton-drive-linux.desktop
source = io.narl.proton-drive-linux-tray.desktop::https://raw.githubusercontent.com/narrrl/proton-drive-linux/v2.4.0/packaging/io.narl.proton-drive-linux-tray.desktop
source = io.narl.proton-drive-linux.svg::https://raw.githubusercontent.com/narrrl/proton-drive-linux/v2.4.0/packaging/io.narl.proton-drive-linux.svg
source = proton-drive.service::https://raw.githubusercontent.com/narrrl/proton-drive-linux/v2.4.0/packaging/proton-drive.service
source = LICENSE-2.4.0::https://raw.githubusercontent.com/narrrl/proton-drive-linux/v2.4.0/LICENSE
sha256sums = 00446aa9016466827bb0fe5ea1e1d171f478ab4194845f9005b690a05543fcca
sha256sums = d190d6771fff0b975271fb62fd3fb0fa8bbf17d7278c10853c18557855b0c123
sha256sums = 1d95e250370220e3bb6aead6ce34d1d6cc759f42c4803b75f1667e78ff47c6c0
sha256sums = e598a93c2715c3a9fdc7fb937902083d4a1135e8fbdfe6fe7e37f0383ebbd828
@@ -1,7 +1,7 @@
# Maintainer: Nils Pukropp <contact@narl.io>
pkgname=proton-drive-for-linux-bin
pkgver=2.3.0
pkgver=2.4.0
pkgrel=1
pkgdesc="Unofficial Proton Drive client: FUSE files-on-demand mount, CLI, GTK4 app, tray (binaries)"
arch=('x86_64')
@@ -31,7 +31,7 @@ source=("proton-drive-linux-$pkgver-x86_64.tar.gz::$url/releases/download/$_tag/
"io.narl.proton-drive-linux.svg::$_raw/packaging/io.narl.proton-drive-linux.svg"
"proton-drive.service::$_raw/packaging/proton-drive.service"
"LICENSE-$pkgver::$_raw/LICENSE")
sha256sums=('1d313f30a6f1bc7c2089f3233c7ffcec32daaf17c2b6710e481d73f2f15f82f4'
sha256sums=('00446aa9016466827bb0fe5ea1e1d171f478ab4194845f9005b690a05543fcca'
'd190d6771fff0b975271fb62fd3fb0fa8bbf17d7278c10853c18557855b0c123'
'1d95e250370220e3bb6aead6ce34d1d6cc759f42c4803b75f1667e78ff47c6c0'
'e598a93c2715c3a9fdc7fb937902083d4a1135e8fbdfe6fe7e37f0383ebbd828'
@@ -1,6 +1,6 @@
pkgbase = proton-drive-for-linux-git
pkgdesc = Unofficial Proton Drive client: FUSE files-on-demand mount, CLI, GTK4 app, tray (git)
pkgver = 2.3.0.r1.gfde9c2d
pkgver = 2.4.0.r0.gda35a05
pkgrel = 1
url = https://github.com/narrrl/proton-drive-linux
arch = x86_64
@@ -24,8 +24,8 @@ pkgbase = proton-drive-for-linux-git
optdepends = xdg-utils: "Open folder" action in the tray menu
optdepends = fzf: search-as-you-type launcher (pdfs-prompt --fzf)
optdepends = foot: terminal that hosts pdfs-prompt --fzf when started from a keybinding
provides = proton-drive-for-linux=2.3.0.r1.gfde9c2d
provides = proton-drive-linux=2.3.0.r1.gfde9c2d
provides = proton-drive-for-linux=2.4.0.r0.gda35a05
provides = proton-drive-linux=2.4.0.r0.gda35a05
provides = pdfs
conflicts = proton-drive-linux
conflicts = proton-drive-for-linux
@@ -1,7 +1,7 @@
# Maintainer: Nils Pukropp <contact@narl.io>
pkgname=proton-drive-for-linux-git
pkgver=2.3.0.r1.gfde9c2d
pkgver=2.4.0.r0.gda35a05
pkgrel=1
pkgdesc="Unofficial Proton Drive client: FUSE files-on-demand mount, CLI, GTK4 app, tray (git)"
arch=('x86_64')
@@ -1,6 +1,6 @@
pkgbase = proton-drive-for-linux
pkgdesc = Unofficial Proton Drive client: files-on-demand FUSE mount, CLI, GTK4 app and tray
pkgver = 2.3.0
pkgver = 2.4.0
pkgrel = 1
url = https://github.com/narrrl/proton-drive-linux
arch = x86_64
@@ -23,13 +23,13 @@ pkgbase = proton-drive-for-linux
optdepends = xdg-utils: "Open folder" action in the tray menu
optdepends = fzf: search-as-you-type launcher (pdfs-prompt --fzf)
optdepends = foot: terminal that hosts pdfs-prompt --fzf when started from a keybinding
provides = proton-drive-linux=2.3.0
provides = proton-drive-linux=2.4.0
provides = pdfs
conflicts = proton-drive-linux
conflicts = proton-drive-for-linux-bin
conflicts = proton-drive-for-linux-git
options = !lto
source = proton-drive-for-linux-2.3.0.tar.gz::https://github.com/narrrl/proton-drive-linux/archive/refs/tags/v2.3.0.tar.gz
sha256sums = ac89c79170bba4fda85c924739b5248d9e324a1d45c30faee25c3c9389f297f1
source = proton-drive-for-linux-2.4.0.tar.gz::https://github.com/narrrl/proton-drive-linux/archive/refs/tags/v2.4.0.tar.gz
sha256sums = ae0f6daec257e9f7ba464ed6385bab7ac99f4247db0176296b2a58f703c24799
pkgname = proton-drive-for-linux
@@ -1,7 +1,7 @@
# Maintainer: Nils Pukropp <contact@narl.io>
pkgname=proton-drive-for-linux
pkgver=2.3.0
pkgver=2.4.0
pkgrel=1
pkgdesc="Unofficial Proton Drive client: files-on-demand FUSE mount, CLI, GTK4 app and tray"
arch=('x86_64')
@@ -23,7 +23,7 @@ conflicts=('proton-drive-linux' 'proton-drive-for-linux-bin' 'proton-drive-for-l
# LTO has broken GTK/Rust links for this workspace; the release profile keeps it off.
options=('!lto')
source=("$pkgname-$pkgver.tar.gz::$url/archive/refs/tags/v$pkgver.tar.gz")
sha256sums=('ac89c79170bba4fda85c924739b5248d9e324a1d45c30faee25c3c9389f297f1')
sha256sums=('ae0f6daec257e9f7ba464ed6385bab7ac99f4247db0176296b2a58f703c24799')
_srcname="proton-drive-linux-$pkgver"
+4
View File
@@ -1,6 +1,8 @@
crates/pdfs-gui/src/activation.rs
crates/pdfs-gui/src/app/dates.rs
crates/pdfs-gui/src/app/main.rs
crates/pdfs-gui/src/app/pages/activity.rs
crates/pdfs-gui/src/app/pages/activity_text.rs
crates/pdfs-gui/src/app/pages/albums.rs
crates/pdfs-gui/src/app/pages/browser.rs
crates/pdfs-gui/src/app/pages/devices.rs
@@ -17,7 +19,9 @@ crates/pdfs-gui/src/app/pages/status.rs
crates/pdfs-gui/src/app/pages/takeout.rs
crates/pdfs-gui/src/app/pages/trash.rs
crates/pdfs-gui/src/app/pages/verify.rs
crates/pdfs-gui/src/app/widgets/compat.rs
crates/pdfs-gui/src/app/widgets/details.rs
crates/pdfs-gui/src/app/widgets/file_list.rs
crates/pdfs-gui/src/app/widgets/menu.rs
crates/pdfs-gui/src/app/widgets/share_dialog.rs
crates/pdfs-gui/src/app/widgets/thumbnails.rs
+2528 -1615
View File
File diff suppressed because it is too large. Load diff
+2543 -1648
View File
File diff suppressed because it is too large. Load diff
+2514 -1611
View File
File diff suppressed because it is too large. Load diff
+2530 -1616
View File
File diff suppressed because it is too large. Load diff
+2522 -1614
View File
File diff suppressed because it is too large. Load diff
+2525 -1619
View File
File diff suppressed because it is too large. Load diff
+2163 -1544
View File
File diff suppressed because it is too large. Load diff
+2553 -1615
View File
File diff suppressed because it is too large. Load diff
+2519 -1612
View File
File diff suppressed because it is too large. Load diff