Compare commits

..
Author SHA1 Message Date
nvrl 8e50a52081 Merge pull request #203 from narrrl/fix/bulk-share-outcome
fix(gui): report each item of a bulk stop-sharing or leave
2026-11-28 10:50:53 +01:00
72 changed files with 4162 additions and 8147 deletions

No files matched your search

-1
View File
@@ -162,7 +162,6 @@ jobs:
cp packaging/io.narl.proton-drive-linux.desktop deb/usr/share/applications/
cp packaging/io.narl.proton-drive-linux-tray.desktop deb/etc/xdg/autostart/
cp packaging/io.narl.proton-drive-linux.svg deb/usr/share/icons/hicolor/scalable/apps/
install -Dm644 -t deb/usr/share/icons/hicolor/scalable/status crates/pdfs-gui/resources/icons/tray/*.svg
install -Dm644 packaging/io.narl.proton-drive-linux.policy deb/usr/share/polkit-1/actions/io.narl.proton-drive-linux.policy
cp packaging/proton-drive.service deb/usr/lib/systemd/user/
cp LICENSE deb/usr/share/licenses/proton-drive-linux/
Generated
+10 -10
View File
@@ -3634,7 +3634,7 @@ checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
[[package]]
name = "pdfs-cli"
version = "4.0.0"
version = "3.10.0"
dependencies = [
"anyhow",
"clap",
@@ -3653,7 +3653,7 @@ dependencies = [
[[package]]
name = "pdfs-core"
version = "4.0.0"
version = "3.10.0"
dependencies = [
"async-trait",
"base64 0.23.1",
@@ -3683,7 +3683,7 @@ dependencies = [
[[package]]
name = "pdfs-daemon"
version = "4.0.0"
version = "3.10.0"
dependencies = [
"anyhow",
"pdfs-core",
@@ -3695,7 +3695,7 @@ dependencies = [
[[package]]
name = "pdfs-drive"
version = "4.0.0"
version = "3.10.0"
dependencies = [
"async-trait",
"futures",
@@ -3710,7 +3710,7 @@ dependencies = [
[[package]]
name = "pdfs-fuse"
version = "4.0.0"
version = "3.10.0"
dependencies = [
"async-trait",
"base64 0.23.1",
@@ -3748,7 +3748,7 @@ dependencies = [
[[package]]
name = "pdfs-gui"
version = "4.0.0"
version = "3.10.0"
dependencies = [
"anyhow",
"async-channel",
@@ -3773,7 +3773,7 @@ dependencies = [
[[package]]
name = "pdfs-sched"
version = "4.0.0"
version = "3.10.0"
dependencies = [
"parking_lot 0.13.0",
"tokio",
@@ -3781,7 +3781,7 @@ dependencies = [
[[package]]
name = "pdfs-store"
version = "4.0.0"
version = "3.10.0"
dependencies = [
"libc",
"parking_lot 0.13.0",
@@ -3797,7 +3797,7 @@ dependencies = [
[[package]]
name = "pdfs-sync"
version = "4.0.0"
version = "3.10.0"
dependencies = [
"notify",
"parking_lot 0.13.0",
@@ -3813,7 +3813,7 @@ dependencies = [
[[package]]
name = "pdfs-vfs"
version = "4.0.0"
version = "3.10.0"
dependencies = [
"libc",
"parking_lot 0.13.0",
+1 -1
View File
@@ -3,7 +3,7 @@ resolver = "2"
members = ["crates/pdfs-core", "crates/pdfs-store", "crates/pdfs-drive", "crates/pdfs-sync", "crates/pdfs-sched", "crates/pdfs-vfs", "crates/pdfs-fuse", "crates/pdfs-daemon", "crates/pdfs-cli", "crates/pdfs-gui"]
[workspace.package]
version = "4.0.0"
version = "3.10.0"
edition = "2024"
license = "MIT"
authors = ["Nils Pukropp <contact@narl.io>"]
+2 -65
View File
@@ -289,29 +289,6 @@ pub(super) fn admission_line(load: &pdfs_core::control::AdmissionLoad) -> String
line
}
/// One mirror effect not settled yet in `pdfs diagnostics`:
/// `folder 3 upload docs/a.txt: retry, sent 2 times, 5m0s ago (timed out)`.
pub(super) fn effect_line(intent: &pdfs_core::control::EffectIntent) -> String {
let times = if intent.attempts == 1 {
"time"
} else {
"times"
};
let mut line = format!(
"folder {} {} {}: {}, sent {} {times}, {} ago",
intent.folder_id,
intent.kind,
intent.rel_path,
intent.state,
intent.attempts,
human_secs(intent.age_secs),
);
if let Some(error) = &intent.last_error {
line.push_str(&format!(" ({error})"));
}
line
}
/// A wait, in ms below a second, where most admission waits fall.
fn wait_ms(ms: u64) -> String {
if ms < 1000 {
@@ -421,19 +398,6 @@ pub(super) fn cmd_diagnostics() -> Result<()> {
);
}
}
match &d.effects {
None => {}
Some(effects) if effects.count == 0 => println!("sync effects not settled: none"),
Some(effects) => {
println!("sync effects not settled: {} (oldest first)", effects.count);
for intent in &effects.oldest {
println!(" {}", effect_line(intent));
}
if effects.count > effects.oldest.len() {
println!(" and {} more", effects.count - effects.oldest.len());
}
}
}
if d.inflight.is_empty() {
println!("in-flight requests: none");
} else {
@@ -562,36 +526,9 @@ pub(super) fn cmd_cache_inspect(deep: bool) -> Result<()> {
#[cfg(test)]
mod tests {
use pdfs_core::control::{AdmissionLoad, EffectIntent};
use pdfs_core::control::AdmissionLoad;
use super::{admission_line, effect_line};
#[test]
fn an_effect_line_says_what_waits_and_why() {
let intent = EffectIntent {
folder_id: 3,
rel_path: "docs/a.txt".into(),
kind: "upload".into(),
state: "retry".into(),
attempts: 2,
age_secs: 300,
last_error: Some("timed out".into()),
};
assert_eq!(
effect_line(&intent),
"folder 3 upload docs/a.txt: retry, sent 2 times, 5m0s ago (timed out)"
);
let sent = EffectIntent {
state: "issued".into(),
attempts: 1,
last_error: None,
..intent
};
assert_eq!(
effect_line(&sent),
"folder 3 upload docs/a.txt: issued, sent 1 time, 5m0s ago"
);
}
use super::admission_line;
#[test]
fn an_admission_line_says_who_waits_and_for_how_long() {
-35
View File
@@ -2400,41 +2400,6 @@ pub struct Diagnostics {
/// Empty from a daemon that predates the field.
#[serde(default)]
pub admission: Vec<AdmissionLoad>,
/// The mirror effects not settled yet: sent and waiting for an answer,
/// left unsure by a stop, or failed. `None` when the database did not
/// answer in time, or from a daemon that predates the field.
#[serde(default)]
pub effects: Option<EffectReport>,
}
/// The mirror effects not settled yet, in [`Diagnostics::effects`].
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
pub struct EffectReport {
/// How many there are.
pub count: usize,
/// The oldest of them, at most [`EffectReport::SHOWN`].
pub oldest: Vec<EffectIntent>,
}
impl EffectReport {
/// How many effects a report lists.
pub const SHOWN: usize = 20;
}
/// One mirror effect not settled yet, in [`EffectReport::oldest`].
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
pub struct EffectIntent {
pub folder_id: i64,
pub rel_path: String,
/// What it does, such as `upload`, `download` or `trash`.
pub kind: String,
/// `issued`, `unsure`, `retry` or `blocked`.
pub state: String,
/// How many times it was sent.
pub attempts: u32,
/// How long ago it was last sent.
pub age_secs: u64,
pub last_error: Option<String>,
}
/// One class of background step in the daemon's admission, in
-14
View File
@@ -139,11 +139,6 @@ pub struct PromptConfig {
/// false for a launcher that advertises support but is themed without them.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub menu_icons: Option<bool>,
/// Remember what the search window opens, to list it before a search and
/// rank it higher in one. Defaults to true. Off, the history is cleared
/// the next time the window opens and nothing more is kept.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub remember_recent: Option<bool>,
}
/// Which front end the prompt presents.
@@ -163,11 +158,6 @@ pub enum PromptMode {
/// than the GTK prompt's cap because filtering happens launcher-side.
pub const DEFAULT_MENU_LIMIT: usize = 50;
/// The search window's history of what it opened, in the state directory.
/// The app deletes it to clear the list; the window reads it again each time
/// it opens.
pub const PROMPT_HISTORY_FILE: &str = "prompt-history.json";
impl PromptConfig {
pub fn resolved_mode(&self) -> PromptMode {
self.mode.unwrap_or_default()
@@ -180,10 +170,6 @@ impl PromptConfig {
pub fn resolved_menu_icons(&self) -> bool {
self.menu_icons.unwrap_or(true)
}
pub fn resolved_remember_recent(&self) -> bool {
self.remember_recent.unwrap_or(true)
}
}
/// One line offered to the launcher.
+5 -20
View File
@@ -16,7 +16,6 @@ use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use pdfs_core::config::AppDirs;
use pdfs_core::control::ErrorKind;
use pdfs_core::control::{
ActivityKind, Event, HEARTBEAT, PhotoMonth, RefreshScope, Request as CtlRequest,
Response as CtlResponse, Topic, TransferDirection, TrashFailure,
@@ -648,23 +647,8 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
},
Err(e) => CtlResponse::error(e),
},
Ok(CtlRequest::Unpin { path }) => {
let unpinned = route_keep(core, mountpoint, &path)
.and_then(|(routed, rel)| routed.unpin(&rel))
.or_else(|e| match e.kind {
// The node is gone, and its pin with it unless the pin
// was left behind; drop that one by the path it is listed
// under.
ErrorKind::NotFound => match core.unpin_stale(&path) {
Ok(true) => Ok(Path::new(&path)
.file_name()
.map_or_else(|| path.clone(), |n| n.to_string_lossy().into_owned())),
Ok(false) => Err(e),
Err(stale) => Err(stale),
},
_ => Err(e),
});
match unpinned {
Ok(CtlRequest::Unpin { path }) => match route_keep(core, mountpoint, &path) {
Ok((routed, rel)) => match routed.unpin(&rel) {
Ok(name) => {
core.profile().touch_profile();
CtlResponse::Ok {
@@ -672,8 +656,9 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
}
}
Err(e) => CtlResponse::error(e),
}
}
},
Err(e) => CtlResponse::error(e),
},
Ok(CtlRequest::ListPins) => CtlResponse::Pins {
pins: core.list_pins(),
},
+7 -17
View File
@@ -9,13 +9,12 @@
use std::path::Path;
use pdfs_core::CoreResult;
use pdfs_core::control::ErrorKind;
use pdfs_core::control::{ActivityKind, Request as CtlRequest, Response as CtlResponse};
use proton_drive_rs::proton_sdk::ids::NodeUid;
use super::rel_to_mount;
use crate::Core;
use crate::sharing::StopSharingOutcome;
use crate::{Core, parse_uid};
/// The requests [`answer`] serves, as a pattern, so the control socket's
/// match hands exactly these over and the compiler still checks that it covers
@@ -74,22 +73,13 @@ impl Target {
})
}
/// A node named by its uid, which one of this daemon's locations, the
/// Photos timeline, or Drive's list of what this account shared must show
/// to be this account's. The last covers a node shared from elsewhere and
/// never browsed to here: Shared by me lists it, and without it the share
/// could not be managed, nor stopped, from this computer.
/// A node named by its uid, which one of this daemon's locations, or the
/// Photos timeline, must show to be this account's.
fn uid(core: &Core, uid: String) -> Self {
let node = core.resolve_shareable(&uid).or_else(|e| {
if e.kind != ErrorKind::NotFound {
return Err(e);
}
match parse_uid(&uid) {
Some(node) if core.sharing.shared_by_me(&node)? => Ok(node),
_ => Err(e),
}
});
Self { node, label: uid }
Self {
node: core.resolve_shareable(&uid),
label: uid,
}
}
}
+9 -74
View File
@@ -19,13 +19,11 @@ use std::time::{Duration, Instant};
use parking_lot::Mutex;
use pdfs_core::control::{
AdmissionLoad, Diagnostics, DriveCallStat, EffectIntent, EffectReport, InflightRequest,
ServiceState, UploadPathStat, WorkerState,
AdmissionLoad, Diagnostics, DriveCallStat, InflightRequest, ServiceState, UploadPathStat,
WorkerState,
};
use pdfs_core::lifecycle::ServiceBoard;
use pdfs_core::timestamp::now_secs;
use pdfs_store::db::StoredIntent;
use super::Core;
@@ -148,7 +146,6 @@ impl Core {
})
.unwrap_or_default();
inflight.sort_by_key(|request| std::cmp::Reverse(request.age_secs));
let (pending_ops, effects) = self.database_quickly().unzip();
Diagnostics {
uptime_secs: STARTED.elapsed().as_secs(),
@@ -170,8 +167,7 @@ impl Core {
inflight,
control_handlers: super::control::active_handlers(),
control_handler_limit: super::control::handler_limit(),
pending_ops,
effects,
pending_ops: self.pending_ops_quickly(),
sync: Some(self.sync.engine.report()),
services: self
.services
@@ -234,50 +230,26 @@ impl Core {
}
}
/// Queued mutations and the mirror effects not settled yet, or `None`
/// when the database did not answer within [`DATABASE_DEADLINE`] or an
/// earlier probe is still waiting on it.
/// Queued mutations, or `None` when the database did not answer within
/// [`PENDING_COUNT_DEADLINE`] or an earlier probe is still waiting on it.
///
/// The supervisor asks for a report every tick. One thread per report
/// would pile up behind a database that never answers, so a second probe
/// is not started until the first one has returned.
fn database_quickly(&self) -> Option<(u64, EffectReport)> {
fn pending_ops_quickly(&self) -> Option<u64> {
let db = self.db.clone();
probe_once(
&self.services,
&self.pending_probe,
DATABASE_DEADLINE,
PENDING_COUNT_DEADLINE,
move || {
let counts = db.pending_op_counts().ok()?;
let pending = counts.uploads.max(0) as u64 + counts.changes.max(0) as u64;
let intents = db.sync_intents(None).ok()?;
Some((pending, effect_report(intents, now_secs())))
Some(counts.uploads.max(0) as u64 + counts.changes.max(0) as u64)
},
)
}
}
/// The report of the unsettled `intents`, oldest first, at `now`.
fn effect_report(mut intents: Vec<StoredIntent>, now: i64) -> EffectReport {
intents.sort_by_key(|intent| (intent.issued_at, intent.id));
EffectReport {
count: intents.len(),
oldest: intents
.into_iter()
.take(EffectReport::SHOWN)
.map(|intent| EffectIntent {
folder_id: intent.folder_id,
rel_path: intent.rel_path,
kind: intent.kind,
state: intent.state,
attempts: intent.attempts,
age_secs: u64::try_from(now - intent.issued_at).unwrap_or(0),
last_error: intent.last_error,
})
.collect(),
}
}
fn millis(took: Duration) -> u64 {
u64::try_from(took.as_millis()).unwrap_or(u64::MAX)
}
@@ -310,49 +282,12 @@ fn probe_once<T: Send + 'static>(
}
/// How long the report waits for the database before reporting without it.
const DATABASE_DEADLINE: Duration = Duration::from_millis(500);
const PENDING_COUNT_DEADLINE: Duration = Duration::from_millis(500);
#[cfg(test)]
mod tests {
use super::*;
/// The report counts every unsettled effect but lists only the oldest,
/// so a folder with thousands of failed uploads stays readable.
#[test]
fn the_effect_report_lists_the_oldest_and_counts_them_all() {
let intent = |id: i64, issued_at: i64| StoredIntent {
id,
folder_id: 1,
rel_path: format!("f{id}"),
kind: "trash".into(),
state: "retry".into(),
attempts: 2,
issued_at,
last_error: Some("offline".into()),
sent_sha1s: Vec::new(),
};
let total = EffectReport::SHOWN as i64 + 5;
let intents = (0..total).map(|id| intent(id, 1_000 - id)).collect();
let report = effect_report(intents, 1_100);
assert_eq!(report.count, total as usize);
assert_eq!(report.oldest.len(), EffectReport::SHOWN);
let first = &report.oldest[0];
assert_eq!(first.rel_path, format!("f{}", total - 1));
assert_eq!(first.age_secs, 100 + total as u64 - 1);
assert_eq!(first.last_error.as_deref(), Some("offline"));
assert!(
report
.oldest
.windows(2)
.all(|pair| pair[0].age_secs >= pair[1].age_secs)
);
// A clock that went back reads as just sent, not as a wrap.
assert_eq!(
effect_report(vec![intent(1, 2_000)], 1_000).oldest[0].age_secs,
0
);
}
/// The request name is read off the wire format, so it must match both
/// shapes serde produces.
#[test]
+2 -13
View File
@@ -637,16 +637,6 @@ impl Core {
// answer may still have the old name (`docs/BUGS.md` B161).
let real_key = real.to_string();
let renaming = self.db.has_pending_op(&real_key, OP_RENAME)?;
// Where the tree has the node before the read-back. A rename queued
// after the check above and landed before the one under the lock
// below leaves no op for either to see, while the read-back can still
// have the old name. The tree moved the entry when the rename was
// queued, so a placement that changed meanwhile is the user's
// (docs/BUGS.md B309).
let before = {
let st = self.state();
placed_in(&st, real).or_else(|| placed_in(&st, local))
};
// Drive answers a create before it lists the new node.
let mut node = self
.read_back(real)
@@ -679,9 +669,8 @@ impl Core {
// before it renames the entry under this lock. Asked only before,
// a rename made since was overwritten with the name the create was
// sent with, here and in the node row (`docs/BUGS.md` B152).
let renaming = renaming
|| placed_in(st, real) != before
|| matches!(self.db.has_pending_op(&real_key, OP_RENAME), Ok(true));
let renaming =
renaming || matches!(self.db.has_pending_op(&real_key, OP_RENAME), Ok(true));
if renaming && let Some(e) = st.entries.get(&ino) {
node.name = e.node.name.clone();
node.parent_uid = e.node.parent_uid.clone();
-6
View File
@@ -627,12 +627,6 @@ impl Core {
.db
.has_pending_op(&uid.to_string(), OP_RENAME)
.unwrap_or(false);
// A write queued since the check above has stamped its size on the
// tree already, and the node read back must not put the landed size
// back over it. Listings do the same (B308).
let mut landed = [node.clone()];
self.stamp_pending_sizes(&mut landed);
let [node] = landed;
self.for_each_state(|st| {
let moved = placed_in(st, uid) != before;
let Some(entry) = st.by_uid.get(uid).and_then(|ino| st.entries.get(ino)) else {
-16
View File
@@ -194,22 +194,6 @@ impl Core {
Ok(name)
}
/// Drop the pins recorded under `path`, the path a front end lists a pin
/// by, when their node is gone. A deleted node leaves no path to resolve,
/// so [`unpin`](Self::unpin) cannot find it, and the pin would stay listed
/// as kept offline for good. Returns whether any pin was dropped.
pub(super) fn unpin_stale(&self, path: &str) -> CoreResult<bool> {
let uids = self
.cache
.remove_pins_at(path)
.map_err(|e| CoreError::from_api(&e, "unpin"))?;
for uid in uids.iter().filter_map(|s| parse_uid(s)) {
self.cache.evict(&uid);
self.evict_reader(&uid);
}
Ok(!uids.is_empty())
}
/// Whether the node at `ino` is kept offline because a folder above it is
/// pinned, whether or not it is also pinned on its own.
pub(super) fn pinned_by_folder(&self, ino: u64) -> bool {
-11
View File
@@ -645,17 +645,6 @@ impl Sharing {
Ok(items)
}
/// Whether Drive lists `uid` among the nodes this account shared. That list
/// is the account's own word that the node is its share, so it stands in
/// for the residency proof a node never browsed to cannot give.
pub(crate) fn shared_by_me(&self, uid: &NodeUid) -> CoreResult<bool> {
let uids = self
.rt
.block_on(self.client.enumerate_shared_by_me_node_uids())
.map_err(|e| CoreError::from_api(&e, "enumerate shared-by-me"))?;
Ok(uids.contains(uid))
}
/// Best-effort mountpoint-relative path for a node already interned in the live
/// tree, by walking parent inodes to the root. `None` when the node has never
/// been seen through the mount (e.g. shared but not browsed to this session) —
-138
View File
@@ -1547,86 +1547,6 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_file_renamed_while_its_create_is_read_back_keeps_its_new_name() {
// The create had landed and the drain was reading the node back. The
// rename came after the drain's first look for a queued rename, and
// landed before its second, so neither saw it. The answer still had
// the old name, which the tree took back. A rename over the new name
// then found nothing to replace and waited on its own name (B309).
let drive = FakeDrive::new();
let dir = scratch("renamed-while-read-back");
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
let mnt = daemon.mountpoint.clone().join("x");
std::fs::create_dir(&mnt).unwrap();
assert!(wait_until(Duration::from_secs(30), || {
daemon.pending().is_ok_and(|items| items.is_empty()) && drive.lookup("x").is_some()
}));
let create = daemon.client.hold_reply_to_next_create();
daemon.write_new(&mnt.join("d"), b"abc").unwrap();
assert!(wait_until(Duration::from_secs(30), || create.reached()));
let uid = drive.lookup("x/d").unwrap();
// Answer read-backs in turn until the create is retired; hold the
// first one after that, which is the adoption's.
let mut held = create;
let adopting = loop {
let next = daemon.client.hold_answer_to_next_read(&uid);
drop(held);
assert!(wait_until(Duration::from_secs(30), || next.reached()));
if daemon
.pending()
.is_ok_and(|items| items.iter().all(|op| op.kind != "create"))
{
break next;
}
held = next;
};
std::fs::rename(mnt.join("d"), mnt.join("b.txt")).unwrap();
assert!(
wait_until(Duration::from_secs(10), || drive
.lookup("x/b.txt")
.is_some()),
"{:?} {:?}",
daemon.pending(),
drive.tree()
);
drop(adopting);
// Before any listing or event could put it right.
std::thread::sleep(Duration::from_millis(100));
assert!(mnt.join("b.txt").exists() && !mnt.join("d").exists());
assert!(
wait_until(Duration::from_secs(30), || {
daemon.pending().is_ok_and(|items| items.is_empty())
}),
"{:?}",
daemon.pending()
);
let names: Vec<_> = std::fs::read_dir(&mnt)
.unwrap()
.map(|e| e.unwrap().file_name().into_string().unwrap())
.collect();
assert_eq!(names, ["b.txt"]);
// And a rename over it replaces it, as it does on any file.
daemon.write_new(&mnt.join("e.md"), b"new").unwrap();
std::fs::rename(mnt.join("e.md"), mnt.join("b.txt")).unwrap();
let file = Some(Entry::File(Arc::new(b"new".to_vec())));
assert!(
wait_until(Duration::from_secs(10), || {
daemon.pending().is_ok_and(|items| items.is_empty())
&& drive.tree().get("x/b.txt").cloned() == file
}),
"{:?} {:?}",
daemon.pending(),
drive.tree()
);
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_file_read_back_before_drive_committed_it_keeps_its_bytes() {
@@ -2276,64 +2196,6 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
/// The mirror effects not settled yet, from `pdfs diagnostics`.
fn effects(daemon: &Daemon) -> Vec<control::EffectIntent> {
let Ok(Response::Diagnostics { diagnostics }) = daemon.request(&Request::Diagnostics)
else {
panic!("no diagnostics");
};
diagnostics.effects.map(|e| e.oldest).unwrap_or_default()
}
/// A deletion a mirror pass sends is recorded like any other effect, and
/// `pdfs diagnostics` lists it until it lands: a trash on Drive while its
/// answer is outstanding, and a removal from disk.
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_deletion_is_an_effect_until_it_lands() {
let drive = FakeDrive::new();
let dir = scratch("deletion-effect");
let (daemon, folder, _client) = start_mirror(
&drive,
&dir,
&[
("a.txt", b"one"),
("b.txt", b"two"),
("c.txt", b"three"),
("d.txt", b"four"),
],
);
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
let uid = drive.lookup("mirrored/a.txt").unwrap();
let held = daemon.client.hold_next_trash(&uid);
std::fs::remove_file(dir.join("local").join("a.txt")).unwrap();
assert!(wait_until(Duration::from_secs(60), || held.reached()));
let listed = effects(&daemon);
assert!(
listed.iter().any(|e| e.folder_id == folder
&& e.rel_path == "a.txt"
&& e.kind == "trash"
&& e.state == "issued"),
"{listed:#?}"
);
drop(held);
assert!(wait_until(Duration::from_secs(60), || {
drive.lookup("mirrored/a.txt").is_none() && effects(&daemon).is_empty()
}));
drive.device().trash("mirrored/b.txt");
assert!(wait_until(Duration::from_secs(60), || {
!dir.join("local").join("b.txt").exists()
}));
assert!(
wait_until(Duration::from_secs(30), || effects(&daemon).is_empty()),
"{:#?}",
effects(&daemon)
);
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
let _ = std::fs::remove_dir_all(&dir);
}
/// A restart owes the disk a walk in full, since nothing watched it
/// meanwhile, and owes Drive nothing: its event stream resumes from the
/// cursor (`root`).
@@ -1,5 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<!-- Generated by scripts/render-tray-icons.py; edit that, not this. -->
<style>.ColorScheme-Text{color:#2e3436}</style>
<path class="ColorScheme-Text" fill="currentColor" fill-rule="evenodd" d="M1 3.5Q1 2.5 2 2.5H5.6Q6.1 2.5 6.45 2.85L7.4 3.8Q7.6 4 7.9 4H14Q15 4 15 5V6.75H7.05L5.8 5.5H1ZM1 7.25Q1 6.25 2 6.25H5.2Q5.6 6.25 5.9 6.55L6.6 7.25Q6.85 7.5 7.2 7.5H14Q15 7.5 15 8.5V8.646A4.5 4.5 0 0 0 7.757 13.5H2Q1 13.5 1 12.5ZM8.5 12A3.5 3.5 0 1 0 15.5 12A3.5 3.5 0 1 0 8.5 12ZM11.8 9.5H12.2Q12.7 9.5 12.7 10V12.1Q12.7 12.6 12.2 12.6H11.8Q11.3 12.6 11.3 12.1V10Q11.3 9.5 11.8 9.5ZM11.25 14.05A0.75 0.75 0 1 0 12.75 14.05A0.75 0.75 0 1 0 11.25 14.05Z"/>
</svg>

Before

Width:  |  Height:  |  Size: 741 B

@@ -1,5 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<!-- Generated by scripts/render-tray-icons.py; edit that, not this. -->
<style>.ColorScheme-Text{color:#2e3436}</style>
<path class="ColorScheme-Text" fill="currentColor" fill-rule="evenodd" d="M1 3.5Q1 2.5 2 2.5H5.6Q6.1 2.5 6.45 2.85L7.4 3.8Q7.6 4 7.9 4H14Q15 4 15 5V6.75H7.05L5.8 5.5H1ZM1 7.25Q1 6.25 2 6.25H5.2Q5.6 6.25 5.9 6.55L6.6 7.25Q6.85 7.5 7.2 7.5H14Q15 7.5 15 8.5V8.646A4.5 4.5 0 0 0 7.757 13.5H2Q1 13.5 1 12.5ZM2.25 8.75H8.888A4.5 4.5 0 0 0 7.507 12.25H2.25ZM12 11.081L13.379 9.702L14.298 10.621L12.919 12L14.298 13.379L13.379 14.298L12 12.919L10.621 14.298L9.702 13.379L11.081 12L9.702 10.621L10.621 9.702Z"/>
</svg>

Before

Width:  |  Height:  |  Size: 715 B

@@ -1,5 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<!-- Generated by scripts/render-tray-icons.py; edit that, not this. -->
<style>.ColorScheme-Text{color:#2e3436}</style>
<path class="ColorScheme-Text" fill="currentColor" fill-rule="evenodd" d="M1 3.5Q1 2.5 2 2.5H5.6Q6.1 2.5 6.45 2.85L7.4 3.8Q7.6 4 7.9 4H14Q15 4 15 5V6.75H7.05L5.8 5.5H1ZM1 7.25Q1 6.25 2 6.25H5.2Q5.6 6.25 5.9 6.55L6.6 7.25Q6.85 7.5 7.2 7.5H14Q15 7.5 15 8.5V12.5Q15 13.5 14 13.5H2Q1 13.5 1 12.5ZM2.25 8.75H13.75V12.25H2.25Z"/>
</svg>

Before

Width:  |  Height:  |  Size: 536 B

@@ -1,5 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<!-- Generated by scripts/render-tray-icons.py; edit that, not this. -->
<style>.ColorScheme-Text{color:#2e3436}</style>
<path class="ColorScheme-Text" fill="currentColor" fill-rule="evenodd" d="M1 3.5Q1 2.5 2 2.5H5.6Q6.1 2.5 6.45 2.85L7.4 3.8Q7.6 4 7.9 4H14Q15 4 15 5V6.75H7.05L5.8 5.5H1ZM1 7.25Q1 6.25 2 6.25H5.2Q5.6 6.25 5.9 6.55L6.6 7.25Q6.85 7.5 7.2 7.5H14Q15 7.5 15 8.5V8.646A4.5 4.5 0 0 0 7.757 13.5H2Q1 13.5 1 12.5ZM10.1 9.25H10.8Q11.2 9.25 11.2 9.65V14.35Q11.2 14.75 10.8 14.75H10.1Q9.7 14.75 9.7 14.35V9.65Q9.7 9.25 10.1 9.25ZM13.2 9.25H13.9Q14.3 9.25 14.3 9.65V14.35Q14.3 14.75 13.9 14.75H13.2Q12.8 14.75 12.8 14.35V9.65Q12.8 9.25 13.2 9.25Z"/>
</svg>

Before

Width:  |  Height:  |  Size: 747 B

@@ -1,5 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<!-- Generated by scripts/render-tray-icons.py; edit that, not this. -->
<style>.ColorScheme-Text{color:#2e3436}</style>
<path class="ColorScheme-Text" fill="currentColor" fill-rule="evenodd" d="M1 3.5Q1 2.5 2 2.5H5.6Q6.1 2.5 6.45 2.85L7.4 3.8Q7.6 4 7.9 4H14Q15 4 15 5V6.75H7.05L5.8 5.5H1ZM1 7.25Q1 6.25 2 6.25H5.2Q5.6 6.25 5.9 6.55L6.6 7.25Q6.85 7.5 7.2 7.5H14Q15 7.5 15 8.5V8.646A4.5 4.5 0 0 0 7.757 13.5H2Q1 13.5 1 12.5ZM10.1 11.6V11.5A1.9 1.9 0 0 1 13.9 11.5V11.6H13.05V11.5A1.05 1.05 0 0 0 10.95 11.5V11.6ZM10.1 11.6H13.9Q14.5 11.6 14.5 12.2V14.2Q14.5 14.8 13.9 14.8H10.1Q9.5 14.8 9.5 14.2V12.2Q9.5 11.6 10.1 11.6Z"/>
</svg>

Before

Width:  |  Height:  |  Size: 714 B

@@ -1,5 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<!-- Generated by scripts/render-tray-icons.py; edit that, not this. -->
<style>.ColorScheme-Text{color:#2e3436}</style>
<path class="ColorScheme-Text" fill="currentColor" fill-rule="evenodd" d="M1 3.5Q1 2.5 2 2.5H5.6Q6.1 2.5 6.45 2.85L7.4 3.8Q7.6 4 7.9 4H14Q15 4 15 5V6.75H7.05L5.8 5.5H1ZM1 7.25Q1 6.25 2 6.25H5.2Q5.6 6.25 5.9 6.55L6.6 7.25Q6.85 7.5 7.2 7.5H14Q15 7.5 15 8.5V12.5Q15 13.5 14 13.5H2Q1 13.5 1 12.5Z"/>
</svg>

Before

Width:  |  Height:  |  Size: 508 B

@@ -1,5 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<!-- Generated by scripts/render-tray-icons.py; edit that, not this. -->
<style>.ColorScheme-Text{color:#2e3436}</style>
<path class="ColorScheme-Text" fill="currentColor" fill-rule="evenodd" d="M1 3.5Q1 2.5 2 2.5H5.6Q6.1 2.5 6.45 2.85L7.4 3.8Q7.6 4 7.9 4H14Q15 4 15 5V6.75H7.05L5.8 5.5H1ZM1 7.25Q1 6.25 2 6.25H5.2Q5.6 6.25 5.9 6.55L6.6 7.25Q6.85 7.5 7.2 7.5H14Q15 7.5 15 8.5V8.646A4.5 4.5 0 0 0 7.757 13.5H2Q1 13.5 1 12.5ZM9.087 10.94L9.461 10.222L10.007 9.625L10.69 9.19L11.462 8.947L12.27 8.912L13.06 9.087L13.778 9.461L14.375 10.007L15.026 9.461L14.498 12.087L12.804 11.325L13.455 10.779L13.09 10.444L12.65 10.215L12.166 10.107L11.67 10.129L11.197 10.278L10.779 10.545L10.444 10.91L10.215 11.35ZM14.913 13.06L14.539 13.778L13.993 14.375L13.31 14.81L12.538 15.053L11.73 15.088L10.94 14.913L10.222 14.539L9.625 13.993L8.974 14.539L9.502 11.913L11.196 12.675L10.545 13.221L10.91 13.556L11.35 13.785L11.834 13.893L12.33 13.871L12.803 13.722L13.221 13.455L13.556 13.09L13.785 12.65Z"/>
</svg>

Before

Width:  |  Height:  |  Size: 1.1 KiB

-1
View File
@@ -59,7 +59,6 @@ scale.browser-status-meter trough { min-width: 140px; min-height: 6px; }
.dropzone-active { border-color: var(--accent-bg-color); background: color-mix(in srgb, var(--accent-bg-color) 10%, transparent); }
.files-drop-active { outline: 2px dashed var(--accent-bg-color); outline-offset: -4px; border-radius: 12px; background: color-mix(in srgb, var(--accent-bg-color) 6%, transparent); }
.files-drop-folder { border-radius: 8px; background: color-mix(in srgb, var(--accent-bg-color) 22%, transparent); box-shadow: inset 0 0 0 2px var(--accent-bg-color); }
.files-drop-hint { padding: 8px 16px; border-radius: 9999px; background: var(--accent-bg-color); color: var(--accent-fg-color); font-weight: bold; box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2); }
.file-pending { opacity: 0.45; }
/* Photo viewer: always light-on-dark, whatever the system style */
-1
View File
@@ -500,7 +500,6 @@ fn build_window(app: &adw::Application) {
restore: RefCell::new(None),
crumb: browser_widgets.crumb.clone(),
content: browser_widgets.content.clone(),
drop_hint: browser_widgets.drop_hint.clone(),
status: browser_widgets.status.clone(),
retry: browser_widgets.retry.clone(),
split: browser_widgets.split.clone(),
+9 -195
View File
@@ -31,9 +31,6 @@ pub(crate) struct BrowserState {
/// Swaps the Files content area between the grid/list views and the status
/// page below; see [`browser_status`].
pub(crate) content: gtk4::Stack,
/// Floats over the views while something is dragged over them, saying
/// what a drop there does; see [`show_drop_preview`].
pub(crate) drop_hint: gtk4::Label,
/// The Files empty/loading/error surface, shown in place of the views.
pub(crate) status: adw::StatusPage,
/// Sits in [`Self::status`]; shown when a load failed because the mount
@@ -138,7 +135,6 @@ pub(crate) struct BrowserWidgets {
pub(crate) crumb: gtk4::Box,
/// Swaps the content area between the grid/list views and the status page.
pub(crate) content: gtk4::Stack,
pub(crate) drop_hint: gtk4::Label,
/// The empty/loading/error surface shown in place of the views.
pub(crate) status: adw::StatusPage,
/// Sits in the status page; shown only when the mount service is down.
@@ -348,19 +344,6 @@ pub(crate) fn build_browser_page() -> (gtk4::Widget, BrowserWidgets) {
content.set_transition_type(gtk4::StackTransitionType::Crossfade);
content.add_named(&view_stack, Some("views"));
content.add_named(&status, Some("status"));
// What a drop does, over the views while a drag is over them.
let drop_hint = gtk4::Label::builder()
.halign(gtk4::Align::Center)
.valign(gtk4::Align::End)
.margin_bottom(18)
.justify(gtk4::Justification::Center)
.wrap(true)
.visible(false)
.can_target(false)
.build();
drop_hint.add_css_class("files-drop-hint");
let content_overlay = gtk4::Overlay::builder().child(&content).build();
content_overlay.add_overlay(&drop_hint);
// The details pane slides in from the right while its header toggle is on.
let (details_pane, details) = build_details_pane();
@@ -373,7 +356,7 @@ pub(crate) fn build_browser_page() -> (gtk4::Widget, BrowserWidgets) {
// itself; the header toggle alone decides.
.pin_sidebar(true)
.max_sidebar_width(300.0)
.content(&content_overlay)
.content(&content)
.sidebar(&details_pane)
.build();
@@ -509,7 +492,6 @@ pub(crate) fn build_browser_page() -> (gtk4::Widget, BrowserWidgets) {
files,
crumb,
content,
drop_hint,
status,
retry,
search,
@@ -1419,16 +1401,11 @@ pub(crate) fn wire_browser_actions(ui: &Rc<Ui>, build_thumbnails: &gtk4::Button)
gtk4::gdk::FileList::static_type(),
gtk4::gdk::DragAction::COPY | gtk4::gdk::DragAction::MOVE,
);
// Loaded on enter, so the hint can say what the drop does before it lands.
drop.set_preload(true);
let ui_enter = ui.clone();
drop.connect_enter(move |target, _, _| {
drop.connect_enter(move |_, _, _| {
ui_enter.browser.content.add_css_class("files-drop-active");
page_drop_preview(&ui_enter, target);
browser_drop_action()
});
let ui_value = ui.clone();
drop.connect_value_notify(move |target| page_drop_preview(&ui_value, target));
drop.connect_motion(|_, _, _| browser_drop_action());
let ui_leave = ui.clone();
drop.connect_leave(move |_| {
@@ -1436,7 +1413,6 @@ pub(crate) fn wire_browser_actions(ui: &Rc<Ui>, build_thumbnails: &gtk4::Button)
.browser
.content
.remove_css_class("files-drop-active");
ui_leave.browser.drop_hint.set_visible(false);
});
let ui_drop = ui.clone();
drop.connect_drop(move |target, value, _, _| {
@@ -1444,7 +1420,6 @@ pub(crate) fn wire_browser_actions(ui: &Rc<Ui>, build_thumbnails: &gtk4::Button)
.browser
.content
.remove_css_class("files-drop-active");
ui_drop.browser.drop_hint.set_visible(false);
let Ok(files) = value.get::<gtk4::gdk::FileList>() else {
return false;
};
@@ -3049,29 +3024,19 @@ pub(crate) fn attach_drop(ui: &Rc<Ui>, item: &gtk4::ListItem, anchor: &gtk4::Box
.formats()
.contains_type(gtk4::gdk::FileList::static_type())
});
target.set_preload(true);
let (anchor_enter, ui_enter, item_enter) = (anchor.clone(), ui.clone(), item.clone());
target.connect_enter(move |target, _, _| {
let anchor_enter = anchor.clone();
target.connect_enter(move |_, _, _| {
anchor_enter.add_css_class("files-drop-folder");
folder_drop_preview(&ui_enter, target, &item_enter);
browser_drop_action()
});
let (ui_value, item_value) = (ui.clone(), item.clone());
target.connect_value_notify(move |target| folder_drop_preview(&ui_value, target, &item_value));
target.connect_motion(|_, _, _| browser_drop_action());
let (anchor_leave, ui_leave) = (anchor.clone(), ui.clone());
target.connect_leave(move |_| {
anchor_leave.remove_css_class("files-drop-folder");
// The page's own target takes over under the pointer; it repaints the
// hint for the folder on screen as it is entered.
ui_leave.browser.drop_hint.set_visible(false);
});
let anchor_leave = anchor.clone();
target.connect_leave(move |_| anchor_leave.remove_css_class("files-drop-folder"));
let ui = ui.clone();
let item = item.clone();
let anchor_drop = anchor.clone();
target.connect_drop(move |target, value, _, _| {
anchor_drop.remove_css_class("files-drop-folder");
ui.browser.drop_hint.set_visible(false);
let Some(obj) = item.item().and_downcast::<BoxedAnyObject>() else {
return false;
};
@@ -3090,123 +3055,6 @@ pub(crate) fn attach_drop(ui: &Rc<Ui>, item: &gtk4::ListItem, anchor: &gtk4::Box
anchor.add_controller(target);
}
/// The page's drop hint, for the folder on screen.
fn page_drop_preview(ui: &Rc<Ui>, target: &gtk4::DropTarget) {
if !ui.browser.search.text().trim().is_empty() {
// Search results have no one folder to drop into.
ui.browser.drop_hint.set_visible(false);
return;
}
let dest = ui.browser.path.borrow().clone();
let name = match dest.rsplit('/').next().filter(|name| !name.is_empty()) {
Some(name) => name.to_string(),
None => gettext("My files"),
};
show_drop_preview(ui, target, &dest, &name);
}
/// A folder cell's drop hint, for that folder.
fn folder_drop_preview(ui: &Rc<Ui>, target: &gtk4::DropTarget, item: &gtk4::ListItem) {
let Some(obj) = item.item().and_downcast::<BoxedAnyObject>() else {
return;
};
let (dest, name) = {
let entry = obj.borrow::<DirEntry>();
(entry_rel(ui, &entry), entry.name.clone())
};
show_drop_preview(ui, target, &dest, &name);
}
/// Say what dropping what `target` holds into `dest` would do, the way
/// [`drop_files`] will do it. Nothing is shown until the files have loaded.
fn show_drop_preview(ui: &Rc<Ui>, target: &gtk4::DropTarget, dest: &str, name: &str) {
let hint = &ui.browser.drop_hint;
let Some(files) = target
.value()
.and_then(|value| value.get::<gtk4::gdk::FileList>().ok())
else {
hint.set_visible(false);
return;
};
let mountpoint = ui.dirs.resolved_mountpoint(&ui.dirs.load_config());
let (in_drive, uploads) =
split_dropped(&mountpoint, files.files().iter().filter_map(|f| f.path()));
let moving = from_this_app(target);
let dropped = in_drive.len();
let going = drop_targets(in_drive, dest, moving).len();
hint.set_label(&drop_preview(
DropPlan {
going,
skipped: dropped - going,
uploads: uploads.len(),
moving,
},
name,
));
hint.set_visible(true);
}
/// What a drop would do, counted: see [`drop_files`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct DropPlan {
/// Items already in Proton Drive that go to the folder.
pub(crate) going: usize,
/// Items already in Proton Drive that cannot go there: the folder itself,
/// one of its parents, or, for a move, what is in it already.
pub(crate) skipped: usize,
/// Files from outside Proton Drive, uploaded into the folder.
pub(crate) uploads: usize,
/// The items in Proton Drive move rather than copy.
pub(crate) moving: bool,
}
/// The drop hint for `plan` into the folder called `folder`. Each line is one
/// sentence, so no translation is put together from pieces.
pub(crate) fn drop_preview(plan: DropPlan, folder: &str) -> String {
if plan.going == 0 && plan.uploads == 0 {
return gettext("Nothing here can go into this folder");
}
let mut lines = Vec::new();
if plan.going > 0 {
let n = plan.going as u64;
lines.push(if plan.moving {
// Translators: shown while dragging; {folder} is the folder the items would go to.
ngettext_f(
"Move {n} item to “{folder}”",
"Move {n} items to “{folder}”",
n,
&[("folder", folder)],
)
} else {
// Translators: shown while dragging; {folder} is the folder the items would go to.
ngettext_f(
"Copy {n} item to “{folder}”",
"Copy {n} items to “{folder}”",
n,
&[("folder", folder)],
)
});
}
if plan.uploads > 0 {
// Translators: shown while dragging; {folder} is the folder the files would go to.
lines.push(ngettext_f(
"Upload {n} item to “{folder}”",
"Upload {n} items to “{folder}”",
plan.uploads as u64,
&[("folder", folder)],
));
}
if plan.skipped > 0 {
lines.push(ngettext_f(
"{n} item can't go there and is left out",
"{n} items can't go there and are left out",
plan.skipped as u64,
&[],
));
}
lines.join("\n")
}
/// The action to answer a drag over the browser with: always a copy. Rows
/// dragged from this app offer nothing else (see [`attach_drag`]), and an
/// outside drag is never answered with a move, which would have the source
@@ -3716,9 +3564,9 @@ fn listing_summary(files: usize, folders: usize, file_bytes: u64) -> String {
#[cfg(test)]
mod tests {
use super::{
DropPlan, MoveTarget, badge_for, copy_target_allowed, drop_preview, drop_targets,
hit_location, icon_base_for, listing_summary, move_target_allowed,
show_thumbnail_build_progress, sort_entries, split_dropped,
MoveTarget, badge_for, copy_target_allowed, drop_targets, hit_location, icon_base_for,
listing_summary, move_target_allowed, show_thumbnail_build_progress, sort_entries,
split_dropped,
};
use std::path::{Path, PathBuf};
@@ -3797,40 +3645,6 @@ mod tests {
["Docs/a.pdf", "Photos/b.jpg"]
);
}
/// The hint says the same thing the drop will do: a move for rows from
/// this app, a copy for files from a file manager browsing the mount, and
/// how many are left out.
#[test]
fn the_drop_hint_names_the_action_and_what_is_left_out() {
let plan = |going, skipped, uploads, moving| DropPlan {
going,
skipped,
uploads,
moving,
};
assert_eq!(
drop_preview(plan(3, 0, 0, true), "Receipts"),
"Move 3 items to “Receipts”"
);
assert_eq!(
drop_preview(plan(1, 0, 0, false), "Receipts"),
"Copy 1 item to “Receipts”"
);
assert_eq!(
drop_preview(plan(0, 0, 2, false), "Receipts"),
"Upload 2 items to “Receipts”"
);
// A selection that holds the folder itself: the rest still moves.
assert_eq!(
drop_preview(plan(2, 1, 0, true), "Receipts"),
"Move 2 items to “Receipts”\n1 item can't go there and is left out"
);
assert_eq!(
drop_preview(plan(0, 2, 0, true), "Receipts"),
"Nothing here can go into this folder"
);
}
use pdfs_core::config::{FileSort, FilesView};
use pdfs_core::control::{DirEntry, SyncIssue, ThumbnailBuildStatus};
+19 -192
View File
@@ -310,7 +310,6 @@ fn duplicate_review(
// Every copy's toggle, by set, so the button can count what goes.
let toggles: Rc<RefCell<SetToggles>> = Rc::new(RefCell::new(Vec::new()));
let mut kept_labels: Vec<gtk4::Label> = Vec::new();
for set in sets {
let Some(first) = set.first() else {
continue;
@@ -334,29 +333,20 @@ fn duplicate_review(
};
let heading = gtk4::Label::builder().label(title).xalign(0.0).build();
heading.add_css_class("heading");
// How many of the set stay, in the heading's line: a set wider than
// the window hides some of its cards, and this still says what goes.
let kept = gtk4::Label::builder().xalign(1.0).hexpand(true).build();
kept.add_css_class("dim-label");
let header = gtk4::Box::new(gtk4::Orientation::Horizontal, 12);
header.append(&heading);
header.append(&kept);
let row = gtk4::Box::new(gtk4::Orientation::Horizontal, 12);
let mut set_toggles = Vec::new();
for (index, photo) in set.into_iter().enumerate() {
let (card, keep) =
copy_card(ui, &photo, index == 0 || finder == Finder::Similar, finder);
let (card, keep) = copy_card(ui, &photo, index == 0 || finder == Finder::Similar);
row.append(&card);
set_toggles.push((photo, keep));
}
kept_labels.push(kept);
let row_scroll = gtk4::ScrolledWindow::builder()
.vscrollbar_policy(gtk4::PolicyType::Never)
.propagate_natural_height(true)
.child(&row)
.build();
let section = gtk4::Box::new(gtk4::Orientation::Vertical, 6);
section.append(&header);
section.append(&heading);
section.append(&row_scroll);
content.append(&section);
toggles.borrow_mut().push(set_toggles);
@@ -366,14 +356,22 @@ fn duplicate_review(
let toggles = toggles.clone();
let trash = trash.clone();
move || {
let toggles = toggles.borrow();
let (n, files) = doomed_counts(&toggles, finder);
trash.set_label(&trash_label(finder, n, files));
let n = doomed(&toggles.borrow()).len();
trash.set_label(&match finder {
Finder::Exact => ngettext_f(
"Move {n} copy to Trash",
"Move {n} copies to Trash",
n as u64,
&[],
),
Finder::Similar => ngettext_f(
"Move {n} photo to Trash",
"Move {n} photos to Trash",
n as u64,
&[],
),
});
trash.set_sensitive(n > 0);
for (set, label) in toggles.iter().zip(&kept_labels) {
let keep = set.iter().filter(|(_, t)| t.is_active()).count();
label.set_label(&kept_label(keep, set.len()));
}
}
};
sync();
@@ -423,94 +421,6 @@ fn duplicate_review(
(scroll.upcast(), handler)
}
/// How many photos go to Trash, and how many files that is. An exact copy is
/// one file. A similar photo takes its whole shot, a RAW and its JPEG
/// together.
fn doomed_counts(toggles: &SetToggles, finder: Finder) -> (usize, usize) {
let doomed: Vec<&PhotoItem> = toggles
.iter()
.flatten()
.filter(|(_, keep)| !keep.is_active())
.map(|(photo, _)| photo)
.collect();
(doomed.len(), files_of(doomed.into_iter(), finder))
}
/// How many files trashing `photos` moves.
fn files_of<'a>(photos: impl Iterator<Item = &'a PhotoItem>, finder: Finder) -> usize {
photos
.map(|photo| match finder {
Finder::Exact => 1,
Finder::Similar => photo.group_size.max(1) as usize,
})
.sum()
}
/// The footer button: what it moves, in photos and, when that differs, files.
fn trash_label(finder: Finder, photos: usize, files: usize) -> String {
match finder {
Finder::Exact => ngettext_f(
"Move {n} copy to Trash",
"Move {n} copies to Trash",
photos as u64,
&[],
),
Finder::Similar if files > photos => ngettext_f(
// Translators: {n} is a number of photos, {files} how many files they are stored as (always more than {n}).
"Move {n} photo ({files} files) to Trash",
"Move {n} photos ({files} files) to Trash",
photos as u64,
&[("files", &files.to_string())],
),
Finder::Similar => ngettext_f(
"Move {n} photo to Trash",
"Move {n} photos to Trash",
photos as u64,
&[],
),
}
}
/// How many of a set stay.
fn kept_label(kept: usize, of: usize) -> String {
ngettext_f(
// Translators: {n} photos of a set of {total} stay; the rest go to Trash.
"Keeping {n} of {total}",
"Keeping {n} of {total}",
kept as u64,
&[("total", &of.to_string())],
)
}
/// What a card's photo is stored as, when that is more than one file.
fn stored_as(photo: &PhotoItem) -> Option<String> {
let n = photo.group_size;
(n > 1).then(|| {
if photo.has_raw {
ngettext_f(
// Translators: a shot stored as a camera RAW file and others, such as its JPEG.
"RAW + {n} more file",
"RAW + {n} more files",
u64::from(n - 1),
&[],
)
} else {
ngettext_f("{n} file", "{n} files", u64::from(n), &[])
}
})
}
/// What happens to a card's photo, under its toggle.
fn outcome_label(keep: bool) -> String {
if keep {
// Translators: a photo in the duplicates review that stays.
pgettext("duplicates", "Kept")
} else {
// Translators: a photo in the duplicates review that goes to Trash.
pgettext("duplicates", "Moves to Trash")
}
}
/// The uids of every copy not kept.
fn doomed(toggles: &SetToggles) -> Vec<String> {
toggles
@@ -521,14 +431,8 @@ fn doomed(toggles: &SetToggles) -> Vec<String> {
.collect()
}
/// One copy: its thumbnail, its file name, and whether to keep it. A similar
/// shot stored as several files says so, since all of them go with it.
fn copy_card(
ui: &Rc<Ui>,
photo: &PhotoItem,
keep: bool,
finder: Finder,
) -> (gtk4::Box, gtk4::ToggleButton) {
/// One copy: its thumbnail, its file name, and whether to keep it.
fn copy_card(ui: &Rc<Ui>, photo: &PhotoItem, keep: bool) -> (gtk4::Box, gtk4::ToggleButton) {
let picture = gtk4::Picture::builder()
.content_fit(gtk4::ContentFit::Cover)
.can_shrink(true)
@@ -560,88 +464,11 @@ fn copy_card(
.active(keep)
.build();
toggle.add_css_class("pill");
let outcome = gtk4::Label::builder().label(outcome_label(keep)).build();
outcome.add_css_class("caption");
if !keep {
outcome.add_css_class("error");
}
let outcome_t = outcome.clone();
toggle.connect_toggled(move |toggle| {
outcome_t.set_label(&outcome_label(toggle.is_active()));
if toggle.is_active() {
outcome_t.remove_css_class("error");
} else {
outcome_t.add_css_class("error");
}
});
let card = gtk4::Box::new(gtk4::Orientation::Vertical, 6);
card.set_size_request(COPY_SIZE, -1);
card.append(&overlay);
card.append(&label);
if finder == Finder::Similar
&& let Some(files) = stored_as(photo)
{
let files = gtk4::Label::builder().label(files).build();
files.add_css_class("caption");
files.add_css_class("dim-label");
card.append(&files);
}
card.append(&toggle);
card.append(&outcome);
(card, toggle)
}
#[cfg(test)]
mod tests {
use super::*;
fn shot(files: u32, has_raw: bool) -> PhotoItem {
PhotoItem {
uid: "vol~shot".into(),
capture_time: 0,
thumb_path: None,
name: None,
ratio: None,
no_thumb: false,
kind: PhotoKind::Photo,
favorite: false,
group_size: files,
has_raw,
place_id: None,
}
}
/// One RAW+JPEG shot marked and another kept: the footer counts both.
#[test]
fn the_footer_counts_files_when_a_shot_is_several() {
let raw_jpeg = shot(2, true);
let files = files_of([&raw_jpeg].into_iter(), Finder::Similar);
assert_eq!(files, 2);
assert_eq!(
trash_label(Finder::Similar, 1, files),
"Move 1 photo (2 files) to Trash"
);
assert_eq!(trash_label(Finder::Similar, 2, 2), "Move 2 photos to Trash");
}
/// An exact copy is one file, whatever its shot holds.
#[test]
fn an_exact_copy_is_one_file() {
let raw_jpeg = shot(2, true);
assert_eq!(files_of([&raw_jpeg].into_iter(), Finder::Exact), 1);
assert_eq!(trash_label(Finder::Exact, 1, 1), "Move 1 copy to Trash");
}
#[test]
fn a_card_names_what_its_shot_is_stored_as() {
assert_eq!(stored_as(&shot(1, false)), None);
assert_eq!(stored_as(&shot(0, false)), None);
assert_eq!(
stored_as(&shot(2, true)).as_deref(),
Some("RAW + 1 more file")
);
assert_eq!(stored_as(&shot(3, false)).as_deref(), Some("3 files"));
assert_eq!(kept_label(1, 4), "Keeping 1 of 4");
}
}
+20 -69
View File
@@ -682,40 +682,32 @@ pub(crate) fn sign_out(ui: &Rc<Ui>) {
let rx = spawn_request(ui.dirs.control_socket(), Request::Status);
let ui = ui.clone();
glib::spawn_future_local(async move {
// `None` when the service did not answer: then nobody knows whether
// changes are still waiting, which is not the same as none.
let queued = match rx.recv().await {
Ok(Ok(Response::Status {
pending_uploads,
pending_changes,
parked_uploads,
..
})) => Some(pending_uploads + pending_changes + parked_uploads),
_ => None,
})) => pending_uploads + pending_changes + parked_uploads,
_ => 0,
};
confirm_sign_out(&ui, queued);
});
}
fn confirm_sign_out(ui: &Rc<Ui>, queued: Option<u64>) {
fn confirm_sign_out(ui: &Rc<Ui>, queued: u64) {
let Some(window) = ui_window(ui) else { return };
let ui = ui.clone();
let mut body = gettext(
"Proton Drive will disconnect and stop syncing until you sign in again. Files already on this computer stay where they are.",
);
let warning = match queued {
Some(0) => None,
Some(queued) => Some(ngettext_f(
if queued > 0 {
let warning = ngettext_f(
"{n} change is not on Proton Drive yet. It stays on this computer and is sent after you sign in again.",
"{n} changes are not on Proton Drive yet. They stay on this computer and are sent after you sign in again.",
queued,
&[],
)),
None => Some(gettext(
"The Proton Drive service didn't answer, so it isn't known whether changes are still waiting to be sent. Any that are stay on this computer and are sent after you sign in again.",
)),
};
if let Some(warning) = warning {
);
body = format!("{warning}\n\n{body}");
}
confirm_destructive(
@@ -728,65 +720,24 @@ fn confirm_sign_out(ui: &Rc<Ui>, queued: Option<u64>) {
if let Some(galleries) = galleries {
galleries.reset();
}
sign_out_now(&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(|_| ()).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);
});
},
);
}
/// Stop the service and forget the stored session, then say what happened.
///
/// Two parts can fail on their own. Proton may not confirm that the session
/// ended, which leaves it listed in the account's security settings until it
/// expires. Removing the sign-in from the keyring may fail, which leaves this
/// computer signed in at the next start. The first is a notice, the second
/// needs the user, so it stays on screen with a way to try again.
fn sign_out_now(ui: &Rc<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
.unwrap_or_else(|_| Err("the sign-out worker stopped".into()));
*ui.session.borrow_mut() = None;
refresh(&ui);
match result {
Ok(true) => {}
Ok(false) => toast(
&ui,
&gettext(
"Signed out on this computer. Proton didn't confirm that the session ended; you can end it in your Proton account's security settings.",
),
),
Err(error) => {
tracing::error!("logout failed: {error}");
present_sign_out_failure(&ui, &error);
}
}
});
}
fn present_sign_out_failure(ui: &Rc<Ui>, error: &str) {
let dialog = adw::AlertDialog::builder()
.heading(gettext("Sign-In Still Saved"))
// Translators: {error} is the reason the keyring gave.
.body(gettext_f(
"Proton Drive stopped, but your sign-in couldn't be removed from this computer: {error}\n\nUntil it is removed, Proton Drive may sign in again at the next start. Unlock your keyring, then try again.",
&[("error", error)],
))
.build();
dialog.add_response("close", &gettext("Close"));
dialog.add_response("again", &gettext("Try Again"));
dialog.set_response_appearance("again", adw::ResponseAppearance::Suggested);
dialog.set_default_response(Some("again"));
dialog.set_close_response("close");
let ui_c = ui.clone();
dialog.connect_response(Some("again"), move |_, _| sign_out_now(&ui_c));
dialog.present(ui_window(ui).as_ref());
}
#[cfg(test)]
mod tests {
use super::login_error_message;
@@ -24,9 +24,6 @@ pub(crate) struct AppsPrefs {
prompt_terminal_row: adw::EntryRow,
limit_row: adw::SpinRow,
icons_row: adw::SwitchRow,
remember_row: adw::SwitchRow,
clear_row: adw::ActionRow,
clear_button: gtk4::Button,
}
/// The launcher modes in the order the combo row lists them.
@@ -105,23 +102,6 @@ pub(crate) fn build_apps_prefs() -> AppsPrefs {
.title(gettext("Show icons"))
.subtitle(gettext("When the launcher can show them"))
.build();
let remember_row = adw::SwitchRow::builder()
.title(gettext("Remember recent files"))
.subtitle(gettext(
"List what you opened before you type, and rank it higher in results. Off, the list is cleared.",
))
.build();
let clear_button = gtk4::Button::builder()
.label(gettext("Clear"))
.valign(gtk4::Align::Center)
.build();
let clear_row = adw::ActionRow::builder()
.title(gettext("Clear recent files"))
.subtitle(gettext(
"The search window forgets what it opened. Your files are not touched.",
))
.build();
clear_row.add_suffix(&clear_button);
let launcher = adw::PreferencesGroup::builder()
.title(gettext("Search Launcher"))
.description(gettext(
@@ -133,8 +113,6 @@ pub(crate) fn build_apps_prefs() -> AppsPrefs {
launcher.add(&prompt_terminal_row);
launcher.add(&limit_row);
launcher.add(&icons_row);
launcher.add(&remember_row);
launcher.add(&clear_row);
let page = adw::PreferencesPage::builder()
.title(gettext("Apps"))
@@ -155,9 +133,6 @@ pub(crate) fn build_apps_prefs() -> AppsPrefs {
prompt_terminal_row,
limit_row,
icons_row,
remember_row,
clear_row,
clear_button,
}
}
@@ -208,7 +183,6 @@ pub(crate) fn wire_apps_prefs(ui: &Rc<Ui>, widgets: AppsPrefs) {
.set_text(&format_command(prompt.terminal.as_deref().unwrap_or(&[])));
w.limit_row.set_value(prompt.resolved_menu_limit() as f64);
w.icons_row.set_active(prompt.resolved_menu_icons());
w.remember_row.set_active(prompt.resolved_remember_recent());
show_mode_rows(w, mode);
ui.status.settings_suppress.set(suppress);
@@ -265,56 +239,6 @@ pub(crate) fn wire_apps_prefs(ui: &Rc<Ui>, widgets: AppsPrefs) {
prompt_of(config).menu_icons = (!on).then_some(false)
});
});
let a = apps.clone();
w.remember_row.connect_active_notify(move |row| {
if a.ui.status.settings_suppress.get() {
return;
}
let on = row.is_active();
// The window clears the list itself the next time it opens; clearing
// here as well means nothing waits on disk until then.
if !on {
clear_history(&a);
}
save(&a, move |config| {
prompt_of(config).remember_recent = (!on).then_some(false)
});
});
let a = apps.clone();
w.clear_button.connect_clicked(move |_| {
if clear_history(&a) {
prefs_toast(&a.ui, &gettext("Recent files cleared"));
}
});
}
/// Delete the search window's history. It reads the file again each time it
/// opens. Says whether that worked.
fn clear_history(apps: &Rc<Apps>) -> bool {
match std::fs::remove_file(history_path(&apps.ui)) {
Ok(()) => true,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => true,
Err(e) => {
prefs_toast(
&apps.ui,
&gettext_f(
"{what}: {detail}",
&[
("what", &gettext("Couldn't clear recent files")),
("detail", &e.to_string()),
],
),
);
false
}
}
}
/// Where the search window keeps what it opened (`hud/history.rs`).
fn history_path(ui: &Ui) -> std::path::PathBuf {
ui.dirs
.state_dir()
.join(pdfs_core::menu::PROMPT_HISTORY_FILE)
}
/// Show only the rows the chosen launcher mode uses.
@@ -323,9 +247,6 @@ fn show_mode_rows(w: &AppsPrefs, mode: PromptMode) {
w.icons_row.set_visible(mode == PromptMode::Dmenu);
w.prompt_terminal_row.set_visible(mode == PromptMode::Fzf);
w.limit_row.set_visible(mode != PromptMode::Gtk);
// Only the search window keeps a history.
w.remember_row.set_visible(mode == PromptMode::Gtk);
w.clear_row.set_visible(mode == PromptMode::Gtk);
}
/// The `open_with` section, created when absent.
+3 -11
View File
@@ -466,16 +466,6 @@ fn rebind_rows(ui: &Rc<Ui>, uids: &HashSet<String>) {
/// 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 now = glib::real_time() / 1_000_000;
let link = find_item(&ui.shared_by_me.items, &entry.uid).and_then(|item| item.link);
// An expired link has nothing to copy or open; what it needs is a new
// expiry, which the Share dialog's link settings give it.
if link.as_ref().is_some_and(|link| link_expired(link, now)) {
let (ui_c, entry_c) = (ui.clone(), entry.clone());
menu.item(&gettext("Edit Link Expiry…"), move || {
open_share_dialog(&ui_c, &entry_c)
});
}
let (ui_c, entry_c) = (ui.clone(), entry.clone());
menu.item(&gettext("Manage Access…"), move || {
open_share_dialog(&ui_c, &entry_c)
@@ -491,7 +481,9 @@ fn shared_by_me_menu(ui: &Rc<Ui>, entry: &DirEntry) -> ActionMenu {
show_in_my_files(&ui_c, &entry_c)
});
}
let url = link
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 {
+118 -438
View File
@@ -669,70 +669,30 @@ pub(crate) fn repaint_share_link(state: &Rc<ShareDialog>, link: Option<&PublicLi
match link {
Some(link) => {
let now = glib::real_time() / 1_000_000;
let url = link.url.clone().unwrap_or_default();
let expired = link.expires.is_some_and(|at| at <= now);
// The row says how the link works, not where it is: the address
// is a key, and someone showing their screen should not hand it
// out by opening the dialog.
let role = role_label(&link.role).unwrap_or_else(|| capitalize(&link.role));
// Translators: {role} is the link's role, such as "Viewer".
let mut subtitle = gettext_f("Anyone with the link ({role})", &[("role", &role)]);
if link.has_password {
subtitle.push_str(" · ");
subtitle.push_str(&gettext("password-protected"));
}
if let Some(expires) = link.expires {
subtitle.push_str(" · ");
subtitle.push_str(&link_expiry_label(expires, glib::real_time() / 1_000_000));
}
let row = adw::ActionRow::builder()
.title(link_row_title(link.role == "editor", expired))
.subtitle(link_policy(
link.role == "editor",
link.has_password,
link.expires,
now,
))
.title(if url.is_empty() {
gettext("Public link")
} else {
url.clone()
})
.subtitle(&subtitle)
.use_markup(false)
.build();
row.add_css_class("property");
let (settings, expiry_drop) = link_settings_row(state, link);
// The address, hidden until asked for. Every repaint hides it again.
let address = adw::ActionRow::builder()
.title(&url)
.title_selectable(true)
.use_markup(false)
.visible(false)
.build();
address.add_css_class("monospace");
if expired {
// An expired link gives nothing to copy: whoever gets it sees an
// error. What the owner can do is give it a new expiry.
let edit = gtk4::Button::builder()
.label(gettext("Edit Expiry"))
.valign(gtk4::Align::Center)
.build();
let (settings, expiry_drop) = (settings.clone(), expiry_drop.clone());
edit.connect_clicked(move |_| {
settings.set_expanded(true);
expiry_drop.grab_focus();
});
row.add_suffix(&edit);
} else if !url.is_empty() {
let reveal = gtk4::ToggleButton::builder()
.icon_name("view-reveal-symbolic")
.tooltip_text(gettext("Show link address"))
.valign(gtk4::Align::Center)
.build();
reveal.add_css_class("flat");
let address_t = address.clone();
reveal.connect_toggled(move |btn| {
address_t.set_visible(btn.is_active());
btn.set_icon_name(if btn.is_active() {
"view-conceal-symbolic"
} else {
"view-reveal-symbolic"
});
btn.set_tooltip_text(Some(&if btn.is_active() {
gettext("Hide link address")
} else {
gettext("Show link address")
}));
});
row.add_suffix(&reveal);
if !url.is_empty() {
let copy = gtk4::Button::builder()
.icon_name("edit-copy-symbolic")
.tooltip_text(gettext("Copy link"))
@@ -784,8 +744,8 @@ pub(crate) fn repaint_share_link(state: &Rc<ShareDialog>, link: Option<&PublicLi
state.link_group.add(&row);
rows.push(row.upcast());
state.link_group.add(&address);
rows.push(address.upcast());
let settings = link_settings_row(state, link);
state.link_group.add(&settings);
rows.push(settings.upcast());
}
@@ -797,45 +757,11 @@ pub(crate) fn repaint_share_link(state: &Rc<ShareDialog>, link: Option<&PublicLi
let expiry_names: Vec<String> =
LINK_EXPIRY.iter().map(|(name, _)| gettext(name)).collect();
let (expiry_row, expiry_drop) = dropdown_row(&gettext("Expires"), &expiry_names, 0);
// How the link will work, right above the button that makes it.
let now = glib::real_time() / 1_000_000;
let summary = adw::ActionRow::builder()
.title(gettext("The new link"))
.subtitle(link_policy(false, false, None, now))
.use_markup(false)
.build();
summary.add_css_class("property");
let create = group_button(&gettext("Create Public Link"));
let refresh: Rc<dyn Fn()> = {
let (summary, role_drop, pw_row, expiry_drop) = (
summary.clone(),
role_drop.clone(),
pw_row.clone(),
expiry_drop.clone(),
);
Rc::new(move || {
let now = glib::real_time() / 1_000_000;
summary.set_subtitle(&link_policy(
role_drop.selected() == 1,
!pw_row.text().is_empty(),
link_expiry_at(expiry_drop.selected(), now),
now,
));
})
};
let r = refresh.clone();
role_drop.connect_selected_notify(move |_| r());
let r = refresh.clone();
pw_row.connect_changed(move |_| r());
expiry_drop.connect_selected_notify(move |_| refresh());
// Enter in the password field moves on to the expiry, which comes
// next: creating the link there would skip it.
let next = expiry_drop.clone();
pw_row.connect_entry_activated(move |_| {
next.grab_focus();
});
// Enter in the password field creates the link.
let btn = create.clone();
pw_row.connect_entry_activated(move |_| btn.emit_clicked());
let state_c = Rc::downgrade(state);
let pw_for = pw_row.clone();
@@ -861,265 +787,124 @@ pub(crate) fn repaint_share_link(state: &Rc<ShareDialog>, link: Option<&PublicLi
state.link_group.add(&role_row);
state.link_group.add(&pw_row);
state.link_group.add(&expiry_row);
state.link_group.add(&summary);
state.link_group.add(&create);
rows.push(role_row.upcast());
rows.push(pw_row.upcast());
rows.push(expiry_row.upcast());
rows.push(summary.upcast());
rows.push(create.upcast());
}
}
*state.link_rows.borrow_mut() = rows;
}
/// What the owner has chosen in an existing link's settings and not saved yet.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct LinkDraft {
/// Anyone with the link can edit.
pub(crate) editor: bool,
/// The chosen entry of [`link_expiry_choices`].
pub(crate) expiry: u32,
/// The link asks for a password.
pub(crate) protect: bool,
/// A new password; empty keeps the one the link has.
pub(crate) password: String,
}
impl LinkDraft {
/// The draft that changes nothing about `link`.
pub(crate) fn of(link: &PublicLinkInfo) -> Self {
Self {
editor: link.role == "editor",
expiry: 0,
protect: link.has_password,
password: String::new(),
}
}
}
/// The one update that saving a [`LinkDraft`] sends.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct LinkEdit {
pub(crate) role: Option<String>,
pub(crate) password: LinkChange<String>,
pub(crate) expires: LinkChange<i64>,
}
/// What saving `draft` would ask of `link`: `Ok(None)` when it changes
/// nothing, `Err(())` when it cannot be saved yet. That is a password asked for
/// on a link that has none, with no password typed.
pub(crate) fn link_edit(
link: &PublicLinkInfo,
draft: &LinkDraft,
now: i64,
) -> Result<Option<LinkEdit>, ()> {
let role = (draft.editor != (link.role == "editor"))
.then(|| if draft.editor { "editor" } else { "viewer" }.to_string());
let password = match (draft.protect, draft.password.is_empty(), link.has_password) {
(false, _, true) => LinkChange::Remove,
(false, _, false) | (true, true, true) => LinkChange::Keep,
(true, true, false) => return Err(()),
(true, false, _) => LinkChange::Set(draft.password.clone()),
};
let expires = link_expiry_change(draft.expiry, link.expires, now);
let edit = LinkEdit {
role,
password,
expires,
};
let unchanged = edit.role.is_none()
&& edit.password == LinkChange::Keep
&& edit.expires == LinkChange::Keep;
Ok((!unchanged).then_some(edit))
}
/// The title of an existing link's row: what kind of link it is, never its
/// address.
pub(crate) fn link_row_title(editor: bool, expired: bool) -> String {
match (expired, editor) {
(true, _) => gettext("Expired public link"),
(false, true) => gettext("Public editor link"),
(false, false) => gettext("Public viewer link"),
}
}
/// How a link works, in one line: who can do what, the password, the expiry.
pub(crate) fn link_policy(editor: bool, password: bool, expires: Option<i64>, now: i64) -> String {
let mut parts = vec![if editor {
gettext("Anyone with the link can edit")
} else {
gettext("Anyone with the link can view")
}];
parts.push(if password {
gettext("password-protected")
} else {
gettext("no password")
});
parts.push(match expires {
Some(at) => link_expiry_label(at, now),
None => gettext("never expires"),
});
parts.join(" · ")
}
/// How `link` works once `edit` is saved.
fn link_policy_after(
link: &PublicLinkInfo,
draft: &LinkDraft,
edit: &LinkEdit,
now: i64,
) -> String {
let expires = match edit.expires {
LinkChange::Keep => link.expires,
LinkChange::Remove => None,
LinkChange::Set(at) => Some(at),
};
link_policy(draft.editor, draft.protect, expires, now)
}
/// The settings of an existing link, collapsed under one row. Nothing reaches
/// Drive until Save: an owner turning a viewer link into an editor link with a
/// password must not hand out editing before the password is set, so every
/// change goes in one update. Closing the dialog drops what was not saved.
/// Returns the row and its Expires dropdown, which an expired link's Edit
/// Expiry button opens the row on.
fn link_settings_row(
state: &Rc<ShareDialog>,
link: &PublicLinkInfo,
) -> (adw::ExpanderRow, gtk4::DropDown) {
/// The settings of an existing link, collapsed under one row. Each control
/// applies at once, the way a member's role does. While a change is on its way
/// the whole row is insensitive: the daemon fills in what a change keeps from
/// the link as it stands, so two changes in flight could undo each other.
fn link_settings_row(state: &Rc<ShareDialog>, link: &PublicLinkInfo) -> adw::ExpanderRow {
let now = glib::real_time() / 1_000_000;
let expander = adw::ExpanderRow::builder()
.title(gettext("Link settings"))
.subtitle(gettext(
"Change who can edit, the password or the expiry, then save. The link stays the same.",
"Change who can edit, the password or the expiry. The link stays the same.",
))
.build();
let draft = Rc::new(RefCell::new(LinkDraft::of(link)));
let (role_row, role_drop) = dropdown_row(
&gettext("Link role"),
&link_roles(),
u32::from(draft.borrow().editor),
);
expander.add_row(&role_row);
let (expiry_row, expiry_drop) = dropdown_row(
&gettext("Expires"),
&link_expiry_choices(link.expires, now),
0,
);
expander.add_row(&expiry_row);
let protect = adw::SwitchRow::builder()
.title(gettext("Require a password"))
.active(link.has_password)
.build();
expander.add_row(&protect);
let pw_row = adw::PasswordEntryRow::builder()
.title(if link.has_password {
gettext("New password (optional)")
} else {
gettext("Password")
})
.visible(link.has_password)
.build();
expander.add_row(&pw_row);
// What the link will do once saved, right above the one action that sends it.
let summary = adw::ActionRow::builder()
.title(gettext("No changes"))
.use_markup(false)
.build();
summary.add_css_class("property");
let save = gtk4::Button::builder()
.label(gettext("Save Link Settings"))
.valign(gtk4::Align::Center)
.sensitive(false)
.build();
save.add_css_class("suggested-action");
summary.add_suffix(&save);
expander.add_row(&summary);
let refresh: Rc<dyn Fn()> = {
let (draft, link, summary, save) =
(draft.clone(), link.clone(), summary.clone(), save.clone());
Rc::new(move || {
let draft = draft.borrow();
let now = glib::real_time() / 1_000_000;
match link_edit(&link, &draft, now) {
Ok(None) => {
summary.set_title(&gettext("No changes"));
summary.set_subtitle("");
save.set_sensitive(false);
}
Ok(Some(edit)) => {
summary.set_title(&gettext("After saving"));
summary.set_subtitle(&link_policy_after(&link, &draft, &edit, now));
save.set_sensitive(true);
}
Err(()) => {
summary.set_title(&gettext("Enter a password to save"));
summary.set_subtitle("");
save.set_sensitive(false);
}
}
})
};
{
let (draft, refresh) = (draft.clone(), refresh.clone());
role_drop.connect_selected_notify(move |d| {
draft.borrow_mut().editor = d.selected() == 1;
refresh();
});
}
{
let (draft, refresh) = (draft.clone(), refresh.clone());
expiry_drop.connect_selected_notify(move |d| {
draft.borrow_mut().expiry = d.selected();
refresh();
});
}
{
let (draft, refresh, pw_row) = (draft.clone(), refresh.clone(), pw_row.clone());
protect.connect_active_notify(move |s| {
draft.borrow_mut().protect = s.is_active();
pw_row.set_visible(s.is_active());
if s.is_active() {
pw_row.grab_focus();
}
refresh();
});
}
{
let (draft, refresh) = (draft.clone(), refresh.clone());
pw_row.connect_changed(move |row| {
draft.borrow_mut().password = row.text().to_string();
refresh();
});
}
{
let save = save.clone();
pw_row.connect_entry_activated(move |_| {
if save.is_sensitive() {
save.emit_clicked();
}
});
}
let (state_w, expander_w, link) = (Rc::downgrade(state), expander.clone(), link.clone());
save.connect_clicked(move |_| {
let selected_role = u32::from(link.role == "editor");
let (role_row, role_drop) = dropdown_row(&gettext("Link role"), &link_roles(), selected_role);
let (state_w, expander_w, id) = (Rc::downgrade(state), expander.clone(), link.id.clone());
role_drop.connect_selected_notify(move |d| {
let Some(state) = state_w.upgrade() else {
return;
};
let Ok(Some(edit)) = link_edit(&link, &draft.borrow(), glib::real_time() / 1_000_000)
else {
return;
let role = if d.selected() == 1 {
"editor"
} else {
"viewer"
};
let request =
state
.target
.update_link(link.id.clone(), edit.role, edit.password, edit.expires);
let request = state.target.update_link(
id.clone(),
Some(role.into()),
LinkChange::Keep,
LinkChange::Keep,
);
share_dialog_update_link(&state, request, &expander_w);
});
(expander, expiry_drop)
expander.add_row(&role_row);
let current = link.expires;
let (expiry_row, expiry_drop) =
dropdown_row(&gettext("Expires"), &link_expiry_choices(current, now), 0);
let (state_w, expander_w, id) = (Rc::downgrade(state), expander.clone(), link.id.clone());
expiry_drop.connect_selected_notify(move |d| {
let Some(state) = state_w.upgrade() else {
return;
};
let expires = link_expiry_change(d.selected(), current, glib::real_time() / 1_000_000);
if expires == LinkChange::Keep {
return;
}
let request = state
.target
.update_link(id.clone(), None, LinkChange::Keep, expires);
share_dialog_update_link(&state, request, &expander_w);
});
expander.add_row(&expiry_row);
let pw_row = adw::PasswordEntryRow::builder()
.title(if link.has_password {
gettext("New password")
} else {
gettext("Add a password")
})
.show_apply_button(true)
.build();
let (state_w, expander_w, id) = (Rc::downgrade(state), expander.clone(), link.id.clone());
pw_row.connect_apply(move |row| {
let Some(state) = state_w.upgrade() else {
return;
};
let password = row.text().to_string();
if password.is_empty() {
return;
}
let request = state.target.update_link(
id.clone(),
None,
LinkChange::Set(password),
LinkChange::Keep,
);
share_dialog_update_link(&state, request, &expander_w);
});
expander.add_row(&pw_row);
if link.has_password {
let remove = gtk4::Button::builder()
.label(gettext("Remove"))
.valign(gtk4::Align::Center)
.build();
remove.add_css_class("flat");
let row = adw::ActionRow::builder()
.title(gettext("Remove the password"))
.subtitle(gettext(
"Anyone with the link can open it without a password.",
))
.build();
row.add_suffix(&remove);
let (state_w, expander_w, id) = (Rc::downgrade(state), expander.clone(), link.id.clone());
remove.connect_clicked(move |_| {
let Some(state) = state_w.upgrade() else {
return;
};
let request =
state
.target
.update_link(id.clone(), None, LinkChange::Remove, LinkChange::Keep);
share_dialog_update_link(&state, request, &expander_w);
});
expander.add_row(&row);
}
expander
}
/// Send a link change, then reload the dialog: on success to show the link as
@@ -1299,111 +1084,6 @@ mod tests {
);
}
fn viewer_link(has_password: bool, expires: Option<i64>) -> PublicLinkInfo {
PublicLinkInfo {
id: "link".into(),
url: Some("https://drive.proton.me/urls/X#y".into()),
role: "viewer".into(),
expires,
has_password,
created: 0,
}
}
#[test]
fn an_untouched_draft_sends_nothing() {
let link = viewer_link(true, Some(2_000_000_000));
assert_eq!(link_edit(&link, &LinkDraft::of(&link), 1_000), Ok(None));
}
/// Editor and a password go in one update, so link holders never get edit
/// access without the password.
#[test]
fn editor_and_a_password_are_saved_together() {
let link = viewer_link(false, None);
let draft = LinkDraft {
editor: true,
protect: true,
password: "hunter2".into(),
..LinkDraft::of(&link)
};
assert_eq!(
link_edit(&link, &draft, 1_000),
Ok(Some(LinkEdit {
role: Some("editor".into()),
password: LinkChange::Set("hunter2".into()),
expires: LinkChange::Keep,
}))
);
}
#[test]
fn asking_for_a_password_without_one_cannot_be_saved() {
let link = viewer_link(false, None);
let draft = LinkDraft {
editor: true,
protect: true,
..LinkDraft::of(&link)
};
assert_eq!(link_edit(&link, &draft, 1_000), Err(()));
}
#[test]
fn a_kept_password_stays_and_a_dropped_one_goes() {
let link = viewer_link(true, None);
let keep = LinkDraft {
expiry: 2,
..LinkDraft::of(&link)
};
assert_eq!(
link_edit(&link, &keep, 1_000).unwrap().unwrap().password,
LinkChange::Keep
);
let drop = LinkDraft {
protect: false,
password: "typed then switched off".into(),
..LinkDraft::of(&link)
};
assert_eq!(
link_edit(&link, &drop, 1_000),
Ok(Some(LinkEdit {
role: None,
password: LinkChange::Remove,
expires: LinkChange::Keep,
}))
);
}
#[test]
fn the_summary_shows_the_policy_after_saving() {
let link = viewer_link(true, Some(2_000_000_000));
let draft = LinkDraft {
editor: true,
expiry: 1,
protect: false,
..LinkDraft::of(&link)
};
let edit = link_edit(&link, &draft, 1_000).unwrap().unwrap();
assert_eq!(
link_policy_after(&link, &draft, &edit, 1_000),
"Anyone with the link can edit · no password · never expires"
);
}
/// The row names the kind of link and never its address.
#[test]
fn a_link_row_is_titled_by_what_the_link_does() {
assert_eq!(link_row_title(false, false), "Public viewer link");
assert_eq!(link_row_title(true, false), "Public editor link");
assert_eq!(link_row_title(true, true), "Expired public link");
let link = viewer_link(false, Some(10));
assert!(!link_row_title(false, false).contains(link.url.as_deref().unwrap()));
assert_eq!(
link_policy(false, false, link.expires, 20),
"Anyone with the link can view · no password · expired"
);
}
#[test]
fn past_expiry_reads_expired() {
assert_eq!(link_expiry_label(10, 20), "expired");
+20 -213
View File
@@ -5,13 +5,6 @@
//! searching a file opened often and lately gets a bonus on top of its match
//! score (see [`frecency_bonus`]).
//!
//! A Drive file is remembered with the account it was opened from, and only
//! that account's files are shown: after a switch to another account, the
//! first one's names and paths stay out of the window. Local files are shown
//! whoever is signed in. Preferences can turn the history off or clear it; the
//! window loads the file again each time it opens, so a clear made in the app
//! takes effect at once.
//!
//! One writer thread owns the file: it loads it, applies every recorded visit
//! in order and writes the result back atomically. A visit recorded before the
//! first load finished simply waits in the channel, so it is merged into the
@@ -49,19 +42,6 @@ pub(crate) struct Visit {
/// When the file was last opened, in epoch seconds.
pub(crate) last: i64,
pub(crate) count: u32,
/// The account a Drive file was opened from. `None` for a local file, and
/// for a Drive file remembered before accounts were recorded, which is
/// never shown since nobody can say whose it is.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) account: Option<String>,
}
/// Whether `visit` may be shown while `account` is signed in.
fn visible(visit: &Visit, account: Option<&str>) -> bool {
match visit.hit {
Hit::Local(_) => true,
Hit::Drive(_) => account.is_some() && visit.account.as_deref() == account,
}
}
/// The history bonus for a file opened `count` times, the last time
@@ -75,16 +55,9 @@ pub(crate) fn frecency_bonus(count: u32, age_secs: i64) -> i64 {
/// Count one more visit of `hit` at `now`, newest first, and keep at most
/// [`MAX_VISITS`]. The stored hit is replaced, so its size, date and sync
/// state are the ones from the latest search.
fn record(visits: &mut Vec<Visit>, hit: Hit, now: i64, account: Option<String>) {
fn record(visits: &mut Vec<Visit>, hit: Hit, now: i64) {
let key = hit.key();
let account = match hit {
Hit::Local(_) => None,
Hit::Drive(_) => account,
};
let count = match visits
.iter()
.position(|visit| visit.hit.key() == key && visit.account == account)
{
let count = match visits.iter().position(|visit| visit.hit.key() == key) {
Some(at) => visits.remove(at).count.saturating_add(1),
None => 1,
};
@@ -94,7 +67,6 @@ fn record(visits: &mut Vec<Visit>, hit: Hit, now: i64, account: Option<String>)
hit,
last: now,
count,
account,
},
);
visits.truncate(MAX_VISITS);
@@ -135,19 +107,9 @@ fn save(path: &Path, visits: &[Visit]) -> std::io::Result<()> {
std::fs::rename(&tmp, path)
}
/// Delete the history file. Used by the window when the history is turned off,
/// and by the app's Clear Recent Files.
pub(crate) fn clear(path: &Path) -> std::io::Result<()> {
std::fs::remove_file(path)
}
enum Command {
Record(Hit, i64, Option<String>),
Record(Hit, i64),
Prune,
/// Read the file again: the app may have cleared it.
Reload,
/// Forget everything, on disk too.
Clear,
}
/// The writer thread's loop: load, then apply commands until the launcher
@@ -161,29 +123,11 @@ fn serve(path: &Path, commands: &async_channel::Receiver<Command>, publish: impl
}
while let Ok(command) = commands.recv_blocking() {
let changed = match command {
Command::Record(hit, now, account) => {
record(&mut visits, hit, now, account);
Command::Record(hit, now) => {
record(&mut visits, hit, now);
true
}
Command::Prune => prune(&mut visits),
Command::Reload => {
visits = load(path);
publish(visits.clone());
false
}
Command::Clear => {
if let Err(e) = clear(path)
&& e.kind() != std::io::ErrorKind::NotFound
{
tracing::warn!("cannot remove {}: {e}", path.display());
}
let had = !visits.is_empty();
visits.clear();
if had {
publish(Vec::new());
}
false
}
};
if changed {
if let Err(e) = save(path, &visits) {
@@ -198,10 +142,6 @@ fn serve(path: &Path, commands: &async_channel::Receiver<Command>, publish: impl
pub(crate) struct History {
visits: Rc<RefCell<Vec<Visit>>>,
commands: async_channel::Sender<Command>,
/// Who is signed in, as the service last said; `None` until it has.
account: RefCell<Option<String>>,
/// Whether to remember anything, as Preferences last said.
remember: std::cell::Cell<bool>,
}
impl History {
@@ -229,38 +169,12 @@ impl History {
changed();
}
});
Self {
visits,
commands,
account: RefCell::new(None),
remember: std::cell::Cell::new(true),
}
}
/// Who is signed in now. Drive files opened by anyone else stay hidden.
pub(crate) fn set_account(&self, account: Option<String>) {
*self.account.borrow_mut() = account;
}
/// Apply Preferences as the window opens: read the file again, since the
/// app may have cleared it, or clear it when the history is turned off.
pub(crate) fn refresh(&self, remember: bool) {
self.remember.set(remember);
let command = if remember {
Command::Reload
} else {
Command::Clear
};
let _ = self.commands.try_send(command);
Self { visits, commands }
}
/// Remember that `hit` was opened just now.
pub(crate) fn record(&self, hit: Hit) {
if !self.remember.get() {
return;
}
let account = self.account.borrow().clone();
let _ = self.commands.try_send(Command::Record(hit, now(), account));
let _ = self.commands.try_send(Command::Record(hit, now()));
}
/// Forget local files that were deleted since they were opened.
@@ -270,11 +184,9 @@ impl History {
/// The most recently opened files, newest first.
pub(crate) fn recent(&self, limit: usize) -> Vec<Hit> {
let account = self.account.borrow();
self.visits
.borrow()
.iter()
.filter(|visit| visible(visit, account.as_deref()))
.take(limit)
.map(|visit| visit.hit.clone())
.collect()
@@ -283,11 +195,9 @@ impl History {
/// The frecency bonus of every remembered file, by [`Hit::key`].
pub(crate) fn bonuses(&self) -> HashMap<(bool, String), i64> {
let now = now();
let account = self.account.borrow();
self.visits
.borrow()
.iter()
.filter(|visit| visible(visit, account.as_deref()))
.map(|visit| {
(
visit.hit.key(),
@@ -310,8 +220,6 @@ mod tests {
use pdfs_core::control::{LocalHit, SearchHit};
const DAY: i64 = 86_400;
/// The account the tests open Drive files from.
const A: &str = "a@proton.me";
fn drive(name: &str) -> Hit {
Hit::Drive(SearchHit {
@@ -358,9 +266,9 @@ mod tests {
#[test]
fn a_repeat_visit_moves_the_file_to_the_top_and_counts_it() {
let mut visits = Vec::new();
record(&mut visits, drive("a.pdf"), 10, Some(A.into()));
record(&mut visits, drive("b.pdf"), 20, Some(A.into()));
record(&mut visits, drive("a.pdf"), 30, Some(A.into()));
record(&mut visits, drive("a.pdf"), 10);
record(&mut visits, drive("b.pdf"), 20);
record(&mut visits, drive("a.pdf"), 30);
assert_eq!(visits.len(), 2);
assert_eq!(visits[0].hit.name(), "a.pdf");
assert_eq!((visits[0].count, visits[0].last), (2, 30));
@@ -371,7 +279,7 @@ mod tests {
fn the_history_keeps_the_newest_fifty_files() {
let mut visits = Vec::new();
for n in 0..60 {
record(&mut visits, drive(&format!("{n}.pdf")), n, Some(A.into()));
record(&mut visits, drive(&format!("{n}.pdf")), n);
}
assert_eq!(visits.len(), MAX_VISITS);
assert_eq!(visits[0].hit.name(), "59.pdf");
@@ -383,8 +291,8 @@ mod tests {
let dir = scratch_dir("round-trip");
let path = dir.join("prompt-history.json");
let mut visits = Vec::new();
record(&mut visits, drive("a.pdf"), 10, Some(A.into()));
record(&mut visits, drive("a.pdf"), 20, Some(A.into()));
record(&mut visits, drive("a.pdf"), 10);
record(&mut visits, drive("a.pdf"), 20);
save(&path, &visits).unwrap();
let loaded = load(&path);
@@ -400,17 +308,17 @@ mod tests {
let dir = scratch_dir("merge");
let path = dir.join("prompt-history.json");
let mut stored = Vec::new();
record(&mut stored, drive("old.pdf"), 10, Some(A.into()));
record(&mut stored, drive("old.pdf"), 20, Some(A.into()));
record(&mut stored, drive("old.pdf"), 10);
record(&mut stored, drive("old.pdf"), 20);
save(&path, &stored).unwrap();
// Both visits are queued before the writer has read the file.
let (commands, inbox) = async_channel::unbounded();
commands
.send_blocking(Command::Record(drive("old.pdf"), 30, Some(A.into())))
.send_blocking(Command::Record(drive("old.pdf"), 30))
.unwrap();
commands
.send_blocking(Command::Record(drive("new.pdf"), 40, Some(A.into())))
.send_blocking(Command::Record(drive("new.pdf"), 40))
.unwrap();
drop(commands);
@@ -443,114 +351,13 @@ mod tests {
})
};
let mut visits = Vec::new();
record(&mut visits, local(&kept), 1, Some(A.into()));
record(&mut visits, local(&dir.join("gone.txt")), 2, Some(A.into()));
record(&mut visits, drive("remote.pdf"), 3, Some(A.into()));
record(&mut visits, local(&kept), 1);
record(&mut visits, local(&dir.join("gone.txt")), 2);
record(&mut visits, drive("remote.pdf"), 3);
assert!(prune(&mut visits));
let names: Vec<&str> = visits.iter().map(|visit| visit.hit.name()).collect();
assert_eq!(names, ["remote.pdf", "kept.txt"]);
std::fs::remove_dir_all(dir).unwrap();
}
/// After a switch to account B, account A's Drive files are not shown and
/// give no ranking bonus. Local files stay.
#[test]
fn only_the_signed_in_accounts_drive_files_are_shown() {
let mut visits = Vec::new();
record(&mut visits, drive("a-secret.pdf"), 1, Some(A.into()));
record(
&mut visits,
drive("b-notes.pdf"),
2,
Some("b@proton.me".into()),
);
let local = Hit::Local(LocalHit {
name: "here.txt".into(),
path: "/home/me/here.txt".into(),
is_dir: false,
size: 1,
modified: 1,
score: 0,
});
record(&mut visits, local, 3, Some(A.into()));
assert_eq!(
visits[0].account, None,
"a local file belongs to no account"
);
let shown = |account: Option<&str>| -> Vec<&str> {
visits
.iter()
.filter(|visit| visible(visit, account))
.map(|visit| visit.hit.name())
.collect()
};
assert_eq!(shown(Some("b@proton.me")), ["here.txt", "b-notes.pdf"]);
assert_eq!(shown(Some(A)), ["here.txt", "a-secret.pdf"]);
// Before the service has said who is signed in, no Drive file shows.
assert_eq!(shown(None), ["here.txt"]);
}
/// A Drive file remembered before accounts were recorded has no owner, so
/// it is never shown.
#[test]
fn a_drive_file_from_before_accounts_were_recorded_stays_hidden() {
let old: Vec<Visit> = serde_json::from_value(
serde_json::json!([{"hit": drive("old.pdf"), "last": 1, "count": 1}]),
)
.unwrap();
assert!(!visible(&old[0], Some(A)));
}
#[test]
fn clearing_forgets_everything_on_disk_too() {
let dir = scratch_dir("clear");
let path = dir.join("prompt-history.json");
let mut stored = Vec::new();
record(&mut stored, drive("old.pdf"), 10, Some(A.into()));
save(&path, &stored).unwrap();
let (commands, inbox) = async_channel::unbounded();
commands.send_blocking(Command::Clear).unwrap();
drop(commands);
let published = RefCell::new(Vec::new());
serve(&path, &inbox, |visits| published.borrow_mut().push(visits));
assert!(published.borrow().last().unwrap().is_empty());
assert!(!path.exists());
std::fs::remove_dir_all(dir).unwrap();
}
/// The app clears the file while the window is hidden; the window reads
/// it again when it opens and shows nothing.
#[test]
fn a_reload_picks_up_a_clear_made_elsewhere() {
let dir = scratch_dir("reload");
let path = dir.join("prompt-history.json");
let mut stored = Vec::new();
record(&mut stored, drive("old.pdf"), 10, Some(A.into()));
save(&path, &stored).unwrap();
let (commands, inbox) = async_channel::unbounded();
let published = std::sync::Mutex::new(Vec::new());
std::thread::scope(|scope| {
scope.spawn(|| {
serve(&path, &inbox, |visits| {
published.lock().unwrap().push(visits)
})
});
// Let the first load happen, then clear behind the writer's back.
while published.lock().unwrap().is_empty() {
std::thread::yield_now();
}
clear(&path).unwrap();
commands.send_blocking(Command::Reload).unwrap();
drop(commands);
});
let published = published.into_inner().unwrap();
assert_eq!(published.first().unwrap().len(), 1);
assert!(published.last().unwrap().is_empty());
std::fs::remove_dir_all(dir).unwrap();
}
}
+8 -22
View File
@@ -286,16 +286,13 @@ pub(crate) fn build_window(app: &adw::Application) -> Option<Rc<Ui>> {
thumbs: Thumbs::new(socket.clone()),
// A visit recorded elsewhere, or the first load finishing, adds
// to the recent list the user may be looking at.
history: History::start(
dirs.state_dir().join(pdfs_core::menu::PROMPT_HISTORY_FILE),
move || {
if let Some(ui) = weak.upgrade()
&& ui.showing_suggestions()
{
ui.render();
}
},
),
history: History::start(dirs.state_dir().join("prompt-history.json"), move || {
if let Some(ui) = weak.upgrade()
&& ui.showing_suggestions()
{
ui.render();
}
}),
socket,
mountpoint: RefCell::new(dirs.default_mountpoint()),
opener: RefCell::new(dirs.load_config().resolved_open_with()),
@@ -539,8 +536,6 @@ impl Ui {
let config = dirs.load_config();
set_proton_theme(config.proton_theme.unwrap_or(false));
*self.opener.borrow_mut() = config.resolved_open_with();
self.history
.refresh(config.resolved_prompt().resolved_remember_recent());
}
self.history.prune();
// Supersede replies from the previous showing before clearing the
@@ -586,22 +581,13 @@ impl Ui {
let ui = self.clone();
glib::spawn_future_local(async move {
match rx.recv().await {
Ok(Ok(Response::Status {
mountpoint,
username,
..
})) => {
// Recent Drive files are shown only to the account that
// opened them; asked again each time the window opens.
ui.history
.set_account((!username.is_empty()).then_some(username));
Ok(Ok(Response::Status { mountpoint, .. })) => {
*ui.mountpoint.borrow_mut() = PathBuf::from(mountpoint);
ui.entry.set_sensitive(true);
ui.stack.set_visible_child_name("results");
ui.load_suggestions();
}
_ => {
ui.history.set_account(None);
ui.entry.set_sensitive(false);
ui.hint.set_label(&gettext("Proton Drive isn't running"));
ui.stack.set_visible_child_name("offline");
+11 -58
View File
@@ -28,7 +28,6 @@ use pdfs_core::control::{
use pdfs_core::service;
mod i18n;
mod tray_icons;
use i18n::{gettext, gettext_f, ngettext_f};
/// How long the tray lets a burst of events arrive before it repaints. Progress
@@ -55,19 +54,17 @@ enum Phase {
}
impl Phase {
/// The tray's own symbolic icon for the phase ([`tray_icons`]). Symbolic
/// icons take the panel's text colour.
/// A stock symbolic icon for the phase. Stock names follow the panel's
/// theme and colour, and need nothing installed beside the binary.
fn icon(self) -> &'static str {
match self {
Phase::Synced => "io.narl.proton-drive-linux-tray-synced-symbolic",
Phase::Syncing => "io.narl.proton-drive-linux-tray-syncing-symbolic",
Phase::Paused => "io.narl.proton-drive-linux-tray-paused-symbolic",
Phase::Offline => "io.narl.proton-drive-linux-tray-offline-symbolic",
Phase::Attention => "io.narl.proton-drive-linux-tray-attention-symbolic",
Phase::SessionExpired => "io.narl.proton-drive-linux-tray-session-expired-symbolic",
Phase::Disconnected | Phase::SignedOut => {
"io.narl.proton-drive-linux-tray-disconnected-symbolic"
}
Phase::Synced => "folder-remote-symbolic",
Phase::Syncing => "view-refresh-symbolic",
Phase::Paused => "media-playback-pause-symbolic",
Phase::Offline => "network-offline-symbolic",
Phase::Attention => "dialog-warning-symbolic",
Phase::SessionExpired => "dialog-password-symbolic",
Phase::Disconnected | Phase::SignedOut => "network-offline-symbolic",
}
}
}
@@ -157,9 +154,6 @@ fn sync_line(items: &[TransferItem], jobs: &[JobItem]) -> String {
struct DriveTray {
state: DriveState,
socket: PathBuf,
/// Where [`tray_icons::install`] put the icons, or empty when it could
/// not, which leaves the panel to the installed theme.
icon_theme_path: String,
}
/// Ask the daemon for its status, falling back to the stored session so the
@@ -428,10 +422,6 @@ impl Tray for DriveTray {
self.state.phase.icon().into()
}
fn icon_theme_path(&self) -> String {
self.icon_theme_path.clone()
}
fn attention_icon_name(&self) -> String {
self.icon_name()
}
@@ -618,18 +608,9 @@ fn main() -> Result<()> {
let socket = dirs.control_socket();
let default_mountpoint = dirs.default_mountpoint();
let icons = dirs.cache_dir().join("tray-icons");
let icon_theme_path = match tray_icons::install(&icons) {
Ok(()) => icons.to_string_lossy().into_owned(),
Err(e) => {
tracing::warn!(error = %e, "could not write the tray icons; using the installed theme");
String::new()
}
};
let tray = DriveTray {
state: poll_state(&socket, &default_mountpoint),
socket: socket.clone(),
icon_theme_path,
};
// The tray autostarts with the session and can beat the desktop's SNI
@@ -698,43 +679,15 @@ mod tests {
assert_eq!(phase_of(false, 0, true, false), Phase::Synced);
}
#[test]
fn every_phase_has_an_icon_the_tray_ships() {
for phase in [
Phase::Synced,
Phase::Syncing,
Phase::Paused,
Phase::Offline,
Phase::Attention,
Phase::SessionExpired,
Phase::Disconnected,
Phase::SignedOut,
] {
assert!(
tray_icons::ICONS
.iter()
.any(|(name, _)| *name == phase.icon()),
"{phase:?}"
);
}
}
#[test]
fn attention_states_supply_the_icon_the_tray_requests() {
let mut tray = DriveTray {
state: status_state(&status(""), &[], &[], Path::new("/m")),
socket: PathBuf::new(),
icon_theme_path: String::new(),
};
for (phase, icon) in [
(
Phase::Attention,
"io.narl.proton-drive-linux-tray-attention-symbolic",
),
(
Phase::SessionExpired,
"io.narl.proton-drive-linux-tray-session-expired-symbolic",
),
(Phase::Attention, "dialog-warning-symbolic"),
(Phase::SessionExpired, "dialog-password-symbolic"),
] {
tray.state.phase = phase;
assert_eq!(tray.status(), Status::NeedsAttention);
-89
View File
@@ -1,89 +0,0 @@
//! The tray's own status icons, drawn from the app icon's folder.
//!
//! The packages install them into the hicolor theme. The tray also writes
//! them to a directory of its own at start and names it as the item's
//! `IconThemePath`, so a build run from source, or a panel that does not
//! read the system theme again after an update, still finds them.
use std::path::Path;
macro_rules! icon {
($state:literal) => {
(
concat!("io.narl.proton-drive-linux-tray-", $state, "-symbolic"),
include_str!(concat!(
"../resources/icons/tray/io.narl.proton-drive-linux-tray-",
$state,
"-symbolic.svg"
)),
)
};
}
/// Every icon, by name, with its SVG.
pub const ICONS: [(&str, &str); 7] = [
icon!("synced"),
icon!("syncing"),
icon!("paused"),
icon!("offline"),
icon!("attention"),
icon!("session-expired"),
icon!("disconnected"),
];
/// A theme index just big enough for one scalable status directory.
const INDEX: &str = "[Icon Theme]\nName=Hicolor\nComment=Proton Drive tray icons\n\
Directories=scalable/status\n\n[scalable/status]\nSize=16\nMinSize=8\nMaxSize=512\n\
Type=Scalable\nContext=Status\n";
/// Write the icons under `base`: as a hicolor theme, which KDE looks for in
/// an `IconThemePath`, and loose, which GTK hosts also accept. A file that
/// already holds the right bytes is left alone.
pub fn install(base: &Path) -> std::io::Result<()> {
let status = base.join("hicolor/scalable/status");
std::fs::create_dir_all(&status)?;
write_if_changed(&base.join("hicolor/index.theme"), INDEX)?;
for (name, svg) in ICONS {
let file = format!("{name}.svg");
write_if_changed(&status.join(&file), svg)?;
write_if_changed(&base.join(&file), svg)?;
}
Ok(())
}
fn write_if_changed(path: &Path, contents: &str) -> std::io::Result<()> {
if std::fs::read(path).is_ok_and(|have| have == contents.as_bytes()) {
return Ok(());
}
std::fs::write(path, contents)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_icon_is_one_recolourable_path() {
for (name, svg) in ICONS {
assert!(name.ends_with("-symbolic"), "{name}");
assert_eq!(svg.matches("<path").count(), 1, "{name}");
for banned in ["stroke", "mask", "opacity", "<circle", "<rect"] {
assert!(!svg.contains(banned), "{name} has {banned}");
}
}
}
#[test]
fn install_writes_a_theme_and_loose_copies() {
let dir = std::env::temp_dir().join(format!("pdfs-tray-icons-{}", std::process::id()));
install(&dir).unwrap();
install(&dir).unwrap();
assert!(dir.join("hicolor/index.theme").is_file());
for (name, svg) in ICONS {
let themed = dir.join(format!("hicolor/scalable/status/{name}.svg"));
assert_eq!(std::fs::read_to_string(themed).unwrap(), svg);
assert!(dir.join(format!("{name}.svg")).is_file());
}
std::fs::remove_dir_all(&dir).unwrap();
}
}
-2
View File
@@ -71,7 +71,6 @@ const STOCK: &[&str] = &[
"text-x-generic-symbolic",
"user-trash-symbolic",
"video-x-generic-symbolic",
"view-conceal-symbolic",
"view-fullscreen-symbolic",
"view-grid-symbolic",
"view-list-symbolic",
@@ -80,7 +79,6 @@ const STOCK: &[&str] = &[
"view-pin-symbolic",
"view-refresh-symbolic",
"view-restore-symbolic",
"view-reveal-symbolic",
"window-close-symbolic",
"zoom-fit-best-symbolic",
"zoom-in-symbolic",
-7
View File
@@ -1900,13 +1900,6 @@ impl ContentCache {
Ok(())
}
/// Drop every pin recorded under `path`. Returns the uids it dropped,
/// whose blobs the caller evicts. For a pin whose node is gone, so its
/// path no longer resolves to a uid.
pub fn remove_pins_at(&self, path: &str) -> Result<Vec<String>> {
self.db.pin_remove_by_path(path)
}
/// All pins (files and recursive folders), ordered by uid.
pub fn list_pins(&self) -> Vec<Pin> {
self.db
-6
View File
@@ -259,9 +259,6 @@ impl Db {
if let Some(rowid) = rowid {
tx.execute("DELETE FROM nodes_fts WHERE rowid = ?1", params![rowid])?;
}
// A pin outlives its node otherwise, listed as kept offline with no
// path left to unpin it by.
tx.execute("DELETE FROM pins WHERE uid = ?1", params![uid])?;
tx.commit()?;
Ok(())
}
@@ -302,9 +299,6 @@ impl Db {
if let Some(rowid) = rowid {
tx.execute("DELETE FROM nodes_fts WHERE rowid = ?1", params![rowid])?;
}
// A pin outlives its node otherwise, listed as kept offline with no
// path left to unpin it by.
tx.execute("DELETE FROM pins WHERE uid = ?1", params![uid])?;
tx.execute("DELETE FROM pending_op WHERE id = ?1", params![op_id])?;
if let Some(name) = name {
wake_ops_waiting_for_tx(&tx, &name)?;
-15
View File
@@ -38,21 +38,6 @@ impl Db {
Ok(n > 0)
}
/// Drop every pin recorded under `path`. Returns the uids it dropped.
///
/// For a pin whose node is gone: the path no longer resolves to a uid, and
/// the recorded path is all that is left to name the pin by.
pub fn pin_remove_by_path(&self, path: &str) -> Result<Vec<String>> {
let conn = self.conn.lock();
let mut stmt = conn.prepare("DELETE FROM pins WHERE path = ?1 RETURNING uid")?;
let rows = stmt.query_map(params![path], |r| r.get::<_, String>(0))?;
let mut out = Vec::new();
for r in rows {
out.push(r?);
}
Ok(out)
}
/// Every directly-pinned entry, ordered by uid.
pub fn pin_list(&self) -> Result<Vec<PinRow>> {
let conn = self.read()?;
-34
View File
@@ -5841,40 +5841,6 @@ fn pin_add_list_remove_roundtrip() {
assert_eq!(db.pin_list().unwrap().len(), 1);
}
#[test]
fn deleting_a_node_drops_its_pin() {
// A pin that outlived its node stayed listed as kept offline, and the path
// it was listed by no longer resolved, so it could not be unpinned.
let db = Db::open_in_memory().unwrap();
db.upsert_node(&folder("root", None, "My Files")).unwrap();
db.upsert_node(&file("gone", "root", "gone.mkv", 1))
.unwrap();
db.upsert_node(&file("kept", "root", "kept.mkv", 1))
.unwrap();
let du = |l: &str| uid(l).to_string();
db.pin_add(&du("gone"), "gone.mkv", false).unwrap();
db.pin_add(&du("kept"), "kept.mkv", false).unwrap();
db.delete_node(&uid("gone")).unwrap();
let pins: Vec<String> = db.pin_list().unwrap().into_iter().map(|p| p.uid).collect();
assert_eq!(pins, vec![du("kept")]);
}
#[test]
fn a_pin_left_behind_is_removed_by_its_path() {
let db = Db::open_in_memory().unwrap();
db.pin_add("vol~gone", "Videos/gone.mkv", false).unwrap();
db.pin_add("vol~kept", "Videos/kept.mkv", false).unwrap();
assert_eq!(
db.pin_remove_by_path("Videos/gone.mkv").unwrap(),
vec!["vol~gone".to_string()]
);
assert!(db.pin_remove_by_path("Videos/gone.mkv").unwrap().is_empty());
assert_eq!(db.pin_list().unwrap().len(), 1);
}
#[test]
fn is_pinned_direct_without_node_row() {
// A direct pin counts even when the node was never hydrated into `nodes`.
-8
View File
@@ -22,14 +22,6 @@ use std::fmt;
/// Failures in a row after which an effect is reported as blocked.
pub const BLOCKED_AFTER: u32 = 5;
/// The kind of intent for a file or folder removed from disk because Drive
/// deleted it. The other kinds are named by [`Pending::intent`](crate::model::Pending::intent).
pub const DELETE_LOCAL: &str = "delete-local";
/// The kind of intent for a file or folder moved to Drive's trash because it
/// was deleted on disk.
pub const TRASH: &str = "trash";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EffectState {
/// Sent, or about to be; no result yet.
+1 -24
View File
@@ -900,11 +900,7 @@ impl Syncer {
continue;
}
outcome.local_changes += 1;
let intent = self.issue_effect(folder_id, rel, effect::DELETE_LOCAL);
let removed = removed_locally(std::fs::remove_file(&path));
let error = removed.as_ref().err().map(ToString::to_string);
self.settle_effect(intent.as_ref(), error.as_deref());
if let Err(e) = removed {
if let Err(e) = removed_locally(std::fs::remove_file(&path)) {
warn!(rel, error = %e, "sync: remove local file failed");
self.log_activity(
ActivityKind::Trash,
@@ -929,15 +925,12 @@ impl Syncer {
continue;
}
let remote = r.expect("remote deletion requires a remote file");
let intent = self.issue_effect(folder_id, rel, effect::TRASH);
let step = Instant::now();
let trashed = self
.rt
.block_on(self.drive.trash_nodes(std::slice::from_ref(&remote.uid)))
.and_then(batch::into_unit);
self.trace_call(Call::Trash, step.elapsed());
let error = trashed.as_ref().err().map(ToString::to_string);
self.settle_effect(intent.as_ref(), error.as_deref());
if let Err(e) = trashed {
warn!(rel, error = %e, "sync: trash remote failed");
self.log_activity(
@@ -985,21 +978,8 @@ impl Syncer {
.store
.sync_entries(folder_id)
.map_err(|e| format!("reload baseline: {e:?}"))?;
let intents: HashMap<String, StoredIntent> = delete_local_dirs
.iter()
.filter_map(|rel| {
let intent = self.issue_effect(folder_id, rel, effect::DELETE_LOCAL)?;
Some((rel.clone(), intent))
})
.collect();
for removal in remove_local_dirs(local_root, delete_local_dirs, &mut current) {
outcome.local_changes += 1;
// Kept is settled too: nothing is left to do about it.
let (rel, error) = match &removal {
DirRemoval::Removed(rel) | DirRemoval::Kept(rel, _) => (rel, None),
DirRemoval::Failed(rel, e) => (rel, Some(e.to_string())),
};
self.settle_effect(intents.get(rel), error.as_deref());
match removal {
DirRemoval::Removed(rel) => {
let _ = self.store.sync_entry_remove(folder_id, &rel);
@@ -1055,15 +1035,12 @@ impl Syncer {
);
continue;
}
let intent = self.issue_effect(folder_id, &rel, effect::TRASH);
let step = Instant::now();
let trashed = self
.rt
.block_on(self.drive.trash_nodes(&[uid]))
.and_then(batch::into_unit);
self.trace_call(Call::Trash, step.elapsed());
let error = trashed.as_ref().err().map(ToString::to_string);
self.settle_effect(intent.as_ref(), error.as_deref());
if let Err(e) = trashed {
warn!(rel, error = %e, "sync: trash remote folder failed");
self.log_activity(ActivityKind::Trash, base_name(&rel), e.to_string(), false);
+20 -37
View File
@@ -137,24 +137,15 @@ impl Syncer {
/// Write the intent of `op` before it is sent (`effect`). In shadow: a
/// failure to write it is logged, and the op is sent anyway.
fn issue_intent(&self, folder_id: i64, op: &Pending) -> Option<StoredIntent> {
self.issue_effect(folder_id, op.rel(), op.intent())
}
/// Write the intent of an effect of `kind` on `rel` before it is sent,
/// for the ops that are not a [`Pending`], such as a deletion.
pub(super) fn issue_effect(
&self,
folder_id: i64,
rel: &str,
kind: &'static str,
) -> Option<StoredIntent> {
let (intent, before) = match self
.store
.sync_intent_issue(folder_id, rel, kind, now_secs())
{
let (intent, before) = match self.store.sync_intent_issue(
folder_id,
op.rel(),
op.intent(),
now_secs(),
) {
Ok(issued) => issued,
Err(e) => {
debug!(id = folder_id, rel, error = ?e, "sync: cannot record an intent");
debug!(id = folder_id, rel = op.rel(), error = ?e, "sync: cannot record an intent");
return None;
}
};
@@ -165,8 +156,8 @@ impl Syncer {
self.trace_count(Count::UnsureResent, 1);
info!(
id = folder_id,
rel,
kind,
rel = op.rel(),
kind = op.intent(),
attempts = intent.attempts,
"sync: sending again an effect a stopped daemon may have made"
);
@@ -179,22 +170,17 @@ impl Syncer {
Some(intent)
}
/// Settle `intent` when its effect succeeded (`error` is `None`), or
/// keep it with the failure. No intent, when it could not be written,
/// does nothing.
pub(super) fn settle_effect(&self, intent: Option<&StoredIntent>, error: Option<&str>) {
let Some(intent) = intent else {
return;
};
let written = match error {
None => self.store.sync_intent_settle(intent.id),
Some(e) => {
/// Settle or keep `intent` by how its op ended.
fn settle_intent(&self, intent: &StoredIntent, op: &Pending, result: &Result<Applied, String>) {
let written = match result {
Ok(_) => self.store.sync_intent_settle(intent.id),
Err(e) => {
let state = effect::failed(intent.attempts);
if state == EffectState::Blocked && intent.state != EffectState::Blocked.name() {
warn!(
id = intent.folder_id,
rel = %intent.rel_path,
kind = %intent.kind,
rel = op.rel(),
kind = op.intent(),
attempts = intent.attempts,
error = %e,
"sync: an effect keeps failing"
@@ -204,12 +190,7 @@ impl Syncer {
}
};
if let Err(e) = written {
debug!(
id = intent.folder_id,
rel = %intent.rel_path,
error = ?e,
"sync: cannot settle an intent"
);
debug!(id = intent.folder_id, rel = op.rel(), error = ?e, "sync: cannot settle an intent");
}
}
@@ -313,7 +294,9 @@ impl Syncer {
let step = Instant::now();
let result = self.apply_one(folder_id, local_root, &op).await;
self.trace_call(op.call(), step.elapsed());
self.settle_effect(intent.as_ref(), result.as_ref().err().map(String::as_str));
if let Some(intent) = intent {
self.settle_intent(&intent, &op, &result);
}
self.progress_finished(folder_id);
let name = base_name(op.rel());
match &result {
+3 -6
View File
@@ -331,14 +331,11 @@ impl Syncer {
let _ = self.store.sync_entry_remove(folder_id, rel);
continue;
};
let intent = self.issue_effect(folder_id, rel, effect::TRASH);
let result = self
if let Err(e) = self
.rt
.block_on(self.drive.trash_nodes(&[uid]))
.and_then(batch::into_unit);
let error = result.as_ref().err().map(ToString::to_string);
self.settle_effect(intent.as_ref(), error.as_deref());
if let Err(e) = result {
.and_then(batch::into_unit)
{
warn!(rel, error = %e, "sync: trash remote failed");
self.log_activity(ActivityKind::Trash, base_name(rel), e.to_string(), false);
outcome.failed(&format!("{rel}: {e}"));
+1 -52
View File
@@ -320,14 +320,6 @@ impl<H: FilesHost> Files<H> {
}
}
}
// A queued revision is the whole file, so its length is the
// file's, whatever the tree says. The tree can be behind it: an
// upload that lands as the next write queues puts its own size
// back over the one that write stamped. Taken from the tree, a
// longer length left the copied bytes past the blob unauthored,
// and the commit refilled them from the older revision. A
// shorter one cut the file at that length (docs/BUGS.md B308).
let len = pending_base.as_ref().map_or(base.size, |p| p.meta.len);
let fh = st.open.open_writer(ino, || {
WriteHandle {
ino,
@@ -337,7 +329,7 @@ impl<H: FilesHost> Files<H> {
written: initial_written,
// Starts at the current size; reads in [0, base_size)
// come from the base until overwritten.
len,
len: base.size,
base_size: base.size,
base_mtime: base.mtime,
base_revision_id: base.revision_id.clone(),
@@ -985,49 +977,6 @@ mod tests {
assert_eq!(fx.open_count(ino), 0);
}
/// A queued edit is the whole file, so a write open over it starts at the
/// edit's length even when the tree still has an older, longer size.
/// Started at the tree's 23 bytes, the hole a write past the edit leaves
/// was refilled from the older revision at commit (B308).
#[test]
fn a_write_open_over_a_queued_edit_takes_the_edits_length() {
let fx = Fixture::new();
let ino = fx.add("f", false);
// The tree has the revision that landed as the edit was queued.
if let NodeKind::File { claimed_size, .. } =
&mut fx.state().entries.get_mut(&ino).unwrap().node.kind
{
*claimed_size = Some(23);
}
let path = fx._dir.0.join("queued");
std::fs::write(&path, b"mnopqrst").unwrap();
fx.writes.pending.lock().insert(
uid("f"),
PendingRevision {
path,
meta: StagedWrite {
uid: uid("f").to_string(),
len: 8,
base_size: 23,
base_mtime: 1,
authored: vec![(0, 8)],
complete: true,
based_on: None,
},
},
);
let fh = fx.files.open(ino, true).unwrap();
fx.files.write(ino, fh, 12, b"hijk").unwrap();
let st = fx.state();
let handle = st.open.by_fh(fh).unwrap();
assert_eq!(handle.len, 16);
// Everything is the user's: the edit, the hole and the write.
assert_eq!(handle.written.0, vec![(0, 16)]);
let mut bytes = vec![0; 16];
std::os::unix::fs::FileExt::read_exact_at(&*handle.file, &mut bytes, 0).unwrap();
assert_eq!(&bytes, b"mnopqrst\0\0\0\0hijk");
}
/// A write open over a partial queued edit has to fill its gaps from
/// Drive first. Offline it fails with the host's own error.
#[test]
-128
View File
@@ -68,8 +68,6 @@ original wording.
| Entry | Title | What is left |
|---|---|---|
| [B310](#b310--a-write-soon-after-a-create-landed-was-kept-as-a-conflict-copy-of-it) | A write soon after a create landed was kept as a conflict copy of it | Cause not found; seen once in CI |
| [B307](#b307--a-write-in-the-echoes-simulation-can-wait-20-s-for-a-drive-call-that-never-answers) | A write in the echoes simulation can wait 20 s for a Drive call that never answers | Cause not found; seen once in CI |
| [B275](#b275--on-a-slow-link-a-files-last-write-can-land-only-in-a-conflict-copy) | On a slow link, a file's last write can land only in a conflict copy | Cause not found; seen once in CI |
| [B273](#b273--a-restore-proposes-another-computers-paths-when-the-two-share-a-hostname) | A restore proposes another computer's paths when the two share a hostname | Not fixed |
| [B267](#b267--a-key-failure-at-a-start-from-a-warm-cache-shows-as-offline-for-good) | A key failure at a start from a warm cache shows as offline for good | Not fixed |
@@ -320,8 +318,6 @@ a live account since.
| Entry | Title |
|---|---|
| [B309](#b309--a-file-renamed-while-its-create-was-read-back-went-back-to-its-old-name) | A file renamed while its create was read back went back to its old name |
| [B308](#b308--a-write-opened-over-a-queued-edit-took-the-trees-older-size) | A write opened over a queued edit took the tree's older size |
| [B295](#b295--a-resize-the-scratch-file-refused-still-succeeded) | A resize the scratch file refused still succeeded |
| [B293](#b293--a-large-trash-never-lists-and-empty-trash-never-empties-it) | A large trash never lists, and Empty Trash never empties it |
| [B292](#b292--two-programs-changing-settings-at-once-lose-one-of-the-changes) | Two programs changing settings at once lose one of the changes |
@@ -413,130 +409,6 @@ a live account since.
Newest first.
### B310 — A write soon after a create landed was kept as a conflict copy of it
**Status:** Open
**Found:** 2026-11-28, CI on `main` at `d79c26f`
([run](https://github.com/narrrl/proton-drive-linux/actions/runs/46152926170), artifact
`simulation-diagnostics`): `one_client_on_a_good_link` seed 5. `e.md` was created with 28
bytes, and 0.6 s later `write e.md at 27 (47 bytes)` took 111 ms. The write landed only as
`e (sync-conflict …).md`, and `e.md` kept its 28 bytes. The daemon logged `the remote revision
changed under the queued write (expected 28 bytes at mtime 1795875819, found 28 at
1795875820)`. Seed 5 passed 30 runs locally on the same commit, and 25 on `9667b7d`.
**Where:** not located; the write's baseline, from `Files::install_writer` through
`Core::remote_baseline`, against `placeholder_base` in `crates/pdfs-fuse/src/drain.rs`
**Cause.** Not known. The baseline has no revision id and the placeholder's local mtime, one
second before the stamp Drive gave the create. That is the base of a write opened over the
create's placeholder (B113). But the create had landed long before the write, and the tree
should have had Drive's node with its revision id by then. `placeholder_base` maps exactly this
base to the create's revision, but only while the `placeholders` entry exists. Either the tree
still had the placeholder's stamp, or the entry was gone or never written. The log does not say
which.
**Fix.** Not done. A debug log of a failing run would show the write open's base
(`write open took the base the file has now`) and whether adoption saw a placeholder.
---
### B309 — A file renamed while its create was read back went back to its old name
**Status:** Fixed
**Found:** 2026-11-28, looping `one_client_on_a_good_link` seed 5 on `d79c26f` with debug logging,
after a CI failure of the same seed on that commit. It failed once in 38 runs:
`liveness: the queues did not drain within 4s`, with a rename owing `b.txt is still held by a node
whose trash or rename is queued`. Drive had `b.txt` with the bytes of the file created as `d`,
and the model had the file renamed over it.
**Where:** `Core::adopt_real_uid` in `crates/pdfs-fuse/src/drain/create.rs`
**Repro:** Create `d` and let its create land. While the drain reads the new node back, rename
`d` to `b.txt`, and let the rename land before the read-back answers.
**Cause.** Adoption keeps the tree's name while a rename is queued. It asks once before the
read-back (B161) and once under the tree lock (B152). A rename queued after the first look and
landed before the second leaves no op for either to see, and the read-back still has the old name.
The tree took `d` back while Drive had `b.txt`. A later `rename z/b.txt b.txt` then found no
`b.txt` to replace, so it queued no trash. On Drive the name was taken. The rename also counted
as a move away from `b.txt` (it left `z/b.txt`), so it waited on itself for four attempts.
**Fix.** Adoption notes where the tree has the node before the read-back. The tree moves an
entry when its rename is queued, so a placement that changed meanwhile keeps the tree's name and
folder, like a queued rename.
**Verified:** sim test `a_file_renamed_while_its_create_is_read_back_keeps_its_new_name`, which
holds the adoption's read-back until the rename has landed. It fails without the fix (the mount
shows `d`) and passes with it.
The CI failure of seed 5 itself is a different bug, B310.
---
### B308 — A write opened over a queued edit took the tree's older size
**Status:** Fixed (unverified)
**Found:** 2026-11-28, looping `one_client_with_stale_hashes_and_reordered_echoes` seed 4 under
`stress-ng --cpu 4 --cpu-load 70` while chasing B307. Three runs of 89 failed with `liveness: the
queues did not drain within 6s`, none with B307's 20 s stall. Run 45 ended with `a.txt` holding
`mnopqrstcdefhijk…` where the model has `mnopqrst\0\0\0\0hijk…`, and run 33 with `f.txt` cut at 62
bytes of 81.
**Where:** `crates/pdfs-vfs/src/files.rs` (`Files::install_writer`) and
`crates/pdfs-fuse/src/drain/revision.rs` (`Core::place_landed`)
**Repro:** Create `a.txt` with 23 bytes and let its upload start. As it lands, open `a.txt` with
`O_TRUNC`, write 8 bytes and close. Then open it again and write 4 bytes at offset 12.
**Cause.** Two steps, each harmless alone:
- `place_landed` asks `rebaseline_pending` whether a write is queued, and if none is, puts the node
it read back into the tree. A write queued between the two stamps its own size first, and the
landed node then puts the old size back. The tree said 23 bytes while the queued edit held 8.
- `install_writer` copies the queued blob into the new handle's scratch file and marks `[0, 8)` as
written, but it started the handle at the tree's size. With 23, the write at 12 left `[8, 12)`
unmarked, and the commit filled it from the 23-byte revision instead of zeros. Run 33 was the
same with a tree size below the queued edit's, so the handle was cut short.
**Fix.** A write open over a queued edit starts at the edit's length, since the blob is the whole
file. `place_landed` applies queued sizes to the node it read back before putting it in the tree,
as listings already do.
**Verified:** `a_write_open_over_a_queued_edit_takes_the_edits_length` in `pdfs-vfs` fails
without the fix (`left: 23, right: 16`) and passes with it. The seed-4 loop under load has not
been rerun on the fix yet.
The third failure, run 59, is likely the same cause by another route. The edit to `a.txt`
landed only as a conflict copy ("based on revision rev2, remote now at rev5"). The handle had
started at the tree's 23 bytes over the queued 8, so the hole at `[8, 12)` was unauthored and
the write was queued with `complete: false`. `is_own_self_supersede` only chains a complete write
onto a revision this daemon sealed, so the incomplete one forked. With the length fixed, the hole
counts as written and the write is complete.
---
### B307 — A write in the echoes simulation can wait 20 s for a Drive call that never answers
**Status:** Open
**Found:** 2026-11-28, CI on #210 ([run](https://github.com/narrrl/proton-drive-linux/actions/runs/46140440107)):
`one_client_with_stale_hashes_and_reordered_echoes`, profile `one-client-echoes` seed 4, failed
with `liveness: client 0: write c.bin at 25 (4 bytes) took 20.961719651s, over 2s`. #210
changes only the GUI, and the same seed passed 28 times locally on `cf2632a`. In the same run,
`three_clients_one_writer_each` seed 2 failed with `truncate c.bin to 12 took 2.089572866s`, which is
just over the budget and looks like runner load.
**Where:** not located; a foreground call bounded by `INTERACTIVE_CALL_TIMEOUT` in
`crates/pdfs-fuse/src/link.rs`
**Repro:** The client creates `c.bin`, writes to it, renames `d` over it, and lets the queue
settle. The next write into `c.bin` then succeeds, but only after 21 s.
**Cause.** Not known. 21 s is the 20 s `INTERACTIVE_CALL_TIMEOUT` plus about a second, so a
call the write waited on got no answer from the fake Drive and timed out. The echoes profile
delays, duplicates and reorders events, but it never drops a reply or stalls a call. So the
call either waited on something held elsewhere, or the fake left it without an answer.
**Fix.** Not done. Needs a reproduction under load with the state directory and `daemon.log`
of a failing run, which the simulation keeps.
---
### B306 — A change made as its node's create lands is refused with "Permission denied"
**Status:** Fixed (unverified)
-77
View File
@@ -11,21 +11,6 @@ scratch (user data in `staging/` and `recovery/` is never touched by this).
## [Unreleased]
## [4.0.0] — 2026-11-28
4.0.0 splits the daemon into services that each own their state. The sync engine, the mounted
files, Drive access, the database and the admission of background work each have a crate of
their own (`pdfs-sync`, `pdfs-vfs`, `pdfs-drive`, `pdfs-store`, `pdfs-sched`), and the daemon
builds them in `pdfs-daemon` (see [Architecture](ARCHITECTURE.md#40-from-one-daemon-to-composed-services)).
A sync pass now keeps track of what each side owes: it lists only what changed on Proton Drive,
trusts the watcher for the folder on disk, resumes a walk a restart cut short, and records every
effect it sends until the result is in. Small files go up in one request.
**Upgrading:** the database moves from schema 47 to 52 on first start. 3.10 and older refuse to
open it, so going back to 3.10 means removing the cache and letting it build again. Files in
`staging/` and `recovery/`, and synced folders on disk, are not touched by this. Nothing else
needs doing: configuration, sign-in and synced folders carry over.
Schema: **52**. New tables save a mirror folder's walk of Proton Drive (48). A finished walk is
kept, with a list of the folders that changed on Proton Drive since (49). Each mirror folder
counts the deletions it made in the last day (50). Each upload, download or folder a mirror pass
@@ -50,11 +35,6 @@ digest of what it sent (52).
its own directories, keyring entry, kernel keys and mountpoint, so a test account can run
alongside the account you use. `scripts/live-bench.py` uses it to time one edit, from the
write to the new revision on Proton Drive.
- **`pdfs diagnostics` lists the sync effects that have not settled.** An upload, download,
folder or deletion a synced folder's pass sent and has not heard a success for is listed,
oldest first, with how many times it was sent, how long ago, and its last error. Deletions on
either side are now recorded like the other effects, so one that keeps failing says so in the
journal too. The JSON report has them as `effects`.
- **`pdfs diagnostics` says how many uploads went up in one request.** It counts the uploads
since start that took the one-request path for small files and those that went up in blocks,
with their failures and times. If small files stop taking the one-request path, because
@@ -80,10 +60,6 @@ digest of what it sent (52).
any more.
### Changed
- **The tray has its own icons.** They are the app's folder, solid when everything is up to date,
with a badge for syncing, paused, a failing change or an expired sign-in, and hollow when
offline or stopped. They used to be stock icons from the desktop theme. They take the panel's
text colour like other tray icons, and the packages install them into the hicolor theme.
- **An upload into a folder and an edit of a synced file make fewer requests.** The key that
hashes a folder's file names is now read once per folder, not once per upload. A synced
folder no longer reads a file again before it sends an edit. It checks that nobody else
@@ -115,24 +91,6 @@ digest of what it sent (52).
first pass, and whenever the change feed lost track (#53).
### Fixed
- **A file renamed just as it reached Proton Drive keeps its new name.** If the rename landed
while the app was reading the new file back, the folder could show the old name again, and a
later rename over the new name waited and then failed (B309).
- **A write right after another can no longer bring back old bytes or cut the file short.** When
an upload landed just as the next edit to the same file was queued, the file could keep the
size of the upload that landed. A write opened next then started at that size, not the queued
edit's. If the landed size was larger, a gap the write left past the edit was filled from the
older revision instead of zeros. If it was smaller, the file was cut at that size. Seen in
the echoes simulation about once in 40 runs under CPU load (B308).
- **A file kept offline and then deleted can be made online only again.** Deleting or trashing a
file left its entry under Settings → Storage → Available offline, and making it online only
failed with "could not resolve", because its path no longer led anywhere. Deleting a file now
drops the entry with it, and an entry already left behind is removed by the path it is listed
under. The app also stops asking for that file's thumbnail every second.
- **A share can be stopped from Shared by me when its file was never opened here.** Stopping the
share, or changing its people or link, failed with "node is not present in any location" for a
file in a folder this computer had not loaded. Drive's own list of what you shared now counts as
proof that the file is yours.
- **Stopping a sync with "Also delete from Proton Drive" says that it deletes, and says so when
the deletion failed.** With the switch on, the dialog now reads "Stop Syncing and Delete
Folder?" and its button "Stop Syncing and Delete". If the folder stopped syncing but its folder
@@ -160,40 +118,6 @@ digest of what it sent (52).
tried. If any did not go through, a summary names it, with the reason or "not tried yet", and
offers to try only those again. If the service stopped answering, the page is reloaded first,
so it shows which items really changed.
- **Sign Out says what it could not finish.**
- If the service did not answer, the confirmation no longer reads as if no changes were waiting.
It says that this is not known.
- If your sign-in could not be removed from the keyring, a dialog says so and offers to try
again. Before, the sign-in page appeared while the sign-in was still saved.
- If Proton did not confirm that the session ended, a notice says where in your Proton account
you can end it.
- **A public link's settings change only when you save them.** Before, choosing Editor changed
the link at once, so anyone holding a viewer link could edit before the password you were about
to add was set. Removing the password also took effect at once. Now the role, the password and
the expiry are sent together by "Save Link Settings". Above that button is a line that says how
the link will work. Closing the dialog sends nothing. When you create a link, Enter in the
password field moves on to Expires instead of creating the link.
- **The Share dialog no longer shows a public link's address until you ask.** The row is titled by
what the link does, for example "Public viewer link", with how it works below. The eye button
shows the address, and reopening the dialog hides it again. An expired link offers no Copy;
"Edit Expiry" opens its settings instead. In Shared by me, an expired link's menu leads with
"Edit Link Expiry…".
- **Find Similar Photos counts files as well as photos.** A shot stored as a RAW and a JPEG moves
both to Trash. The footer now reads, for example, "Move 1 photo (2 files) to Trash", and each
card shows what its shot is stored as, such as "RAW + 1 more file". Each card says whether the
photo stays or moves to Trash, and each set's heading says how many of the set stay. A set wider
than the window still shows what happens to it.
- **The search window shows recent Drive files only to the account that opened them.** Before, an
empty search listed the last files opened from any account signed in on this computer. Now
each Drive file is remembered with its account. Recent Drive files from before this change are
no longer shown, because nobody can say whose they are. Preferences → Apps adds "Remember
recent files" and "Clear recent files", and a clear takes effect the next time the window
opens. See [Configuration](CONFIGURATION.md#prompt) for `remember_recent`.
- **Dragging onto a folder in Files says what the drop will do.** A label over the view reads, for
example, "Move 3 items to “Receipts”" for rows dragged within the app, and "Copy 3 items to
“Receipts”" for files dragged from a file manager browsing the drive. Files from elsewhere read
"Upload…". It also says how many items can't go there, such as the folder itself in a
selection.
- **A mirrored file whose upload went unanswered no longer gets a conflict copy of its own
edit.** Proton Drive can make a file and lose the answer. If the file was then written again
before the next sync, for example while the daemon was stopped, that sync saw two different
@@ -2676,7 +2600,6 @@ First stable release: FUSE files-on-demand mount, sync daemon under `proton-driv
- The outstanding FUSE defects tracked in `docs/BUGS.md`, plus a truncate defect, validated
by a new POSIX compliance suite for the filesystem.
[4.0.0]: https://github.com/narrrl/proton-drive-linux/releases/tag/v4.0.0
[3.10.0]: https://github.com/narrrl/proton-drive-linux/releases/tag/v3.10.0
[3.9.0]: https://github.com/narrrl/proton-drive-linux/releases/tag/v3.9.0
[3.8.1]: https://github.com/narrrl/proton-drive-linux/releases/tag/v3.8.1
-1
View File
@@ -196,7 +196,6 @@ Settings for `pdfs-prompt`.
| `terminal` | first installed of foot, ghostty, kitty, alacritty, wezterm, xterm | Terminal for `fzf` mode. `{cmd}` is replaced by the command; without it, the command is appended |
| `menu_limit` | `50` | Results shown in `dmenu` and `fzf` mode |
| `menu_icons` | `true` | File-type icons in launchers that support them |
| `remember_recent` | `true` | The `gtk` window remembers what it opens, in `prompt-history.json` under the state directory. It lists those files before a search and ranks them higher in one. A Drive file is shown only while the account that opened it is signed in. `false` clears the list the next time the window opens and keeps nothing more |
```json
{
+1 -1
View File
@@ -103,7 +103,7 @@ That URL follows `main`. To stay on releases, pin the input to a release tag ins
the tag to update:
```nix
inputs.proton-drive-linux.url = "github:narrrl/proton-drive-linux/v4.0.0";
inputs.proton-drive-linux.url = "github:narrrl/proton-drive-linux/v3.10.0";
```
Each release tag is built with Nix before the release is published.
-7
View File
@@ -80,13 +80,6 @@ Which program opens a file you pick is set under **Preferences → Apps → Open
offline. Its menu opens the app or `~/ProtonDrive`, pauses or resumes sync, and stops or connects
the service.
![The tray icons on a dark and a light panel](../images/tray-icons.png)
The icon is the app's folder. A solid folder is up to date. A badge in its corner says it is
syncing, paused, needs a look (a failing change), or needs you to sign in again (a lock). A hollow
folder means it is offline and showing cached files, and with a cross that the service is not
running or nobody is signed in. The icons take the panel's text colour.
- **GNOME** shows tray icons only with the
[AppIndicator extension](https://extensions.gnome.org/extension/615/appindicator-support/).
KDE Plasma and most other desktops show it without help.
+3 -12
View File
@@ -262,10 +262,7 @@ made again reaches Drive within a minute; the second fails without the inode che
The second reducer, `pdfs_sync::effect`, follows one effect a mirror pass sends: a folder made on
Drive, an upload, a new revision, a download, an adopted file or a conflict copy (the `Pending`
ops), and the deletions a pass makes: `trash` for a file or folder moved to Drive's trash because
it went from disk, `delete-local` for one removed from disk because Drive deleted it. A folder Drive
deleted that still holds something Drive never had is kept, and its intent settles: nothing is left
to do about it. Before an op is sent, its intent is written to `sync_intent` (schema 51): one row per
ops). Before an op is sent, its intent is written to `sync_intent` (schema 51): one row per
folder, path and kind, with the number of attempts and the time it was last sent. Its result
decides what happens next:
@@ -305,19 +302,13 @@ that went unanswered.
Otherwise nothing reads the intents to decide what to send. The apply step's own checks still
decide whether an effect that may have landed is sent again (B266 for a create, B39 for a
download). Trace counts: `unsure resent`, `retried`, `superseded`.
`pdfs diagnostics` lists the intents not settled yet, oldest first (at most 20, with the count of
all of them), with their kind, state, attempts, age and last error. The list is the
`effects` field of the JSON report.
download). Deletions on either side are not recorded yet. Trace counts: `unsure resent`,
`retried`, `superseded`.
**Tests:**
- the `effect::tests` unit tests;
- DB: `an_effect_intent_is_kept_until_it_is_settled_or_its_folder_changes`, and
`an_upload_notes_each_digest_it_sent_once`;
- sim `a_deletion_is_an_effect_until_it_lands`: a trash held on its way to Drive is listed
`issued` in `pdfs diagnostics`, and the list is empty once it lands, and once a file Drive
deleted is gone from disk;
- sim `an_effect_left_unsure_by_a_stop_is_sent_again_or_settled`: of two uploads a stopped daemon
left unsure, the one still needed is sent again and the other is settled;
- sim `a_mirror_create_whose_reply_was_lost_is_adopted_after_a_restart_and_its_edit_lands`:
+1 -6
View File
@@ -331,12 +331,7 @@ What the parts mean:
from; the apply step checks whether each already landed before it sends it. **`retried`**
counts effects sent again after a failure, and **`superseded`** counts unsettled effects of
earlier passes that were no longer needed. A `sync: an effect keeps failing` line names an
upload, download, folder or deletion that failed five times in a row.
The `sync effects not settled` lines in `pdfs diagnostics` list the oldest of these effects
now, one per line, for example
`folder 2 trash Old/report.pdf: retry, sent 3 times, 12m4s ago (timed out)`. `issued` means
sent and waiting for an answer, `unsure` means a stopped daemon sent it and the next pass has
not looked yet, and `retry` or `blocked` means it failed.
upload, download or folder that failed five times in a row.
Please include these lines when you report a slow folder.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.7 KiB

+1 -2
View File
@@ -9,7 +9,7 @@
# Build + install: cd packaging && makepkg -fi
pkgname=proton-drive-linux
pkgver=4.0.0
pkgver=3.10.0
pkgrel=1
pkgdesc="Unofficial Proton Drive client for Linux: files-on-demand FUSE mount, CLI, GTK4 app + tray"
arch=('x86_64')
@@ -71,7 +71,6 @@ package() {
"$pkgdir/etc/xdg/autostart/io.narl.proton-drive-linux-tray.desktop"
install -Dm644 "packaging/io.narl.proton-drive-linux.svg" \
"$pkgdir/usr/share/icons/hicolor/scalable/apps/io.narl.proton-drive-linux.svg"
install -Dm644 -t "$pkgdir/usr/share/icons/hicolor/scalable/status" crates/pdfs-gui/resources/icons/tray/*.svg
# systemd user service that runs the auto-mount daemon. Enabled per-user by
# the GUI on login (`systemctl --user enable --now proton-drive.service`).
@@ -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 = 4.0.0
pkgver = 3.10.0
pkgrel = 1
url = https://proton-drive.narl.io
install = proton-drive.install
@@ -23,15 +23,15 @@ 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=4.0.0
provides = proton-drive-linux=4.0.0
provides = proton-drive-for-linux=3.10.0
provides = proton-drive-linux=3.10.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-4.0.0-x86_64.tar.gz::https://github.com/narrrl/proton-drive-linux/releases/download/v4.0.0/proton-drive-linux-4.0.0-x86_64.tar.gz
sha256sums = e7f7f17f6c418ce26a8070abd0a10828112d25e77b70e6130d0e9bdabaafd2da
source = proton-drive-linux-3.10.0-x86_64.tar.gz::https://github.com/narrrl/proton-drive-linux/releases/download/v3.10.0/proton-drive-linux-3.10.0-x86_64.tar.gz
sha256sums = 464986f2516ecbe249f98570189bfd36c2f372205c4095eccd515325f113c651
pkgname = proton-drive-for-linux-bin
@@ -1,7 +1,7 @@
# Maintainer: Nils Pukropp <contact@narl.io>
pkgname=proton-drive-for-linux-bin
pkgver=4.0.0
pkgver=3.10.0
pkgrel=1
pkgdesc="Unofficial Proton Drive client: FUSE files-on-demand mount, CLI, GTK4 app, tray (binaries)"
arch=('x86_64')
@@ -29,7 +29,7 @@ _tag="v$pkgver"
# (desktop files, icon, user service, translations, completions) in a /usr-like
# tree under one directory.
source=("proton-drive-linux-$pkgver-x86_64.tar.gz::$_repo/releases/download/$_tag/proton-drive-linux-$pkgver-x86_64.tar.gz")
sha256sums=('e7f7f17f6c418ce26a8070abd0a10828112d25e77b70e6130d0e9bdabaafd2da')
sha256sums=('464986f2516ecbe249f98570189bfd36c2f372205c4095eccd515325f113c651')
package() {
cd "$srcdir/proton-drive-linux-$pkgver-x86_64"
@@ -44,8 +44,6 @@ package() {
"$pkgdir/etc/xdg/autostart/io.narl.proton-drive-linux-tray.desktop"
install -Dm644 share/icons/hicolor/scalable/apps/io.narl.proton-drive-linux.svg \
"$pkgdir/usr/share/icons/hicolor/scalable/apps/io.narl.proton-drive-linux.svg"
install -Dm644 -t "$pkgdir/usr/share/icons/hicolor/scalable/status" \
share/icons/hicolor/scalable/status/*.svg
# systemd user unit for the auto-mount daemon; enabled per user, not by pacman.
install -Dm644 lib/systemd/user/proton-drive.service \
@@ -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 = 4.0.0.r0.g153e8e9
pkgver = 3.10.0.r0.g5ffaa2c
pkgrel = 1
url = https://proton-drive.narl.io
install = proton-drive.install
@@ -26,8 +26,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=4.0.0.r0.g153e8e9
provides = proton-drive-linux=4.0.0.r0.g153e8e9
provides = proton-drive-for-linux=3.10.0.r0.g5ffaa2c
provides = proton-drive-linux=3.10.0.r0.g5ffaa2c
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=4.0.0.r0.g153e8e9
pkgver=3.10.0.r0.g5ffaa2c
pkgrel=1
pkgdesc="Unofficial Proton Drive client: FUSE files-on-demand mount, CLI, GTK4 app, tray (git)"
arch=('x86_64')
@@ -75,7 +75,6 @@ package() {
"$pkgdir/etc/xdg/autostart/io.narl.proton-drive-linux-tray.desktop"
install -Dm644 packaging/io.narl.proton-drive-linux.svg \
"$pkgdir/usr/share/icons/hicolor/scalable/apps/io.narl.proton-drive-linux.svg"
install -Dm644 -t "$pkgdir/usr/share/icons/hicolor/scalable/status" crates/pdfs-gui/resources/icons/tray/*.svg
# systemd user unit for the auto-mount daemon; enabled per user, not by pacman.
install -Dm644 packaging/proton-drive.service \
@@ -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 = 4.0.0
pkgver = 3.10.0
pkgrel = 1
url = https://proton-drive.narl.io
install = proton-drive.install
@@ -25,15 +25,15 @@ 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=4.0.0
provides = proton-drive-linux=3.10.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-4.0.0.tar.gz::https://github.com/narrrl/proton-drive-linux/archive/refs/tags/v4.0.0.tar.gz
source = proton-drive-for-linux-3.10.0.tar.gz::https://github.com/narrrl/proton-drive-linux/archive/refs/tags/v3.10.0.tar.gz
source = basemap-v1.pmtiles::https://github.com/narrrl/proton-rs/releases/download/basemap-v1/basemap-v1.pmtiles
sha256sums = 59cfe5dc1172be6fa73cda898cfe70081d74582e8064168dde3758ed765affa4
sha256sums = 181abf766bed0ab7b3a7f1c1c0092e93d18ce945eb98816f5eb2c549dc8f13ad
sha256sums = ce9acab1b7ed7f15b23e2365b1b6a580db79f4bc4421851ee673eff4c920d280
pkgname = proton-drive-for-linux
@@ -1,7 +1,7 @@
# Maintainer: Nils Pukropp <contact@narl.io>
pkgname=proton-drive-for-linux
pkgver=4.0.0
pkgver=3.10.0
pkgrel=1
pkgdesc="Unofficial Proton Drive client: files-on-demand FUSE mount, CLI, GTK4 app and tray"
arch=('x86_64')
@@ -27,7 +27,7 @@ options=('!lto')
install=proton-drive.install
source=("$pkgname-$pkgver.tar.gz::$_repo/archive/refs/tags/v$pkgver.tar.gz"
"basemap-v1.pmtiles::https://github.com/narrrl/proton-rs/releases/download/basemap-v1/basemap-v1.pmtiles")
sha256sums=('59cfe5dc1172be6fa73cda898cfe70081d74582e8064168dde3758ed765affa4'
sha256sums=('181abf766bed0ab7b3a7f1c1c0092e93d18ce945eb98816f5eb2c549dc8f13ad'
'ce9acab1b7ed7f15b23e2365b1b6a580db79f4bc4421851ee673eff4c920d280')
_srcname="proton-drive-linux-$pkgver"
@@ -70,7 +70,6 @@ package() {
"$pkgdir/etc/xdg/autostart/io.narl.proton-drive-linux-tray.desktop"
install -Dm644 packaging/io.narl.proton-drive-linux.svg \
"$pkgdir/usr/share/icons/hicolor/scalable/apps/io.narl.proton-drive-linux.svg"
install -Dm644 -t "$pkgdir/usr/share/icons/hicolor/scalable/status" crates/pdfs-gui/resources/icons/tray/*.svg
# systemd user unit for the auto-mount daemon; enabled per user, not by pacman.
install -Dm644 packaging/proton-drive.service \
-1
View File
@@ -103,7 +103,6 @@ rustPlatform.buildRustPackage {
$out/etc/xdg/autostart/io.narl.proton-drive-linux-tray.desktop
install -Dm644 packaging/io.narl.proton-drive-linux.svg \
$out/share/icons/hicolor/scalable/apps/io.narl.proton-drive-linux.svg
install -Dm644 -t $out/share/icons/hicolor/scalable/status crates/pdfs-gui/resources/icons/tray/*.svg
substituteInPlace $out/share/applications/io.narl.proton-drive-linux.desktop \
--replace-fail "Exec=pdfs-app" "Exec=$out/bin/pdfs-app"
substituteInPlace $out/etc/xdg/autostart/io.narl.proton-drive-linux-tray.desktop \
+1 -4
View File
@@ -10,7 +10,7 @@
# Match Arch PKGBUILD `!lto` — LTO has broken some GTK/Rust links in practice.
%global _lto_cflags %{nil}
%{!?version: %global version 4.0.0}
%{!?version: %global version 3.10.0}
%global forge https://github.com/narrrl/proton-drive-linux
# Files come from the checkout, or from the unpacked tag archive.
%global src %{?git_dir}%{!?git_dir:.}
@@ -119,8 +119,6 @@ install -D -m0644 %{src}/packaging/io.narl.proton-drive-linux-tray.desktop \
%{buildroot}%{_sysconfdir}/xdg/autostart/io.narl.proton-drive-linux-tray.desktop
install -D -m0644 %{src}/packaging/io.narl.proton-drive-linux.svg \
%{buildroot}%{_datadir}/icons/hicolor/scalable/apps/io.narl.proton-drive-linux.svg
install -D -m0644 -t %{buildroot}%{_datadir}/icons/hicolor/scalable/status \
%{src}/crates/pdfs-gui/resources/icons/tray/*.svg
install -D -m0644 %{src}/packaging/io.narl.proton-drive-linux.policy \
%{buildroot}/usr/share/polkit-1/actions/io.narl.proton-drive-linux.policy
install -D -m0644 %{src}/packaging/proton-drive.service \
@@ -168,7 +166,6 @@ fi
%{_datadir}/applications/io.narl.proton-drive-linux.desktop
%{_sysconfdir}/xdg/autostart/io.narl.proton-drive-linux-tray.desktop
%{_datadir}/icons/hicolor/scalable/apps/io.narl.proton-drive-linux.svg
%{_datadir}/icons/hicolor/scalable/status/io.narl.proton-drive-linux-tray-*-symbolic.svg
/usr/lib/systemd/user/proton-drive.service
%{_datadir}/polkit-1/actions/io.narl.proton-drive-linux.policy
%{_datadir}/locale/*/LC_MESSAGES/pdfs.mo
-1
View File
@@ -32,7 +32,6 @@ install -Dm644 "$repo/packaging/io.narl.proton-drive-linux-tray.desktop" \
"$root/etc/xdg/autostart/io.narl.proton-drive-linux-tray.desktop"
install -Dm644 "$repo/packaging/io.narl.proton-drive-linux.svg" \
"$root/share/icons/hicolor/scalable/apps/io.narl.proton-drive-linux.svg"
install -Dm644 -t "$root/share/icons/hicolor/scalable/status" "$repo"/crates/pdfs-gui/resources/icons/tray/*.svg
install -Dm644 "$repo/packaging/io.narl.proton-drive-linux.policy" \
"$root/share/polkit-1/actions/io.narl.proton-drive-linux.policy"
install -Dm644 "$repo/packaging/proton-drive.service" \
-1
View File
@@ -63,7 +63,6 @@ grep -qx "Exec=\"$prefix/bin/pdfs-tray\"" "$tray" || fail "the tray's Exec= was
grep -qx "ExecStart=\"$prefix/bin/pdfs\" daemon" "$unit" || fail "ExecStart= was not rewritten: $(grep ^ExecStart= "$unit")"
[ -f "$prefix/share/locale/de/LC_MESSAGES/pdfs.mo" ] || fail "no translations"
[ -f "$prefix/share/icons/hicolor/scalable/apps/io.narl.proton-drive-linux.svg" ] || fail "no icon"
[ -f "$prefix/share/icons/hicolor/scalable/status/io.narl.proton-drive-linux-tray-synced-symbolic.svg" ] || fail "no tray icons"
[ -f "$prefix/share/bash-completion/completions/pdfs" ] || fail "no bash completion"
[ -f "$prefix/share/proton-drive-linux/basemap-v1.pmtiles" ] || fail "no Places basemap"
[ ! -e "$prefix/share/proton-drive-linux/managed-updates" ] || fail "the update check must stay on offer"
+428 -633
View File
File diff suppressed because it is too large. Load diff
+454 -656
View File
File diff suppressed because it is too large. Load diff
+427 -629
View File
File diff suppressed because it is too large. Load diff
+428 -632
View File
File diff suppressed because it is too large. Load diff
+428 -632
View File
File diff suppressed because it is too large. Load diff
+428 -631
View File
File diff suppressed because it is too large. Load diff
+421 -600
View File
File diff suppressed because it is too large. Load diff
+428 -636
View File
File diff suppressed because it is too large. Load diff
+427 -630
View File
File diff suppressed because it is too large. Load diff
-191
View File
@@ -1,191 +0,0 @@
#!/usr/bin/env python3
"""Write the tray's symbolic status icons to crates/pdfs-gui/resources/icons/tray/.
Each icon is the app icon's folder, reduced to one colour on a 16 px grid,
with a small badge for the state in a bite out of its lower right corner.
Panels recolour symbolic icons, and several do it by forcing the fill of
every path, rect and circle. So every shape here is a filled path in one
colour: no strokes, masks or opacity. Holes come from the even-odd rule.
Run it again after changing a shape: python3 -I scripts/render-tray-icons.py
"""
import math
import pathlib
OUT = (
pathlib.Path(__file__).resolve().parent.parent
/ "crates" / "pdfs-gui" / "resources" / "icons" / "tray"
)
PREFIX = "io.narl.proton-drive-linux-tray"
# The badge sits on a circle of radius BITE around (CX, CY), and the folder
# keeps a one-pixel gap from it.
CX, CY, BITE = 12.0, 12.0, 4.5
def f(v):
return f"{v:.3f}".rstrip("0").rstrip(".")
def pt(x, y):
return f"{f(x)} {f(y)}"
def polar(r, deg):
a = math.radians(deg)
return CX + r * math.cos(a), CY + r * math.sin(a)
def circle(cx, cy, r):
return (
f"M{pt(cx - r, cy)}A{f(r)} {f(r)} 0 1 0 {pt(cx + r, cy)}"
f"A{f(r)} {f(r)} 0 1 0 {pt(cx - r, cy)}Z"
)
def rounded_rect(x0, y0, x1, y1, r):
return (
f"M{pt(x0 + r, y0)}H{f(x1 - r)}Q{pt(x1, y0)} {pt(x1, y0 + r)}"
f"V{f(y1 - r)}Q{pt(x1, y1)} {pt(x1 - r, y1)}H{f(x0 + r)}"
f"Q{pt(x0, y1)} {pt(x0, y1 - r)}V{f(y0 + r)}Q{pt(x0, y0)} {pt(x0 + r, y0)}Z"
)
def bite_from_right(x, y_bottom):
"""The bite's arc, from where it crosses the edge x = `x` to where it
crosses the edge y = `y_bottom`, going round its upper left."""
y = CY - math.sqrt(BITE**2 - (x - CX) ** 2)
bx = CX - math.sqrt(BITE**2 - (y_bottom - CY) ** 2)
return y, f"A{f(BITE)} {f(BITE)} 0 0 0 {pt(bx, y_bottom)}"
# The back of the folder: its tab, and the band the front flap leaves.
# Its lower edge follows the front flap's top 0.75 px higher.
BACK = (
"M1 3.5Q1 2.5 2 2.5H5.6Q6.1 2.5 6.45 2.85L7.4 3.8Q7.6 4 7.9 4"
"H14Q15 4 15 5V6.75H7.05L5.8 5.5H1Z"
)
# The front flap has a tab of its own, as in the app icon, so the two
# flaps read as the app's folder rather than a stock one.
FRONT_TOP = (
"M1 7.25Q1 6.25 2 6.25H5.2Q5.6 6.25 5.9 6.55L6.6 7.25Q6.85 7.5 7.2 7.5"
"H14Q15 7.5 15 8.5"
)
RIGHT, BOTTOM = 15.0, 13.5
def front(bitten):
if not bitten:
return FRONT_TOP + "V12.5Q15 13.5 14 13.5H2Q1 13.5 1 12.5Z"
y, arc = bite_from_right(RIGHT, BOTTOM)
return FRONT_TOP + f"V{f(y)}{arc}H2Q1 13.5 1 12.5Z"
def front_hole(bitten):
"""The inside of a hollow front flap: a 1.25 px wall below its tab."""
x0, y0, x1, y1 = 2.25, 8.75, 13.75, 12.25
if not bitten:
return f"M{pt(x0, y0)}H{f(x1)}V{f(y1)}H{f(x0)}Z"
# The bite crosses the top of the hole, not its right side.
tx = CX - math.sqrt(BITE**2 - (y0 - CY) ** 2)
bx = CX - math.sqrt(BITE**2 - (y1 - CY) ** 2)
return (
f"M{pt(x0, y0)}H{f(tx)}A{f(BITE)} {f(BITE)} 0 0 0 {pt(bx, y1)}"
f"H{f(x0)}Z"
)
def arrow(start, end, inner=1.9, outer=3.1, head=0.85):
"""A thick arc from `start` to `end` degrees, clockwise on screen, with an
arrowhead at `end`."""
mid = (inner + outer) / 2
steps = 8
out = [polar(outer, start + (end - start) * i / steps) for i in range(steps + 1)]
inn = [polar(inner, end - (end - start) * i / steps) for i in range(steps + 1)]
tip = polar(mid, end + 42)
head_out = polar(outer + head, end)
head_in = polar(inner - head, end)
points = out + [head_out, tip, head_in] + inn
return "M" + "L".join(pt(*p) for p in points) + "Z"
def bars(points):
return "M" + "L".join(pt(CX + x, CY + y) for x, y in points) + "Z"
def cross(length=2.6, width=0.65):
a, w = length / math.sqrt(2), width / math.sqrt(2)
# A plus sign turned 45 degrees: twelve corners.
pts = [
(0, -2 * w), (a - w, -a - w), (a + w, -a + w), (2 * w, 0),
(a + w, a - w), (a - w, a + w), (0, 2 * w), (-a + w, a + w),
(-a - w, a - w), (-2 * w, 0), (-a - w, -a + w), (-a + w, -a - w),
]
return bars(pts)
def lock():
body = rounded_rect(9.5, 11.6, 14.5, 14.8, 0.6)
# The shackle: half a ring, open at the bottom where it meets the body.
ro, ri, cy = 1.9, 1.05, 11.6
shackle = (
f"M{pt(CX - ro, cy)}V{f(cy - 0.1)}A{f(ro)} {f(ro)} 0 0 1 {pt(CX + ro, cy - 0.1)}"
f"V{f(cy)}H{f(CX + ri)}V{f(cy - 0.1)}A{f(ri)} {f(ri)} 0 0 0 {pt(CX - ri, cy - 0.1)}"
f"V{f(cy)}Z"
)
return shackle + body
# A disc with the badge's mark cut out, for the states that need a look.
def disc_with(mark):
return circle(CX, CY, 3.5) + mark
BADGES = {
"syncing": arrow(200, 320) + arrow(20, 140),
"paused": rounded_rect(9.7, 9.25, 11.2, 14.75, 0.4)
+ rounded_rect(12.8, 9.25, 14.3, 14.75, 0.4),
"attention": disc_with(
rounded_rect(11.3, 9.5, 12.7, 12.6, 0.5) + circle(12, 14.05, 0.75)
),
"session-expired": lock(),
"disconnected": cross(),
}
# State: (hollow front flap, badge).
ICONS = {
"synced": (False, None),
"syncing": (False, "syncing"),
"paused": (False, "paused"),
"attention": (False, "attention"),
"session-expired": (False, "session-expired"),
"offline": (True, None),
"disconnected": (True, "disconnected"),
}
TEMPLATE = """<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<!-- Generated by scripts/render-tray-icons.py; edit that, not this. -->
<style>.ColorScheme-Text{{color:#2e3436}}</style>
<path class="ColorScheme-Text" fill="currentColor" fill-rule="evenodd" d="{d}"/>
</svg>
"""
def main():
OUT.mkdir(parents=True, exist_ok=True)
for name, (hollow, badge) in ICONS.items():
bitten = badge is not None
d = BACK + front(bitten)
if hollow:
d += front_hole(bitten)
if badge:
d += BADGES[badge]
path = OUT / f"{PREFIX}-{name}-symbolic.svg"
path.write_text(TEMPLATE.format(d=d))
print(path.relative_to(OUT.parents[4]))
if __name__ == "__main__":
main()