mirror of
https://github.com/narrrl/proton-drive-linux.git
synced 2026-11-28 20:12:14 +01:00
Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
99f76ba95f | ||
|
|
bb13097604 | ||
|
|
58bbac76aa | ||
|
|
1e041150f3 | ||
|
|
61dcdf3493 | ||
|
|
bbd4784ccf | ||
|
|
c747802240 | ||
|
|
d0efbcddeb | ||
|
|
79d4013b8c | ||
|
|
e5f37d8359 | ||
|
|
3a02c56440 | ||
|
|
40484bbbae | ||
|
|
6803571802 | ||
|
|
861af49d22 | ||
|
|
c5f40f63b2 | ||
|
|
7e12c747a0 | ||
|
|
8881c79f15 | ||
|
|
f975d9cf17 | ||
|
|
deb15a3327 | ||
|
|
8c7a0a8a17 | ||
|
|
9533ebcdfc | ||
|
|
ccc679eef5 | ||
|
|
d1421a84b1 | ||
|
|
670ec7db31 | ||
|
|
30b20fc444 | ||
|
|
5c6360e6e7 | ||
|
|
42926b71a9 | ||
|
|
21e7c03460 |
No files matched your search
@@ -17,6 +17,9 @@ jobs:
|
||||
|
||||
- name: Install native dependencies
|
||||
run: |
|
||||
# The runner image lists Microsoft's apt repository, which nothing here
|
||||
# needs and which at times answers 403 and fails the update.
|
||||
grep -rl packages.microsoft.com /etc/apt/sources.list.d/ | xargs -r sudo rm -f || true
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y \
|
||||
pkg-config \
|
||||
@@ -80,6 +83,9 @@ jobs:
|
||||
|
||||
- name: Install native dependencies
|
||||
run: |
|
||||
# The runner image lists Microsoft's apt repository, which nothing here
|
||||
# needs and which at times answers 403 and fails the update.
|
||||
grep -rl packages.microsoft.com /etc/apt/sources.list.d/ | xargs -r sudo rm -f || true
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y \
|
||||
pkg-config \
|
||||
@@ -129,6 +135,9 @@ jobs:
|
||||
|
||||
- name: Install native dependencies
|
||||
run: |
|
||||
# The runner image lists Microsoft's apt repository, which nothing here
|
||||
# needs and which at times answers 403 and fails the update.
|
||||
grep -rl packages.microsoft.com /etc/apt/sources.list.d/ | xargs -r sudo rm -f || true
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y \
|
||||
pkg-config \
|
||||
|
||||
@@ -20,6 +20,9 @@ jobs:
|
||||
|
||||
- name: Install system dependencies
|
||||
run: |
|
||||
# The runner image lists Microsoft's apt repository, which nothing here
|
||||
# needs and which at times answers 403 and fails the update.
|
||||
grep -rl packages.microsoft.com /etc/apt/sources.list.d/ | xargs -r sudo rm -f || true
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y \
|
||||
pkg-config \
|
||||
@@ -75,6 +78,9 @@ jobs:
|
||||
|
||||
- name: Install system dependencies
|
||||
run: |
|
||||
# The runner image lists Microsoft's apt repository, which nothing here
|
||||
# needs and which at times answers 403 and fails the update.
|
||||
grep -rl packages.microsoft.com /etc/apt/sources.list.d/ | xargs -r sudo rm -f || true
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y \
|
||||
pkg-config \
|
||||
|
||||
Generated
+4
-4
@@ -4071,9 +4071,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "proton-drive-rs"
|
||||
version = "0.12.6"
|
||||
version = "0.12.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8b1a71d0e737a9bd6cff07105218e7bef3bddcfd9d6651646d7302cdbba71961"
|
||||
checksum = "11c09c245784d7253072b751e43b1919140fdbc8641c5328a7e2801889c86041"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.23.1",
|
||||
@@ -4191,9 +4191,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "proton-sdk"
|
||||
version = "0.12.6"
|
||||
version = "0.12.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "81edef2b4b174e936a3537793ee901b92dd7c0484eb7fed09ad69432f407f86b"
|
||||
checksum = "7a6ed261fbcabf35abe67ebf8c8aff85b01fc43aef5b298380a6e6f7d3dd31d3"
|
||||
dependencies = [
|
||||
"aes-gcm 0.11.1",
|
||||
"async-trait",
|
||||
|
||||
+2
-2
@@ -15,8 +15,8 @@ keywords = ["proton", "drive", "fuse", "sync", "linux"]
|
||||
categories = ["filesystem", "command-line-utilities"]
|
||||
|
||||
[workspace.dependencies]
|
||||
proton-sdk = { version = "0.12.6" }
|
||||
proton-drive-rs = { version = "0.12.6" }
|
||||
proton-sdk = { version = "0.12.8" }
|
||||
proton-drive-rs = { version = "0.12.8" }
|
||||
proton-gallery-app-rs = "0.1.0"
|
||||
proton-gallery-rs = "0.1.5"
|
||||
proton-map-rs = "0.1.0"
|
||||
|
||||
@@ -389,6 +389,15 @@ pub(super) fn cmd_diagnostics() -> Result<()> {
|
||||
);
|
||||
}
|
||||
}
|
||||
if d.upload_paths.iter().any(|stat| stat.count > 0) {
|
||||
println!("uploads since start, by path:");
|
||||
for stat in &d.upload_paths {
|
||||
println!(
|
||||
" {:<38} {:>7} files {:>5} failed {:>9} ms total {:>7} ms longest",
|
||||
stat.path, stat.count, stat.errors, stat.total_ms, stat.longest_ms,
|
||||
);
|
||||
}
|
||||
}
|
||||
if d.inflight.is_empty() {
|
||||
println!("in-flight requests: none");
|
||||
} else {
|
||||
|
||||
@@ -38,7 +38,6 @@ use proton_sdk::error::ProtonError;
|
||||
use proton_sdk::http::Tokens;
|
||||
use proton_sdk::login::{self, LoginError, Step};
|
||||
use proton_sdk::session::{PasswordMode, ProtonApiSession, ResumeParameters};
|
||||
use proton_sdk::telemetry::TracingTelemetry;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
@@ -771,7 +770,7 @@ async fn migrate_legacy(
|
||||
/// default.
|
||||
fn tune(client: ProtonDriveClient, passphrases: &KeyPassphrases) -> ProtonDriveClient {
|
||||
let client = client
|
||||
.with_telemetry(TracingTelemetry::shared())
|
||||
.with_telemetry(crate::uploads::telemetry())
|
||||
.with_small_file_upload(true);
|
||||
match AppDirs::new().and_then(|dirs| crate::sdkcache::SdkCache::shared(&dirs)) {
|
||||
Ok(cache) => {
|
||||
|
||||
@@ -278,6 +278,12 @@ pub struct AppConfig {
|
||||
/// the field.
|
||||
#[serde(default)]
|
||||
pub local_first: Option<bool>,
|
||||
/// Send a file small enough, with its thumbnails, to fit 128 KiB in one
|
||||
/// request instead of three or more. `None` means on. `false` uploads
|
||||
/// every file in blocks, the way all files went before. Defaulted for
|
||||
/// configs predating the field.
|
||||
#[serde(default)]
|
||||
pub small_uploads: Option<bool>,
|
||||
/// Ask GitHub once a day whether a newer release is out, and say so in the
|
||||
/// desktop app. Off by default: GitHub then sees the address and version
|
||||
/// asking. Never used where a package manager installs updates (see
|
||||
@@ -1077,6 +1083,7 @@ mod tests {
|
||||
language: Some("de".to_string()),
|
||||
online_map: true,
|
||||
local_first: Some(false),
|
||||
small_uploads: Some(false),
|
||||
update_check: true,
|
||||
update_last_checked: Some(1_760_000_000),
|
||||
update_latest: Some("3.6.0".to_string()),
|
||||
@@ -1096,6 +1103,7 @@ mod tests {
|
||||
assert_eq!(decoded.update_latest.as_deref(), Some("3.6.0"));
|
||||
assert_eq!(decoded.language.as_deref(), Some("de"));
|
||||
assert_eq!(decoded.upload_limit, Some(500_000));
|
||||
assert_eq!(decoded.small_uploads, Some(false));
|
||||
assert_eq!(decoded.download_limit, None);
|
||||
assert_eq!(decoded.files_view, config.files_view);
|
||||
assert_eq!(decoded.photos_view, config.photos_view);
|
||||
|
||||
@@ -1171,6 +1171,15 @@ pub struct PendingOpInfo {
|
||||
/// Carries file content that [`Request::ExportPendingOp`] can save.
|
||||
#[serde(default)]
|
||||
pub exportable: bool,
|
||||
/// The node the op changes. A discard drops every op queued on the same
|
||||
/// node (see [`Request::DiscardPendingOp`]), so this tells which rows go
|
||||
/// together. Empty from a daemon that predates the field.
|
||||
#[serde(default)]
|
||||
pub node: String,
|
||||
/// The node was made on this computer and Drive has never had it. A
|
||||
/// discard removes it here, rather than putting back what Drive has.
|
||||
#[serde(default)]
|
||||
pub local_only: bool,
|
||||
}
|
||||
|
||||
/// Why Drive refused a queued change (in [`PendingOpInfo`]). The change stays
|
||||
@@ -2374,6 +2383,11 @@ pub struct Diagnostics {
|
||||
/// field.
|
||||
#[serde(default)]
|
||||
pub drive_calls: Vec<DriveCallStat>,
|
||||
/// Uploads since start, by how the SDK sent their content: `small` in one
|
||||
/// request, `blocks` as a draft, its blocks and a commit. Empty from a
|
||||
/// daemon that predates the field.
|
||||
#[serde(default)]
|
||||
pub upload_paths: Vec<UploadPathStat>,
|
||||
/// The daemon's long-lived threads, in start order, and whether each is
|
||||
/// still running. Empty from a daemon that predates the field.
|
||||
#[serde(default)]
|
||||
@@ -2433,6 +2447,17 @@ pub struct DriveCallStat {
|
||||
pub longest_ms: u64,
|
||||
}
|
||||
|
||||
/// Uploads that took one path, in [`Diagnostics::upload_paths`].
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct UploadPathStat {
|
||||
/// `small` or `blocks`.
|
||||
pub path: String,
|
||||
pub count: u64,
|
||||
pub errors: u64,
|
||||
pub total_ms: u64,
|
||||
pub longest_ms: u64,
|
||||
}
|
||||
|
||||
/// What the folder-sync engine is doing, for [`Diagnostics`].
|
||||
///
|
||||
/// The engine is one thread that runs every synced folder's passes in turn.
|
||||
|
||||
@@ -30,6 +30,7 @@ pub mod timestamp;
|
||||
pub mod transfers;
|
||||
pub mod tray;
|
||||
pub mod update;
|
||||
pub mod uploads;
|
||||
|
||||
// Photo logic shared with Proton Gallery through the proton-rs crates.
|
||||
pub use proton_gallery_rs::{exiftime, places, similar, takeout};
|
||||
|
||||
@@ -139,6 +139,11 @@ 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.
|
||||
@@ -158,6 +163,11 @@ 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()
|
||||
@@ -170,6 +180,10 @@ 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.
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
//! How the SDK sent each upload's content, counted from its telemetry.
|
||||
//!
|
||||
//! A file whose encrypted size is under 128 KiB goes up in one request
|
||||
//! (`small`). Any other file goes up as a draft, its blocks and a commit
|
||||
//! (`blocks`). The SDK picks the path inside each upload call and reports it
|
||||
//! only as the `backend` attribute of the `upload_file` and
|
||||
//! `upload_new_revision` timers, so this module counts those events. If the
|
||||
//! share of small uploads drops to zero for small files, the one-request path
|
||||
//! is off or the server refuses it, and `pdfs diagnostics` shows that.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use proton_sdk::telemetry::{Outcome, Telemetry, TelemetryEvent, TracingTelemetry};
|
||||
|
||||
/// The counts of every upload of this process, by path.
|
||||
pub static UPLOAD_PATHS: UploadPaths = UploadPaths::new();
|
||||
|
||||
/// Upload counts for each path.
|
||||
#[derive(Debug)]
|
||||
pub struct UploadPaths {
|
||||
small: PathStat,
|
||||
blocks: PathStat,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct PathStat {
|
||||
count: AtomicU64,
|
||||
errors: AtomicU64,
|
||||
total_ms: AtomicU64,
|
||||
longest_ms: AtomicU64,
|
||||
}
|
||||
|
||||
/// One path's counts at one moment.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct UploadPathStat {
|
||||
/// `small` or `blocks`.
|
||||
pub path: &'static str,
|
||||
pub count: u64,
|
||||
pub errors: u64,
|
||||
pub total_ms: u64,
|
||||
pub longest_ms: u64,
|
||||
}
|
||||
|
||||
impl PathStat {
|
||||
const fn new() -> Self {
|
||||
Self {
|
||||
count: AtomicU64::new(0),
|
||||
errors: AtomicU64::new(0),
|
||||
total_ms: AtomicU64::new(0),
|
||||
longest_ms: AtomicU64::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
fn add(&self, failed: bool, took: Duration) {
|
||||
let ms = u64::try_from(took.as_millis()).unwrap_or(u64::MAX);
|
||||
self.count.fetch_add(1, Ordering::Relaxed);
|
||||
if failed {
|
||||
self.errors.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
self.total_ms.fetch_add(ms, Ordering::Relaxed);
|
||||
self.longest_ms.fetch_max(ms, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
fn snapshot(&self, path: &'static str) -> UploadPathStat {
|
||||
UploadPathStat {
|
||||
path,
|
||||
count: self.count.load(Ordering::Relaxed),
|
||||
errors: self.errors.load(Ordering::Relaxed),
|
||||
total_ms: self.total_ms.load(Ordering::Relaxed),
|
||||
longest_ms: self.longest_ms.load(Ordering::Relaxed),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for UploadPaths {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl UploadPaths {
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
small: PathStat::new(),
|
||||
blocks: PathStat::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Count `event` if it is the end of an upload.
|
||||
pub fn record(&self, event: &TelemetryEvent) {
|
||||
if !matches!(event.operation, "upload_file" | "upload_new_revision") {
|
||||
return;
|
||||
}
|
||||
let backend = event
|
||||
.attributes
|
||||
.iter()
|
||||
.find_map(|(key, value)| (*key == "backend").then_some(value.as_str()));
|
||||
let stat = match backend {
|
||||
Some("small") => &self.small,
|
||||
Some("blocks") => &self.blocks,
|
||||
_ => return,
|
||||
};
|
||||
stat.add(event.outcome == Outcome::Failure, event.duration);
|
||||
}
|
||||
|
||||
/// The counts so far, small first.
|
||||
pub fn snapshot(&self) -> [UploadPathStat; 2] {
|
||||
[self.small.snapshot("small"), self.blocks.snapshot("blocks")]
|
||||
}
|
||||
}
|
||||
|
||||
/// The SDK's telemetry sink for this process: every event goes to `tracing`
|
||||
/// as before, and uploads are also counted in [`UPLOAD_PATHS`].
|
||||
pub fn telemetry() -> Arc<dyn Telemetry> {
|
||||
Arc::new(Counting {
|
||||
inner: TracingTelemetry::shared(),
|
||||
})
|
||||
}
|
||||
|
||||
struct Counting {
|
||||
inner: Arc<dyn Telemetry>,
|
||||
}
|
||||
|
||||
impl Telemetry for Counting {
|
||||
fn record(&self, event: &TelemetryEvent) {
|
||||
UPLOAD_PATHS.record(event);
|
||||
self.inner.record(event);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn event(operation: &'static str, backend: &str, outcome: Outcome, ms: u64) -> TelemetryEvent {
|
||||
TelemetryEvent {
|
||||
operation,
|
||||
outcome,
|
||||
duration: Duration::from_millis(ms),
|
||||
attributes: vec![
|
||||
("backend", backend.to_owned()),
|
||||
("aead", "false".to_owned()),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uploads_are_counted_by_the_path_the_sdk_took() {
|
||||
let paths = UploadPaths::new();
|
||||
paths.record(&event("upload_file", "small", Outcome::Success, 300));
|
||||
paths.record(&event(
|
||||
"upload_new_revision",
|
||||
"small",
|
||||
Outcome::Failure,
|
||||
500,
|
||||
));
|
||||
paths.record(&event("upload_file", "blocks", Outcome::Success, 2_000));
|
||||
|
||||
let [small, blocks] = paths.snapshot();
|
||||
assert_eq!(
|
||||
small,
|
||||
UploadPathStat {
|
||||
path: "small",
|
||||
count: 2,
|
||||
errors: 1,
|
||||
total_ms: 800,
|
||||
longest_ms: 500,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
(blocks.count, blocks.errors, blocks.longest_ms),
|
||||
(1, 0, 2_000)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_operations_and_events_without_a_backend_are_not_counted() {
|
||||
let paths = UploadPaths::new();
|
||||
paths.record(&event("http_request", "small", Outcome::Success, 10));
|
||||
paths.record(&TelemetryEvent {
|
||||
operation: "upload_file",
|
||||
outcome: Outcome::Success,
|
||||
duration: Duration::from_millis(10),
|
||||
attributes: Vec::new(),
|
||||
});
|
||||
|
||||
assert!(paths.snapshot().iter().all(|stat| stat.count == 0));
|
||||
}
|
||||
}
|
||||
@@ -241,6 +241,13 @@ pub fn mount_once(mountpoint: Option<PathBuf>) -> Result<pdfs_fuse::MountOutcome
|
||||
let (client, session) = rt
|
||||
.block_on(auth::resume_client())
|
||||
.context("resume session (run `pdfs login` first)")?;
|
||||
// On unless the config turns it off: the one-request upload for small
|
||||
// files is new, and this lets it be switched off without a new build.
|
||||
let small_uploads = config.small_uploads.unwrap_or(true);
|
||||
if !small_uploads {
|
||||
tracing::info!("small files are uploaded in blocks: small_uploads is off in the config");
|
||||
}
|
||||
let client = client.with_small_file_upload(small_uploads);
|
||||
|
||||
// Token updates are persisted automatically in real-time. The SDK session has
|
||||
// a token refresh callback registered during `resume_client` that writes updated
|
||||
|
||||
@@ -23,7 +23,7 @@ use proton_drive_rs::{
|
||||
Thumbnail, ThumbnailType, TrashedNode,
|
||||
};
|
||||
|
||||
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead};
|
||||
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead, RevisionUpload};
|
||||
|
||||
/// Every kind of call [`DriveApi`] makes, one per method.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -393,6 +393,30 @@ impl DriveApi for Counted {
|
||||
.await
|
||||
}
|
||||
|
||||
async fn upload_new_revision_over_dyn(
|
||||
&self,
|
||||
file_uid: &NodeUid,
|
||||
expected: &str,
|
||||
reader: &mut (dyn Read + Send),
|
||||
intended_size: i64,
|
||||
thumbnails: Vec<Thumbnail>,
|
||||
last_modification_time: Option<i64>,
|
||||
) -> Result<RevisionUpload> {
|
||||
// Counted with the other revision uploads: it is one, with its check.
|
||||
self.timed(
|
||||
DriveCall::UploadNewRevision,
|
||||
self.inner.upload_new_revision_over_dyn(
|
||||
file_uid,
|
||||
expected,
|
||||
reader,
|
||||
intended_size,
|
||||
thumbnails,
|
||||
last_modification_time,
|
||||
),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn open_revision(&self, uid: &NodeUid) -> Result<Arc<dyn RevisionRead>> {
|
||||
self.timed(DriveCall::OpenRevision, self.inner.open_revision(uid))
|
||||
.await
|
||||
|
||||
@@ -33,6 +33,8 @@ use proton_drive_rs::{
|
||||
NodeMoveItem, ProtonDriveClient, RevisionReader, Thumbnail, ThumbnailType, TrashedNode,
|
||||
};
|
||||
|
||||
pub use proton_drive_rs::{RevisionUpload, SealedUpload};
|
||||
|
||||
pub mod counted;
|
||||
pub mod digest;
|
||||
|
||||
@@ -120,6 +122,18 @@ pub trait DriveApi: Send + Sync {
|
||||
last_modification_time: Option<i64>,
|
||||
) -> Result<()>;
|
||||
|
||||
/// A new revision of `file_uid`, only over the revision `expected`. See
|
||||
/// [`ProtonDriveClient::upload_new_revision_over`].
|
||||
async fn upload_new_revision_over_dyn(
|
||||
&self,
|
||||
file_uid: &NodeUid,
|
||||
expected: &str,
|
||||
reader: &mut (dyn Read + Send),
|
||||
intended_size: i64,
|
||||
thumbnails: Vec<Thumbnail>,
|
||||
last_modification_time: Option<i64>,
|
||||
) -> Result<RevisionUpload>;
|
||||
|
||||
async fn open_revision(&self, uid: &NodeUid) -> Result<Arc<dyn RevisionRead>>;
|
||||
|
||||
/// The file's thumbnail of `thumbnail_type`, or `None` when its revision
|
||||
@@ -287,6 +301,26 @@ impl dyn DriveApi {
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn upload_new_revision_over<R: Read + Send>(
|
||||
&self,
|
||||
file_uid: &NodeUid,
|
||||
expected: &str,
|
||||
mut reader: R,
|
||||
intended_size: i64,
|
||||
thumbnails: Vec<Thumbnail>,
|
||||
last_modification_time: Option<i64>,
|
||||
) -> Result<RevisionUpload> {
|
||||
self.upload_new_revision_over_dyn(
|
||||
file_uid,
|
||||
expected,
|
||||
&mut reader,
|
||||
intended_size,
|
||||
thumbnails,
|
||||
last_modification_time,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn download_file_to<W: Write + Send>(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
@@ -468,6 +502,27 @@ impl DriveApi for ProtonDriveClient {
|
||||
.await
|
||||
}
|
||||
|
||||
async fn upload_new_revision_over_dyn(
|
||||
&self,
|
||||
file_uid: &NodeUid,
|
||||
expected: &str,
|
||||
reader: &mut (dyn Read + Send),
|
||||
intended_size: i64,
|
||||
thumbnails: Vec<Thumbnail>,
|
||||
last_modification_time: Option<i64>,
|
||||
) -> Result<RevisionUpload> {
|
||||
ProtonDriveClient::upload_new_revision_over(
|
||||
self,
|
||||
file_uid,
|
||||
expected,
|
||||
reader,
|
||||
intended_size,
|
||||
thumbnails,
|
||||
last_modification_time.and_then(pdfs_core::timestamp::modification_time),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn open_revision(&self, uid: &NodeUid) -> Result<Arc<dyn RevisionRead>> {
|
||||
let reader = ProtonDriveClient::open_revision(self, uid).await?;
|
||||
Ok(Arc::new(reader))
|
||||
|
||||
@@ -67,7 +67,7 @@ use proton_drive_rs::{
|
||||
use sha1::{Digest as _, Sha1};
|
||||
|
||||
use super::rng::Rng;
|
||||
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead};
|
||||
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead, RevisionUpload, SealedUpload};
|
||||
|
||||
/// The volume every fake node lives on.
|
||||
pub const VOLUME: &str = "simvol";
|
||||
@@ -1531,6 +1531,57 @@ impl DriveApi for FakeClient {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn upload_new_revision_over_dyn(
|
||||
&self,
|
||||
file_uid: &NodeUid,
|
||||
expected: &str,
|
||||
reader: &mut (dyn Read + Send),
|
||||
intended_size: i64,
|
||||
thumbnails: Vec<Thumbnail>,
|
||||
last_modification_time: Option<i64>,
|
||||
) -> Result<RevisionUpload> {
|
||||
// The SDK reads the file's link for its keys and checks the revision
|
||||
// on that read, so it is held, lags and counts like any other read.
|
||||
self.wait_if_held(&self.0.hold, std::slice::from_ref(file_uid))
|
||||
.await;
|
||||
let lag = self.lag();
|
||||
let seen = self
|
||||
.request(false, |server| {
|
||||
Ok(server
|
||||
.visible(file_uid, lag, Instant::now())
|
||||
.map(|remote| (remote.trashed, remote.file.map(|file| file.revision))))
|
||||
})
|
||||
.await?;
|
||||
match seen {
|
||||
None => return Err(api(ResponseCode::DoesNotExist, "file not found")),
|
||||
Some((true, _)) => return Ok(RevisionUpload::Trashed),
|
||||
Some((false, revision)) if revision.as_deref() != Some(expected) => {
|
||||
return Ok(RevisionUpload::Moved);
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
self.upload_new_revision_from_dyn(
|
||||
file_uid,
|
||||
reader,
|
||||
intended_size,
|
||||
thumbnails,
|
||||
last_modification_time,
|
||||
)
|
||||
.await?;
|
||||
let revision_id = self
|
||||
.0
|
||||
.drive
|
||||
.server
|
||||
.lock()
|
||||
.current(file_uid)
|
||||
.and_then(|remote| remote.file.as_ref().map(|file| file.revision.clone()))
|
||||
.unwrap_or_default();
|
||||
Ok(RevisionUpload::Sealed(SealedUpload {
|
||||
node_uid: file_uid.clone(),
|
||||
revision_id,
|
||||
}))
|
||||
}
|
||||
|
||||
async fn open_revision(&self, uid: &NodeUid) -> Result<Arc<dyn RevisionRead>> {
|
||||
let file = self
|
||||
.request(false, |server| {
|
||||
|
||||
@@ -130,12 +130,26 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
},
|
||||
CtlRequest::RemoveSyncFolder { id, delete_remote } => {
|
||||
match core.remove_sync_folder(id, delete_remote) {
|
||||
Ok(()) => {
|
||||
Ok(None) => {
|
||||
core.profile().touch_profile();
|
||||
CtlResponse::Ok {
|
||||
message: "removed synced folder".to_string(),
|
||||
message: if delete_remote {
|
||||
"removed synced folder and moved its folder in Proton Drive to the trash"
|
||||
} else {
|
||||
"removed synced folder"
|
||||
}
|
||||
.to_string(),
|
||||
}
|
||||
}
|
||||
// The folder no longer syncs, but its copy in Proton Drive is
|
||||
// still there. That is not what was asked, so it is an error,
|
||||
// and the message says which half happened.
|
||||
Ok(Some(trash_error)) => {
|
||||
core.profile().touch_profile();
|
||||
CtlResponse::error(CoreError::remote(format!(
|
||||
"stopped syncing the folder, but its folder in Proton Drive was not moved to the trash: {trash_error}"
|
||||
)))
|
||||
}
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -765,9 +765,18 @@ impl Core {
|
||||
jobs
|
||||
}
|
||||
|
||||
/// Remove a synced folder from the sync set. `delete_remote` also deletes its
|
||||
/// folder under the device root; otherwise the cloud copy is left in place.
|
||||
pub(crate) fn remove_sync_folder(&self, id: i64, delete_remote: bool) -> CoreResult<()> {
|
||||
/// Remove a synced folder from the sync set. `delete_remote` also moves its
|
||||
/// folder under the device root to the trash; otherwise the cloud copy is
|
||||
/// left in place.
|
||||
///
|
||||
/// The folder is out of the sync set before the trash is asked, so a trash
|
||||
/// that fails does not fail the removal. It comes back as `Some(error)`,
|
||||
/// for the caller to say that the cloud copy is still there.
|
||||
pub(crate) fn remove_sync_folder(
|
||||
&self,
|
||||
id: i64,
|
||||
delete_remote: bool,
|
||||
) -> CoreResult<Option<String>> {
|
||||
let lock = self.sync.lock(id);
|
||||
// A pass holds the lock for as long as it runs, hours on a large
|
||||
// folder. Ask it to stop at its next checkpoint rather than wait it
|
||||
@@ -823,16 +832,24 @@ impl Core {
|
||||
self.clear_sync_folder_paused(id);
|
||||
// Stop watching the folder we just dropped.
|
||||
let _ = self.sync.tx.send(sync::SyncMsg::Rewatch);
|
||||
if delete_remote
|
||||
&& let Some(uid) = parse_uid(&folder.remote_uid)
|
||||
&& let Err(e) = self
|
||||
.rt
|
||||
.block_on(self.drive.trash_nodes(&[uid]))
|
||||
.and_then(batch::into_unit)
|
||||
if !delete_remote {
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(uid) = parse_uid(&folder.remote_uid) else {
|
||||
warn!(id, remote = %folder.remote_uid, "delete remote device folder: bad uid");
|
||||
return Ok(Some(format!("bad folder id {}", folder.remote_uid)));
|
||||
};
|
||||
match self
|
||||
.rt
|
||||
.block_on(self.drive.trash_nodes(&[uid]))
|
||||
.and_then(batch::into_unit)
|
||||
{
|
||||
warn!(id, error = %e, "delete remote device folder failed");
|
||||
Ok(()) => Ok(None),
|
||||
Err(e) => {
|
||||
warn!(id, error = %e, "delete remote device folder failed");
|
||||
Ok(Some(e.to_string()))
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Trigger a reconcile: one folder by id, or every folder when `id` is `None`.
|
||||
|
||||
@@ -19,7 +19,8 @@ use std::time::{Duration, Instant};
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use pdfs_core::control::{
|
||||
AdmissionLoad, Diagnostics, DriveCallStat, InflightRequest, ServiceState, WorkerState,
|
||||
AdmissionLoad, Diagnostics, DriveCallStat, InflightRequest, ServiceState, UploadPathStat,
|
||||
WorkerState,
|
||||
};
|
||||
|
||||
use pdfs_core::lifecycle::ServiceBoard;
|
||||
@@ -200,6 +201,17 @@ impl Core {
|
||||
longest_ms: u64::try_from(stat.longest.as_millis()).unwrap_or(u64::MAX),
|
||||
})
|
||||
.collect(),
|
||||
upload_paths: pdfs_core::uploads::UPLOAD_PATHS
|
||||
.snapshot()
|
||||
.into_iter()
|
||||
.map(|stat| UploadPathStat {
|
||||
path: stat.path.to_owned(),
|
||||
count: stat.count,
|
||||
errors: stat.errors,
|
||||
total_ms: stat.total_ms,
|
||||
longest_ms: stat.longest_ms,
|
||||
})
|
||||
.collect(),
|
||||
admission: self
|
||||
.sync
|
||||
.admission
|
||||
|
||||
@@ -37,6 +37,7 @@ impl Core {
|
||||
.filter(|path| !path.is_empty())
|
||||
.or_else(|| op.name.clone())
|
||||
.unwrap_or_else(|| op.uid.clone());
|
||||
let local_only = parse_node_uid(&op.uid).is_some_and(|uid| is_local_uid(&uid));
|
||||
PendingOpInfo {
|
||||
id: op.id,
|
||||
kind: op.kind,
|
||||
@@ -49,6 +50,8 @@ impl Core {
|
||||
failing: op.attempts >= FAILING_ATTEMPTS || issues.contains_key(&op.id),
|
||||
issue: issues.get(&op.id).map(|issue| SyncIssue::parse(issue)),
|
||||
exportable,
|
||||
node: op.uid,
|
||||
local_only,
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
|
||||
@@ -1332,6 +1332,33 @@ mod tests {
|
||||
std::fs::remove_file(mnt.join("gone.txt")).unwrap();
|
||||
std::fs::write(mnt.join("new.txt"), b"new").unwrap();
|
||||
std::fs::create_dir(mnt.join("dir")).unwrap();
|
||||
std::fs::rename(mnt.join("edit.txt"), mnt.join("edited.txt")).unwrap();
|
||||
|
||||
// The queue says which changes share a node, so the app can name
|
||||
// every change a discard drops, and which nodes Drive never had.
|
||||
let queued = daemon.pending().unwrap();
|
||||
let on = |name: &str| -> Vec<&PendingOpInfo> {
|
||||
queued.iter().filter(|op| op.path.ends_with(name)).collect()
|
||||
};
|
||||
// By node, not by path: the path an op shows may still be the old
|
||||
// name for a moment after the rename.
|
||||
let edit = queued
|
||||
.iter()
|
||||
.find(|op| op.kind == "revision")
|
||||
.expect("the edit is queued");
|
||||
let same: Vec<&str> = queued
|
||||
.iter()
|
||||
.filter(|op| op.node == edit.node)
|
||||
.map(|op| op.kind.as_str())
|
||||
.collect();
|
||||
assert!(!edit.node.is_empty());
|
||||
assert_eq!(same, ["revision", "rename"], "{queued:?}");
|
||||
assert!(!edit.local_only);
|
||||
assert!(on("new.txt").iter().all(|op| op.local_only), "{queued:?}");
|
||||
assert!(
|
||||
on("moved.txt").iter().all(|op| !op.local_only),
|
||||
"{queued:?}"
|
||||
);
|
||||
|
||||
// Discarding one change drops the others queued on its node.
|
||||
for _ in 0..10 {
|
||||
@@ -4485,6 +4512,57 @@ mod tests {
|
||||
id
|
||||
}
|
||||
|
||||
/// Stop syncing with "Also delete from Proton Drive" on, while Drive cannot
|
||||
/// be reached. The folder stops syncing, but its copy in Proton Drive
|
||||
/// stays. The reply was a plain success, so the app said "Stopped syncing
|
||||
/// folder" and nothing told the user the cloud copy was still there.
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn stopping_sync_says_so_when_its_drive_folder_could_not_be_deleted() {
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("stop-sync-delete-offline");
|
||||
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
|
||||
let local = dir.join("docs");
|
||||
let id = sync_folder(&daemon, &local, "mirror");
|
||||
std::fs::write(local.join("keep.txt"), b"keep").unwrap();
|
||||
daemon.request(&Request::SyncNow { id: Some(id) }).unwrap();
|
||||
let on_drive = || {
|
||||
drive.tree().iter().any(|(path, entry)| {
|
||||
path.ends_with("docs/keep.txt") && *entry == Entry::File(Arc::new(b"keep".to_vec()))
|
||||
})
|
||||
};
|
||||
assert!(
|
||||
wait_until(Duration::from_secs(30), || on_drive()
|
||||
&& listed_folder(&daemon, id).is_some_and(|f| f.state == "idle")),
|
||||
"the folder synced: {:?}",
|
||||
listed_folder(&daemon, id)
|
||||
);
|
||||
|
||||
daemon.client.set_online(false);
|
||||
let error = daemon
|
||||
.request(&Request::RemoveSyncFolder {
|
||||
id,
|
||||
delete_remote: true,
|
||||
})
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
daemon.client.set_online(true);
|
||||
|
||||
assert!(
|
||||
error.contains("stopped syncing the folder")
|
||||
&& error.contains("was not moved to the trash"),
|
||||
"{error}"
|
||||
);
|
||||
assert!(
|
||||
listed_folder(&daemon, id).is_none(),
|
||||
"the folder still syncs"
|
||||
);
|
||||
assert!(on_drive(), "the copy in Proton Drive is gone after all");
|
||||
assert_eq!(std::fs::read(local.join("keep.txt")).unwrap(), b"keep");
|
||||
daemon.stop().unwrap();
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_move_out_of_an_on_demand_folder_refuses_a_file_still_open_for_writing() {
|
||||
|
||||
@@ -59,6 +59,7 @@ 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 */
|
||||
|
||||
@@ -500,6 +500,7 @@ 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(),
|
||||
@@ -548,6 +549,8 @@ fn build_window(app: &adw::Application) {
|
||||
subtitle: trash_widgets.subtitle.clone(),
|
||||
selection_bar: trash_widgets.selection_bar.clone(),
|
||||
selection_label: trash_widgets.selection_label.clone(),
|
||||
restore_selected: trash_widgets.restore_selected.clone(),
|
||||
delete_selected: trash_widgets.delete_selected.clone(),
|
||||
loader: Loader::new(&trash_widgets.content),
|
||||
back: trash_widgets.back.clone(),
|
||||
crumb: trash_widgets.crumb.clone(),
|
||||
|
||||
@@ -31,6 +31,9 @@ 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
|
||||
@@ -135,6 +138,7 @@ 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.
|
||||
@@ -344,6 +348,19 @@ 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();
|
||||
@@ -356,7 +373,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)
|
||||
.content(&content_overlay)
|
||||
.sidebar(&details_pane)
|
||||
.build();
|
||||
|
||||
@@ -492,6 +509,7 @@ pub(crate) fn build_browser_page() -> (gtk4::Widget, BrowserWidgets) {
|
||||
files,
|
||||
crumb,
|
||||
content,
|
||||
drop_hint,
|
||||
status,
|
||||
retry,
|
||||
search,
|
||||
@@ -1401,11 +1419,16 @@ pub(crate) fn wire_browser_actions(ui: &Rc<Ui>, build_thumbnails: >k4::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 |_, _, _| {
|
||||
drop.connect_enter(move |target, _, _| {
|
||||
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 |_| {
|
||||
@@ -1413,6 +1436,7 @@ pub(crate) fn wire_browser_actions(ui: &Rc<Ui>, build_thumbnails: >k4::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, _, _| {
|
||||
@@ -1420,6 +1444,7 @@ pub(crate) fn wire_browser_actions(ui: &Rc<Ui>, build_thumbnails: >k4::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;
|
||||
};
|
||||
@@ -3024,19 +3049,29 @@ pub(crate) fn attach_drop(ui: &Rc<Ui>, item: >k4::ListItem, anchor: >k4::Box
|
||||
.formats()
|
||||
.contains_type(gtk4::gdk::FileList::static_type())
|
||||
});
|
||||
let anchor_enter = anchor.clone();
|
||||
target.connect_enter(move |_, _, _| {
|
||||
target.set_preload(true);
|
||||
let (anchor_enter, ui_enter, item_enter) = (anchor.clone(), ui.clone(), item.clone());
|
||||
target.connect_enter(move |target, _, _| {
|
||||
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 = anchor.clone();
|
||||
target.connect_leave(move |_| anchor_leave.remove_css_class("files-drop-folder"));
|
||||
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 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;
|
||||
};
|
||||
@@ -3055,6 +3090,123 @@ pub(crate) fn attach_drop(ui: &Rc<Ui>, item: >k4::ListItem, anchor: >k4::Box
|
||||
anchor.add_controller(target);
|
||||
}
|
||||
|
||||
/// The page's drop hint, for the folder on screen.
|
||||
fn page_drop_preview(ui: &Rc<Ui>, target: >k4::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: >k4::DropTarget, item: >k4::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: >k4::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
|
||||
@@ -3564,9 +3716,9 @@ fn listing_summary(files: usize, folders: usize, file_bytes: u64) -> String {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
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,
|
||||
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,
|
||||
};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -3645,6 +3797,40 @@ 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};
|
||||
|
||||
|
||||
@@ -1007,20 +1007,54 @@ pub(crate) fn prompt_remove_sync_folder(
|
||||
dialog.set_response_appearance("remove", adw::ResponseAppearance::Destructive);
|
||||
dialog.set_default_response(Some("cancel"));
|
||||
dialog.set_close_response("cancel");
|
||||
let ui = ui.clone();
|
||||
dialog.connect_response(None, move |_, resp| {
|
||||
if resp == "remove" {
|
||||
run_devices_mutation(
|
||||
&ui,
|
||||
Request::RemoveSyncFolder {
|
||||
id,
|
||||
delete_remote: !attached && delete_remote.is_active(),
|
||||
// With the switch on, the button does more than stop syncing, so it says
|
||||
// so: the heading, the button and the outcome all name the deletion.
|
||||
delete_remote.connect_active_notify({
|
||||
let dialog = dialog.clone();
|
||||
move |row| {
|
||||
let deleting = row.is_active();
|
||||
dialog.set_heading(Some(&if deleting {
|
||||
gettext("Stop Syncing and Delete Folder?")
|
||||
} else {
|
||||
gettext("Stop Syncing Folder?")
|
||||
}));
|
||||
dialog.set_response_label(
|
||||
"remove",
|
||||
&if deleting {
|
||||
gettext("Stop Syncing and Delete")
|
||||
} else {
|
||||
gettext("Stop Syncing")
|
||||
},
|
||||
&gettext("Stopped syncing folder"),
|
||||
&gettext("Couldn't stop syncing the folder"),
|
||||
);
|
||||
}
|
||||
});
|
||||
let ui = ui.clone();
|
||||
dialog.connect_response(None, move |_, resp| {
|
||||
if resp != "remove" {
|
||||
return;
|
||||
}
|
||||
let deleting = !attached && delete_remote.is_active();
|
||||
let (done, failed) = if deleting {
|
||||
(
|
||||
gettext("Stopped syncing and moved the folder in Proton Drive to the trash"),
|
||||
gettext("Couldn't stop syncing and delete the folder"),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
gettext("Stopped syncing folder"),
|
||||
gettext("Couldn't stop syncing the folder"),
|
||||
)
|
||||
};
|
||||
run_devices_mutation(
|
||||
&ui,
|
||||
Request::RemoveSyncFolder {
|
||||
id,
|
||||
delete_remote: deleting,
|
||||
},
|
||||
&done,
|
||||
&failed,
|
||||
);
|
||||
});
|
||||
dialog.present(win.as_ref());
|
||||
}
|
||||
|
||||
|
||||
@@ -310,6 +310,7 @@ 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;
|
||||
@@ -333,20 +334,29 @@ 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);
|
||||
let (card, keep) =
|
||||
copy_card(ui, &photo, index == 0 || finder == Finder::Similar, finder);
|
||||
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(&heading);
|
||||
section.append(&header);
|
||||
section.append(&row_scroll);
|
||||
content.append(§ion);
|
||||
toggles.borrow_mut().push(set_toggles);
|
||||
@@ -356,22 +366,14 @@ fn duplicate_review(
|
||||
let toggles = toggles.clone();
|
||||
let trash = trash.clone();
|
||||
move || {
|
||||
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,
|
||||
&[],
|
||||
),
|
||||
});
|
||||
let toggles = toggles.borrow();
|
||||
let (n, files) = doomed_counts(&toggles, finder);
|
||||
trash.set_label(&trash_label(finder, n, files));
|
||||
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();
|
||||
@@ -421,6 +423,94 @@ 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
|
||||
@@ -431,8 +521,14 @@ fn doomed(toggles: &SetToggles) -> Vec<String> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
/// 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) {
|
||||
let picture = gtk4::Picture::builder()
|
||||
.content_fit(gtk4::ContentFit::Cover)
|
||||
.can_shrink(true)
|
||||
@@ -464,11 +560,88 @@ fn copy_card(ui: &Rc<Ui>, photo: &PhotoItem, keep: bool) -> (gtk4::Box, gtk4::To
|
||||
.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");
|
||||
}
|
||||
}
|
||||
@@ -671,15 +671,34 @@ fn repaint_queue(ui: &Rc<Ui>, items: &[PendingOpInfo]) {
|
||||
.map(|now| now.to_unix())
|
||||
.unwrap_or_default();
|
||||
let mut rows = queue.rows.borrow_mut();
|
||||
for op in items.into_iter().take(QUEUE_ROWS_SHOWN) {
|
||||
let row = queue_row(ui, op, now);
|
||||
for op in items.iter().copied().take(QUEUE_ROWS_SHOWN) {
|
||||
let scope = discard_scope(op, &items);
|
||||
let row = queue_row(ui, op, &scope, now);
|
||||
queue.group.add(&row);
|
||||
rows.push(row);
|
||||
}
|
||||
}
|
||||
|
||||
fn queue_row(ui: &Rc<Ui>, op: &PendingOpInfo, now: i64) -> adw::ActionRow {
|
||||
let (icon, action) = match op.kind.as_str() {
|
||||
/// The queued ops a discard of `op` drops: every op on the same node, `op`
|
||||
/// first and the rest in queue order. The daemon drops them all, since each
|
||||
/// was made on top of the one before.
|
||||
fn discard_scope<'a>(op: &'a PendingOpInfo, all: &[&'a PendingOpInfo]) -> Vec<&'a PendingOpInfo> {
|
||||
let mut scope = vec![op];
|
||||
if !op.node.is_empty() {
|
||||
let mut others: Vec<&PendingOpInfo> = all
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|other| other.node == op.node && other.id != op.id)
|
||||
.collect();
|
||||
others.sort_by_key(|other| other.id);
|
||||
scope.extend(others);
|
||||
}
|
||||
scope
|
||||
}
|
||||
|
||||
/// A queued op's kind, as an icon and a short action.
|
||||
fn op_action(kind: &str) -> (&'static str, String) {
|
||||
match kind {
|
||||
"revision" => ("pdfs-upload-symbolic", gettext("Upload changes")),
|
||||
"create" => ("pdfs-upload-symbolic", gettext("Upload new file")),
|
||||
"mkdir" => ("folder-new-symbolic", gettext("Create folder")),
|
||||
@@ -687,7 +706,28 @@ fn queue_row(ui: &Rc<Ui>, op: &PendingOpInfo, now: i64) -> adw::ActionRow {
|
||||
"trash" => ("user-trash-symbolic", gettext("Move to trash")),
|
||||
// Translators: a queued change of an unknown kind.
|
||||
_ => ("pdfs-sync-symbolic", pgettext("noun", "Change")),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// What the discard dialog needs to say about one discard.
|
||||
#[derive(Clone)]
|
||||
struct DiscardScope {
|
||||
id: i64,
|
||||
path: String,
|
||||
/// The op whose content can be exported, if any of them carries some.
|
||||
exportable: Option<i64>,
|
||||
local_only: bool,
|
||||
/// Each dropped op's action, the asked one first.
|
||||
actions: Vec<String>,
|
||||
}
|
||||
|
||||
fn queue_row(
|
||||
ui: &Rc<Ui>,
|
||||
op: &PendingOpInfo,
|
||||
scope: &[&PendingOpInfo],
|
||||
now: i64,
|
||||
) -> adw::ActionRow {
|
||||
let (icon, action) = op_action(&op.kind);
|
||||
let state = match (op.parked, op.next_attempt_at) {
|
||||
(true, _) => gettext("waiting for the app writing it to finish"),
|
||||
(false, Some(at)) if at > now && op.attempts > 0 => {
|
||||
@@ -769,10 +809,15 @@ fn queue_row(ui: &Rc<Ui>, op: &PendingOpInfo, now: i64) -> adw::ActionRow {
|
||||
.build();
|
||||
discard.add_css_class("flat");
|
||||
let ui = ui.clone();
|
||||
let id = op.id;
|
||||
let path = op.path.clone();
|
||||
let exportable = op.exportable;
|
||||
discard.connect_clicked(move |_| prompt_discard_queued(&ui, id, &path, exportable));
|
||||
let scope = DiscardScope {
|
||||
id: op.id,
|
||||
path: op.path.clone(),
|
||||
// The newest content is the version the user would lose.
|
||||
exportable: scope.iter().rev().find(|op| op.exportable).map(|op| op.id),
|
||||
local_only: op.local_only,
|
||||
actions: scope.iter().map(|op| op_action(&op.kind).1).collect(),
|
||||
};
|
||||
discard.connect_clicked(move |_| prompt_discard_queued(&ui, &scope));
|
||||
row.add_suffix(&discard);
|
||||
}
|
||||
row
|
||||
@@ -844,35 +889,77 @@ fn prompt_export_queued(ui: &Rc<Ui>, id: i64, name: &str) {
|
||||
}
|
||||
|
||||
/// Confirm, then have the daemon drop a queued change and undo it here.
|
||||
fn prompt_discard_queued(ui: &Rc<Ui>, id: i64, path: &str, exportable: bool) {
|
||||
let body = if exportable {
|
||||
// Translators: {path} is the file whose queued change would be dropped.
|
||||
///
|
||||
/// The daemon drops every change queued on the same file or folder, so the
|
||||
/// dialog lists them all, says whether the item goes back to how Proton Drive
|
||||
/// has it or disappears from this computer, and offers the export first.
|
||||
fn prompt_discard_queued(ui: &Rc<Ui>, scope: &DiscardScope) {
|
||||
let name = Path::new(&scope.path)
|
||||
.file_name()
|
||||
.map(|name| name.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| scope.path.clone());
|
||||
let count = scope.actions.len() as u64;
|
||||
let outcome = if scope.local_only {
|
||||
// Translators: {path} is a file or folder made on this computer that never reached Proton Drive.
|
||||
gettext_f(
|
||||
"Your changes to {path} are undone here and never reach Proton Drive. Export the file first to keep your version.",
|
||||
&[("path", path)],
|
||||
"{path} was made on this computer and is not on Proton Drive yet. Discarding removes it from this computer.",
|
||||
&[("path", &scope.path)],
|
||||
)
|
||||
} else {
|
||||
// Translators: {path} is the file or folder whose queued change would be dropped.
|
||||
// Translators: {path} is a file or folder that is on Proton Drive.
|
||||
gettext_f(
|
||||
"The change to {path} is undone here and never reaches Proton Drive.",
|
||||
&[("path", path)],
|
||||
"{path} goes back to how it is on Proton Drive, and the changes below are undone here.",
|
||||
&[("path", &scope.path)],
|
||||
)
|
||||
};
|
||||
let body = if scope.exportable.is_some() {
|
||||
format!(
|
||||
"{outcome}\n\n{}",
|
||||
gettext("Export the file first to keep your version.")
|
||||
)
|
||||
} else {
|
||||
outcome
|
||||
};
|
||||
let dialog = adw::AlertDialog::builder()
|
||||
.heading(gettext("Discard Change?"))
|
||||
// Translators: {name} is the file or folder name, {n} how many queued changes a discard drops.
|
||||
.heading(ngettext_f(
|
||||
"Discard the Change to “{name}”?",
|
||||
"Discard {n} Changes to “{name}”?",
|
||||
count,
|
||||
&[("name", &name)],
|
||||
))
|
||||
.body(body)
|
||||
.build();
|
||||
let list = gtk4::ListBox::builder()
|
||||
.selection_mode(gtk4::SelectionMode::None)
|
||||
.css_classes(["boxed-list"])
|
||||
.build();
|
||||
for action in &scope.actions {
|
||||
list.append(&adw::ActionRow::builder().title(action.as_str()).build());
|
||||
}
|
||||
dialog.set_extra_child(Some(&list));
|
||||
dialog.add_response("cancel", &gettext("Cancel"));
|
||||
dialog.add_response("discard", &gettext("Discard"));
|
||||
if scope.exportable.is_some() {
|
||||
dialog.add_response("export", &gettext("Export My Version…"));
|
||||
}
|
||||
dialog.add_response(
|
||||
"discard",
|
||||
&ngettext_f("Discard Change", "Discard {n} Changes", count, &[]),
|
||||
);
|
||||
dialog.set_response_appearance("discard", adw::ResponseAppearance::Destructive);
|
||||
dialog.set_default_response(Some("cancel"));
|
||||
dialog.set_close_response("cancel");
|
||||
let window = ui_window(ui);
|
||||
let ui = ui.clone();
|
||||
dialog.connect_response(None, move |_, resp| {
|
||||
if resp == "discard" {
|
||||
discard_queued(&ui, id);
|
||||
let scope = scope.clone();
|
||||
dialog.connect_response(None, move |_, resp| match resp {
|
||||
"discard" => discard_queued(&ui, scope.id),
|
||||
"export" => {
|
||||
if let Some(id) = scope.exportable {
|
||||
prompt_export_queued(&ui, id, &name);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
dialog.present(window.as_ref());
|
||||
}
|
||||
@@ -1786,6 +1873,51 @@ pub(crate) fn location_subtitle(spec: &MountSpec) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn queued(id: i64, kind: &str, node: &str) -> PendingOpInfo {
|
||||
PendingOpInfo {
|
||||
id,
|
||||
kind: kind.into(),
|
||||
path: "Docs/report.odt".into(),
|
||||
attempts: 0,
|
||||
last_error: None,
|
||||
queued_at: 0,
|
||||
next_attempt_at: None,
|
||||
parked: false,
|
||||
failing: true,
|
||||
issue: None,
|
||||
exportable: kind == "revision",
|
||||
node: node.into(),
|
||||
local_only: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_discard_names_every_change_queued_on_the_same_node() {
|
||||
let rename = queued(9, "rename", "vol~a");
|
||||
let edit = queued(4, "revision", "vol~a");
|
||||
let other = queued(5, "revision", "vol~b");
|
||||
let all = [&rename, &edit, &other];
|
||||
|
||||
let scope: Vec<i64> = discard_scope(&rename, &all)
|
||||
.iter()
|
||||
.map(|op| op.id)
|
||||
.collect();
|
||||
assert_eq!(
|
||||
scope,
|
||||
[9, 4],
|
||||
"the asked change first, then the rest by age"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_discard_from_an_older_daemon_names_only_its_own_change() {
|
||||
let rename = queued(9, "rename", "");
|
||||
let edit = queued(4, "revision", "");
|
||||
let all = [&rename, &edit];
|
||||
|
||||
assert_eq!(discard_scope(&rename, &all).len(), 1);
|
||||
}
|
||||
|
||||
fn spec(kind: MountKind, mode: MountMode, mounted: bool) -> MountSpec {
|
||||
MountSpec {
|
||||
id: 1,
|
||||
|
||||
@@ -682,32 +682,40 @@ 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,
|
||||
..
|
||||
})) => pending_uploads + pending_changes + parked_uploads,
|
||||
_ => 0,
|
||||
})) => Some(pending_uploads + pending_changes + parked_uploads),
|
||||
_ => None,
|
||||
};
|
||||
confirm_sign_out(&ui, queued);
|
||||
});
|
||||
}
|
||||
|
||||
fn confirm_sign_out(ui: &Rc<Ui>, queued: u64) {
|
||||
fn confirm_sign_out(ui: &Rc<Ui>, queued: Option<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.",
|
||||
);
|
||||
if queued > 0 {
|
||||
let warning = ngettext_f(
|
||||
let warning = match queued {
|
||||
Some(0) => None,
|
||||
Some(queued) => Some(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(
|
||||
@@ -720,24 +728,65 @@ fn confirm_sign_out(ui: &Rc<Ui>, queued: u64) {
|
||||
if let Some(galleries) = galleries {
|
||||
galleries.reset();
|
||||
}
|
||||
// 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);
|
||||
});
|
||||
sign_out_now(&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,6 +24,9 @@ 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.
|
||||
@@ -102,6 +105,23 @@ 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(
|
||||
@@ -113,6 +133,8 @@ 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"))
|
||||
@@ -133,6 +155,9 @@ pub(crate) fn build_apps_prefs() -> AppsPrefs {
|
||||
prompt_terminal_row,
|
||||
limit_row,
|
||||
icons_row,
|
||||
remember_row,
|
||||
clear_row,
|
||||
clear_button,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,6 +208,7 @@ 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);
|
||||
|
||||
@@ -239,6 +265,56 @@ 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.
|
||||
@@ -247,6 +323,9 @@ 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.
|
||||
|
||||
@@ -955,16 +955,36 @@ pub(crate) fn prompt_leave_shared(ui: &Rc<Ui>, entries: &[DirEntry]) {
|
||||
dialog.set_default_response(Some("cancel"));
|
||||
dialog.set_close_response("cancel");
|
||||
let ui_c = ui.clone();
|
||||
let uids: Vec<String> = entries.iter().map(|e| e.uid.clone()).collect();
|
||||
let targets: Vec<(String, String)> = entries
|
||||
.iter()
|
||||
.map(|e| (e.name.clone(), e.uid.clone()))
|
||||
.collect();
|
||||
dialog.connect_response(Some("leave"), move |_, _| {
|
||||
let count = uids.len();
|
||||
let count = targets.len();
|
||||
let items = targets
|
||||
.iter()
|
||||
.map(|(name, uid)| BatchItem {
|
||||
name: name.clone(),
|
||||
uid: uid.clone(),
|
||||
request: |uid| Request::LeaveShared { uid },
|
||||
})
|
||||
.collect();
|
||||
let text = BatchText {
|
||||
failed: gettext_noop("Couldn't leave the shared item"),
|
||||
partial: |went, total| {
|
||||
ngettext_f(
|
||||
"Left {went} of {n} Shared Item",
|
||||
"Left {went} of {n} Shared Items",
|
||||
total,
|
||||
&[("went", &went.to_string())],
|
||||
)
|
||||
},
|
||||
};
|
||||
run_requests(
|
||||
&ui_c,
|
||||
uids.iter()
|
||||
.map(|uid| Request::LeaveShared { uid: uid.clone() })
|
||||
.collect(),
|
||||
gettext_noop("Couldn't leave the shared item"),
|
||||
move |ui| {
|
||||
items,
|
||||
text,
|
||||
Rc::new(move |ui| {
|
||||
load_shared(ui);
|
||||
toast(
|
||||
ui,
|
||||
@@ -975,50 +995,158 @@ pub(crate) fn prompt_leave_shared(ui: &Rc<Ui>, entries: &[DirEntry]) {
|
||||
&[],
|
||||
),
|
||||
);
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
dialog.present(ui_window(ui).as_ref());
|
||||
}
|
||||
|
||||
/// Send `requests` one after the other, stopping at the first failure, which
|
||||
/// is reported under `failed` (an untranslated msgid). `done` runs once all
|
||||
/// succeeded. After a failure the page on screen is reloaded instead, since
|
||||
/// the requests before it went through.
|
||||
pub(crate) fn run_requests(
|
||||
ui: &Rc<Ui>,
|
||||
requests: Vec<Request>,
|
||||
failed: &'static str,
|
||||
done: impl FnOnce(&Rc<Ui>) + 'static,
|
||||
) {
|
||||
/// What became of one request of a batch.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) enum Outcome {
|
||||
Done,
|
||||
/// The service refused it, with this message.
|
||||
Failed(String),
|
||||
/// The service did not answer, so it may or may not have happened.
|
||||
Unknown,
|
||||
/// Not sent: the service had stopped answering before its turn.
|
||||
NotTried,
|
||||
}
|
||||
|
||||
/// One item of a batch: its name, as the summary lists it, and the uid its
|
||||
/// request acts on. A retry sends the request again, so it is built from the
|
||||
/// uid each time.
|
||||
pub(crate) struct BatchItem {
|
||||
pub(crate) name: String,
|
||||
pub(crate) uid: String,
|
||||
pub(crate) request: fn(String) -> Request,
|
||||
}
|
||||
|
||||
/// What runs once every item of a batch went through. Kept for a retry.
|
||||
pub(crate) type BatchDone = Rc<dyn Fn(&Rc<Ui>)>;
|
||||
|
||||
/// The texts a batch reports with.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct BatchText {
|
||||
/// The failure title, an untranslated msgid.
|
||||
pub(crate) failed: &'static str,
|
||||
/// The heading of a batch that partly went through, from how many items
|
||||
/// went through and how many there were.
|
||||
pub(crate) partial: fn(u64, u64) -> String,
|
||||
}
|
||||
|
||||
/// Send each request in turn. `done` runs once all succeeded.
|
||||
///
|
||||
/// A request the service refuses does not stop the others, since each item
|
||||
/// stands on its own. Once the service stops answering, the rest are not
|
||||
/// sent. When any item did not go through, the page on screen is reloaded,
|
||||
/// so a lost reply shows its real state, and a summary names every item that
|
||||
/// did not, with a way to try those again. A batch of one reports as before,
|
||||
/// with a toast.
|
||||
pub(crate) fn run_requests(ui: &Rc<Ui>, items: Vec<BatchItem>, text: BatchText, done: BatchDone) {
|
||||
ui.busy_begin();
|
||||
let ui = ui.clone();
|
||||
let socket = ui.dirs.control_socket();
|
||||
glib::spawn_future_local(async move {
|
||||
for req in requests {
|
||||
let result = spawn_request(socket.clone(), req).recv().await;
|
||||
let error = match result {
|
||||
Ok(Ok(Response::Ok { .. })) => continue,
|
||||
Ok(Ok(Response::Error { message, kind })) => Some((message, kind)),
|
||||
_ => None,
|
||||
};
|
||||
ui.busy_end();
|
||||
reload_current_page(&ui);
|
||||
match error {
|
||||
Some((message, kind)) => toast_failure(&ui, &gettext(failed), &message, kind),
|
||||
let mut outcomes = Vec::with_capacity(items.len());
|
||||
let mut first_error = None;
|
||||
let mut answering = true;
|
||||
for item in &items {
|
||||
if !answering {
|
||||
outcomes.push(Outcome::NotTried);
|
||||
continue;
|
||||
}
|
||||
let result = spawn_request(socket.clone(), (item.request)(item.uid.clone()))
|
||||
.recv()
|
||||
.await;
|
||||
outcomes.push(match result {
|
||||
Ok(Ok(Response::Ok { .. })) => Outcome::Done,
|
||||
Ok(Ok(Response::Error { message, kind })) => {
|
||||
first_error.get_or_insert((message.clone(), kind));
|
||||
Outcome::Failed(message)
|
||||
}
|
||||
_ => {
|
||||
answering = false;
|
||||
Outcome::Unknown
|
||||
}
|
||||
});
|
||||
}
|
||||
ui.busy_end();
|
||||
if outcomes.iter().all(|outcome| *outcome == Outcome::Done) {
|
||||
done(&ui);
|
||||
return;
|
||||
}
|
||||
reload_current_page(&ui);
|
||||
if items.len() == 1 {
|
||||
match first_error {
|
||||
Some((message, kind)) => toast_failure(&ui, &gettext(text.failed), &message, kind),
|
||||
None => toast_error(
|
||||
&ui,
|
||||
&gettext(failed),
|
||||
&gettext(text.failed),
|
||||
&gettext("The Proton Drive service didn't respond."),
|
||||
),
|
||||
}
|
||||
return;
|
||||
}
|
||||
ui.busy_end();
|
||||
done(&ui);
|
||||
present_batch_summary(&ui, items, outcomes, text, done);
|
||||
});
|
||||
}
|
||||
|
||||
/// Name every item of a batch that did not go through, and offer to try
|
||||
/// them again.
|
||||
fn present_batch_summary(
|
||||
ui: &Rc<Ui>,
|
||||
items: Vec<BatchItem>,
|
||||
outcomes: Vec<Outcome>,
|
||||
text: BatchText,
|
||||
done: BatchDone,
|
||||
) {
|
||||
let total = items.len() as u64;
|
||||
let went = outcomes.iter().filter(|o| **o == Outcome::Done).count() as u64;
|
||||
let list = gtk4::ListBox::builder()
|
||||
.selection_mode(gtk4::SelectionMode::None)
|
||||
.css_classes(["boxed-list"])
|
||||
.build();
|
||||
let mut again = Vec::new();
|
||||
for (item, outcome) in items.into_iter().zip(&outcomes) {
|
||||
let state = match outcome {
|
||||
Outcome::Done => continue,
|
||||
// Translators: {error} is the reason the service gave.
|
||||
Outcome::Failed(error) => gettext_f("Refused: {error}", &[("error", error)]),
|
||||
Outcome::Unknown => {
|
||||
gettext("The service didn't answer. The page shows whether it went through.")
|
||||
}
|
||||
Outcome::NotTried => gettext("Not tried yet"),
|
||||
};
|
||||
list.append(
|
||||
&adw::ActionRow::builder()
|
||||
.title(glib::markup_escape_text(&item.name).as_str())
|
||||
.subtitle(glib::markup_escape_text(&state).as_str())
|
||||
.subtitle_lines(3)
|
||||
.build(),
|
||||
);
|
||||
again.push(item);
|
||||
}
|
||||
let dialog = adw::AlertDialog::builder()
|
||||
.heading((text.partial)(went, total))
|
||||
.body(gettext("These items did not go through:"))
|
||||
.extra_child(&list)
|
||||
.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("close"));
|
||||
dialog.set_close_response("close");
|
||||
let ui_c = ui.clone();
|
||||
let again = RefCell::new(Some(again));
|
||||
dialog.connect_response(Some("again"), move |_, _| {
|
||||
if let Some(items) = again.borrow_mut().take() {
|
||||
run_requests(&ui_c, items, text, done.clone());
|
||||
}
|
||||
});
|
||||
dialog.present(ui_window(ui).as_ref());
|
||||
}
|
||||
|
||||
/// Confirm, then remove a saved link. The shared item itself is untouched.
|
||||
pub(crate) fn prompt_remove_bookmark(ui: &Rc<Ui>, token: &str, name: &str) {
|
||||
let win = ui_window(ui);
|
||||
|
||||
@@ -466,6 +466,16 @@ 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)
|
||||
@@ -481,9 +491,7 @@ fn shared_by_me_menu(ui: &Rc<Ui>, entry: &DirEntry) -> ActionMenu {
|
||||
show_in_my_files(&ui_c, &entry_c)
|
||||
});
|
||||
}
|
||||
let now = glib::real_time() / 1_000_000;
|
||||
let url = find_item(&ui.shared_by_me.items, &entry.uid)
|
||||
.and_then(|item| item.link)
|
||||
let url = link
|
||||
.filter(|link| !link_expired(link, now))
|
||||
.and_then(|link| link.url);
|
||||
if let Some(url) = url {
|
||||
@@ -564,21 +572,41 @@ pub(crate) fn prompt_stop_sharing(ui: &Rc<Ui>, entries: &[DirEntry]) {
|
||||
&[],
|
||||
),
|
||||
};
|
||||
let uids: Vec<String> = entries.iter().map(|e| e.uid.clone()).collect();
|
||||
let targets: Vec<(String, String)> = entries
|
||||
.iter()
|
||||
.map(|e| (e.name.clone(), e.uid.clone()))
|
||||
.collect();
|
||||
dialog.connect_response(Some("stop"), move |_, _| {
|
||||
let done = done.clone();
|
||||
let stopped = uids.clone();
|
||||
let stopped: Vec<String> = targets.iter().map(|(_, uid)| uid.clone()).collect();
|
||||
let items = targets
|
||||
.iter()
|
||||
.map(|(name, uid)| BatchItem {
|
||||
name: name.clone(),
|
||||
uid: uid.clone(),
|
||||
request: |uid| Request::StopSharingByUid { uid },
|
||||
})
|
||||
.collect();
|
||||
let text = BatchText {
|
||||
failed: gettext_noop("Couldn't stop sharing"),
|
||||
partial: |went, total| {
|
||||
ngettext_f(
|
||||
"Stopped Sharing {went} of {n} Item",
|
||||
"Stopped Sharing {went} of {n} Items",
|
||||
total,
|
||||
&[("went", &went.to_string())],
|
||||
)
|
||||
},
|
||||
};
|
||||
run_requests(
|
||||
&ui_c,
|
||||
uids.iter()
|
||||
.map(|uid| Request::StopSharingByUid { uid: uid.clone() })
|
||||
.collect(),
|
||||
gettext_noop("Couldn't stop sharing"),
|
||||
move |ui| {
|
||||
items,
|
||||
text,
|
||||
Rc::new(move |ui| {
|
||||
forget_shared_by_me(ui, &stopped);
|
||||
reload_listing(ui);
|
||||
toast(ui, &done);
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
dialog.present(ui_window(ui).as_ref());
|
||||
|
||||
@@ -14,6 +14,10 @@ pub(crate) struct TrashState {
|
||||
/// The bottom bar acting on the selection; revealed while anything is selected.
|
||||
pub(crate) selection_bar: gtk4::Revealer,
|
||||
pub(crate) selection_label: gtk4::Label,
|
||||
/// The bar's actions, labelled for what they act on (see
|
||||
/// [`sync_trash_selection`]).
|
||||
pub(crate) restore_selected: gtk4::Button,
|
||||
pub(crate) delete_selected: gtk4::Button,
|
||||
/// Runs the loads; the rows stay up while one runs.
|
||||
pub(crate) loader: Rc<Loader>,
|
||||
/// Back, the breadcrumb and the search entry over the list.
|
||||
@@ -312,11 +316,13 @@ fn trash_entry_menu(ui: &Rc<Ui>, entry: &DirEntry) -> ActionMenu {
|
||||
&& !in_trash(ui, &entry.uid)
|
||||
&& let Some(folder) = outer_folder(ui)
|
||||
{
|
||||
// Went to the trash with the folder, so only the folder goes back.
|
||||
// Went to the trash with the folder, so only the folder goes back,
|
||||
// and only the folder can be deleted for good.
|
||||
menu.labelled_section(&gettext("Deleted with its folder"));
|
||||
let ui_c = ui.clone();
|
||||
let label = gettext_f(
|
||||
// Translators: {name} is a folder name.
|
||||
"Restore “{name}”",
|
||||
"Restore Folder “{name}”",
|
||||
&[("name", &folder.name)],
|
||||
);
|
||||
menu.item(&label, move || {
|
||||
@@ -324,8 +330,16 @@ fn trash_entry_menu(ui: &Rc<Ui>, entry: &DirEntry) -> ActionMenu {
|
||||
});
|
||||
return menu;
|
||||
}
|
||||
let restore = match location_key(&entry.uid) {
|
||||
// A location row stands for everything deleted from that folder.
|
||||
Some(_) => {
|
||||
let n = trashed_targets(ui, std::slice::from_ref(entry)).len() as u64;
|
||||
ngettext_f("Restore {n} Item", "Restore {n} Items", n, &[])
|
||||
}
|
||||
None => pgettext("verb", "Restore"),
|
||||
};
|
||||
let (ui_c, entry_c) = (ui.clone(), entry.clone());
|
||||
menu.item(&pgettext("verb", "Restore"), move || {
|
||||
menu.item(&restore, move || {
|
||||
restore_entries(&ui_c, std::slice::from_ref(&entry_c))
|
||||
});
|
||||
menu.section();
|
||||
@@ -374,18 +388,52 @@ fn trash_background_menu(ui: &Rc<Ui>) -> ActionMenu {
|
||||
menu
|
||||
}
|
||||
|
||||
/// Reveal the selection bar while anything is selected and count what is.
|
||||
/// Reveal the selection bar while anything is selected, count what is, and
|
||||
/// label its actions for what they act on, which is not always the selection.
|
||||
fn sync_trash_selection(ui: &Rc<Ui>) {
|
||||
let count = ui.trash.files.selection.selection().size() as usize;
|
||||
ui.trash.selection_bar.set_reveal_child(count > 0);
|
||||
if count > 0 {
|
||||
ui.trash.selection_label.set_label(&ngettext_f(
|
||||
"{n} item selected",
|
||||
"{n} items selected",
|
||||
count as u64,
|
||||
&[],
|
||||
));
|
||||
if count == 0 {
|
||||
return;
|
||||
}
|
||||
ui.trash.selection_label.set_label(&ngettext_f(
|
||||
"{n} item selected",
|
||||
"{n} items selected",
|
||||
count as u64,
|
||||
&[],
|
||||
));
|
||||
let selected = ui.trash.files.selected();
|
||||
let targets = {
|
||||
let all = ui.trash.all.borrow();
|
||||
resolve_targets(&all, outer_folder(ui).as_ref(), &selected)
|
||||
};
|
||||
let (restore, deletable) = match (&targets.inherited, targets.own.len()) {
|
||||
(Some(folder), 0) => (
|
||||
// Translators: {name} is a folder name.
|
||||
gettext_f("Restore Folder “{name}”", &[("name", &folder.name)]),
|
||||
false,
|
||||
),
|
||||
(inherited, own) if inherited.is_some() || own != count => {
|
||||
let n = (own + usize::from(inherited.is_some())) as u64;
|
||||
(
|
||||
ngettext_f("Restore {n} Item", "Restore {n} Items", n, &[]),
|
||||
own > 0,
|
||||
)
|
||||
}
|
||||
_ => (pgettext("verb", "Restore"), true),
|
||||
};
|
||||
ui.trash.restore_selected.set_label(&restore);
|
||||
let delete = &ui.trash.delete_selected;
|
||||
delete.set_sensitive(deletable);
|
||||
delete.set_tooltip_text(
|
||||
(!deletable)
|
||||
.then(|| {
|
||||
gettext(
|
||||
"These went to the trash with their folder. Only the whole folder can be deleted permanently, from the top of the trash.",
|
||||
)
|
||||
})
|
||||
.as_deref(),
|
||||
);
|
||||
}
|
||||
|
||||
/// Fetch the trash listing and repaint the page.
|
||||
@@ -727,14 +775,24 @@ fn outer_folder(ui: &Ui) -> Option<DirEntry> {
|
||||
ui.trash.all.borrow().iter().find(|e| e.uid == uid).cloned()
|
||||
}
|
||||
|
||||
/// What acting on `entries` acts on: a location row stands for everything
|
||||
/// deleted from that folder, and an item that went with its folder for the
|
||||
/// folder. Each node once.
|
||||
fn trashed_targets(ui: &Ui, entries: &[DirEntry]) -> Vec<DirEntry> {
|
||||
let all = ui.trash.all.borrow();
|
||||
let outer = outer_folder(ui);
|
||||
/// What acting on a selection acts on.
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
struct Targets {
|
||||
/// The trashed items themselves: each selected item that is in the trash
|
||||
/// on its own, and for a location row everything deleted from that folder.
|
||||
own: Vec<DirEntry>,
|
||||
/// The open trashed folder, when the selection holds items that went to
|
||||
/// the trash with it. They can only go back with the folder, so a restore
|
||||
/// restores it. A permanent deletion does not: deleting the folder for
|
||||
/// good takes an explicit choice of the folder itself.
|
||||
inherited: Option<DirEntry>,
|
||||
}
|
||||
|
||||
/// Resolve `entries` against the trash listing `all`, inside `outer` when a
|
||||
/// trashed folder is open. Each node once.
|
||||
fn resolve_targets(all: &[DirEntry], outer: Option<&DirEntry>, entries: &[DirEntry]) -> Targets {
|
||||
let mut seen = HashSet::new();
|
||||
let mut targets = Vec::new();
|
||||
let mut targets = Targets::default();
|
||||
for entry in entries {
|
||||
let picked: Vec<DirEntry> = if let Some(key) = location_key(&entry.uid) {
|
||||
all.iter()
|
||||
@@ -744,17 +802,38 @@ fn trashed_targets(ui: &Ui, entries: &[DirEntry]) -> Vec<DirEntry> {
|
||||
} else if all.iter().any(|e| e.uid == entry.uid) {
|
||||
vec![entry.clone()]
|
||||
} else {
|
||||
outer.clone().into_iter().collect()
|
||||
if targets.inherited.is_none() {
|
||||
targets.inherited = outer.cloned();
|
||||
}
|
||||
Vec::new()
|
||||
};
|
||||
for target in picked {
|
||||
if seen.insert(target.uid.clone()) {
|
||||
targets.push(target);
|
||||
targets.own.push(target);
|
||||
}
|
||||
}
|
||||
}
|
||||
// The folder may be selected too, at a level that shows it.
|
||||
if let Some(folder) = &targets.inherited
|
||||
&& seen.contains(&folder.uid)
|
||||
{
|
||||
targets.inherited = None;
|
||||
}
|
||||
targets
|
||||
}
|
||||
|
||||
/// What a restore of `entries` restores: the items, and the open folder for
|
||||
/// those that went to the trash with it.
|
||||
fn trashed_targets(ui: &Ui, entries: &[DirEntry]) -> Vec<DirEntry> {
|
||||
let targets = {
|
||||
let all = ui.trash.all.borrow();
|
||||
resolve_targets(&all, outer_folder(ui).as_ref(), entries)
|
||||
};
|
||||
let mut restore = targets.own;
|
||||
restore.extend(targets.inherited);
|
||||
restore
|
||||
}
|
||||
|
||||
/// Rebuild the path bar for `nav`: "Trash", then each place down to the
|
||||
/// current one. Hidden at the top, where there is nowhere to go back to.
|
||||
fn repaint_trash_crumb(ui: &Rc<Ui>) {
|
||||
@@ -850,9 +929,26 @@ fn common_origin(entries: &[DirEntry]) -> Option<String> {
|
||||
}
|
||||
|
||||
/// Confirm, then permanently delete trashed entries. Irreversible, so it asks.
|
||||
///
|
||||
/// Only what was selected is deleted. An item that went to the trash with its
|
||||
/// folder cannot be deleted on its own, and is not taken to mean its folder.
|
||||
pub(crate) fn prompt_delete_forever(ui: &Rc<Ui>, entries: &[DirEntry]) {
|
||||
let entries = &trashed_targets(ui, entries)[..];
|
||||
let targets = {
|
||||
let all = ui.trash.all.borrow();
|
||||
resolve_targets(&all, outer_folder(ui).as_ref(), entries)
|
||||
};
|
||||
let entries = &targets.own[..];
|
||||
if entries.is_empty() {
|
||||
if let Some(folder) = targets.inherited {
|
||||
toast(
|
||||
ui,
|
||||
// Translators: {name} is a folder name.
|
||||
&gettext_f(
|
||||
"These went to the trash with “{name}”. Delete the whole folder from the top of the trash.",
|
||||
&[("name", &folder.name)],
|
||||
),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let win = ui_window(ui);
|
||||
@@ -973,6 +1069,55 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn uids(entries: &[DirEntry]) -> Vec<&str> {
|
||||
entries.iter().map(|e| e.uid.as_str()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_item_deleted_with_its_folder_restores_the_folder_and_deletes_nothing() {
|
||||
let projects = DirEntry {
|
||||
is_dir: true,
|
||||
..trashed("projects", 5, 1, Some("Work"))
|
||||
};
|
||||
let all = vec![projects.clone()];
|
||||
// Two siblings inside the open trashed folder: neither is in the trash
|
||||
// on its own.
|
||||
let a = trashed("a.txt", 5, 1, None);
|
||||
let b = trashed("b.txt", 5, 1, None);
|
||||
|
||||
let targets = resolve_targets(&all, Some(&projects), &[a, b]);
|
||||
|
||||
assert!(targets.own.is_empty(), "nothing of its own to delete");
|
||||
assert_eq!(targets.inherited, Some(projects));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_location_row_stands_for_every_item_deleted_from_that_folder() {
|
||||
let all = vec![
|
||||
trashed("one", 3, 1, Some("Work")),
|
||||
trashed("two", 2, 1, Some("Work")),
|
||||
trashed("other", 1, 1, Some("Home")),
|
||||
inside("nested", "one"),
|
||||
];
|
||||
let row = location_row(Some("Work".into()));
|
||||
|
||||
let targets = resolve_targets(&all, None, &[row]);
|
||||
|
||||
assert_eq!(uids(&targets.own), ["one", "two"]);
|
||||
assert_eq!(targets.inherited, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selected_item_counts_once_and_stays_itself() {
|
||||
let all = vec![trashed("one", 3, 1, Some("Work"))];
|
||||
let one = all[0].clone();
|
||||
|
||||
let targets = resolve_targets(&all, None, &[one.clone(), one]);
|
||||
|
||||
assert_eq!(uids(&targets.own), ["one"]);
|
||||
assert_eq!(targets.inherited, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locations_group_top_level_items_by_folder() {
|
||||
let all = vec![
|
||||
|
||||
@@ -669,30 +669,70 @@ 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 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 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 row = adw::ActionRow::builder()
|
||||
.title(if url.is_empty() {
|
||||
gettext("Public link")
|
||||
} else {
|
||||
url.clone()
|
||||
})
|
||||
.subtitle(&subtitle)
|
||||
.title(link_row_title(link.role == "editor", expired))
|
||||
.subtitle(link_policy(
|
||||
link.role == "editor",
|
||||
link.has_password,
|
||||
link.expires,
|
||||
now,
|
||||
))
|
||||
.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"))
|
||||
@@ -744,8 +784,8 @@ pub(crate) fn repaint_share_link(state: &Rc<ShareDialog>, link: Option<&PublicLi
|
||||
|
||||
state.link_group.add(&row);
|
||||
rows.push(row.upcast());
|
||||
|
||||
let settings = link_settings_row(state, link);
|
||||
state.link_group.add(&address);
|
||||
rows.push(address.upcast());
|
||||
state.link_group.add(&settings);
|
||||
rows.push(settings.upcast());
|
||||
}
|
||||
@@ -757,11 +797,45 @@ 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"));
|
||||
|
||||
// Enter in the password field creates the link.
|
||||
let btn = create.clone();
|
||||
pw_row.connect_entry_activated(move |_| btn.emit_clicked());
|
||||
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();
|
||||
});
|
||||
|
||||
let state_c = Rc::downgrade(state);
|
||||
let pw_for = pw_row.clone();
|
||||
@@ -787,124 +861,265 @@ 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;
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
/// 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) {
|
||||
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. The link stays the same.",
|
||||
"Change who can edit, the password or the expiry, then save. The link stays the same.",
|
||||
))
|
||||
.build();
|
||||
let draft = Rc::new(RefCell::new(LinkDraft::of(link)));
|
||||
|
||||
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 role = if d.selected() == 1 {
|
||||
"editor"
|
||||
} else {
|
||||
"viewer"
|
||||
};
|
||||
let request = state.target.update_link(
|
||||
id.clone(),
|
||||
Some(role.into()),
|
||||
LinkChange::Keep,
|
||||
LinkChange::Keep,
|
||||
);
|
||||
share_dialog_update_link(&state, request, &expander_w);
|
||||
});
|
||||
let (role_row, role_drop) = dropdown_row(
|
||||
&gettext("Link role"),
|
||||
&link_roles(),
|
||||
u32::from(draft.borrow().editor),
|
||||
);
|
||||
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);
|
||||
});
|
||||
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")
|
||||
gettext("New password (optional)")
|
||||
} else {
|
||||
gettext("Add a password")
|
||||
gettext("Password")
|
||||
})
|
||||
.show_apply_button(true)
|
||||
.visible(link.has_password)
|
||||
.build();
|
||||
let (state_w, expander_w, id) = (Rc::downgrade(state), expander.clone(), link.id.clone());
|
||||
pw_row.connect_apply(move |row| {
|
||||
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 Some(state) = state_w.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let password = row.text().to_string();
|
||||
if password.is_empty() {
|
||||
let Ok(Some(edit)) = link_edit(&link, &draft.borrow(), glib::real_time() / 1_000_000)
|
||||
else {
|
||||
return;
|
||||
}
|
||||
let request = state.target.update_link(
|
||||
id.clone(),
|
||||
None,
|
||||
LinkChange::Set(password),
|
||||
LinkChange::Keep,
|
||||
);
|
||||
};
|
||||
let request =
|
||||
state
|
||||
.target
|
||||
.update_link(link.id.clone(), edit.role, edit.password, edit.expires);
|
||||
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
|
||||
(expander, expiry_drop)
|
||||
}
|
||||
|
||||
/// Send a link change, then reload the dialog: on success to show the link as
|
||||
@@ -1084,6 +1299,111 @@ 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");
|
||||
|
||||
@@ -5,6 +5,13 @@
|
||||
//! 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
|
||||
@@ -42,6 +49,19 @@ 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
|
||||
@@ -55,9 +75,16 @@ 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) {
|
||||
fn record(visits: &mut Vec<Visit>, hit: Hit, now: i64, account: Option<String>) {
|
||||
let key = hit.key();
|
||||
let count = match visits.iter().position(|visit| visit.hit.key() == 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)
|
||||
{
|
||||
Some(at) => visits.remove(at).count.saturating_add(1),
|
||||
None => 1,
|
||||
};
|
||||
@@ -67,6 +94,7 @@ fn record(visits: &mut Vec<Visit>, hit: Hit, now: i64) {
|
||||
hit,
|
||||
last: now,
|
||||
count,
|
||||
account,
|
||||
},
|
||||
);
|
||||
visits.truncate(MAX_VISITS);
|
||||
@@ -107,9 +135,19 @@ 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),
|
||||
Record(Hit, i64, Option<String>),
|
||||
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
|
||||
@@ -123,11 +161,29 @@ 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) => {
|
||||
record(&mut visits, hit, now);
|
||||
Command::Record(hit, now, account) => {
|
||||
record(&mut visits, hit, now, account);
|
||||
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) {
|
||||
@@ -142,6 +198,10 @@ 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 {
|
||||
@@ -169,12 +229,38 @@ impl History {
|
||||
changed();
|
||||
}
|
||||
});
|
||||
Self { visits, commands }
|
||||
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);
|
||||
}
|
||||
|
||||
/// Remember that `hit` was opened just now.
|
||||
pub(crate) fn record(&self, hit: Hit) {
|
||||
let _ = self.commands.try_send(Command::Record(hit, now()));
|
||||
if !self.remember.get() {
|
||||
return;
|
||||
}
|
||||
let account = self.account.borrow().clone();
|
||||
let _ = self.commands.try_send(Command::Record(hit, now(), account));
|
||||
}
|
||||
|
||||
/// Forget local files that were deleted since they were opened.
|
||||
@@ -184,9 +270,11 @@ 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()
|
||||
@@ -195,9 +283,11 @@ 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(),
|
||||
@@ -220,6 +310,8 @@ 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 {
|
||||
@@ -266,9 +358,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);
|
||||
record(&mut visits, drive("b.pdf"), 20);
|
||||
record(&mut visits, drive("a.pdf"), 30);
|
||||
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()));
|
||||
assert_eq!(visits.len(), 2);
|
||||
assert_eq!(visits[0].hit.name(), "a.pdf");
|
||||
assert_eq!((visits[0].count, visits[0].last), (2, 30));
|
||||
@@ -279,7 +371,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);
|
||||
record(&mut visits, drive(&format!("{n}.pdf")), n, Some(A.into()));
|
||||
}
|
||||
assert_eq!(visits.len(), MAX_VISITS);
|
||||
assert_eq!(visits[0].hit.name(), "59.pdf");
|
||||
@@ -291,8 +383,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);
|
||||
record(&mut visits, drive("a.pdf"), 20);
|
||||
record(&mut visits, drive("a.pdf"), 10, Some(A.into()));
|
||||
record(&mut visits, drive("a.pdf"), 20, Some(A.into()));
|
||||
save(&path, &visits).unwrap();
|
||||
|
||||
let loaded = load(&path);
|
||||
@@ -308,17 +400,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);
|
||||
record(&mut stored, drive("old.pdf"), 20);
|
||||
record(&mut stored, drive("old.pdf"), 10, Some(A.into()));
|
||||
record(&mut stored, drive("old.pdf"), 20, Some(A.into()));
|
||||
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))
|
||||
.send_blocking(Command::Record(drive("old.pdf"), 30, Some(A.into())))
|
||||
.unwrap();
|
||||
commands
|
||||
.send_blocking(Command::Record(drive("new.pdf"), 40))
|
||||
.send_blocking(Command::Record(drive("new.pdf"), 40, Some(A.into())))
|
||||
.unwrap();
|
||||
drop(commands);
|
||||
|
||||
@@ -351,13 +443,114 @@ mod tests {
|
||||
})
|
||||
};
|
||||
let mut visits = Vec::new();
|
||||
record(&mut visits, local(&kept), 1);
|
||||
record(&mut visits, local(&dir.join("gone.txt")), 2);
|
||||
record(&mut visits, drive("remote.pdf"), 3);
|
||||
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()));
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -286,13 +286,16 @@ 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("prompt-history.json"), move || {
|
||||
if let Some(ui) = weak.upgrade()
|
||||
&& ui.showing_suggestions()
|
||||
{
|
||||
ui.render();
|
||||
}
|
||||
}),
|
||||
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();
|
||||
}
|
||||
},
|
||||
),
|
||||
socket,
|
||||
mountpoint: RefCell::new(dirs.default_mountpoint()),
|
||||
opener: RefCell::new(dirs.load_config().resolved_open_with()),
|
||||
@@ -536,6 +539,8 @@ 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
|
||||
@@ -581,13 +586,22 @@ impl Ui {
|
||||
let ui = self.clone();
|
||||
glib::spawn_future_local(async move {
|
||||
match rx.recv().await {
|
||||
Ok(Ok(Response::Status { mountpoint, .. })) => {
|
||||
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));
|
||||
*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");
|
||||
|
||||
@@ -71,6 +71,7 @@ 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",
|
||||
@@ -79,6 +80,7 @@ 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",
|
||||
|
||||
@@ -100,8 +100,13 @@ impl Db {
|
||||
/// so it still does once its create has landed and the row has the uid
|
||||
/// Drive gave it. The tree learns that uid a moment later, and a rename in
|
||||
/// between was refused (`docs/BUGS.md` B174).
|
||||
///
|
||||
/// Every statement reads one snapshot. Apart, a create that landed between
|
||||
/// finding the row's uid and checking the row left the stand-in with no
|
||||
/// row at all, and the change was refused (B306).
|
||||
pub fn effective_node_access(&self, uid: &NodeUid) -> Result<Option<Access>> {
|
||||
let conn = self.read()?;
|
||||
let reader = self.read()?;
|
||||
let conn = reader.unchecked_transaction()?;
|
||||
let key = uid.to_string();
|
||||
let key = match super::local_lid(&key) {
|
||||
Some(lid) => conn
|
||||
|
||||
@@ -3726,6 +3726,66 @@ fn a_stand_in_keeps_its_access_once_its_create_has_landed() {
|
||||
);
|
||||
}
|
||||
|
||||
/// A stand-in asked about while its create lands is never missing: the
|
||||
/// lookup that turns it into the landed row's uid and the check on that row
|
||||
/// see one state of the database (`docs/BUGS.md` B306).
|
||||
#[test]
|
||||
fn a_stand_in_is_never_missing_while_its_create_lands() {
|
||||
let path = std::env::temp_dir().join(format!("pdfs-db-landing-{}.db", std::process::id()));
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let db = Db::open(&path).unwrap();
|
||||
db.upsert_node(&folder("parent", None, "My Files")).unwrap();
|
||||
let parent = uid("parent").to_string();
|
||||
let current = std::sync::Mutex::new(None::<NodeUid>);
|
||||
let done = std::sync::atomic::AtomicBool::new(false);
|
||||
let missing = std::sync::atomic::AtomicUsize::new(0);
|
||||
|
||||
std::thread::scope(|scope| {
|
||||
scope.spawn(|| {
|
||||
while !done.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
let Some(stand_in) = current.lock().unwrap().clone() else {
|
||||
std::thread::yield_now();
|
||||
continue;
|
||||
};
|
||||
if db.effective_node_access(&stand_in).unwrap().is_none() {
|
||||
missing.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
});
|
||||
for n in 0..300 {
|
||||
let name = format!("new-{n}.txt");
|
||||
let lid = db.add_local_row(&parent, &name, false, 1).unwrap();
|
||||
let local = local_uid(lid);
|
||||
let stand_in = NodeUid::new(VolumeId::from("local"), LinkId::from(lid.to_string()));
|
||||
let mut node = file(&format!("new-{n}"), "parent", &name, 1);
|
||||
node.uid = stand_in.clone();
|
||||
db.upsert_node(&node).unwrap();
|
||||
let (id, _) = db
|
||||
.enqueue_op(&op_on(OP_CREATE, &local, Some(&parent)))
|
||||
.unwrap();
|
||||
*current.lock().unwrap() = Some(stand_in);
|
||||
db.claim_next_due_op(1).unwrap().unwrap();
|
||||
let real = uid(&format!("real-{n}")).to_string();
|
||||
db.finish_create(
|
||||
id,
|
||||
Some("/staging/create"),
|
||||
&landing(&local, &real, &parent, &name),
|
||||
|_| None,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
done.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
});
|
||||
|
||||
drop(db);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
assert_eq!(
|
||||
missing.into_inner(),
|
||||
0,
|
||||
"a landing stand-in read as missing"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stand_in_folder_stays_listed_once_its_create_has_landed() {
|
||||
let db = Db::open_in_memory().unwrap();
|
||||
|
||||
@@ -521,9 +521,13 @@ impl Syncer {
|
||||
/// folder may have committed a revision since, and uploading over it would
|
||||
/// leave that edit only in the revision history. So Drive is asked first,
|
||||
/// and a file that moved on is left for the next pass, which keeps the
|
||||
/// local edit as a conflict copy (B249). A revision committed between this
|
||||
/// check and the upload's own draft is not caught here; the read-back after
|
||||
/// the upload catches one committed after it.
|
||||
/// local edit as a conflict copy (B249). A revision committed after the
|
||||
/// upload is caught by the read-back.
|
||||
///
|
||||
/// When the pass knows the revision id, the check rides on the read of the
|
||||
/// file the upload makes for its keys (`upload_new_revision_over`), and the
|
||||
/// revision is created over that id, so Drive refuses one committed in
|
||||
/// between. A baseline without an id still reads the node first.
|
||||
pub(super) async fn upload_revision(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
@@ -536,22 +540,16 @@ impl Syncer {
|
||||
let Some(file) = open_to_upload(&path, rel)? else {
|
||||
return Ok(Applied::Vanished);
|
||||
};
|
||||
let current = self
|
||||
.drive
|
||||
.enumerate_nodes(std::slice::from_ref(uid))
|
||||
.await
|
||||
.map_err(|e| format!("check {rel} on Drive: {e}"))?;
|
||||
match current.first() {
|
||||
Some(node) if !node.trashed && seen.still_current(node) => {}
|
||||
Some(node) if !node.trashed => {
|
||||
return Err(format!(
|
||||
"{rel} changed on Drive since this pass looked; it is compared again on the next pass"
|
||||
));
|
||||
}
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"{rel} is no longer on Drive where this pass saw it; it is compared again on the next pass"
|
||||
));
|
||||
if seen.revision.is_none() {
|
||||
let current = self
|
||||
.drive
|
||||
.enumerate_nodes(std::slice::from_ref(uid))
|
||||
.await
|
||||
.map_err(|e| format!("check {rel} on Drive: {e}"))?;
|
||||
match current.first() {
|
||||
Some(node) if !node.trashed && seen.still_current(node) => {}
|
||||
Some(node) if !node.trashed => return Err(moved_on_drive(rel)),
|
||||
_ => return Err(gone_from_drive(rel)),
|
||||
}
|
||||
}
|
||||
let meta = file.metadata().map_err(|e| format!("stat {rel}: {e}"))?;
|
||||
@@ -569,13 +567,27 @@ impl Syncer {
|
||||
meta.len(),
|
||||
),
|
||||
));
|
||||
if let Err(e) = self
|
||||
.drive
|
||||
.upload_new_revision_from(uid, reader, meta.len() as i64, thumbnails, Some(mtime))
|
||||
.await
|
||||
{
|
||||
self.note_sent(folder_id, rel, "upload-revision", &sent.digest());
|
||||
return Err(format!("upload revision {rel}: {e}"));
|
||||
let size = meta.len() as i64;
|
||||
let uploaded = match seen.revision.as_deref() {
|
||||
Some(expected) => self
|
||||
.drive
|
||||
.upload_new_revision_over(uid, expected, reader, size, thumbnails, Some(mtime))
|
||||
.await
|
||||
.map(Some),
|
||||
None => self
|
||||
.drive
|
||||
.upload_new_revision_from(uid, reader, size, thumbnails, Some(mtime))
|
||||
.await
|
||||
.map(|()| None),
|
||||
};
|
||||
match uploaded {
|
||||
Ok(None | Some(pdfs_drive::RevisionUpload::Sealed(_))) => {}
|
||||
Ok(Some(pdfs_drive::RevisionUpload::Moved)) => return Err(moved_on_drive(rel)),
|
||||
Ok(Some(pdfs_drive::RevisionUpload::Trashed)) => return Err(gone_from_drive(rel)),
|
||||
Err(e) => {
|
||||
self.note_sent(folder_id, rel, "upload-revision", &sent.digest());
|
||||
return Err(format!("upload revision {rel}: {e}"));
|
||||
}
|
||||
}
|
||||
warn_if_torn(rel, &path, streamed);
|
||||
let remote = self
|
||||
@@ -745,3 +757,16 @@ impl Syncer {
|
||||
.map_err(|e| format!("baseline {rel}: {e:?}"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a revision was not sent: Drive's file moved on since the pass looked.
|
||||
fn moved_on_drive(rel: &str) -> String {
|
||||
format!("{rel} changed on Drive since this pass looked; it is compared again on the next pass")
|
||||
}
|
||||
|
||||
/// Why a revision was not sent: the file is no longer on Drive where the pass
|
||||
/// saw it.
|
||||
fn gone_from_drive(rel: &str) -> String {
|
||||
format!(
|
||||
"{rel} is no longer on Drive where this pass saw it; it is compared again on the next pass"
|
||||
)
|
||||
}
|
||||
+28
-1
@@ -108,6 +108,7 @@ a live account since.
|
||||
|
||||
| Entry | Title |
|
||||
|---|---|
|
||||
| [B306](#b306--a-change-made-as-its-nodes-create-lands-is-refused-with-permission-denied) | A change made as its node's create lands is refused with "Permission denied" |
|
||||
| [B305](#b305--a-mirrored-file-whose-upload-went-unanswered-gets-a-conflict-copy-of-its-own-edit) | A mirrored file whose upload went unanswered gets a conflict copy of its own edit |
|
||||
| [B304](#b304--a-write-released-while-its-files-create-lands-is-kept-as-a-conflict-copy) | A write released while its file's create lands is kept as a conflict copy |
|
||||
| [B303](#b303--a-file-made-where-a-withdrawn-create-was-listed-refuses-every-write) | A file made where a withdrawn create was listed refuses every write |
|
||||
@@ -408,6 +409,32 @@ a live account since.
|
||||
|
||||
Newest first.
|
||||
|
||||
### B306 — A change made as its node's create lands is refused with "Permission denied"
|
||||
|
||||
**Status:** Fixed (unverified)
|
||||
**Found:** 2026-11-28, from two simulation failures on #204, a GUI-only change.
|
||||
`one_client_with_stale_hashes_and_reordered_echoes` seed 5: `write e.md` was kept in staging
|
||||
with "access changed before the staged write could be queued", and the queues did not drain.
|
||||
`a_move_blocked_by_trash_can_be_retried_after_restore`: `mkdir source/nested` right after
|
||||
`mkdir source` failed with `EACCES`. The evidence logging from #177 said
|
||||
`refused=Unknown persisted=Ok(Some(Owner)) live=[Owner]`. By the time the evidence was read,
|
||||
both authorities called the node writable.
|
||||
**Where:** `Db::effective_node_access` in `crates/pdfs-store/src/db/share_access.rs`
|
||||
|
||||
**Cause.** B174's fix was incomplete. It finds a stand-in's row by local id, then checks that a
|
||||
row with the uid it found exists, then walks the ancestors. Each statement on a pooled reader is
|
||||
its own read, so each sees whatever was last committed. When a create landed between the first
|
||||
two, the first statement found the stand-in uid and the second checked a row that by then had
|
||||
Drive's uid. The answer was "no such node", which is `WriteAuthority::Unknown`, and the change
|
||||
was refused.
|
||||
|
||||
**Fix.** The statements run in one read transaction, so they see one snapshot.
|
||||
|
||||
**Verified:** `a_stand_in_is_never_missing_while_its_create_lands` lands 300 creates on a
|
||||
file-backed database while another thread asks for the stand-in's access. Without the fix it read
|
||||
the stand-in as missing 37 to 47 times in each of four runs. With the fix it read none in five
|
||||
runs.
|
||||
|
||||
### B305 — A mirrored file whose upload went unanswered gets a conflict copy of its own edit
|
||||
|
||||
**Status:** Fixed (unverified)
|
||||
@@ -4114,7 +4141,7 @@ tree does (B173's gap). A rename in between asked by the stand-in the tree still
|
||||
row under it, and was refused.
|
||||
|
||||
**Fix.** A stand-in is looked up by its local id, so it finds its row before and after the
|
||||
create lands.
|
||||
create lands. The lookup still left a gap while the create landed, closed by B306.
|
||||
|
||||
**Test:** `a_stand_in_keeps_its_access_once_its_create_has_landed` in
|
||||
`crates/pdfs-core/src/db/tests.rs`.
|
||||
|
||||
@@ -18,6 +18,14 @@ sends is recorded until its result is in (51), and an upload that heard no answe
|
||||
digest of what it sent (52).
|
||||
|
||||
### Added
|
||||
- **Small files go up to Proton Drive in one request.** A file whose encrypted size is under
|
||||
128 KiB, and a new revision of one, is now sent in a single request instead of a draft, its
|
||||
block and a commit. This covers synced folders and the drive mount. On a test account, a first
|
||||
sync of 200 small files ran 58% faster, and 50 edits of them 97% faster. Larger files go up in
|
||||
blocks as before. `proton-sdk` and `proton-drive-rs` are now 0.12.7.
|
||||
- **`small_uploads` in `config.json` turns off the one-request upload for small files.** It is
|
||||
on by default. Set it to `false` to send every file as a draft, its blocks and a commit, as
|
||||
before. The service reads it at start. See [Configuration](CONFIGURATION.md#small_uploads).
|
||||
- **`pdfs diagnostics` says which of the daemon's background services are running.** If one
|
||||
ends while the drive is mounted, for example the sync engine after a crash, the journal says
|
||||
so once, by name, instead of saying nothing until a restart. It also lists the jobs running
|
||||
@@ -27,6 +35,11 @@ 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` 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
|
||||
`small_uploads` is off or Proton Drive refuses it, this shows it. The JSON report has them as
|
||||
`upload_paths`.
|
||||
- **`pdfs diagnostics` counts every call the daemon makes to Proton Drive.** Per kind of call it
|
||||
shows how many were made since start, how many failed, and their total and longest time. The
|
||||
JSON report has them as `drive_calls`.
|
||||
@@ -47,6 +60,11 @@ digest of what it sent (52).
|
||||
any more.
|
||||
|
||||
### Changed
|
||||
- **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
|
||||
changed the file through the read the upload already makes, and it still sends nothing over
|
||||
a revision it has not seen. `proton-sdk` and `proton-drive-rs` are now 0.12.8.
|
||||
- **A sync pass over a quiet folder no longer reads the whole folder on disk.** While the
|
||||
filesystem watcher has been running without a break, a pass reads again only the folders and
|
||||
files it reported changed, and takes the rest from the pass before. The whole folder is still
|
||||
@@ -73,6 +91,67 @@ digest of what it sent (52).
|
||||
first pass, and whenever the change feed lost track (#53).
|
||||
|
||||
### Fixed
|
||||
- **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
|
||||
in Proton Drive could not be moved to the trash, for example while offline, the app and
|
||||
`pdfs sync rm --delete-remote` now report an error that says so. Before, they reported plain
|
||||
success, and the copy in Proton Drive stayed without a word.
|
||||
- **Discarding a queued change lists every change it undoes.** A discard drops every change
|
||||
queued on the same file or folder, but the dialog spoke of one change. It now lists them all,
|
||||
says whether the item goes back to how Proton Drive has it or is removed from this computer,
|
||||
and offers "Export My Version…" when the change carries file content.
|
||||
- **A file or folder changed just as its upload finishes is no longer refused with "Permission
|
||||
denied".** For a moment after Proton Drive took a new file or folder, the mount could find no
|
||||
record of it and refused the change: a write was kept in staging instead of being sent, and a
|
||||
folder made inside a new folder failed. The check now reads the database in one consistent
|
||||
view.
|
||||
- **The Trash page acts on what is selected, and says so when it cannot.** Inside a trashed
|
||||
folder, its items went to the trash with it, and only the folder can be restored. Restore now
|
||||
reads "Restore Folder “Projects”" there. Delete Permanently, from the bar or the
|
||||
Delete key, no longer deletes the whole folder for a selected item inside it. It explains that
|
||||
only the whole folder can be deleted, from the top of the trash. Restore on a row that groups
|
||||
the items deleted from one folder now shows how many items it restores.
|
||||
- **Stopping sharing or leaving several items says which ones did not go through.** The app
|
||||
sent one request per item and stopped at the first failure, with a generic error, so the items
|
||||
before it had already stopped sharing and the ones after it were never tried. Now every item is
|
||||
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
|
||||
|
||||
@@ -88,6 +88,7 @@ fix it.
|
||||
| `device_uid` | string | none | Computers → Continue This Backup Here… or Sync With This Computer… | The computer this machine syncs into. Unset means "match by hostname" |
|
||||
| `conflict_sweep` | `off` / `report` / `enforce` | `report` | Sync → Conflict Copies | See [`conflict_sweep`](#conflict_sweep) |
|
||||
| `local_first` | bool | `true` | — | See [`local_first`](#local_first) |
|
||||
| `small_uploads` | bool | `true` | — | See [`small_uploads`](#small_uploads) |
|
||||
| `language` | gettext code | system | General → Appearance | Language of the app, tray and prompt, such as `de` or `pt_BR` |
|
||||
| `proton_theme` | bool | follow system | General → Appearance | Proton's colours instead of the system theme |
|
||||
| `online_map` | bool | `false` | General → Appearance | Street map for Places from OpenFreeMap |
|
||||
@@ -145,6 +146,16 @@ call returns at once. The change goes to Drive from the queue, the same way it d
|
||||
Set it to `false` to have these calls wait for Drive again, as before 3.0.0. The switch is there
|
||||
for one release, in case the queued path misbehaves for you; please report it if it does.
|
||||
|
||||
### `small_uploads`
|
||||
|
||||
A file that fits in 128 KiB with its thumbnails goes to Proton Drive in one request. A larger one
|
||||
goes as a draft, its blocks, and a commit, which takes three requests or more. Most synced files
|
||||
are small, so this is what decides how fast a folder of many small files syncs.
|
||||
|
||||
Set it to `false` to upload every file in blocks again. The setting is read when the service
|
||||
starts. The journal says `small files are uploaded in blocks` while it is off. Please report it if
|
||||
you need to turn it off.
|
||||
|
||||
### `open_with`
|
||||
|
||||
Decides how files picked in the search launcher or the app are opened. Rules are tried in order;
|
||||
@@ -185,6 +196,7 @@ 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
|
||||
{
|
||||
|
||||
+26
-3
@@ -307,9 +307,32 @@ instance's keyring entry so the next run does not sign in again; `--logout` forg
|
||||
Proton asks for a CAPTCHA, sign in once by hand with `PDFS_INSTANCE=bench pdfs login`.
|
||||
|
||||
The script refuses a `pdfs` built without `PDFS_INSTANCE`, which would act on your own account.
|
||||
A new folder's first sync uploads about one small file every four seconds, so with a 500-file
|
||||
tree the edit is timed about 35 minutes in. A run that is cut short leaves its folder behind; the
|
||||
next run removes it.
|
||||
A new folder's first sync uploads about two small files a second (eight at a time), so with a
|
||||
500-file tree the edit is timed a few minutes in. A run that is cut short leaves its folder behind;
|
||||
the next run removes it.
|
||||
|
||||
### The small-file benchmark
|
||||
|
||||
`--scenario small` times many small files instead, the case that the API's one-request small
|
||||
upload is for. For each tree size (200 by default) it makes files of `--small-size` random bytes
|
||||
(4096 by default), plus `--images` noise PNGs that get thumbnails (10 by default). It then:
|
||||
|
||||
- times the first sync, until every file is uploaded and the folder is quiet
|
||||
- rewrites `--edits` of the files at once (50 by default) and times until all are uploaded again
|
||||
|
||||
For each phase it reports wall time, files per second, the daemon's CPU time, and the requests
|
||||
the daemon sent. The requests are API calls by method, plus storage uploads. It counts them from
|
||||
the SDK's telemetry: the daemon runs with `RUST_LOG=info,pgp=error,proton_sdk::telemetry=debug`,
|
||||
and its log goes to the work directory. If the SDK tags each request with its endpoint, the JSON
|
||||
output also counts requests per endpoint.
|
||||
|
||||
```bash
|
||||
scripts/live-bench.py --account-env path/to/.env --pdfs target/release/pdfs --scenario small \
|
||||
--json small.json
|
||||
```
|
||||
|
||||
Wall time varies by 2x between runs against the live service. Compare medians of three runs,
|
||||
and treat the request counts as the stable measure.
|
||||
|
||||
## Before a release
|
||||
|
||||
|
||||
+1079
-749
File diff suppressed because it is too large.
Load diff
+1029
-750
File diff suppressed because it is too large.
Load diff
+1083
-749
File diff suppressed because it is too large.
Load diff
+319
-6
@@ -2,7 +2,10 @@
|
||||
"""Time one edit in a synced folder, from the write to the new revision on Drive.
|
||||
|
||||
Runs against a real account on a separate instance (`PDFS_INSTANCE`), so the
|
||||
user's own daemon and session are never touched. For each tree size it:
|
||||
user's own daemon and session are never touched. There are two scenarios,
|
||||
picked with `--scenario`.
|
||||
|
||||
`edit` (the default) times one edit. For each tree size it:
|
||||
|
||||
1. makes a disposable folder in My files and a local tree of that many files,
|
||||
2. attaches the local tree to it and waits for the first sync to finish,
|
||||
@@ -12,6 +15,19 @@ user's own daemon and session are never touched. For each tree size it:
|
||||
- verify: the pass end until `pdfs versions list` shows the new revision,
|
||||
4. detaches the folder and trashes the remote copy.
|
||||
|
||||
`small` times many small files, the case Proton's one-request small upload is
|
||||
for. For each tree size it:
|
||||
|
||||
1. makes a tree of files of `--small-size` random bytes, plus `--images` noise
|
||||
PNGs that get thumbnails, and attaches it,
|
||||
2. times the first sync until every file is uploaded and the folder is quiet,
|
||||
3. rewrites `--edits` of the files at once and times until all of them are
|
||||
uploaded again,
|
||||
4. reports, for each phase, the wall time, files per second, the daemon's CPU
|
||||
time and the requests it sent: API calls by method, and storage uploads.
|
||||
The requests come from the SDK's telemetry, so the daemon runs with
|
||||
`proton_sdk::telemetry=debug`.
|
||||
|
||||
The account comes from an env file with `username=`, `password=` and, for an
|
||||
account with two-factor sign-in, `PROTON_TOTP_SECRET=`. It is read here and
|
||||
typed into `pdfs login` over a pseudo-terminal; it is never printed or written
|
||||
@@ -33,6 +49,8 @@ import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import pty
|
||||
import select
|
||||
import shutil
|
||||
@@ -43,6 +61,7 @@ import sys
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
POLL = 0.1
|
||||
@@ -300,6 +319,288 @@ def bench_one(
|
||||
shutil.rmtree(local, ignore_errors=True)
|
||||
|
||||
|
||||
ANSI = re.compile(r"\x1b\[[0-9;]*m")
|
||||
OPERATION = re.compile(r"operation=\W*(\w+)")
|
||||
METHOD = re.compile(r"method=(\w+)")
|
||||
ENDPOINT = re.compile(r"endpoint=(\S+)")
|
||||
SDK_LOG = "info,pgp=error,proton_sdk::telemetry=debug"
|
||||
# Slower than `POLL`: each poll is a diagnostics request to the daemon, and the
|
||||
# small-file scenario measures the daemon's CPU time.
|
||||
SMALL_POLL = 0.5
|
||||
|
||||
|
||||
class Requests:
|
||||
"""Counts the requests the daemon logs through the SDK's telemetry, from a
|
||||
byte offset of its log on."""
|
||||
|
||||
def __init__(self, log: Path) -> None:
|
||||
self.log = log
|
||||
self.offset = log.stat().st_size
|
||||
|
||||
def take(self) -> dict[str, int]:
|
||||
with self.log.open("rb") as file:
|
||||
file.seek(self.offset)
|
||||
chunk = file.read()
|
||||
self.offset = file.tell()
|
||||
counts: dict[str, int] = {}
|
||||
for line in ANSI.sub("", chunk.decode(errors="replace")).splitlines():
|
||||
if "proton_sdk::telemetry" not in line:
|
||||
continue
|
||||
found = OPERATION.search(line)
|
||||
if not found:
|
||||
continue
|
||||
operation = found.group(1)
|
||||
if operation == "http_request":
|
||||
method = METHOD.search(line)
|
||||
key = f"api {method.group(1) if method else '?'}"
|
||||
# SDKs that tag the endpoint also get a count per endpoint.
|
||||
route = ENDPOINT.search(line)
|
||||
if route:
|
||||
detail = f"endpoint {method.group(1) if method else '?'} {route.group(1)}"
|
||||
counts[detail] = counts.get(detail, 0) + 1
|
||||
elif operation.startswith("storage_"):
|
||||
key = operation.replace("_", " ")
|
||||
else:
|
||||
key = f"op {operation}"
|
||||
counts[key] = counts.get(key, 0) + 1
|
||||
return counts
|
||||
|
||||
|
||||
def cpu_seconds(pid: int) -> float:
|
||||
"""User and system CPU time of `pid` so far."""
|
||||
fields = Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()
|
||||
return (int(fields[11]) + int(fields[12])) / os.sysconf("SC_CLK_TCK")
|
||||
|
||||
|
||||
def noise_png(path: Path, side: int, rng: random.Random) -> None:
|
||||
"""A PNG of random pixels: it does not compress, so its size is known, and
|
||||
the daemon makes thumbnails for it."""
|
||||
|
||||
def chunk(kind: bytes, data: bytes) -> bytes:
|
||||
body = kind + data
|
||||
return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body))
|
||||
|
||||
rows = b"".join(b"\x00" + rng.randbytes(side * 3) for _ in range(side))
|
||||
path.write_bytes(
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
+ chunk(b"IHDR", struct.pack(">IIBBBBB", side, side, 8, 2, 0, 0, 0))
|
||||
+ chunk(b"IDAT", zlib.compress(rows, 1))
|
||||
+ chunk(b"IEND", b"")
|
||||
)
|
||||
|
||||
|
||||
def make_small_tree(
|
||||
root: Path, files: int, size: int, images: int, rng: random.Random, per_dir: int = 50
|
||||
) -> list[Path]:
|
||||
paths = []
|
||||
for index in range(files):
|
||||
directory = root / f"d{index // per_dir:04d}"
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
path = directory / f"f{index:06d}.bin"
|
||||
path.write_bytes(rng.randbytes(size))
|
||||
paths.append(path)
|
||||
if images:
|
||||
(root / "pictures").mkdir()
|
||||
for index in range(images):
|
||||
noise_png(root / "pictures" / f"p{index:04d}.png", 120, rng)
|
||||
return paths
|
||||
|
||||
|
||||
class Passes:
|
||||
"""The passes over one folder that ended, as the diagnostics show them.
|
||||
They keep only the last one, so poll often enough to see each."""
|
||||
|
||||
def __init__(self, pdfs: Pdfs, folder_id: int, stale: set[str]) -> None:
|
||||
self.pdfs = pdfs
|
||||
self.folder_id = folder_id
|
||||
self.stale = stale
|
||||
self.last: str | None = None
|
||||
self.ended: list[dict] = []
|
||||
|
||||
def poll(self) -> dict:
|
||||
state = sync_state(self.pdfs)
|
||||
trace = trace_for(state, self.folder_id)
|
||||
if trace and trace.get("ended") and state.get("pass_folder") != self.folder_id:
|
||||
key = json.dumps(trace, sort_keys=True)
|
||||
if key != self.last and key not in self.stale:
|
||||
self.last = key
|
||||
self.ended.append(trace)
|
||||
return state
|
||||
|
||||
def calls(self, name: str, since: int = 0) -> int:
|
||||
return sum(
|
||||
call["count"]
|
||||
for trace in self.ended[since:]
|
||||
for call in trace.get("calls", [])
|
||||
if call["name"] == name
|
||||
)
|
||||
|
||||
def totals(self, since: int = 0) -> dict[str, dict[str, int]]:
|
||||
totals: dict[str, dict[str, int]] = {}
|
||||
for trace in self.ended[since:]:
|
||||
for kind in ("phases", "calls"):
|
||||
for stat in trace.get(kind, []):
|
||||
entry = totals.setdefault(f"{kind[:-1]} {stat['name']}", {"count": 0, "ms": 0})
|
||||
entry["count"] += stat["count"]
|
||||
entry["ms"] += stat["total_ms"]
|
||||
return totals
|
||||
|
||||
def wait_for(
|
||||
self, what: str, name: str, at_least: int, since: int, quiet: float, timeout: float
|
||||
) -> float:
|
||||
"""Wait until the passes since `since` made `at_least` calls of `name`,
|
||||
then until no pass ran for `quiet` seconds. Returns when the last pass
|
||||
that did work was seen to end."""
|
||||
deadline = time.monotonic() + timeout
|
||||
while self.calls(name, since) < at_least:
|
||||
if time.monotonic() > deadline:
|
||||
raise TimeoutError(
|
||||
f"timed out waiting for {what}: {self.calls(name, since)} of {at_least}"
|
||||
)
|
||||
self.poll()
|
||||
time.sleep(SMALL_POLL)
|
||||
done = time.monotonic()
|
||||
seen = len(self.ended)
|
||||
while time.monotonic() - done < quiet:
|
||||
if time.monotonic() > deadline:
|
||||
raise TimeoutError(f"the folder did not go quiet after {what}")
|
||||
state = self.poll()
|
||||
if state.get("pass_folder") == self.folder_id or len(self.ended) != seen:
|
||||
seen = len(self.ended)
|
||||
done = time.monotonic()
|
||||
time.sleep(SMALL_POLL)
|
||||
return done
|
||||
|
||||
|
||||
def upload_paths(pdfs: Pdfs) -> dict[str, int]:
|
||||
"""Uploads since the daemon started, by the path the SDK took (`small` or
|
||||
`blocks`), as `pdfs diagnostics` counts them. Empty from an older build."""
|
||||
value = pdfs.json("diagnostics")
|
||||
|
||||
def find(node: object) -> list | None:
|
||||
if isinstance(node, dict):
|
||||
if isinstance(node.get("upload_paths"), list):
|
||||
return node["upload_paths"]
|
||||
for child in node.values():
|
||||
found = find(child)
|
||||
if found is not None:
|
||||
return found
|
||||
return None
|
||||
|
||||
return {stat["path"]: stat["count"] for stat in find(value) or []}
|
||||
|
||||
|
||||
def since_then(now: dict[str, int], then: dict[str, int]) -> dict[str, int]:
|
||||
return {path: count - then.get(path, 0) for path, count in now.items()}
|
||||
|
||||
|
||||
def phase_result(
|
||||
files: int, wall: float, cpu: float, requests: dict[str, int], passes: Passes, since: int
|
||||
) -> dict:
|
||||
sent = sum(n for key, n in requests.items() if key.startswith(("api ", "storage upload")))
|
||||
return {
|
||||
"files": files,
|
||||
"wall_s": round(wall, 2),
|
||||
"files_per_s": round(files / wall, 3) if wall else None,
|
||||
"cpu_s": round(cpu, 2),
|
||||
"cpu_ms_per_file": round(cpu * 1000 / files) if files else None,
|
||||
"requests": requests,
|
||||
"requests_per_file": round(sent / files, 2) if files else None,
|
||||
"passes": len(passes.ended) - since,
|
||||
"totals": passes.totals(since),
|
||||
}
|
||||
|
||||
|
||||
def bench_small(
|
||||
pdfs: Pdfs, daemon_pid: int, mount: Path, work: Path, files: int, args: argparse.Namespace
|
||||
) -> dict:
|
||||
rng = random.Random(files)
|
||||
name = f"pdfs-bench-small-{files}-{uuid.uuid4().hex[:8]}"
|
||||
local = work / name
|
||||
local.mkdir()
|
||||
paths = make_small_tree(local, files, args.small_size, args.images, rng)
|
||||
uploads = files + args.images
|
||||
pdfs.run("mkdir", str(mount), name)
|
||||
folder_id = None
|
||||
try:
|
||||
stale = {json.dumps(t, sort_keys=True) for t in sync_state(pdfs).get("traces", [])}
|
||||
requests = Requests(work / "daemon.log")
|
||||
paths_before = upload_paths(pdfs)
|
||||
cpu = cpu_seconds(daemon_pid)
|
||||
started = time.monotonic()
|
||||
pdfs.run("sync", "attach", "--to", name, str(local))
|
||||
folder = next(
|
||||
item
|
||||
for item in pdfs.json("sync", "list")["items"]
|
||||
if Path(item["local_path"]).resolve() == local.resolve()
|
||||
)
|
||||
folder_id = folder["id"]
|
||||
passes = Passes(pdfs, folder_id, stale)
|
||||
done = passes.wait_for("the first sync", "upload", uploads, 0, args.quiet, args.timeout)
|
||||
first = phase_result(
|
||||
uploads, done - started, cpu_seconds(daemon_pid) - cpu, requests.take(), passes, 0
|
||||
)
|
||||
paths_after = upload_paths(pdfs)
|
||||
first["upload_paths"] = since_then(paths_after, paths_before)
|
||||
|
||||
edits = min(args.edits, files)
|
||||
edited = rng.sample(paths, edits)
|
||||
since = len(passes.ended)
|
||||
cpu = cpu_seconds(daemon_pid)
|
||||
started = time.monotonic()
|
||||
for path in edited:
|
||||
path.write_bytes(rng.randbytes(args.small_size))
|
||||
done = passes.wait_for(
|
||||
"the edits", "upload revision", edits, since, args.quiet, args.timeout
|
||||
)
|
||||
edit = phase_result(
|
||||
edits, done - started, cpu_seconds(daemon_pid) - cpu, requests.take(), passes, since
|
||||
)
|
||||
edit["upload_paths"] = since_then(upload_paths(pdfs), paths_after)
|
||||
# The counts say the edits were sent; a few read back say they landed.
|
||||
for path in edited[:3]:
|
||||
remote_path = f"{name}/{path.relative_to(local)}"
|
||||
wait("the edit on Drive", lambda p=remote_path: revisions(pdfs, p) >= 2, args.timeout)
|
||||
return {
|
||||
"scenario": "small",
|
||||
"files": files,
|
||||
"images": args.images,
|
||||
"size": args.small_size,
|
||||
"first_sync": first,
|
||||
"edits": edit,
|
||||
}
|
||||
finally:
|
||||
if folder_id is not None:
|
||||
for _ in range(20):
|
||||
try:
|
||||
pdfs.run("sync", "rm", str(folder_id))
|
||||
break
|
||||
except Exception as error: # noqa: BLE001
|
||||
print(f" sync rm: {error}; retrying", file=sys.stderr)
|
||||
time.sleep(6)
|
||||
with contextlib.suppress(Exception):
|
||||
pdfs.run("rm", f"{mount}/{name}")
|
||||
shutil.rmtree(local, ignore_errors=True)
|
||||
|
||||
|
||||
def print_small(result: dict) -> None:
|
||||
print(f"{result['files']:>6} files of {result['size']} B and {result['images']} images:")
|
||||
for phase in ("first_sync", "edits"):
|
||||
r = result[phase]
|
||||
sent = ", ".join(
|
||||
f"{k} {v}" for k, v in sorted(r["requests"].items()) if not k.startswith(("op ", "endpoint "))
|
||||
)
|
||||
print(
|
||||
f" {phase}: {r['files']} files in {r['wall_s']} s ({r['files_per_s']}/s), "
|
||||
f"CPU {r['cpu_s']} s ({r['cpu_ms_per_file']} ms/file), "
|
||||
f"{r['requests_per_file']} requests/file over {r['passes']} passes"
|
||||
)
|
||||
print(f" requests: {sent}")
|
||||
if r.get("upload_paths"):
|
||||
split = ", ".join(f"{k} {v}" for k, v in sorted(r["upload_paths"].items()))
|
||||
print(f" uploads by path: {split}")
|
||||
|
||||
|
||||
def refuse_without_instances(binary: str) -> None:
|
||||
"""Stop unless `binary` honours PDFS_INSTANCE. One built before it existed
|
||||
ignores the variable and would sign in, attach and delete on the default
|
||||
@@ -348,7 +649,11 @@ def main() -> int:
|
||||
parser.add_argument("--account-env", type=Path, required=True, help="env file with the test account")
|
||||
parser.add_argument("--pdfs", default="pdfs", help="the pdfs CLI to run")
|
||||
parser.add_argument("--instance", default="bench", help="PDFS_INSTANCE to run under")
|
||||
parser.add_argument("--sizes", default="20,500", help="tree sizes, comma-separated")
|
||||
parser.add_argument("--scenario", choices=("edit", "small"), default="edit", help="what to time")
|
||||
parser.add_argument("--sizes", help="tree sizes, comma-separated (default 20,500; 200 for small)")
|
||||
parser.add_argument("--small-size", type=int, default=4096, help="bytes per file (small)")
|
||||
parser.add_argument("--images", type=int, default=10, help="noise PNGs with thumbnails (small)")
|
||||
parser.add_argument("--edits", type=int, default=50, help="files rewritten at once (small)")
|
||||
parser.add_argument("--timeout", type=float, default=3600, help="seconds per wait")
|
||||
parser.add_argument(
|
||||
"--quiet", type=float, default=15, help="seconds without a pass before the edit"
|
||||
@@ -368,8 +673,11 @@ def main() -> int:
|
||||
work = args.work or Path(tempfile.mkdtemp(prefix="pdfs-bench-"))
|
||||
work.mkdir(parents=True, exist_ok=True)
|
||||
log = (work / "daemon.log").open("w")
|
||||
daemon_env = dict(pdfs.env)
|
||||
if args.scenario == "small":
|
||||
daemon_env["RUST_LOG"] = SDK_LOG
|
||||
daemon = subprocess.Popen(
|
||||
[args.pdfs, "daemon"], env=pdfs.env, stdin=subprocess.DEVNULL, stdout=log, stderr=log
|
||||
[args.pdfs, "daemon"], env=daemon_env, stdin=subprocess.DEVNULL, stdout=log, stderr=log
|
||||
)
|
||||
results = []
|
||||
try:
|
||||
@@ -380,9 +688,14 @@ def main() -> int:
|
||||
)
|
||||
mount = Path(status["mount"].get("mountpoint") or Path.home() / f"ProtonDrive-{args.instance}")
|
||||
remove_leftovers(pdfs, mount)
|
||||
for size in (int(s) for s in args.sizes.split(",")):
|
||||
result = bench_one(pdfs, mount, work, size, args.timeout, args.quiet)
|
||||
print_result(result)
|
||||
sizes = args.sizes or ("200" if args.scenario == "small" else "20,500")
|
||||
for size in (int(s) for s in sizes.split(",")):
|
||||
if args.scenario == "small":
|
||||
result = bench_small(pdfs, daemon.pid, mount, work, size, args)
|
||||
print_small(result)
|
||||
else:
|
||||
result = bench_one(pdfs, mount, work, size, args.timeout, args.quiet)
|
||||
print_result(result)
|
||||
results.append(result)
|
||||
if args.json:
|
||||
args.json.write_text(json.dumps(results, indent=2))
|
||||
|
||||
Reference in new issue
Block a user