mirror of
https://github.com/narrrl/proton-drive-linux.git
synced 2026-11-16 09:51:59 +01:00
Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f239dffbcc | ||
|
|
e011a0d89f | ||
|
|
f2c4c05f27 | ||
|
|
8598aff7dd | ||
|
|
38a8db0e3e | ||
|
|
db8c0cb382 | ||
|
|
a7baf2313c | ||
|
|
7e0d7d020e | ||
|
|
0df4b3c5f9 | ||
|
|
14b9e0fe64 | ||
|
|
64864562ef | ||
|
|
ce3bfa217d |
No files matched your search
@@ -44,6 +44,9 @@ jobs:
|
||||
- name: Formatting
|
||||
run: cargo fmt --all -- --check
|
||||
|
||||
- name: Shell scripts of the release tarball
|
||||
run: shellcheck packaging/tarball/*.sh
|
||||
|
||||
- name: Lints
|
||||
run: cargo clippy --workspace --all-targets --locked -- -D warnings
|
||||
|
||||
|
||||
@@ -119,17 +119,12 @@ jobs:
|
||||
echo "VERSION=$VERSION" >> $GITHUB_ENV
|
||||
echo "Building version: $VERSION"
|
||||
|
||||
- name: Package raw binaries (.tar.gz)
|
||||
# Binaries plus everything around them, with install.sh for a home
|
||||
# directory install (immutable distributions, anything without a package).
|
||||
- name: Package the installable tarball (.tar.gz)
|
||||
run: |
|
||||
mkdir -p dist/binaries
|
||||
cp target/release/pdfs dist/binaries/
|
||||
cp target/release/pdfs-tray dist/binaries/
|
||||
cp target/release/pdfs-app dist/binaries/
|
||||
cp target/release/pdfs-prompt dist/binaries/
|
||||
po/build.sh dist/binaries/locale
|
||||
|
||||
# Create tarball
|
||||
tar -czf proton-drive-linux-${{ env.VERSION }}-x86_64.tar.gz -C dist/binaries .
|
||||
tarball=$(packaging/tarball/build.sh target/release "${{ env.VERSION }}" .)
|
||||
packaging/tarball/test.sh "$tarball"
|
||||
|
||||
# Every crate the build needs, so COPR can build the spec without network.
|
||||
- name: Package vendored crates (.tar.xz)
|
||||
|
||||
Generated
+8
@@ -3604,6 +3604,7 @@ dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.23.1",
|
||||
"chrono",
|
||||
"dbus-secret-service",
|
||||
"dbus-secret-service-keyring-store",
|
||||
"directories",
|
||||
"ignore",
|
||||
@@ -3618,6 +3619,7 @@ dependencies = [
|
||||
"serde_json",
|
||||
"sha1 0.11.0",
|
||||
"sha2 0.11.1",
|
||||
"shell-words",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"tracing",
|
||||
@@ -4804,6 +4806,12 @@ dependencies = [
|
||||
"lazy_static",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shell-words"
|
||||
version = "1.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc6fe69c597f9c37bfeeeeeb33da3530379845f10be461a66d16d03eca2ded77"
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "2.0.1"
|
||||
|
||||
@@ -39,6 +39,8 @@ tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
directories = "6"
|
||||
ignore = "0.4"
|
||||
# Command lines typed into Preferences, split and shown the way a shell would.
|
||||
shell-words = "1"
|
||||
sha2 = "0.11"
|
||||
# Google Takeout exports are zip sets; the importer reads their central
|
||||
# directories and streams entries out without extracting to disk first.
|
||||
@@ -60,6 +62,9 @@ rusqlite = { version = "0.41", features = ["bundled"] }
|
||||
# with no `target` it matches items v3 wrote, so existing logins survive.
|
||||
keyring-core = "1"
|
||||
dbus-secret-service-keyring-store = { version = "1", features = ["crypto-rust"] }
|
||||
# The same Secret Service client the store wraps, used directly to replace an
|
||||
# item instead of editing it, which oo7 before 0.7.0 kept only in memory (B291).
|
||||
dbus-secret-service = { version = "4.1", features = ["crypto-rust"] }
|
||||
clap = { version = "4", features = ["derive"] }
|
||||
# `unstable-dynamic`: Tab calls `pdfs` back, so arguments complete from the
|
||||
# running service. Only `pdfs-cli/src/complete.rs` uses it.
|
||||
|
||||
@@ -77,7 +77,8 @@ scriptable CLI.
|
||||
| Arch Linux | [`proton-drive-for-linux`](https://aur.archlinux.org/packages/proton-drive-for-linux) (also `-bin` and `-git`) in the AUR |
|
||||
| Debian, Ubuntu 24.04 or newer | `.deb` from the [latest release](https://github.com/narrrl/proton-drive-linux/releases/latest) |
|
||||
| NixOS | The flake in this repository: see [Installation → NixOS](docs/INSTALL.md#nixos-flake) |
|
||||
| Anything else | [Build from source](docs/INSTALL.md#build-from-source) |
|
||||
| Fedora Atomic (Silverblue, Kinoite, Bazzite, Bluefin) | The COPR repository, layered with `rpm-ostree`: see [Installation → Fedora Atomic](docs/INSTALL.md#fedora-atomic-silverblue-kinoite-bazzite-bluefin) |
|
||||
| Anything else, immutable ones included | `.tar.gz` from the [latest release](https://github.com/narrrl/proton-drive-linux/releases/latest), installed into your home folder by its `install.sh`: see [Installation → Other distributions](docs/INSTALL.md#other-distributions), or [build from source](docs/INSTALL.md#build-from-source) |
|
||||
|
||||
**Fedora**
|
||||
|
||||
|
||||
+246
-2
@@ -15,8 +15,8 @@ use pdfs_core::cache::ContentCache;
|
||||
use pdfs_core::config::AppDirs;
|
||||
use pdfs_core::control::{
|
||||
ConflictKeep, ErrorKind, LinkChange, MountKind, RefreshScope, Request as CtlRequest,
|
||||
Response as CtlResponse, RestoreItem as CtlRestoreItem, ShareEntryKind, SyncIssue, SyncPhase,
|
||||
daemon_outdated, pending_summary,
|
||||
Response as CtlResponse, RestoreItem as CtlRestoreItem, ShareEntryKind, SyncFolderInfo,
|
||||
SyncIssue, SyncPhase, daemon_outdated, pending_summary,
|
||||
};
|
||||
use pdfs_core::db::Db;
|
||||
use pdfs_core::service;
|
||||
@@ -751,6 +751,42 @@ enum ConflictCmd {
|
||||
},
|
||||
}
|
||||
|
||||
/// `pdfs sync ignore`: the patterns in `ignore_patterns`, for every synced
|
||||
/// folder, or with `--folder` the ones in that folder's own `.pdfsignore`.
|
||||
#[derive(Subcommand, Debug)]
|
||||
enum IgnoreCmd {
|
||||
/// List the patterns every synced folder leaves out, or one folder's own.
|
||||
List {
|
||||
/// List the own patterns of the synced folder holding this path.
|
||||
#[arg(long, value_hint = ValueHint::DirPath)]
|
||||
folder: Option<PathBuf>,
|
||||
},
|
||||
/// Leave out files matching a gitignore-style pattern, e.g. `*.db` or `build/`.
|
||||
Add {
|
||||
/// The pattern; end it with `/` to match folders only.
|
||||
pattern: String,
|
||||
/// Add it only for the synced folder holding this path.
|
||||
#[arg(long, value_hint = ValueHint::DirPath)]
|
||||
folder: Option<PathBuf>,
|
||||
},
|
||||
/// Stop leaving out files matching a pattern.
|
||||
Remove {
|
||||
/// The pattern, as `sync ignore list` shows it.
|
||||
pattern: String,
|
||||
/// Remove it from the own patterns of the synced folder holding this path.
|
||||
#[arg(long, value_hint = ValueHint::DirPath)]
|
||||
folder: Option<PathBuf>,
|
||||
},
|
||||
/// Go back to the built-in patterns.
|
||||
Reset,
|
||||
/// Say whether a file in a synced folder is synced, and which pattern decides.
|
||||
Check {
|
||||
/// A file or folder inside a synced folder.
|
||||
#[arg(value_hint = ValueHint::AnyPath)]
|
||||
path: PathBuf,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum SyncCmd {
|
||||
/// Add a local folder to this machine's device and upload its contents.
|
||||
@@ -849,6 +885,11 @@ enum SyncCmd {
|
||||
#[arg(add = ArgValueCandidates::new(complete::queue_id))]
|
||||
id: Option<i64>,
|
||||
},
|
||||
/// Show or change the patterns every synced folder leaves out, or check a path.
|
||||
Ignore {
|
||||
#[command(subcommand)]
|
||||
action: IgnoreCmd,
|
||||
},
|
||||
/// Switch a folder between full-copy sync and on-demand (FUSE, no local storage).
|
||||
Mode {
|
||||
/// Synced-folder id (from `sync list`).
|
||||
@@ -1324,6 +1365,7 @@ fn cmd_sync(action: SyncCmd) -> Result<()> {
|
||||
SyncCmd::Issues => return cmd_sync_issues(),
|
||||
SyncCmd::Export { id, dest } => return cmd_sync_export(id, &dest),
|
||||
SyncCmd::Limit { up, down } => return cmd_sync_limit(up, down),
|
||||
SyncCmd::Ignore { action } => return cmd_sync_ignore(action),
|
||||
SyncCmd::Discard { id, yes } => {
|
||||
if !yes {
|
||||
confirm(&format!(
|
||||
@@ -3699,6 +3741,173 @@ fn cmd_sync_limit(up: Option<u64>, down: Option<u64>) -> Result<()> {
|
||||
})?)
|
||||
}
|
||||
|
||||
fn cmd_sync_ignore(action: IgnoreCmd) -> Result<()> {
|
||||
use pdfs_core::syncignore::{
|
||||
DEFAULT_IGNORE_PATTERNS, FolderRules, IgnoreRules, RuleSource, Verdict, add_folder_pattern,
|
||||
check_pattern, remove_folder_pattern,
|
||||
};
|
||||
let dirs = AppDirs::new()?;
|
||||
let change = |edit: &dyn Fn(&mut Vec<String>)| -> Result<()> {
|
||||
dirs.change_ignore_patterns(edit)?;
|
||||
// The next pass picks the change up anyway; this only hurries it.
|
||||
let _ = control_request(CtlRequest::SyncNow { id: None });
|
||||
Ok(())
|
||||
};
|
||||
let valid = |pattern: &str| -> Result<String> {
|
||||
let pattern = pattern.trim();
|
||||
if pattern.is_empty() || pattern.starts_with('#') {
|
||||
bail!("not a pattern: `{pattern}`");
|
||||
}
|
||||
check_pattern(pattern).map_err(|e| anyhow!("not a valid pattern: {e}"))?;
|
||||
Ok(pattern.to_string())
|
||||
};
|
||||
match action {
|
||||
IgnoreCmd::List { folder: None } => {
|
||||
let config = dirs.load_config();
|
||||
let list = config.resolved_ignore_patterns();
|
||||
if list.is_empty() {
|
||||
println!("No patterns: every file is synced.");
|
||||
}
|
||||
for pattern in list {
|
||||
if DEFAULT_IGNORE_PATTERNS.contains(&pattern.as_str()) {
|
||||
println!("{pattern} (built in)");
|
||||
} else {
|
||||
println!("{pattern}");
|
||||
}
|
||||
}
|
||||
}
|
||||
IgnoreCmd::List {
|
||||
folder: Some(folder),
|
||||
} => {
|
||||
let (_, root) = mirror_folder_of(&folder)?;
|
||||
let rules = FolderRules::read(&root)?;
|
||||
let patterns = rules.patterns();
|
||||
if patterns.is_empty() {
|
||||
println!(
|
||||
"{} has no own patterns; the ones for all synced folders apply.",
|
||||
root.display()
|
||||
);
|
||||
}
|
||||
for pattern in patterns {
|
||||
println!("{pattern}");
|
||||
}
|
||||
}
|
||||
IgnoreCmd::Add {
|
||||
pattern,
|
||||
folder: None,
|
||||
} => {
|
||||
let pattern = valid(&pattern)?;
|
||||
change(&|list| {
|
||||
if !list.contains(&pattern) {
|
||||
list.push(pattern.clone());
|
||||
}
|
||||
})?;
|
||||
}
|
||||
IgnoreCmd::Add {
|
||||
pattern,
|
||||
folder: Some(folder),
|
||||
} => {
|
||||
let pattern = valid(&pattern)?;
|
||||
let (id, root) = mirror_folder_of(&folder)?;
|
||||
if add_folder_pattern(&root, &pattern)? {
|
||||
let _ = control_request(CtlRequest::SyncNow { id: Some(id) });
|
||||
} else {
|
||||
println!("`{pattern}` is already in {}/.pdfsignore.", root.display());
|
||||
}
|
||||
}
|
||||
IgnoreCmd::Remove {
|
||||
pattern,
|
||||
folder: None,
|
||||
} => {
|
||||
let pattern = pattern.trim().to_string();
|
||||
let list = dirs.load_config().resolved_ignore_patterns();
|
||||
if !list.contains(&pattern) {
|
||||
bail!("`{pattern}` is not in the list; see `pdfs sync ignore list`");
|
||||
}
|
||||
change(&|list| list.retain(|p| *p != pattern))?;
|
||||
}
|
||||
IgnoreCmd::Remove {
|
||||
pattern,
|
||||
folder: Some(folder),
|
||||
} => {
|
||||
let (id, root) = mirror_folder_of(&folder)?;
|
||||
if !remove_folder_pattern(&root, &pattern)? {
|
||||
bail!(
|
||||
"`{}` is not among the own patterns of {}; see `pdfs sync ignore list --folder {}`",
|
||||
pattern.trim(),
|
||||
root.display(),
|
||||
root.display()
|
||||
);
|
||||
}
|
||||
let _ = control_request(CtlRequest::SyncNow { id: Some(id) });
|
||||
}
|
||||
IgnoreCmd::Reset => change(&|list| {
|
||||
*list = DEFAULT_IGNORE_PATTERNS
|
||||
.iter()
|
||||
.map(|p| (*p).to_string())
|
||||
.collect()
|
||||
})?,
|
||||
IgnoreCmd::Check { path } => {
|
||||
let path = std::path::absolute(&path)?;
|
||||
let folder = synced_folder_of(&path)?;
|
||||
if folder.mode != "mirror" {
|
||||
println!(
|
||||
"{} is online only; patterns apply only to folders kept on this computer.",
|
||||
folder.local_path
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
let root = PathBuf::from(&folder.local_path);
|
||||
let rel = path.strip_prefix(&root).unwrap_or(&path).to_string_lossy();
|
||||
let globals = dirs.load_config().resolved_ignore_patterns();
|
||||
let rules = IgnoreRules::load(&root, &globals);
|
||||
let source = |source: &RuleSource| match source {
|
||||
RuleSource::AllFolders => "the patterns for all synced folders".to_string(),
|
||||
RuleSource::ThisFolder => format!("{}/.pdfsignore", root.display()),
|
||||
};
|
||||
match rules.explain(&rel, path.is_dir()) {
|
||||
Verdict::Synced => println!("Synced: no pattern matches it."),
|
||||
Verdict::Excluded { pattern, source: s } => {
|
||||
println!("Not synced: excluded by `{pattern}` in {}.", source(&s))
|
||||
}
|
||||
Verdict::Included { pattern, source: s } => {
|
||||
println!("Synced: `{pattern}` in {} includes it again.", source(&s))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The synced folder holding `path`: the innermost one, as the daemon lists
|
||||
/// them.
|
||||
fn synced_folder_of(path: &Path) -> Result<SyncFolderInfo> {
|
||||
let path = std::path::absolute(path)?;
|
||||
let folders = match control_request(CtlRequest::ListSyncFolders)? {
|
||||
CtlResponse::SyncFolders { items } => items,
|
||||
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
|
||||
other => bail!("unexpected reply: {other:?}"),
|
||||
};
|
||||
folders
|
||||
.into_iter()
|
||||
.filter(|f| path.starts_with(&f.local_path))
|
||||
.max_by_key(|f| f.local_path.len())
|
||||
.ok_or_else(|| anyhow!("{} is not in a synced folder", path.display()))
|
||||
}
|
||||
|
||||
/// The id and root of the synced folder kept on this computer that holds
|
||||
/// `path`. Own patterns mean nothing to an online-only folder.
|
||||
fn mirror_folder_of(path: &Path) -> Result<(i64, PathBuf)> {
|
||||
let folder = synced_folder_of(path)?;
|
||||
if folder.mode != "mirror" {
|
||||
bail!(
|
||||
"{} is online only; patterns apply only to folders kept on this computer",
|
||||
folder.local_path
|
||||
);
|
||||
}
|
||||
Ok((folder.id, PathBuf::from(folder.local_path)))
|
||||
}
|
||||
|
||||
/// How long the oldest write may wait to upload before `diagnose` calls it
|
||||
/// out. Under a day it is a slow link or a big file; past it, something is
|
||||
/// holding the queue.
|
||||
@@ -4646,6 +4855,41 @@ mod login_wait_tests {
|
||||
Command::ImportGooglePhotos { resume: true, .. }
|
||||
));
|
||||
assert!(Cli::try_parse_from(["pdfs", "import-google-photos"]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_ignore_takes_a_pattern_that_looks_like_an_option_after_dashes() {
|
||||
let cli = Cli::try_parse_from(["pdfs", "sync", "ignore", "add", "--", "-temp*"]).unwrap();
|
||||
assert!(matches!(
|
||||
cli.command,
|
||||
Command::Sync {
|
||||
action: SyncCmd::Ignore {
|
||||
action: IgnoreCmd::Add {
|
||||
ref pattern,
|
||||
folder: None
|
||||
}
|
||||
}
|
||||
} if pattern == "-temp*"
|
||||
));
|
||||
assert!(Cli::try_parse_from(["pdfs", "sync", "ignore", "add"]).is_err());
|
||||
assert!(Cli::try_parse_from(["pdfs", "sync", "ignore", "reset"]).is_ok());
|
||||
let cli =
|
||||
Cli::try_parse_from(["pdfs", "sync", "ignore", "add", "*.db", "--folder", "Work"])
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
cli.command,
|
||||
Command::Sync {
|
||||
action: SyncCmd::Ignore {
|
||||
action: IgnoreCmd::Add {
|
||||
ref pattern,
|
||||
folder: Some(ref folder)
|
||||
}
|
||||
}
|
||||
} if pattern == "*.db" && folder == Path::new("Work")
|
||||
));
|
||||
assert!(
|
||||
Cli::try_parse_from(["pdfs", "sync", "ignore", "list", "--folder", "Work"]).is_ok()
|
||||
);
|
||||
assert!(
|
||||
Cli::try_parse_from(["pdfs", "import-google-photos", "--resume", "a.zip"]).is_err()
|
||||
);
|
||||
|
||||
@@ -20,12 +20,14 @@ thiserror.workspace = true
|
||||
tracing.workspace = true
|
||||
directories.workspace = true
|
||||
ignore.workspace = true
|
||||
shell-words.workspace = true
|
||||
sha2.workspace = true
|
||||
sha1.workspace = true
|
||||
zip.workspace = true
|
||||
rusqlite.workspace = true
|
||||
keyring-core.workspace = true
|
||||
dbus-secret-service-keyring-store.workspace = true
|
||||
dbus-secret-service.workspace = true
|
||||
parking_lot.workspace = true
|
||||
async-trait.workspace = true
|
||||
libc.workspace = true
|
||||
|
||||
@@ -490,11 +490,48 @@ fn classify_verification_gate(e: ProtonError) -> Error {
|
||||
}
|
||||
}
|
||||
|
||||
/// Save `stored` to the keyring.
|
||||
///
|
||||
/// An existing entry is replaced by a new item rather than edited, because
|
||||
/// oo7 before 0.7.0 keeps an edit only in memory and a reboot brings the
|
||||
/// spent refresh token back (`docs/BUGS.md` B291). The usual write is the
|
||||
/// fallback: for the first save, and whenever replacing is not possible.
|
||||
fn write_stored(stored: &StoredSession) -> Result<()> {
|
||||
let json = Zeroizing::new(serde_json::to_string(stored)?);
|
||||
if replace_items() {
|
||||
match crate::secretservice::replace(KEYRING_SERVICE, KEYRING_USER, json.as_bytes()) {
|
||||
crate::secretservice::Replaced::Saved => return Ok(()),
|
||||
crate::secretservice::Replaced::Skipped(why) => {
|
||||
tracing::debug!(%why, "not replacing the keyring item; writing it in place");
|
||||
}
|
||||
}
|
||||
}
|
||||
with_keyring(|entry| entry.set_password(&json))
|
||||
}
|
||||
|
||||
/// Whether [`write_stored`] talks to the Secret Service directly: always,
|
||||
/// except in tests that use the in-memory store.
|
||||
#[cfg(not(test))]
|
||||
fn replace_items() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn replace_items() -> bool {
|
||||
tests::MOCK_STORE.lock().is_none()
|
||||
}
|
||||
|
||||
/// A short, one-way tag for a refresh token, for the log: enough to tell
|
||||
/// whether the token a start finds is the one the last save wrote, and
|
||||
/// nothing that helps anyone use it.
|
||||
fn fingerprint(token: &str) -> String {
|
||||
use sha2::{Digest, Sha256};
|
||||
Sha256::digest(token.as_bytes())[..4]
|
||||
.iter()
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Load the persisted session blob, or `Error::NotLoggedIn` if absent.
|
||||
pub fn load() -> Result<StoredSession> {
|
||||
match with_keyring(|entry| entry.get_password()) {
|
||||
@@ -703,6 +740,10 @@ fn resume_stored(stored: &StoredSession) -> Result<ProtonApiSession> {
|
||||
resumed.access_token = tokens.access_token.clone();
|
||||
resumed.refresh_token = tokens.refresh_token.clone();
|
||||
}
|
||||
tracing::info!(
|
||||
refresh = %fingerprint(&resumed.refresh_token),
|
||||
"resuming the stored session"
|
||||
);
|
||||
let session = ProtonApiSession::resume(client_config(), resumed.to_params())?;
|
||||
let sink = register_refresh_handler(&session, stored.refresh_token.clone());
|
||||
if let Some(tokens) = unsaved {
|
||||
@@ -1082,8 +1123,11 @@ impl TokenSink {
|
||||
) {
|
||||
Rotation::Taken => {
|
||||
write_stored(&stored)?;
|
||||
tracing::info!(
|
||||
refresh = %fingerprint(&tokens.refresh_token),
|
||||
"successfully auto-persisted refreshed tokens in keyring"
|
||||
);
|
||||
state.stored_refresh = tokens.refresh_token;
|
||||
tracing::info!("successfully auto-persisted refreshed tokens in keyring");
|
||||
}
|
||||
Rotation::MovedOn => {
|
||||
tracing::info!(
|
||||
@@ -1408,6 +1452,48 @@ mod tests {
|
||||
keyring_core::unset_default_store();
|
||||
}
|
||||
|
||||
/// B291: every save after the first replaces the keyring item, so a
|
||||
/// provider that keeps an edited secret only in memory (oo7 before 0.7.0)
|
||||
/// still has the last one after a restart, and only one item is left.
|
||||
///
|
||||
/// Run like [`real_secret_service_survives_a_provider_restart`], in a
|
||||
/// throwaway session bus only.
|
||||
#[test]
|
||||
#[ignore = "needs a throwaway Secret Service; see real_secret_service_survives_a_provider_restart"]
|
||||
fn real_secret_service_keeps_the_last_save_across_a_provider_restart() {
|
||||
if std::env::var_os("PDFS_SECRET_SERVICE_RESTART_TEST").is_none() {
|
||||
return;
|
||||
}
|
||||
let restart = std::env::var("PDFS_RESTART_PROVIDER").expect("PDFS_RESTART_PROVIDER");
|
||||
let _turn = KEYRING.lock();
|
||||
*MOCK_STORE.lock() = None;
|
||||
keyring_core::unset_default_store();
|
||||
|
||||
for refresh in ["r1", "r2", "r3"] {
|
||||
write_stored(&stored_with(refresh)).unwrap();
|
||||
}
|
||||
let status = std::process::Command::new("sh")
|
||||
.args(["-c", &restart])
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success(), "restarting the provider failed");
|
||||
std::thread::sleep(Duration::from_secs(1));
|
||||
|
||||
assert_eq!(load().unwrap().refresh_token, "r3");
|
||||
let ss =
|
||||
dbus_secret_service::SecretService::connect(dbus_secret_service::EncryptionType::Plain)
|
||||
.unwrap();
|
||||
let found = ss
|
||||
.search_items(std::collections::HashMap::from([
|
||||
("service", KEYRING_SERVICE),
|
||||
("username", KEYRING_USER),
|
||||
]))
|
||||
.unwrap();
|
||||
assert_eq!(found.unlocked.len() + found.locked.len(), 1);
|
||||
with_keyring(|e| e.delete_credential()).unwrap();
|
||||
keyring_core::unset_default_store();
|
||||
}
|
||||
|
||||
fn stored_with(refresh: &str) -> StoredSession {
|
||||
serde_json::from_str(&blob("").replace(r#""r""#, &format!("{refresh:?}"))).unwrap()
|
||||
}
|
||||
|
||||
+243
-54
@@ -391,6 +391,27 @@ impl AppConfig {
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply `edit` to the ignore patterns in effect in the config at `path`,
|
||||
/// under the config lock, and return the saved config. A list equal to the
|
||||
/// built-in one is stored as unset, so it follows the built-in list in later
|
||||
/// releases.
|
||||
pub fn change_ignore_patterns_at(
|
||||
path: &Path,
|
||||
edit: impl FnOnce(&mut Vec<String>),
|
||||
) -> Result<AppConfig> {
|
||||
update_config_at(path, |config| {
|
||||
let mut list = config.resolved_ignore_patterns();
|
||||
edit(&mut list);
|
||||
let builtin = list.len() == DEFAULT_IGNORE_PATTERNS.len()
|
||||
&& list
|
||||
.iter()
|
||||
.zip(DEFAULT_IGNORE_PATTERNS)
|
||||
.all(|(a, b)| a == b);
|
||||
config.ignore_patterns = (!builtin).then_some(list);
|
||||
config.clone()
|
||||
})
|
||||
}
|
||||
|
||||
/// Fail when the config file at `path` exists but does not parse, so that
|
||||
/// [`AppDirs::save_config`] never writes over settings it could not read.
|
||||
fn refuse_to_replace_unreadable(path: &Path) -> Result<()> {
|
||||
@@ -407,6 +428,116 @@ fn refuse_to_replace_unreadable(path: &Path) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`AppDirs::load_config`] for the file at `path`.
|
||||
fn load_config_at(path: &Path) -> AppConfig {
|
||||
if path.exists() {
|
||||
match std::fs::read_to_string(path)
|
||||
.map_err(Error::from)
|
||||
.and_then(|content| serde_json::from_str::<AppConfig>(&content).map_err(Error::from))
|
||||
{
|
||||
Ok(config) => return config,
|
||||
Err(e) => {
|
||||
// Preserve the original bytes for diagnosis/recovery. In
|
||||
// particular, never replace a truncated config with defaults
|
||||
// and silently lose mount, device, or ignore settings.
|
||||
// `save_config` refuses to write over it for the same reason.
|
||||
tracing::error!(path = %path.display(), error = %e, "config is unreadable; using in-memory defaults without overwriting it");
|
||||
return AppConfig::default();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let default_config = AppConfig::default();
|
||||
if let Err(e) = save_config_at(path, &default_config) {
|
||||
tracing::warn!(path = %path.display(), error = %e, "could not write the default config");
|
||||
}
|
||||
default_config
|
||||
}
|
||||
|
||||
/// [`AppDirs::save_config`] for the file at `path`.
|
||||
fn save_config_at(path: &Path, config: &AppConfig) -> Result<()> {
|
||||
refuse_to_replace_unreadable(path)?;
|
||||
let parent = path
|
||||
.parent()
|
||||
.ok_or_else(|| Error::Other("configuration path has no parent".into()))?;
|
||||
std::fs::create_dir_all(parent)?;
|
||||
let nonce = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|duration| duration.as_nanos())
|
||||
.unwrap_or(0);
|
||||
let tmp = path.with_extension(format!("json.tmp-{}-{nonce}", std::process::id()));
|
||||
use std::os::unix::fs::OpenOptionsExt as _;
|
||||
let mut file = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.mode(0o600)
|
||||
.open(&tmp)?;
|
||||
use std::io::Write as _;
|
||||
file.write_all(&serde_json::to_vec_pretty(config)?)?;
|
||||
file.sync_all()?;
|
||||
std::fs::rename(&tmp, path)?;
|
||||
std::fs::File::open(parent)?.sync_all()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`AppDirs::update_config`] for the file at `path`.
|
||||
fn update_config_at<R>(path: &Path, change: impl FnOnce(&mut AppConfig) -> R) -> Result<R> {
|
||||
let _lock = lock_config(path)?;
|
||||
// Refuse before reading: an unreadable file loads as defaults, and the
|
||||
// change must not be applied to those.
|
||||
refuse_to_replace_unreadable(path)?;
|
||||
let mut config = load_config_at(path);
|
||||
let out = change(&mut config);
|
||||
save_config_at(path, &config)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// How long [`lock_config`] waits for another writer. A change holds the lock
|
||||
/// for one small read and write; anything longer is a stuck process, and the
|
||||
/// setting is better reported as not saved than waited on forever.
|
||||
const CONFIG_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
|
||||
/// Take the lock that orders changes to the config file at `path`, held until
|
||||
/// the returned file is dropped.
|
||||
///
|
||||
/// A separate `config.json.lock`, never the config file itself: that file is
|
||||
/// replaced by a rename on every save, so a lock on it would guard a file
|
||||
/// nobody reads any more.
|
||||
fn lock_config(path: &Path) -> Result<std::fs::File> {
|
||||
use std::os::fd::AsRawFd as _;
|
||||
use std::os::unix::fs::OpenOptionsExt as _;
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let mut name = path.as_os_str().to_owned();
|
||||
name.push(".lock");
|
||||
let file = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.truncate(false)
|
||||
.mode(0o600)
|
||||
.open(PathBuf::from(name))?;
|
||||
let deadline = std::time::Instant::now() + CONFIG_LOCK_WAIT;
|
||||
loop {
|
||||
// SAFETY: `file` owns the descriptor and outlives the call.
|
||||
if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 {
|
||||
return Ok(file);
|
||||
}
|
||||
let e = std::io::Error::last_os_error();
|
||||
if e.raw_os_error() != Some(libc::EWOULDBLOCK) {
|
||||
return Err(Error::Io(e));
|
||||
}
|
||||
if std::time::Instant::now() >= deadline {
|
||||
return Err(Error::Other(format!(
|
||||
"{} is being changed by another process; try again",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolved XDG locations for state, cache, and the default mountpoint.
|
||||
pub struct AppDirs {
|
||||
dirs: ProjectDirs,
|
||||
@@ -426,65 +557,40 @@ impl AppDirs {
|
||||
|
||||
/// Load config from disk, creating default if missing.
|
||||
pub fn load_config(&self) -> AppConfig {
|
||||
let path = self.config_path();
|
||||
if path.exists() {
|
||||
match std::fs::read_to_string(&path)
|
||||
.map_err(Error::from)
|
||||
.and_then(|content| {
|
||||
serde_json::from_str::<AppConfig>(&content).map_err(Error::from)
|
||||
}) {
|
||||
Ok(config) => return config,
|
||||
Err(e) => {
|
||||
// Preserve the original bytes for diagnosis/recovery. In
|
||||
// particular, never replace a truncated config with defaults
|
||||
// and silently lose mount, device, or ignore settings.
|
||||
// `save_config` refuses to write over it for the same reason.
|
||||
tracing::error!(path = %path.display(), error = %e, "config is unreadable; using in-memory defaults without overwriting it");
|
||||
return AppConfig::default();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let default_config = AppConfig::default();
|
||||
if let Err(e) = self.save_config(&default_config) {
|
||||
tracing::warn!(path = %path.display(), error = %e, "could not write the default config");
|
||||
}
|
||||
default_config
|
||||
load_config_at(&self.config_path())
|
||||
}
|
||||
|
||||
/// Persist `config` to [`config_path`](Self::config_path), creating the
|
||||
/// config dir if missing. The Settings page calls this after editing the
|
||||
/// cache budget or mountpoint; the daemon re-reads the file on its next mount.
|
||||
/// config dir if missing.
|
||||
///
|
||||
/// Refuses while the file on disk does not parse. Every caller loads,
|
||||
/// changes one field and saves, and [`load_config`](Self::load_config)
|
||||
/// gives defaults for a file it cannot read, so the first change after
|
||||
/// the file was damaged wrote defaults over the mountpoint, the device and
|
||||
/// the ignore rules the user had (`docs/BUGS.md` B223).
|
||||
/// Refuses while the file on disk does not parse: [`load_config`](Self::load_config)
|
||||
/// gives defaults for a file it cannot read, so the first change after the
|
||||
/// file was damaged would write defaults over the mountpoint, the device
|
||||
/// and the ignore rules the user had (`docs/BUGS.md` B223).
|
||||
///
|
||||
/// Writes the whole file. To change a setting, use
|
||||
/// [`update_config`](Self::update_config), which does not lose another
|
||||
/// process's change.
|
||||
pub fn save_config(&self, config: &AppConfig) -> Result<()> {
|
||||
let path = self.config_path();
|
||||
refuse_to_replace_unreadable(&path)?;
|
||||
let parent = path
|
||||
.parent()
|
||||
.ok_or_else(|| Error::Other("configuration path has no parent".into()))?;
|
||||
std::fs::create_dir_all(parent)?;
|
||||
let nonce = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|duration| duration.as_nanos())
|
||||
.unwrap_or(0);
|
||||
let tmp = path.with_extension(format!("json.tmp-{}-{nonce}", std::process::id()));
|
||||
use std::os::unix::fs::OpenOptionsExt as _;
|
||||
let mut file = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.mode(0o600)
|
||||
.open(&tmp)?;
|
||||
use std::io::Write as _;
|
||||
file.write_all(&serde_json::to_vec_pretty(config)?)?;
|
||||
file.sync_all()?;
|
||||
std::fs::rename(&tmp, &path)?;
|
||||
std::fs::File::open(parent)?.sync_all()?;
|
||||
Ok(())
|
||||
save_config_at(&self.config_path(), config)
|
||||
}
|
||||
|
||||
/// Change settings in place: read the file, apply `change`, write it back,
|
||||
/// all under a lock, and return what `change` returned.
|
||||
///
|
||||
/// The app, the tray and the daemon each write the file. Without the lock,
|
||||
/// two of them changing different settings at once both read the old file,
|
||||
/// and the one that wrote last undid the other's change (`docs/BUGS.md`
|
||||
/// B292).
|
||||
pub fn update_config<R>(&self, change: impl FnOnce(&mut AppConfig) -> R) -> Result<R> {
|
||||
update_config_at(&self.config_path(), change)
|
||||
}
|
||||
|
||||
/// Apply `edit` to the ignore patterns in effect for every synced folder
|
||||
/// and save them, returning the saved config. See
|
||||
/// [`change_ignore_patterns_at`].
|
||||
pub fn change_ignore_patterns(&self, edit: impl FnOnce(&mut Vec<String>)) -> Result<AppConfig> {
|
||||
change_ignore_patterns_at(&self.config_path(), edit)
|
||||
}
|
||||
|
||||
/// This machine's id (e.g. ~/.config/proton-drive-linux/machine-id). See
|
||||
@@ -682,6 +788,89 @@ mod tests {
|
||||
std::fs::metadata(p).unwrap().permissions().mode() & 0o777
|
||||
}
|
||||
|
||||
/// Two writers changing different settings at once both keep their change
|
||||
/// (`docs/BUGS.md` B292).
|
||||
#[test]
|
||||
fn concurrent_changes_to_different_settings_are_all_kept() {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"pdfs-cfg-race-{}-{:?}",
|
||||
std::process::id(),
|
||||
std::thread::current().id()
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("config.json");
|
||||
|
||||
let a = {
|
||||
let path = path.clone();
|
||||
std::thread::spawn(move || {
|
||||
for i in 1..=100u64 {
|
||||
update_config_at(&path, |c| c.upload_limit = Some(i)).unwrap();
|
||||
}
|
||||
})
|
||||
};
|
||||
let b = {
|
||||
let path = path.clone();
|
||||
std::thread::spawn(move || {
|
||||
for i in 1..=100u64 {
|
||||
update_config_at(&path, |c| c.download_limit = Some(i)).unwrap();
|
||||
}
|
||||
})
|
||||
};
|
||||
a.join().unwrap();
|
||||
b.join().unwrap();
|
||||
|
||||
let config = load_config_at(&path);
|
||||
assert_eq!(config.upload_limit, Some(100));
|
||||
assert_eq!(config.download_limit, Some(100));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignore_patterns_back_at_the_built_in_list_are_stored_as_unset() {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"pdfs-cfg-ignore-{}-{:?}",
|
||||
std::process::id(),
|
||||
std::thread::current().id()
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("config.json");
|
||||
|
||||
let config = change_ignore_patterns_at(&path, |list| list.push("*.db".into())).unwrap();
|
||||
assert_eq!(
|
||||
config.ignore_patterns.as_ref().unwrap().last().unwrap(),
|
||||
"*.db"
|
||||
);
|
||||
let config = change_ignore_patterns_at(&path, |list| list.retain(|p| p != "*.db")).unwrap();
|
||||
assert_eq!(config.ignore_patterns, None);
|
||||
assert_eq!(load_config_at(&path).ignore_patterns, None);
|
||||
// An empty list is a choice, not the built-in one.
|
||||
let config = change_ignore_patterns_at(&path, Vec::clear).unwrap();
|
||||
assert_eq!(config.ignore_patterns, Some(Vec::new()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_is_never_applied_over_an_unreadable_config() {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"pdfs-cfg-update-guard-{}-{:?}",
|
||||
std::process::id(),
|
||||
std::thread::current().id()
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("config.json");
|
||||
std::fs::write(&path, br#"{"mountpoint": "/home/me/Pro"#).unwrap();
|
||||
|
||||
assert!(update_config_at(&path, |c| c.tray_hidden = true).is_err());
|
||||
assert_eq!(
|
||||
std::fs::read(&path).unwrap(),
|
||||
br#"{"mountpoint": "/home/me/Pro"#
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A damaged config must not be replaced by defaults the next time a
|
||||
/// setting changes (`docs/BUGS.md` B223).
|
||||
#[test]
|
||||
|
||||
@@ -23,6 +23,7 @@ pub mod places;
|
||||
pub mod profile;
|
||||
pub mod sdkcache;
|
||||
pub mod search;
|
||||
mod secretservice;
|
||||
pub mod service;
|
||||
pub mod shell;
|
||||
pub mod similar;
|
||||
|
||||
@@ -206,26 +206,23 @@ pub fn reap(mut child: std::process::Child) {
|
||||
});
|
||||
}
|
||||
|
||||
/// [`open`] with the policy from the user's `config.json`, read once per
|
||||
/// process. For callers that open the occasional path and have no reason to
|
||||
/// carry a policy around; long-lived windows should hold their own copy.
|
||||
/// [`open`] with the policy from the user's `config.json`, read again on
|
||||
/// every call: the file is small, a path is opened by hand, and a rule changed
|
||||
/// in Preferences then applies to the next file opened, without a restart.
|
||||
pub fn open_default(path: &Path, is_dir: bool) {
|
||||
open(default_policy(), path, is_dir);
|
||||
open(&default_policy(), path, is_dir);
|
||||
}
|
||||
|
||||
/// [`open_default`] matching the rules against `name` — see
|
||||
/// [`OpenWith::command_for_named`].
|
||||
pub fn open_default_named(path: &Path, name: &str, is_dir: bool) {
|
||||
open_named(default_policy(), path, name, is_dir);
|
||||
open_named(&default_policy(), path, name, is_dir);
|
||||
}
|
||||
|
||||
fn default_policy() -> &'static OpenWith {
|
||||
static POLICY: std::sync::OnceLock<OpenWith> = std::sync::OnceLock::new();
|
||||
POLICY.get_or_init(|| {
|
||||
crate::config::AppDirs::new()
|
||||
.map(|dirs| dirs.load_config().resolved_open_with())
|
||||
.unwrap_or_default()
|
||||
})
|
||||
fn default_policy() -> OpenWith {
|
||||
crate::config::AppDirs::new()
|
||||
.map(|dirs| dirs.load_config().resolved_open_with())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `$PDFS_TERMINAL`, then `$TERMINAL`, then the first [`KNOWN_TERMINALS`] entry
|
||||
@@ -266,6 +263,33 @@ fn with_exec_flag(program: &str) -> Vec<String> {
|
||||
argv
|
||||
}
|
||||
|
||||
/// Split a command line typed by the user into argv, the way a shell would:
|
||||
/// quotes keep spaces, nothing is expanded. `None` for an unclosed quote.
|
||||
pub fn parse_command(line: &str) -> Option<Vec<String>> {
|
||||
shell_words::split(line).ok()
|
||||
}
|
||||
|
||||
/// Show `argv` as one line that [`parse_command`] turns back into it.
|
||||
pub fn format_command(argv: &[String]) -> String {
|
||||
shell_words::join(argv)
|
||||
}
|
||||
|
||||
/// Whether the program `argv` starts with can be found: an absolute or
|
||||
/// relative path to a file, or a name on `PATH`. A `$VAR` program counts as
|
||||
/// found, since it is looked up only when a file is opened.
|
||||
pub fn command_available(argv: &[String]) -> bool {
|
||||
let Some(program) = argv.first() else {
|
||||
return false;
|
||||
};
|
||||
if program.starts_with('$') {
|
||||
return true;
|
||||
}
|
||||
if program.contains('/') {
|
||||
return Path::new(program).is_file();
|
||||
}
|
||||
on_path(program)
|
||||
}
|
||||
|
||||
fn on_path(program: &str) -> bool {
|
||||
let Some(path) = std::env::var_os("PATH") else {
|
||||
return false;
|
||||
@@ -703,4 +727,24 @@ mod tests {
|
||||
// Unknown terminals get the near-universal `-e`.
|
||||
assert_eq!(with_exec_flag("mystery-term"), vec!["mystery-term", "-e"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_typed_command_line_round_trips() {
|
||||
let argv = parse_command("alacritty -e 'my editor' --flag").unwrap();
|
||||
assert_eq!(argv, ["alacritty", "-e", "my editor", "--flag"]);
|
||||
assert_eq!(parse_command(&format_command(&argv)).unwrap(), argv);
|
||||
assert_eq!(parse_command("nvim 'unclosed"), None);
|
||||
assert_eq!(parse_command(" ").unwrap(), Vec::<String>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_command_is_available_when_its_program_is() {
|
||||
assert!(command_available(&["sh".to_string()]));
|
||||
assert!(command_available(&["$EDITOR".to_string()]));
|
||||
assert!(!command_available(&[]));
|
||||
assert!(!command_available(
|
||||
&["pdfs-no-such-program-xyz".to_string()]
|
||||
));
|
||||
assert!(!command_available(&["/nonexistent/program".to_string()]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
//! Saving a new secret into an existing Secret Service item by replacing the
|
||||
//! item, not by editing its secret (`docs/BUGS.md` B291).
|
||||
//!
|
||||
//! oo7-daemon before 0.7.0 applies `SetSecret` only in memory: the keyring
|
||||
//! file keeps the old secret, and it comes back once the daemon restarts.
|
||||
//! Fedora 45 ships such a build (`0.7.0~beta^1.e91b98a`). Every refreshed
|
||||
//! sign-in pdfs saved there was gone after a reboot, and the next start found
|
||||
//! a refresh token Proton had already spent.
|
||||
//!
|
||||
//! `CreateItem` with `replace` is written to the file there, and every
|
||||
//! provider implements it. So a secret that changes is written as a new item
|
||||
//! that replaces the old one: in the old one's collection, with its label and
|
||||
//! all of its attributes, so the provider recognises it as the same entry.
|
||||
|
||||
use dbus_secret_service::{Collection, EncryptionType, Path, SecretService};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// The content type the keyring store writes its secrets with.
|
||||
const CONTENT_TYPE: &str = "application/octet-stream";
|
||||
|
||||
/// What [`replace`] did.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Replaced {
|
||||
/// The secret is saved.
|
||||
Saved,
|
||||
/// Nothing was changed; save it the usual way. Says why, for the log.
|
||||
Skipped(String),
|
||||
}
|
||||
|
||||
/// Save `secret` into the one item for `service`/`user` by replacing it.
|
||||
///
|
||||
/// Skips, changing nothing, when there is no such item yet (the store creates
|
||||
/// it), when there is more than one, when it is locked, or when the Secret
|
||||
/// Service fails before the new item exists. Never shows a prompt: one would
|
||||
/// block the caller, so it is dismissed and the write is skipped.
|
||||
pub(crate) fn replace(service: &str, user: &str, secret: &[u8]) -> Replaced {
|
||||
match try_replace(service, user, secret) {
|
||||
Ok(replaced) => replaced,
|
||||
Err(e) => Replaced::Skipped(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn try_replace(
|
||||
service: &str,
|
||||
user: &str,
|
||||
secret: &[u8],
|
||||
) -> Result<Replaced, dbus_secret_service::Error> {
|
||||
let ss = SecretService::connect_with_max_prompt_timeout(EncryptionType::Dh, 0)?;
|
||||
let lookup = HashMap::from([("service", service), ("username", user)]);
|
||||
let found = ss.search_items(lookup.clone())?;
|
||||
if !found.locked.is_empty() {
|
||||
return Ok(Replaced::Skipped("the item is locked".into()));
|
||||
}
|
||||
let [old] = found.unlocked.as_slice() else {
|
||||
return Ok(Replaced::Skipped(format!(
|
||||
"{} items match, not one",
|
||||
found.unlocked.len()
|
||||
)));
|
||||
};
|
||||
let Some(collection) = collection_of(&old.path) else {
|
||||
return Ok(Replaced::Skipped(format!(
|
||||
"no collection in the item path {}",
|
||||
old.path
|
||||
)));
|
||||
};
|
||||
let label = old.get_label()?;
|
||||
let attributes = old.get_attributes()?;
|
||||
let attributes: HashMap<&str, &str> = attributes
|
||||
.iter()
|
||||
.map(|(k, v)| (k.as_str(), v.as_str()))
|
||||
.collect();
|
||||
let collection = Collection::new(&ss, collection);
|
||||
let new = collection.create_item(&label, attributes, secret, true, CONTENT_TYPE)?;
|
||||
|
||||
// A provider that did not match the old item leaves it next to the new
|
||||
// one, and two items make every read ambiguous.
|
||||
let after = ss.search_items(lookup)?;
|
||||
for item in after.unlocked.iter().chain(&after.locked) {
|
||||
if item.path == new.path {
|
||||
continue;
|
||||
}
|
||||
if let Err(e) = item.delete() {
|
||||
// The old item still holds the previous secret, so taking the new
|
||||
// one out leaves things as they were, for the usual write.
|
||||
if let Err(undo) = new.delete() {
|
||||
tracing::error!(
|
||||
error = %undo,
|
||||
"could not remove a duplicate keyring item; remove one of the two \
|
||||
`proton-drive-linux` entries in your keyring and sign in again"
|
||||
);
|
||||
}
|
||||
return Ok(Replaced::Skipped(format!(
|
||||
"could not remove the replaced item: {e}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(Replaced::Saved)
|
||||
}
|
||||
|
||||
/// The collection an item path belongs to: the path without its last part,
|
||||
/// as long as it is a Secret Service object path.
|
||||
fn collection_of(item: &Path<'_>) -> Option<Path<'static>> {
|
||||
let (collection, _) = item.rsplit_once('/')?;
|
||||
if !collection.starts_with("/org/freedesktop/secrets/") || collection.ends_with('/') {
|
||||
return None;
|
||||
}
|
||||
Path::new(collection.to_owned()).ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn collection(item: &str) -> Option<String> {
|
||||
collection_of(&Path::new(item).unwrap()).map(|p| p.to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_item_belongs_to_the_collection_its_path_names() {
|
||||
assert_eq!(
|
||||
collection("/org/freedesktop/secrets/collection/login/14").as_deref(),
|
||||
Some("/org/freedesktop/secrets/collection/login")
|
||||
);
|
||||
assert_eq!(
|
||||
collection("/org/freedesktop/secrets/aliases/default/3").as_deref(),
|
||||
Some("/org/freedesktop/secrets/aliases/default")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_outside_the_secret_service_names_no_collection() {
|
||||
assert_eq!(collection("/org/example/item/1"), None);
|
||||
assert_eq!(collection("/item"), None);
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,11 @@ use ignore::gitignore::{Gitignore, GitignoreBuilder};
|
||||
/// them. Version-control metadata, dependency and build trees, editor
|
||||
/// leftovers, and OS turds — none of which belong on Drive, all of which are
|
||||
/// large or rewritten constantly.
|
||||
///
|
||||
/// The second half is what Nextcloud, Dropbox and Syncthing leave out as well:
|
||||
/// files a desktop, a file system or a program in the middle of a write leaves
|
||||
/// behind, never anything a person made. Every one is in a test, next to a real
|
||||
/// file of a similar name that must stay synced.
|
||||
pub const DEFAULT_IGNORE_PATTERNS: &[&str] = &[
|
||||
".git/",
|
||||
".hg/",
|
||||
@@ -43,6 +48,23 @@ pub const DEFAULT_IGNORE_PATTERNS: &[&str] = &[
|
||||
"*.tmp",
|
||||
".DS_Store",
|
||||
"Thumbs.db",
|
||||
// Folder settings of Windows and KDE's Dolphin.
|
||||
"desktop.ini",
|
||||
".directory",
|
||||
// Trash folders and file-system leftovers: a file deleted while open on a
|
||||
// FUSE or NFS mount lives on under one of these names until it is closed.
|
||||
".Trash-*/",
|
||||
".Trashes/",
|
||||
".Spotlight-V100/",
|
||||
".fuse_hidden*",
|
||||
".nfs*",
|
||||
// Downloads and saves still being written.
|
||||
"*.part",
|
||||
"*.crdownload",
|
||||
"*.kate-swp",
|
||||
// Office lock files: LibreOffice's `.~lock.<name>#`, Microsoft Office's `~$<name>`.
|
||||
".~lock.*#",
|
||||
"~$*",
|
||||
];
|
||||
|
||||
/// Suffixes that mean a file is incomplete *by construction*: only the program
|
||||
@@ -119,6 +141,225 @@ pub fn is_scratch_name(name: &str) -> bool {
|
||||
/// Filenames accepted as a folder's ignore file, in precedence order.
|
||||
const IGNORE_FILE_NAMES: &[&str] = &[".pdfsignore", ".protonignore"];
|
||||
|
||||
/// Whether `line` is a rule [`IgnoreRules::load`] accepts: a pattern, a
|
||||
/// comment or a blank line. The error says what is wrong with it.
|
||||
pub fn check_pattern(line: &str) -> Result<(), String> {
|
||||
GitignoreBuilder::new("/")
|
||||
.add_line(None, line)
|
||||
.map(|_| ())
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The lines of an ignore file that [`IgnoreRules::load`] would skip, by line
|
||||
/// number (from 1), with what is wrong with each.
|
||||
pub fn check_rules(text: &str) -> Vec<(usize, String)> {
|
||||
text.lines()
|
||||
.enumerate()
|
||||
.filter_map(|(i, line)| check_pattern(line).err().map(|e| (i + 1, e)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A synced folder's own ignore file, read so it can be edited and written
|
||||
/// back. See [`FolderRules::read`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct FolderRules {
|
||||
/// The file the rules are in: the one in use, or `.pdfsignore` when there
|
||||
/// is none yet.
|
||||
pub path: std::path::PathBuf,
|
||||
/// The rules as read; empty when there is no file. `None` means there was
|
||||
/// no file, which [`write`](Self::write) checks is still so.
|
||||
pub text: Option<String>,
|
||||
}
|
||||
|
||||
/// Why [`FolderRules::write`] did not write.
|
||||
#[derive(Debug)]
|
||||
pub enum WriteRulesError {
|
||||
/// The file changed after it was read, for example by an edit on another
|
||||
/// computer that sync brought in. The rules on disk are the new ones.
|
||||
Changed,
|
||||
/// Reading or writing failed.
|
||||
Io(std::io::Error),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for WriteRulesError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Changed => f.write_str("the file changed since it was opened"),
|
||||
Self::Io(e) => e.fmt(f),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for WriteRulesError {}
|
||||
|
||||
impl From<std::io::Error> for WriteRulesError {
|
||||
fn from(e: std::io::Error) -> Self {
|
||||
Self::Io(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl FolderRules {
|
||||
/// Read the ignore file of the folder at `root`, the same one
|
||||
/// [`IgnoreRules::load`] uses.
|
||||
pub fn read(root: &Path) -> std::io::Result<Self> {
|
||||
for name in IGNORE_FILE_NAMES {
|
||||
let path = root.join(name);
|
||||
match std::fs::read_to_string(&path) {
|
||||
Ok(text) => {
|
||||
return Ok(Self {
|
||||
path,
|
||||
text: Some(text),
|
||||
});
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
// Like `load`, a missing folder reads as one without rules; the write
|
||||
// is what fails then.
|
||||
Ok(Self {
|
||||
path: root.join(IGNORE_FILE_NAMES[0]),
|
||||
text: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Replace the rules with `text`, unless the file changed since it was
|
||||
/// read. Rules that are all blank remove the file, so a folder never keeps
|
||||
/// an empty one around.
|
||||
///
|
||||
/// Written to a temporary file and renamed over the old one, so the sync
|
||||
/// pass reading the rules at the same moment sees the old ones or the new
|
||||
/// ones, never half of them.
|
||||
pub fn write(&self, text: &str) -> Result<(), WriteRulesError> {
|
||||
let now = match std::fs::read_to_string(&self.path) {
|
||||
Ok(now) => Some(now),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
if now != self.text {
|
||||
return Err(WriteRulesError::Changed);
|
||||
}
|
||||
if text.trim().is_empty() {
|
||||
return match std::fs::remove_file(&self.path) {
|
||||
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e.into()),
|
||||
_ => Ok(()),
|
||||
};
|
||||
}
|
||||
let Some(name) = self.path.file_name() else {
|
||||
return Err(std::io::Error::other("the rules path has no file name").into());
|
||||
};
|
||||
let mut tmp_name = std::ffi::OsString::from(".");
|
||||
tmp_name.push(name);
|
||||
tmp_name.push(format!(".tmp-{}", std::process::id()));
|
||||
let tmp = self.path.with_file_name(tmp_name);
|
||||
let mut body = text.to_string();
|
||||
if !body.ends_with('\n') {
|
||||
body.push('\n');
|
||||
}
|
||||
let written = std::fs::write(&tmp, body).and_then(|()| std::fs::rename(&tmp, &self.path));
|
||||
if written.is_err() {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
}
|
||||
Ok(written?)
|
||||
}
|
||||
|
||||
/// The patterns in the rules: every line that is not blank or a comment,
|
||||
/// trimmed of surrounding white space.
|
||||
pub fn patterns(&self) -> Vec<&str> {
|
||||
self.text
|
||||
.as_deref()
|
||||
.unwrap_or_default()
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.filter(|line| !line.is_empty() && !line.starts_with('#'))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// How often [`add_folder_pattern`] and [`remove_folder_pattern`] read the
|
||||
/// rules again when they changed between the read and the write.
|
||||
const RULES_RETRIES: usize = 3;
|
||||
|
||||
/// Add `pattern` at the end of the own rules of the folder at `root`, keeping
|
||||
/// every other line and comment. Says whether it added it: a pattern already
|
||||
/// there is left alone.
|
||||
pub fn add_folder_pattern(root: &Path, pattern: &str) -> std::io::Result<bool> {
|
||||
let pattern = pattern.trim();
|
||||
edit_folder_rules(root, |rules| {
|
||||
if rules.patterns().contains(&pattern) {
|
||||
return None;
|
||||
}
|
||||
let mut text = rules.text.clone().unwrap_or_default();
|
||||
if !text.is_empty() && !text.ends_with('\n') {
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str(pattern);
|
||||
text.push('\n');
|
||||
Some(text)
|
||||
})
|
||||
}
|
||||
|
||||
/// Remove every line that is `pattern` from the own rules of the folder at
|
||||
/// `root`. Says whether there was one.
|
||||
pub fn remove_folder_pattern(root: &Path, pattern: &str) -> std::io::Result<bool> {
|
||||
let pattern = pattern.trim();
|
||||
edit_folder_rules(root, |rules| {
|
||||
if !rules.patterns().contains(&pattern) {
|
||||
return None;
|
||||
}
|
||||
let text = rules.text.as_deref().unwrap_or_default();
|
||||
Some(
|
||||
text.lines()
|
||||
.filter(|line| line.trim() != pattern)
|
||||
.map(|line| format!("{line}\n"))
|
||||
.collect(),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Read the folder's rules, let `edit` return their new text (or `None` to
|
||||
/// leave them), and write it. Rules that changed in between, such as by sync
|
||||
/// bringing in an edit from another computer, are read again and edited anew.
|
||||
fn edit_folder_rules(
|
||||
root: &Path,
|
||||
edit: impl Fn(&FolderRules) -> Option<String>,
|
||||
) -> std::io::Result<bool> {
|
||||
for _ in 0..RULES_RETRIES {
|
||||
let rules = FolderRules::read(root)?;
|
||||
let Some(text) = edit(&rules) else {
|
||||
return Ok(false);
|
||||
};
|
||||
match rules.write(&text) {
|
||||
Ok(()) => return Ok(true),
|
||||
Err(WriteRulesError::Changed) => continue,
|
||||
Err(WriteRulesError::Io(e)) => return Err(e),
|
||||
}
|
||||
}
|
||||
Err(std::io::Error::other(
|
||||
"the rules kept changing while they were being saved",
|
||||
))
|
||||
}
|
||||
|
||||
/// Where a rule that decided about a path came from.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum RuleSource {
|
||||
/// The rules for every synced folder (`ignore_patterns`).
|
||||
AllFolders,
|
||||
/// The folder's own ignore file.
|
||||
ThisFolder,
|
||||
}
|
||||
|
||||
/// What the rules say about one path, and which rule says it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Verdict {
|
||||
/// No rule matches: the path is synced.
|
||||
Synced,
|
||||
/// Left out by `pattern`. `pattern` may name a folder the path is in.
|
||||
Excluded { pattern: String, source: RuleSource },
|
||||
/// A rule excluded it, and a later `!pattern` brought it back.
|
||||
Included { pattern: String, source: RuleSource },
|
||||
}
|
||||
|
||||
/// Compiled ignore rules for one synced folder.
|
||||
pub struct IgnoreRules {
|
||||
matcher: Option<Gitignore>,
|
||||
@@ -161,6 +402,27 @@ impl IgnoreRules {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`load`](Self::load) with `text` standing in for the folder's ignore
|
||||
/// file, for showing what rules being edited would do before they are
|
||||
/// saved.
|
||||
pub fn with_folder_text(root: &Path, globals: &[String], text: &str) -> Self {
|
||||
let mut builder = GitignoreBuilder::new(root);
|
||||
let mut any = false;
|
||||
for pattern in globals {
|
||||
any |= builder.add_line(None, pattern).is_ok();
|
||||
}
|
||||
let file = root.join(IGNORE_FILE_NAMES[0]);
|
||||
for line in text.lines() {
|
||||
any |= builder.add_line(Some(file.clone()), line).is_ok();
|
||||
}
|
||||
if !any {
|
||||
return Self { matcher: None };
|
||||
}
|
||||
Self {
|
||||
matcher: builder.build().ok(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Rules matching nothing, for callers with no folder context.
|
||||
pub fn empty() -> Self {
|
||||
Self { matcher: None }
|
||||
@@ -207,6 +469,50 @@ impl IgnoreRules {
|
||||
}
|
||||
}
|
||||
|
||||
impl IgnoreRules {
|
||||
/// What the rules say about `rel`, and which rule decides, the way
|
||||
/// [`is_ignored`](Self::is_ignored) decides it.
|
||||
pub fn explain(&self, rel: &str, is_dir: bool) -> Verdict {
|
||||
let Some(matcher) = &self.matcher else {
|
||||
return Verdict::Synced;
|
||||
};
|
||||
let rel = rel.trim_matches('/');
|
||||
if rel.is_empty() {
|
||||
return Verdict::Synced;
|
||||
}
|
||||
let source = |glob: &ignore::gitignore::Glob| match glob.from() {
|
||||
Some(_) => RuleSource::ThisFolder,
|
||||
None => RuleSource::AllFolders,
|
||||
};
|
||||
let mut prefix = String::new();
|
||||
let mut parts = rel.split('/').peekable();
|
||||
while let Some(part) = parts.next() {
|
||||
if !prefix.is_empty() {
|
||||
prefix.push('/');
|
||||
}
|
||||
prefix.push_str(part);
|
||||
let last = parts.peek().is_none();
|
||||
let as_dir = if last { is_dir } else { true };
|
||||
match matcher.matched(&prefix, as_dir) {
|
||||
ignore::Match::Ignore(glob) => {
|
||||
return Verdict::Excluded {
|
||||
pattern: glob.original().to_string(),
|
||||
source: source(glob),
|
||||
};
|
||||
}
|
||||
ignore::Match::Whitelist(glob) if last => {
|
||||
return Verdict::Included {
|
||||
pattern: glob.original().to_string(),
|
||||
source: source(glob),
|
||||
};
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Verdict::Synced
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for IgnoreRules {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("IgnoreRules")
|
||||
@@ -255,6 +561,198 @@ mod tests {
|
||||
std::fs::write(root.join(name), body).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_added_defaults_leave_out_clutter_but_not_look_alikes() {
|
||||
let dir = TempDir::new();
|
||||
let rules = IgnoreRules::load(dir.path(), &globals());
|
||||
for (clutter, is_dir) in [
|
||||
("desktop.ini", false),
|
||||
("Photos/.directory", false),
|
||||
(".Trash-1000", true),
|
||||
(".Trashes", true),
|
||||
(".Spotlight-V100", true),
|
||||
(".fuse_hidden0000001a00000002", false),
|
||||
(".nfs000000000123abcd", false),
|
||||
("movie.mkv.part", false),
|
||||
("setup.exe.crdownload", false),
|
||||
("notes.txt.kate-swp", false),
|
||||
(".~lock.report.odt#", false),
|
||||
("~$budget.xlsx", false),
|
||||
] {
|
||||
assert!(rules.is_ignored(clutter, is_dir), "{clutter}");
|
||||
}
|
||||
for kept in [
|
||||
"Desktop/notes.txt",
|
||||
"directory.txt",
|
||||
"Trash-talk.md",
|
||||
"nfs-setup.md",
|
||||
"parts.csv",
|
||||
"part.txt",
|
||||
"report.odt",
|
||||
"budget.xlsx",
|
||||
] {
|
||||
assert!(!rules.is_ignored(kept, false), "{kept}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_pattern_is_reported_with_its_line() {
|
||||
assert!(check_pattern("*.db").is_ok());
|
||||
assert!(check_pattern("# a comment").is_ok());
|
||||
assert!(check_pattern("").is_ok());
|
||||
assert!(check_pattern("*.{jpg,png").is_err());
|
||||
assert!(check_pattern("[z-a]").is_err());
|
||||
let bad = check_rules("*.log\n{oops\nbuild/\n");
|
||||
assert_eq!(bad.len(), 1);
|
||||
assert_eq!(bad[0].0, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explain_names_the_rule_and_where_it_came_from() {
|
||||
let dir = TempDir::new();
|
||||
write(dir.path(), ".pdfsignore", "*.db\n!keep.tmp\n");
|
||||
let rules = IgnoreRules::load(dir.path(), &globals());
|
||||
assert_eq!(
|
||||
rules.explain("data/cache.db", false),
|
||||
Verdict::Excluded {
|
||||
pattern: "*.db".into(),
|
||||
source: RuleSource::ThisFolder
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
rules.explain("app/node_modules/x/index.js", false),
|
||||
Verdict::Excluded {
|
||||
pattern: "node_modules/".into(),
|
||||
source: RuleSource::AllFolders
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
rules.explain("keep.tmp", false),
|
||||
Verdict::Included {
|
||||
pattern: "!keep.tmp".into(),
|
||||
source: RuleSource::ThisFolder
|
||||
}
|
||||
);
|
||||
assert_eq!(rules.explain("src/main.rs", false), Verdict::Synced);
|
||||
// `explain` and `is_ignored` never disagree.
|
||||
for (path, is_dir) in [
|
||||
("data/cache.db", false),
|
||||
("keep.tmp", false),
|
||||
("x.tmp", false),
|
||||
] {
|
||||
assert_eq!(
|
||||
rules.is_ignored(path, is_dir),
|
||||
matches!(rules.explain(path, is_dir), Verdict::Excluded { .. }),
|
||||
"{path}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rules_being_edited_explain_like_the_saved_ones() {
|
||||
let dir = TempDir::new();
|
||||
let text = "*.db\n!keep.db\n";
|
||||
write(dir.path(), ".pdfsignore", text);
|
||||
let saved = IgnoreRules::load(dir.path(), &globals());
|
||||
let edited = IgnoreRules::with_folder_text(dir.path(), &globals(), text);
|
||||
for path in ["a.db", "keep.db", "node_modules/x", "src/x.rs"] {
|
||||
assert_eq!(
|
||||
saved.explain(path, false),
|
||||
edited.explain(path, false),
|
||||
"{path}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folder_rules_are_written_back_and_removed_when_blank() {
|
||||
let dir = TempDir::new();
|
||||
let rules = FolderRules::read(dir.path()).unwrap();
|
||||
assert_eq!(rules.text, None);
|
||||
assert_eq!(rules.path, dir.path().join(".pdfsignore"));
|
||||
rules.write("*.db").unwrap();
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(dir.path().join(".pdfsignore")).unwrap(),
|
||||
"*.db\n"
|
||||
);
|
||||
assert!(IgnoreRules::load(dir.path(), &[]).is_ignored("x.db", false));
|
||||
|
||||
let rules = FolderRules::read(dir.path()).unwrap();
|
||||
rules.write(" \n").unwrap();
|
||||
assert!(!dir.path().join(".pdfsignore").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folder_rules_keep_the_file_name_in_use() {
|
||||
let dir = TempDir::new();
|
||||
write(dir.path(), ".protonignore", "old/\n");
|
||||
let rules = FolderRules::read(dir.path()).unwrap();
|
||||
assert_eq!(rules.path, dir.path().join(".protonignore"));
|
||||
rules.write("new/\n").unwrap();
|
||||
assert!(!dir.path().join(".pdfsignore").exists());
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(dir.path().join(".protonignore")).unwrap(),
|
||||
"new/\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folder_rules_changed_elsewhere_are_not_written_over() {
|
||||
let dir = TempDir::new();
|
||||
write(dir.path(), ".pdfsignore", "a/\n");
|
||||
let rules = FolderRules::read(dir.path()).unwrap();
|
||||
write(dir.path(), ".pdfsignore", "b/\n");
|
||||
assert!(matches!(rules.write("c/"), Err(WriteRulesError::Changed)));
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(dir.path().join(".pdfsignore")).unwrap(),
|
||||
"b/\n"
|
||||
);
|
||||
|
||||
// A file that appeared after an empty read counts as a change too.
|
||||
let dir = TempDir::new();
|
||||
let rules = FolderRules::read(dir.path()).unwrap();
|
||||
write(dir.path(), ".pdfsignore", "b/\n");
|
||||
assert!(matches!(rules.write("c/"), Err(WriteRulesError::Changed)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pattern_added_to_a_folder_keeps_its_other_lines() {
|
||||
let dir = TempDir::new();
|
||||
assert!(add_folder_pattern(dir.path(), " *.db ").unwrap());
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(dir.path().join(".pdfsignore")).unwrap(),
|
||||
"*.db\n"
|
||||
);
|
||||
|
||||
write(dir.path(), ".pdfsignore", "# my notes\nbuild/");
|
||||
assert!(add_folder_pattern(dir.path(), "*.db").unwrap());
|
||||
assert!(!add_folder_pattern(dir.path(), "build/").unwrap());
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(dir.path().join(".pdfsignore")).unwrap(),
|
||||
"# my notes\nbuild/\n*.db\n"
|
||||
);
|
||||
assert_eq!(
|
||||
FolderRules::read(dir.path()).unwrap().patterns(),
|
||||
["build/", "*.db"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_a_folder_pattern_keeps_comments_and_drops_an_empty_file() {
|
||||
let dir = TempDir::new();
|
||||
write(dir.path(), ".pdfsignore", "# keep\nbuild/\n*.db\n");
|
||||
assert!(remove_folder_pattern(dir.path(), "build/").unwrap());
|
||||
assert!(!remove_folder_pattern(dir.path(), "build/").unwrap());
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(dir.path().join(".pdfsignore")).unwrap(),
|
||||
"# keep\n*.db\n"
|
||||
);
|
||||
|
||||
write(dir.path(), ".pdfsignore", "*.db\n");
|
||||
assert!(remove_folder_pattern(dir.path(), "*.db").unwrap());
|
||||
assert!(!dir.path().join(".pdfsignore").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_rules_at_all_ignores_nothing() {
|
||||
let dir = TempDir::new();
|
||||
|
||||
@@ -1320,11 +1320,9 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
|
||||
core.cache.set_budget(bytes);
|
||||
// Persist so the next mount keeps the new cap. Best-effort: a config
|
||||
// write failure is reported but the live cap is already applied.
|
||||
match AppDirs::new().map(|dirs| {
|
||||
let mut cfg = dirs.load_config();
|
||||
cfg.cache_budget = Some(bytes);
|
||||
dirs.save_config(&cfg)
|
||||
}) {
|
||||
match AppDirs::new()
|
||||
.map(|dirs| dirs.update_config(|cfg| cfg.cache_budget = Some(bytes)))
|
||||
{
|
||||
Ok(Ok(())) => {
|
||||
core.touch_profile();
|
||||
CtlResponse::Ok {
|
||||
@@ -1344,10 +1342,10 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
|
||||
// Persisted like the cache budget: best-effort, the live caps are
|
||||
// already applied.
|
||||
match AppDirs::new().map(|dirs| {
|
||||
let mut cfg = dirs.load_config();
|
||||
cfg.upload_limit = Some(upload);
|
||||
cfg.download_limit = Some(download);
|
||||
dirs.save_config(&cfg)
|
||||
dirs.update_config(|cfg| {
|
||||
cfg.upload_limit = Some(upload);
|
||||
cfg.download_limit = Some(download);
|
||||
})
|
||||
}) {
|
||||
Ok(Ok(())) => CtlResponse::Ok {
|
||||
message: format!(
|
||||
|
||||
@@ -123,9 +123,7 @@ pub(crate) fn sync_root_reserved() -> pdfs_core::syncroot::Reserved {
|
||||
pub(crate) fn set_adopted_device_uid(uid: Option<&str>) -> CoreResult<()> {
|
||||
let dirs = pdfs_core::config::AppDirs::new()
|
||||
.map_err(|e| CoreError::internal(format!("config dirs: {e}")))?;
|
||||
let mut cfg = dirs.load_config();
|
||||
cfg.device_uid = uid.map(|u| u.to_string());
|
||||
dirs.save_config(&cfg)
|
||||
dirs.update_config(|cfg| cfg.device_uid = uid.map(|u| u.to_string()))
|
||||
.map_err(|e| CoreError::internal(format!("write config: {e}")))
|
||||
}
|
||||
|
||||
|
||||
@@ -26,9 +26,12 @@ use pages::photo_viewer::*;
|
||||
use pages::photos::*;
|
||||
use pages::places::*;
|
||||
use pages::places_map::*;
|
||||
use pages::preferences_apps::*;
|
||||
use pages::preferences_sync::*;
|
||||
use pages::shared::*;
|
||||
use pages::shared_by_me::*;
|
||||
use pages::status::*;
|
||||
use pages::sync_exclusions::*;
|
||||
use pages::takeout::*;
|
||||
use pages::trash::*;
|
||||
use pages::verify::*;
|
||||
@@ -39,6 +42,7 @@ use widgets::compat::*;
|
||||
use widgets::crumb::*;
|
||||
use widgets::details::*;
|
||||
use widgets::file_list::*;
|
||||
use widgets::ignore_dialog::*;
|
||||
use widgets::menu::*;
|
||||
use widgets::photo_drag::*;
|
||||
use widgets::player::*;
|
||||
@@ -307,6 +311,18 @@ fn sync_view(page: &str) -> Option<&'static str> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Preferences page a `--page` name opens: "preferences" and
|
||||
/// "preferences-" followed by the page's name.
|
||||
fn preferences_page(page: &str) -> Option<&'static str> {
|
||||
match page {
|
||||
"preferences" | "preferences-general" => Some("general"),
|
||||
"preferences-sync" => Some("sync"),
|
||||
"preferences-apps" => Some("apps"),
|
||||
"preferences-storage" => Some("storage"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The Photos view a `--page` name opens, and whether Places shows its map:
|
||||
/// "albums", "places" and "places-map". Other names are stack pages.
|
||||
fn photos_view(page: &str) -> Option<(u32, bool)> {
|
||||
@@ -329,7 +345,15 @@ fn present_window(app: &adw::Application) {
|
||||
|
||||
/// Spawn the tray icon process in the background.
|
||||
pub(crate) fn spawn_tray() {
|
||||
match Command::new("pdfs-tray").spawn() {
|
||||
// The tray installed next to this app, as the tray finds the app; the
|
||||
// bare name for a PATH install. An install into ~/.local is often not on
|
||||
// the PATH of a desktop session.
|
||||
let tray = std::env::current_exe()
|
||||
.ok()
|
||||
.and_then(|p| p.parent().map(|d| d.join("pdfs-tray")))
|
||||
.filter(|p| p.exists())
|
||||
.unwrap_or_else(|| PathBuf::from("pdfs-tray"));
|
||||
match Command::new(&tray).spawn() {
|
||||
Ok(child) => {
|
||||
tracing::info!("spawned `pdfs-tray`");
|
||||
pdfs_core::opener::reap(child);
|
||||
@@ -658,6 +682,13 @@ fn build_window(app: &adw::Application) {
|
||||
views: locations_widgets.views.clone(),
|
||||
banner: locations_widgets.banner.clone(),
|
||||
failing: Cell::new(0),
|
||||
exclusions: ExclusionsState {
|
||||
group: locations_widgets.exclusions_group.clone(),
|
||||
add: locations_widgets.add_pattern.clone(),
|
||||
rows: RefCell::new(Vec::new()),
|
||||
folders: RefCell::new(Vec::new()),
|
||||
generation: Cell::new(0),
|
||||
},
|
||||
},
|
||||
activity: ActivityState {
|
||||
content: activity_widgets.content.clone(),
|
||||
@@ -710,6 +741,8 @@ fn build_window(app: &adw::Application) {
|
||||
&main_widgets.purge_button,
|
||||
&main_widgets.mountpoint_button,
|
||||
);
|
||||
wire_sync_prefs(&ui, main_widgets.sync_prefs);
|
||||
wire_apps_prefs(&ui, main_widgets.apps_prefs);
|
||||
wire_sidebar(&ui);
|
||||
wire_browser(&ui);
|
||||
wire_bulk(
|
||||
@@ -739,6 +772,7 @@ fn build_window(app: &adw::Application) {
|
||||
wire_shared_by_me(&ui, &shared_by_me_widgets);
|
||||
wire_devices(&ui, &devices_widgets);
|
||||
wire_locations(&ui, &locations_widgets.retry, &locations_widgets.add_folder);
|
||||
wire_exclusions(&ui);
|
||||
wire_activity(&ui, &activity_widgets);
|
||||
wire_takeout(&ui, &takeout_widgets);
|
||||
wire_retry(&ui);
|
||||
@@ -868,12 +902,10 @@ fn save_window_state(ui: &Ui, window: &adw::ApplicationWindow) {
|
||||
height,
|
||||
maximized: window.is_maximized(),
|
||||
};
|
||||
let mut config = ui.dirs.load_config();
|
||||
if config.window == state {
|
||||
if ui.dirs.load_config().window == state {
|
||||
return;
|
||||
}
|
||||
config.window = state;
|
||||
if let Err(e) = ui.dirs.save_config(&config) {
|
||||
if let Err(e) = ui.dirs.update_config(|config| config.window = state) {
|
||||
tracing::warn!("cannot save the window size: {e}");
|
||||
}
|
||||
}
|
||||
@@ -1471,7 +1503,10 @@ fn install_launch_actions(ui: &Rc<Ui>, app: &adw::Application, window: &adw::App
|
||||
show_login(&ui_page);
|
||||
return;
|
||||
}
|
||||
if let Some(view) = sync_view(page) {
|
||||
if let Some(name) = preferences_page(page) {
|
||||
ui_page.status.prefs.set_visible_page_name(name);
|
||||
ui_page.status.prefs.present(ui_window(&ui_page).as_ref());
|
||||
} else if let Some(view) = sync_view(page) {
|
||||
ui_page.locations.views.set_visible_child_name(view);
|
||||
ui_page.stack.set_visible_child_name("locations");
|
||||
} else if let Some((view, map)) = photos_view(page) {
|
||||
@@ -2055,6 +2090,15 @@ mod tests {
|
||||
assert_eq!(sync_view("locations"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_name_can_open_a_preferences_page() {
|
||||
assert_eq!(preferences_page("preferences"), Some("general"));
|
||||
assert_eq!(preferences_page("preferences-sync"), Some("sync"));
|
||||
assert_eq!(preferences_page("preferences-apps"), Some("apps"));
|
||||
assert_eq!(preferences_page("preferences-storage"), Some("storage"));
|
||||
assert_eq!(preferences_page("sync"), None);
|
||||
}
|
||||
|
||||
/// One file of a shot, for the group-switch tests.
|
||||
fn member(uid: &str, name: Option<&str>, kind: PhotoKind) -> PhotoItem {
|
||||
PhotoItem {
|
||||
|
||||
@@ -1431,9 +1431,11 @@ fn save_icon_size(ui: &Rc<Ui>, size: i32) {
|
||||
let ui_save = ui.clone();
|
||||
let source = glib::timeout_add_local_once(Duration::from_millis(500), move || {
|
||||
ui_save.browser.zoom_save.borrow_mut().take();
|
||||
let mut config = ui_save.dirs.load_config();
|
||||
config.files_view.icon_size = ui_save.browser.view.get().icon_size;
|
||||
if let Err(e) = ui_save.dirs.save_config(&config) {
|
||||
let icon_size = ui_save.browser.view.get().icon_size;
|
||||
if let Err(e) = ui_save
|
||||
.dirs
|
||||
.update_config(|config| config.files_view.icon_size = icon_size)
|
||||
{
|
||||
tracing::warn!("cannot save the icon size: {e}");
|
||||
}
|
||||
});
|
||||
@@ -1464,9 +1466,7 @@ pub(crate) fn set_files_view(ui: &Rc<Ui>, view: FilesView) {
|
||||
return;
|
||||
}
|
||||
apply_files_view(ui, view);
|
||||
let mut config = ui.dirs.load_config();
|
||||
config.files_view = view;
|
||||
if let Err(e) = ui.dirs.save_config(&config) {
|
||||
if let Err(e) = ui.dirs.update_config(|config| config.files_view = view) {
|
||||
toast_error(ui, &gettext("Couldn't save the view"), &e.to_string());
|
||||
}
|
||||
if (old.sort, old.descending, old.folders_first)
|
||||
|
||||
@@ -35,6 +35,8 @@ pub(crate) struct LocationsState {
|
||||
pub(crate) banner: adw::Banner,
|
||||
/// Changes the daemon failed to upload, from the last status.
|
||||
pub(crate) failing: Cell<u64>,
|
||||
/// Excluded Files, under the folder list.
|
||||
pub(crate) exclusions: ExclusionsState,
|
||||
}
|
||||
|
||||
/// The status card heading the Sync page's Overview, and Pause/Resume in the
|
||||
@@ -120,6 +122,8 @@ pub(crate) struct LocationsWidgets {
|
||||
pub(crate) conflicts_group: adw::PreferencesGroup,
|
||||
pub(crate) views: adw::ViewStack,
|
||||
pub(crate) banner: adw::Banner,
|
||||
pub(crate) exclusions_group: adw::PreferencesGroup,
|
||||
pub(crate) add_pattern: gtk4::Button,
|
||||
}
|
||||
|
||||
/// The Sync page: Overview (the status, conflicts, transfers and queue),
|
||||
@@ -208,8 +212,14 @@ pub(crate) fn build_locations_page(history: >k4::Widget) -> (gtk4::Widget, Loc
|
||||
.child(&status)
|
||||
.build();
|
||||
|
||||
// What the folders leave out, under them: the rules belong to the folders.
|
||||
let (exclusions_group, add_pattern) = build_exclusions_group();
|
||||
let folders = gtk4::Box::new(gtk4::Orientation::Vertical, 24);
|
||||
folders.append(&group);
|
||||
folders.append(&exclusions_group);
|
||||
|
||||
let content = gtk4::Stack::new();
|
||||
content.add_named(&scrolled_column(&group), Some("list"));
|
||||
content.add_named(&scrolled_column(&folders), Some("list"));
|
||||
content.add_named(&status_scroll, Some("status"));
|
||||
|
||||
let views = adw::ViewStack::new();
|
||||
@@ -267,6 +277,8 @@ pub(crate) fn build_locations_page(history: >k4::Widget) -> (gtk4::Widget, Loc
|
||||
conflicts_group,
|
||||
views,
|
||||
banner,
|
||||
exclusions_group,
|
||||
add_pattern,
|
||||
};
|
||||
(frame.upcast(), widgets)
|
||||
}
|
||||
@@ -1243,6 +1255,7 @@ pub(crate) fn repaint_locations(ui: &Rc<Ui>, items: &[MountSpec]) {
|
||||
};
|
||||
if !unchanged {
|
||||
rebuild_locations(ui, items, keys);
|
||||
paint_exclusions(ui, items);
|
||||
}
|
||||
for (row, spec) in ui.locations.rows.borrow().iter().zip(items) {
|
||||
update_location_row(row, spec);
|
||||
@@ -1498,6 +1511,7 @@ fn folder_mode_label(ondemand: bool) -> String {
|
||||
/// synced folder's menu.
|
||||
fn add_device_items(ui: &Rc<Ui>, menu: &mut ActionMenu, spec: &MountSpec, id: i64) {
|
||||
if spec.mode != MountMode::OnDemand {
|
||||
let ui_ignore = ui.clone();
|
||||
// A paused folder skips its passes, so Sync now would do nothing.
|
||||
if !spec.paused {
|
||||
let ui = ui.clone();
|
||||
@@ -1516,6 +1530,14 @@ fn add_device_items(ui: &Rc<Ui>, menu: &mut ActionMenu, spec: &MountSpec, id: i6
|
||||
menu.item(&gettext("Sync From Scratch…"), move || {
|
||||
confirm_reset_sync_folder(&ui, id, &path)
|
||||
});
|
||||
// Only a synced copy has local files for the rules to leave out.
|
||||
if spec.mode == MountMode::Mirror {
|
||||
let ui = ui_ignore;
|
||||
let root = PathBuf::from(&spec.local_path);
|
||||
menu.item(&gettext("Excluded Files…"), move || {
|
||||
present_ignore_dialog(&ui, id, root.clone())
|
||||
});
|
||||
}
|
||||
menu.section();
|
||||
}
|
||||
let ui = ui.clone();
|
||||
|
||||
@@ -12,9 +12,12 @@ pub(crate) mod photo_viewer;
|
||||
pub(crate) mod photos;
|
||||
pub(crate) mod places;
|
||||
pub(crate) mod places_map;
|
||||
pub(crate) mod preferences_apps;
|
||||
pub(crate) mod preferences_sync;
|
||||
pub(crate) mod shared;
|
||||
pub(crate) mod shared_by_me;
|
||||
pub(crate) mod status;
|
||||
pub(crate) mod sync_exclusions;
|
||||
pub(crate) mod takeout;
|
||||
pub(crate) mod trash;
|
||||
pub(crate) mod verify;
|
||||
@@ -2129,16 +2129,17 @@ fn save_photos_view(ui: &Rc<Ui>) {
|
||||
let ui_save = ui.clone();
|
||||
let source = glib::timeout_add_local_once(Duration::from_millis(500), move || {
|
||||
ui_save.gallery.zoom_save.borrow_mut().take();
|
||||
let mut config = ui_save.dirs.load_config();
|
||||
let view = PhotosView {
|
||||
row_height: Some(ui_save.gallery.row_height.get()),
|
||||
square: ui_save.gallery.square.get(),
|
||||
};
|
||||
if config.photos_view == view {
|
||||
if ui_save.dirs.load_config().photos_view == view {
|
||||
return;
|
||||
}
|
||||
config.photos_view = view;
|
||||
if let Err(e) = ui_save.dirs.save_config(&config) {
|
||||
if let Err(e) = ui_save
|
||||
.dirs
|
||||
.update_config(|config| config.photos_view = view)
|
||||
{
|
||||
tracing::warn!("cannot save the Photos view: {e}");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,606 @@
|
||||
//! Preferences → Apps: which program opens which file (`open_with`) and how
|
||||
//! the search launcher shows itself (`prompt`).
|
||||
//!
|
||||
//! Neither involves the service. The app and the search launcher read both
|
||||
//! again each time they open something, so a change applies to the next file
|
||||
//! opened or the next search.
|
||||
|
||||
use crate::*;
|
||||
use pdfs_core::menu::{PromptConfig, PromptMode};
|
||||
use pdfs_core::opener::{
|
||||
OpenRule, OpenWith, command_available, format_command, parse_command, resolve_terminal,
|
||||
};
|
||||
|
||||
/// The widgets of the Apps page, built with the rest of the dialog and wired
|
||||
/// once the app's state exists.
|
||||
pub(crate) struct AppsPrefs {
|
||||
pub(crate) page: adw::PreferencesPage,
|
||||
rules: adw::PreferencesGroup,
|
||||
add_rule: gtk4::Button,
|
||||
other_row: adw::EntryRow,
|
||||
terminal_row: adw::EntryRow,
|
||||
mode_row: adw::ComboRow,
|
||||
menu_row: adw::EntryRow,
|
||||
prompt_terminal_row: adw::EntryRow,
|
||||
limit_row: adw::SpinRow,
|
||||
icons_row: adw::SwitchRow,
|
||||
}
|
||||
|
||||
/// The launcher modes in the order the combo row lists them.
|
||||
const MODES: [PromptMode; 3] = [PromptMode::Gtk, PromptMode::Dmenu, PromptMode::Fzf];
|
||||
|
||||
/// The file classes a rule can name, with what the dialog calls them.
|
||||
fn classes() -> [(&'static str, String); 6] {
|
||||
[
|
||||
("@text", gettext("Text")),
|
||||
("@document", gettext("Documents")),
|
||||
("@image", gettext("Images")),
|
||||
("@media", gettext("Audio and Video")),
|
||||
("@dir", gettext("Folders")),
|
||||
("@any", gettext("Everything")),
|
||||
]
|
||||
}
|
||||
|
||||
pub(crate) fn build_apps_prefs() -> AppsPrefs {
|
||||
let add_rule = gtk4::Button::builder()
|
||||
.label(gettext("Add Rule…"))
|
||||
.valign(gtk4::Align::Center)
|
||||
.build();
|
||||
add_rule.add_css_class("flat");
|
||||
let rules = adw::PreferencesGroup::builder()
|
||||
.title(gettext("Open Files With"))
|
||||
.description(gettext(
|
||||
"For files opened from Proton Drive and the search launcher. The first rule that matches a file decides; other files open in their default app.",
|
||||
))
|
||||
.header_suffix(&add_rule)
|
||||
.build();
|
||||
|
||||
let other_row = adw::EntryRow::builder()
|
||||
.title(gettext("Other files (empty: default app)"))
|
||||
.show_apply_button(true)
|
||||
.build();
|
||||
other_row.add_css_class("monospace");
|
||||
let terminal_row = adw::EntryRow::builder()
|
||||
.title(terminal_title())
|
||||
.show_apply_button(true)
|
||||
.build();
|
||||
terminal_row.add_css_class("monospace");
|
||||
let other = adw::PreferencesGroup::new();
|
||||
other.add(&other_row);
|
||||
other.add(&terminal_row);
|
||||
|
||||
let mode_row = adw::ComboRow::builder()
|
||||
.title(gettext("Opens as"))
|
||||
.model(>k4::StringList::new(&[
|
||||
&gettext("Window"),
|
||||
&gettext("Your Launcher"),
|
||||
&gettext("fzf in a Terminal"),
|
||||
]))
|
||||
.build();
|
||||
let menu_row = adw::EntryRow::builder()
|
||||
.title(gettext("Launcher command (empty: find one)"))
|
||||
.show_apply_button(true)
|
||||
.build();
|
||||
menu_row.add_css_class("monospace");
|
||||
let prompt_terminal_row = adw::EntryRow::builder()
|
||||
.title(terminal_title())
|
||||
.show_apply_button(true)
|
||||
.build();
|
||||
prompt_terminal_row.add_css_class("monospace");
|
||||
let limit_row = adw::SpinRow::builder()
|
||||
.title(gettext("Results shown"))
|
||||
.adjustment(>k4::Adjustment::new(
|
||||
pdfs_core::menu::DEFAULT_MENU_LIMIT as f64,
|
||||
5.0,
|
||||
500.0,
|
||||
5.0,
|
||||
25.0,
|
||||
0.0,
|
||||
))
|
||||
.build();
|
||||
let icons_row = adw::SwitchRow::builder()
|
||||
.title(gettext("Show icons"))
|
||||
.subtitle(gettext("When the launcher can show them"))
|
||||
.build();
|
||||
let launcher = adw::PreferencesGroup::builder()
|
||||
.title(gettext("Search Launcher"))
|
||||
.description(gettext(
|
||||
"How “pdfs-prompt” shows search results, for example from a keyboard shortcut. Your launcher can be any program that reads choices like dmenu, such as rofi, wofi, fuzzel or bemenu.",
|
||||
))
|
||||
.build();
|
||||
launcher.add(&mode_row);
|
||||
launcher.add(&menu_row);
|
||||
launcher.add(&prompt_terminal_row);
|
||||
launcher.add(&limit_row);
|
||||
launcher.add(&icons_row);
|
||||
|
||||
let page = adw::PreferencesPage::builder()
|
||||
.title(gettext("Apps"))
|
||||
.name("apps")
|
||||
.icon_name("application-x-executable-symbolic")
|
||||
.build();
|
||||
page.add(&rules);
|
||||
page.add(&other);
|
||||
page.add(&launcher);
|
||||
AppsPrefs {
|
||||
page,
|
||||
rules,
|
||||
add_rule,
|
||||
other_row,
|
||||
terminal_row,
|
||||
mode_row,
|
||||
menu_row,
|
||||
prompt_terminal_row,
|
||||
limit_row,
|
||||
icons_row,
|
||||
}
|
||||
}
|
||||
|
||||
/// "Terminal", naming the one used when the row is left empty.
|
||||
fn terminal_title() -> String {
|
||||
match resolve_terminal() {
|
||||
// Translators: {terminal} is a terminal command line such as "foot -e".
|
||||
Some(found) => gettext_f(
|
||||
"Terminal (empty: {terminal})",
|
||||
&[("terminal", &format_command(&found))],
|
||||
),
|
||||
None => gettext("Terminal"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared by every handler of the page.
|
||||
struct Apps {
|
||||
ui: Rc<Ui>,
|
||||
widgets: AppsPrefs,
|
||||
rule_rows: RefCell<Vec<adw::ActionRow>>,
|
||||
}
|
||||
|
||||
/// Fill the page from the config and connect its controls.
|
||||
pub(crate) fn wire_apps_prefs(ui: &Rc<Ui>, widgets: AppsPrefs) {
|
||||
let apps = Rc::new(Apps {
|
||||
ui: ui.clone(),
|
||||
widgets,
|
||||
rule_rows: RefCell::default(),
|
||||
});
|
||||
let config = ui.dirs.load_config();
|
||||
let open_with = config.resolved_open_with();
|
||||
let prompt = config.resolved_prompt();
|
||||
let w = &apps.widgets;
|
||||
|
||||
let suppress = ui.status.settings_suppress.replace(true);
|
||||
paint_rules(&apps, &open_with);
|
||||
w.other_row
|
||||
.set_text(&format_command(open_with.default.as_deref().unwrap_or(&[])));
|
||||
w.terminal_row.set_text(&format_command(
|
||||
open_with.terminal.as_deref().unwrap_or(&[]),
|
||||
));
|
||||
let mode = prompt.resolved_mode();
|
||||
w.mode_row
|
||||
.set_selected(MODES.iter().position(|m| *m == mode).unwrap_or_default() as u32);
|
||||
w.menu_row
|
||||
.set_text(&format_command(prompt.menu.as_deref().unwrap_or(&[])));
|
||||
w.prompt_terminal_row
|
||||
.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());
|
||||
show_mode_rows(w, mode);
|
||||
ui.status.settings_suppress.set(suppress);
|
||||
|
||||
let a = apps.clone();
|
||||
w.add_rule
|
||||
.connect_clicked(move |_| edit_rule(&a, None, OpenRule::default()));
|
||||
|
||||
// Command lines: checked as typed, saved on apply. Empty means "unset".
|
||||
connect_command_row(&apps, &w.other_row, |config, argv| {
|
||||
open_with_of(config).default = argv;
|
||||
});
|
||||
connect_command_row(&apps, &w.terminal_row, |config, argv| {
|
||||
open_with_of(config).terminal = argv;
|
||||
});
|
||||
connect_command_row(&apps, &w.menu_row, |config, argv| {
|
||||
prompt_of(config).menu = argv;
|
||||
});
|
||||
connect_command_row(&apps, &w.prompt_terminal_row, |config, argv| {
|
||||
prompt_of(config).terminal = argv;
|
||||
});
|
||||
|
||||
let a = apps.clone();
|
||||
w.mode_row.connect_selected_notify(move |row| {
|
||||
if a.ui.status.settings_suppress.get() {
|
||||
return;
|
||||
}
|
||||
let mode = MODES
|
||||
.get(row.selected() as usize)
|
||||
.copied()
|
||||
.unwrap_or_default();
|
||||
show_mode_rows(&a.widgets, mode);
|
||||
save(&a, move |config| {
|
||||
prompt_of(config).mode = (mode != PromptMode::default()).then_some(mode);
|
||||
});
|
||||
});
|
||||
let a = apps.clone();
|
||||
w.limit_row.connect_value_notify(move |row| {
|
||||
if a.ui.status.settings_suppress.get() {
|
||||
return;
|
||||
}
|
||||
let limit = row.value().round() as usize;
|
||||
save(&a, move |config| {
|
||||
prompt_of(config).menu_limit =
|
||||
(limit != pdfs_core::menu::DEFAULT_MENU_LIMIT).then_some(limit);
|
||||
});
|
||||
});
|
||||
let a = apps.clone();
|
||||
w.icons_row.connect_active_notify(move |row| {
|
||||
if a.ui.status.settings_suppress.get() {
|
||||
return;
|
||||
}
|
||||
let on = row.is_active();
|
||||
save(&a, move |config| {
|
||||
prompt_of(config).menu_icons = (!on).then_some(false)
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// Show only the rows the chosen launcher mode uses.
|
||||
fn show_mode_rows(w: &AppsPrefs, mode: PromptMode) {
|
||||
w.menu_row.set_visible(mode == PromptMode::Dmenu);
|
||||
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);
|
||||
}
|
||||
|
||||
/// The `open_with` section, created when absent.
|
||||
fn open_with_of(config: &mut pdfs_core::config::AppConfig) -> &mut OpenWith {
|
||||
config.open_with.get_or_insert_with(OpenWith::default)
|
||||
}
|
||||
|
||||
/// The `prompt` section, created when absent.
|
||||
fn prompt_of(config: &mut pdfs_core::config::AppConfig) -> &mut PromptConfig {
|
||||
config.prompt.get_or_insert_with(PromptConfig::default)
|
||||
}
|
||||
|
||||
/// Save a change, then drop sections left at their defaults so the file only
|
||||
/// holds what the user chose. Says whether it saved.
|
||||
fn save(apps: &Rc<Apps>, change: impl FnOnce(&mut pdfs_core::config::AppConfig)) -> bool {
|
||||
let saved = apps.ui.dirs.update_config(|config| {
|
||||
change(config);
|
||||
if config.open_with.as_ref() == Some(&OpenWith::default()) {
|
||||
config.open_with = None;
|
||||
}
|
||||
if config.prompt.as_ref() == Some(&PromptConfig::default()) {
|
||||
config.prompt = None;
|
||||
}
|
||||
config.resolved_open_with()
|
||||
});
|
||||
match saved {
|
||||
Ok(open_with) => {
|
||||
paint_rules(apps, &open_with);
|
||||
true
|
||||
}
|
||||
Err(e) => {
|
||||
prefs_toast(
|
||||
&apps.ui,
|
||||
&gettext_f(
|
||||
"{what}: {detail}",
|
||||
&[
|
||||
("what", &gettext("Couldn't save the setting")),
|
||||
("detail", &e.to_string()),
|
||||
],
|
||||
),
|
||||
);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Check a command line as it is typed, and save it when applied.
|
||||
fn connect_command_row(
|
||||
apps: &Rc<Apps>,
|
||||
row: &adw::EntryRow,
|
||||
store: impl Fn(&mut pdfs_core::config::AppConfig, Option<Vec<String>>) + 'static,
|
||||
) {
|
||||
row.connect_changed(|row| mark_command(row, false));
|
||||
let a = apps.clone();
|
||||
row.connect_apply(move |row| {
|
||||
let Some(argv) = parse_command(&row.text()) else {
|
||||
prefs_toast(&a.ui, &gettext("A quote is not closed in the command"));
|
||||
return;
|
||||
};
|
||||
if !argv.is_empty() && !command_available(&argv) {
|
||||
prefs_toast(
|
||||
&a.ui,
|
||||
// Translators: {program} is a program name such as "nvim".
|
||||
&gettext_f(
|
||||
"“{program}” isn't installed; saved anyway",
|
||||
&[("program", &argv[0])],
|
||||
),
|
||||
);
|
||||
}
|
||||
let argv = (!argv.is_empty()).then_some(argv);
|
||||
save(&a, |config| store(config, argv));
|
||||
mark_command(row, true);
|
||||
});
|
||||
}
|
||||
|
||||
/// Mark a command line that doesn't parse as an error, and, once `applied`,
|
||||
/// one whose program isn't found as a warning.
|
||||
fn mark_command(row: &adw::EntryRow, applied: bool) {
|
||||
row.remove_css_class("error");
|
||||
row.remove_css_class("warning");
|
||||
match parse_command(&row.text()) {
|
||||
None => row.add_css_class("error"),
|
||||
Some(argv) if applied && !argv.is_empty() && !command_available(&argv) => {
|
||||
row.add_css_class("warning")
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Show the rules, one row each, in the order they are tried.
|
||||
fn paint_rules(apps: &Rc<Apps>, open_with: &OpenWith) {
|
||||
let group = &apps.widgets.rules;
|
||||
for row in apps.rule_rows.borrow_mut().drain(..) {
|
||||
group.remove(&row);
|
||||
}
|
||||
let count = open_with.rules.len();
|
||||
if count == 0 {
|
||||
let row = adw::ActionRow::builder()
|
||||
.title(gettext("No rules: every file opens in its default app"))
|
||||
.build();
|
||||
row.add_css_class("dim-label");
|
||||
group.add(&row);
|
||||
apps.rule_rows.borrow_mut().push(row);
|
||||
return;
|
||||
}
|
||||
let names = classes();
|
||||
for (index, rule) in open_with.rules.iter().enumerate() {
|
||||
let patterns: Vec<String> = rule
|
||||
.patterns
|
||||
.iter()
|
||||
.map(|p| {
|
||||
names
|
||||
.iter()
|
||||
.find(|(class, _)| class == p)
|
||||
.map_or_else(|| p.clone(), |(_, name)| name.clone())
|
||||
})
|
||||
.collect();
|
||||
let command = format_command(&rule.command);
|
||||
let subtitle = if rule.terminal {
|
||||
// Translators: {command} is a command line such as "nvim".
|
||||
gettext_f("{command}, in a terminal", &[("command", &command)])
|
||||
} else {
|
||||
command
|
||||
};
|
||||
let row = adw::ActionRow::builder()
|
||||
.title(patterns.join(", "))
|
||||
.subtitle(subtitle)
|
||||
.use_markup(false)
|
||||
.activatable(true)
|
||||
.build();
|
||||
if !command_available(&rule.command) {
|
||||
let warning = gtk4::Image::builder()
|
||||
.icon_name("dialog-warning-symbolic")
|
||||
// Translators: {program} is a program name such as "nvim".
|
||||
.tooltip_text(gettext_f(
|
||||
"“{program}” isn't installed",
|
||||
&[("program", rule.command.first().map_or("", String::as_str))],
|
||||
))
|
||||
.build();
|
||||
warning.add_css_class("warning");
|
||||
row.add_prefix(&warning);
|
||||
}
|
||||
let up = rule_button("go-up-symbolic", &gettext("Move Up"), index > 0);
|
||||
let down = rule_button("go-down-symbolic", &gettext("Move Down"), index + 1 < count);
|
||||
let remove = rule_button("user-trash-symbolic", &gettext("Remove"), true);
|
||||
let a = apps.clone();
|
||||
up.connect_clicked(move |_| {
|
||||
save(&a, |config| {
|
||||
open_with_of(config).rules.swap(index - 1, index)
|
||||
});
|
||||
});
|
||||
let a = apps.clone();
|
||||
down.connect_clicked(move |_| {
|
||||
save(&a, |config| {
|
||||
open_with_of(config).rules.swap(index, index + 1)
|
||||
});
|
||||
});
|
||||
let a = apps.clone();
|
||||
remove.connect_clicked(move |_| {
|
||||
save(&a, |config| {
|
||||
let rules = &mut open_with_of(config).rules;
|
||||
if index < rules.len() {
|
||||
rules.remove(index);
|
||||
}
|
||||
});
|
||||
});
|
||||
row.add_suffix(&up);
|
||||
row.add_suffix(&down);
|
||||
row.add_suffix(&remove);
|
||||
let a = apps.clone();
|
||||
let rule = rule.clone();
|
||||
row.connect_activated(move |_| edit_rule(&a, Some(index), rule.clone()));
|
||||
group.add(&row);
|
||||
apps.rule_rows.borrow_mut().push(row);
|
||||
}
|
||||
}
|
||||
|
||||
fn rule_button(icon: &str, tooltip: &str, sensitive: bool) -> gtk4::Button {
|
||||
let button = gtk4::Button::builder()
|
||||
.icon_name(icon)
|
||||
.tooltip_text(tooltip)
|
||||
.valign(gtk4::Align::Center)
|
||||
.sensitive(sensitive)
|
||||
.build();
|
||||
button.add_css_class("flat");
|
||||
button
|
||||
}
|
||||
|
||||
/// Split a typed pattern list into patterns, dropping empty ones.
|
||||
fn split_patterns(text: &str) -> Vec<String> {
|
||||
text.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|p| !p.is_empty())
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Edit one rule, or a new one when `index` is `None`, in a dialog over the
|
||||
/// Preferences.
|
||||
fn edit_rule(apps: &Rc<Apps>, index: Option<usize>, rule: OpenRule) {
|
||||
let patterns_row = adw::EntryRow::builder()
|
||||
.title(gettext("Files, such as *.md, *.txt"))
|
||||
.text(rule.patterns.join(", "))
|
||||
.build();
|
||||
patterns_row.add_css_class("monospace");
|
||||
let chips = gtk4::FlowBox::builder()
|
||||
.selection_mode(gtk4::SelectionMode::None)
|
||||
.column_spacing(6)
|
||||
.row_spacing(6)
|
||||
.max_children_per_line(6)
|
||||
.margin_top(6)
|
||||
.build();
|
||||
for (class, name) in classes() {
|
||||
let chip = gtk4::Button::builder().label(&name).build();
|
||||
chip.add_css_class("pill");
|
||||
chip.add_css_class("small");
|
||||
let row = patterns_row.clone();
|
||||
chip.connect_clicked(move |_| {
|
||||
let mut list = split_patterns(&row.text());
|
||||
if !list.iter().any(|p| p == class) {
|
||||
list.push(class.to_string());
|
||||
}
|
||||
row.set_text(&list.join(", "));
|
||||
});
|
||||
chips.insert(&chip, -1);
|
||||
}
|
||||
let command_row = adw::EntryRow::builder()
|
||||
.title(gettext("Command, such as nvim or code --wait"))
|
||||
.text(format_command(&rule.command))
|
||||
.build();
|
||||
command_row.add_css_class("monospace");
|
||||
let terminal_row = adw::SwitchRow::builder()
|
||||
.title(gettext("Run in a terminal"))
|
||||
.subtitle(gettext("For programs that run in a terminal, such as vim"))
|
||||
.active(rule.terminal)
|
||||
.build();
|
||||
let hint = gtk4::Label::builder()
|
||||
.wrap(true)
|
||||
.xalign(0.0)
|
||||
.margin_top(6)
|
||||
.build();
|
||||
hint.add_css_class("caption");
|
||||
hint.add_css_class("dim-label");
|
||||
|
||||
let group = adw::PreferencesGroup::new();
|
||||
group.add(&patterns_row);
|
||||
let files = adw::PreferencesGroup::builder()
|
||||
.description(gettext("Or pick kinds of files:"))
|
||||
.build();
|
||||
files.add(&chips);
|
||||
let program = adw::PreferencesGroup::new();
|
||||
program.add(&command_row);
|
||||
program.add(&terminal_row);
|
||||
program.add(&hint);
|
||||
let page = adw::PreferencesPage::new();
|
||||
page.add(&group);
|
||||
page.add(&files);
|
||||
page.add(&program);
|
||||
|
||||
let cancel = gtk4::Button::with_label(&gettext("Cancel"));
|
||||
let save_button = gtk4::Button::with_label(&gettext("Save"));
|
||||
save_button.add_css_class("suggested-action");
|
||||
let header = adw::HeaderBar::builder()
|
||||
.show_start_title_buttons(false)
|
||||
.show_end_title_buttons(false)
|
||||
.build();
|
||||
header.pack_start(&cancel);
|
||||
header.pack_end(&save_button);
|
||||
let view = adw::ToolbarView::new();
|
||||
view.add_top_bar(&header);
|
||||
view.set_content(Some(&page));
|
||||
let dialog = adw::Dialog::builder()
|
||||
.title(if index.is_some() {
|
||||
gettext("Edit Rule")
|
||||
} else {
|
||||
gettext("New Rule")
|
||||
})
|
||||
.content_width(480)
|
||||
.child(&view)
|
||||
.build();
|
||||
|
||||
// Save only a rule that matches something and runs something.
|
||||
let check = {
|
||||
let (patterns_row, command_row, save_button, hint) = (
|
||||
patterns_row.clone(),
|
||||
command_row.clone(),
|
||||
save_button.clone(),
|
||||
hint.clone(),
|
||||
);
|
||||
move || {
|
||||
let patterns = split_patterns(&patterns_row.text());
|
||||
let argv = parse_command(&command_row.text());
|
||||
command_row.remove_css_class("error");
|
||||
hint.set_text("");
|
||||
match &argv {
|
||||
None => {
|
||||
command_row.add_css_class("error");
|
||||
hint.set_text(&gettext("A quote is not closed in the command."));
|
||||
}
|
||||
Some(argv) if !argv.is_empty() && !command_available(argv) => {
|
||||
hint.set_text(&gettext_f(
|
||||
"“{program}” isn't installed.",
|
||||
&[("program", &argv[0])],
|
||||
));
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
save_button
|
||||
.set_sensitive(!patterns.is_empty() && argv.is_some_and(|argv| !argv.is_empty()));
|
||||
}
|
||||
};
|
||||
check();
|
||||
let c = check.clone();
|
||||
patterns_row.connect_changed(move |_| c());
|
||||
command_row.connect_changed(move |_| check());
|
||||
|
||||
let d = dialog.clone();
|
||||
cancel.connect_clicked(move |_| {
|
||||
d.close();
|
||||
});
|
||||
let (a, d) = (apps.clone(), dialog.clone());
|
||||
save_button.connect_clicked(move |_| {
|
||||
let Some(command) = parse_command(&command_row.text()) else {
|
||||
return;
|
||||
};
|
||||
let rule = OpenRule {
|
||||
patterns: split_patterns(&patterns_row.text()),
|
||||
command,
|
||||
terminal: terminal_row.is_active(),
|
||||
};
|
||||
let saved = save(&a, move |config| {
|
||||
let rules = &mut open_with_of(config).rules;
|
||||
match index {
|
||||
Some(i) if i < rules.len() => rules[i] = rule,
|
||||
_ => rules.push(rule),
|
||||
}
|
||||
});
|
||||
if saved {
|
||||
d.close();
|
||||
}
|
||||
});
|
||||
dialog.present(Some(&apps.ui.status.prefs));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn typed_patterns_are_split_on_commas() {
|
||||
assert_eq!(
|
||||
split_patterns(" *.md, @text ,, notes-*.txt "),
|
||||
["*.md", "@text", "notes-*.txt"]
|
||||
);
|
||||
assert!(split_patterns(" , ").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
//! Preferences → Sync: the patterns every synced folder leaves out
|
||||
//! (`ignore_patterns`) and what the conflict sweep may do (`conflict_sweep`).
|
||||
//!
|
||||
//! Both live in `config.json`. The daemon reads the patterns again on every
|
||||
//! sync pass, so a change here is followed by a Sync Now and applies at once;
|
||||
//! the sweep mode is read when the service starts, so a change offers a
|
||||
//! restart, as the mountpoint does.
|
||||
|
||||
use crate::*;
|
||||
use pdfs_core::config::SweepMode;
|
||||
use pdfs_core::syncignore::{DEFAULT_IGNORE_PATTERNS, check_pattern};
|
||||
|
||||
/// The widgets of the Sync page, built with the rest of the dialog and wired
|
||||
/// once the app's state exists.
|
||||
pub(crate) struct SyncPrefs {
|
||||
pub(crate) page: adw::PreferencesPage,
|
||||
patterns: adw::PreferencesGroup,
|
||||
add_row: adw::EntryRow,
|
||||
reset: gtk4::Button,
|
||||
sweep_row: adw::ComboRow,
|
||||
/// Whether the built-in patterns are shown, kept across repaints.
|
||||
builtin_expanded: Cell<bool>,
|
||||
}
|
||||
|
||||
/// The sweep modes in the order the combo row lists them.
|
||||
const SWEEP_MODES: [SweepMode; 3] = [SweepMode::Report, SweepMode::Enforce, SweepMode::Off];
|
||||
|
||||
pub(crate) fn build_sync_prefs() -> SyncPrefs {
|
||||
let reset = gtk4::Button::builder()
|
||||
.label(gettext("Reset"))
|
||||
.tooltip_text(gettext("Use the built-in patterns again"))
|
||||
.valign(gtk4::Align::Center)
|
||||
.build();
|
||||
reset.add_css_class("flat");
|
||||
let patterns = adw::PreferencesGroup::builder()
|
||||
.title(gettext("Excluded Files"))
|
||||
.description(gettext(
|
||||
"Files and folders matching these patterns are not synced in any synced folder. Use * for any characters, end a pattern with / to match folders only, and start it with ! to include something again. Excluding never deletes anything from Proton Drive.",
|
||||
))
|
||||
.header_suffix(&reset)
|
||||
.build();
|
||||
let add_row = adw::EntryRow::builder()
|
||||
.title(gettext("Add Pattern"))
|
||||
.show_apply_button(true)
|
||||
.build();
|
||||
add_row.add_css_class("monospace");
|
||||
patterns.add(&add_row);
|
||||
|
||||
let sweep_row = adw::ComboRow::builder()
|
||||
.title(gettext("Identical conflict copies"))
|
||||
.subtitle(gettext(
|
||||
"A copy made when a file changed in two places, found to be the same as the file",
|
||||
))
|
||||
.model(>k4::StringList::new(&[
|
||||
&gettext("Report Only"),
|
||||
&gettext("Move to Trash"),
|
||||
&gettext("Off"),
|
||||
]))
|
||||
.build();
|
||||
let conflicts = adw::PreferencesGroup::builder()
|
||||
.title(gettext("Conflict Copies"))
|
||||
.build();
|
||||
conflicts.add(&sweep_row);
|
||||
|
||||
let page = adw::PreferencesPage::builder()
|
||||
.title(gettext("Sync"))
|
||||
.name("sync")
|
||||
.icon_name("pdfs-sync-symbolic")
|
||||
.build();
|
||||
page.add(&patterns);
|
||||
page.add(&conflicts);
|
||||
SyncPrefs {
|
||||
page,
|
||||
patterns,
|
||||
add_row,
|
||||
reset,
|
||||
sweep_row,
|
||||
builtin_expanded: Cell::new(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// Fill the page from the config and connect its controls.
|
||||
pub(crate) fn wire_sync_prefs(ui: &Rc<Ui>, widgets: SyncPrefs) {
|
||||
let widgets = Rc::new(widgets);
|
||||
let rows: Rc<RefCell<Vec<adw::PreferencesRow>>> = Rc::default();
|
||||
let config = ui.dirs.load_config();
|
||||
paint_patterns(ui, &widgets, &rows, &config);
|
||||
// The Sync page and `pdfs sync ignore` change the patterns too: show the
|
||||
// saved ones each time the page comes up.
|
||||
let (ui_map, w_map, rows_map) = (ui.clone(), widgets.clone(), rows.clone());
|
||||
widgets.page.connect_map(move |_| {
|
||||
let config = ui_map.dirs.load_config();
|
||||
paint_patterns(&ui_map, &w_map, &rows_map, &config);
|
||||
});
|
||||
|
||||
let mode = config.conflict_sweep.unwrap_or_default();
|
||||
let suppress = ui.status.settings_suppress.replace(true);
|
||||
widgets.sweep_row.set_selected(
|
||||
SWEEP_MODES
|
||||
.iter()
|
||||
.position(|m| *m == mode)
|
||||
.unwrap_or_default() as u32,
|
||||
);
|
||||
ui.status.settings_suppress.set(suppress);
|
||||
|
||||
widgets.add_row.connect_changed(|row| {
|
||||
let text = row.text();
|
||||
if text.trim().is_empty() || check_pattern(text.trim()).is_ok() {
|
||||
row.remove_css_class("error");
|
||||
} else {
|
||||
row.add_css_class("error");
|
||||
}
|
||||
});
|
||||
let (ui_add, w_add, rows_add) = (ui.clone(), widgets.clone(), rows.clone());
|
||||
widgets.add_row.connect_apply(move |row| {
|
||||
let pattern = row.text().trim().to_string();
|
||||
if pattern.is_empty() {
|
||||
return;
|
||||
}
|
||||
if let Err(e) = check_pattern(&pattern) {
|
||||
tracing::debug!(%pattern, error = %e, "not a valid ignore pattern");
|
||||
prefs_toast(
|
||||
&ui_add,
|
||||
// Translators: {pattern} is what the user typed as a pattern.
|
||||
&gettext_f(
|
||||
"“{pattern}” isn't a valid pattern",
|
||||
&[("pattern", &pattern)],
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
let added = change_patterns(&ui_add, &w_add, &rows_add, |list| {
|
||||
if !list.contains(&pattern) {
|
||||
list.push(pattern.clone());
|
||||
}
|
||||
});
|
||||
if added {
|
||||
row.set_text("");
|
||||
}
|
||||
});
|
||||
|
||||
let (ui_reset, w_reset, rows_reset) = (ui.clone(), widgets.clone(), rows.clone());
|
||||
widgets.reset.connect_clicked(move |_| {
|
||||
let (ui, w, rows) = (ui_reset.clone(), w_reset.clone(), rows_reset.clone());
|
||||
confirm_destructive(
|
||||
&ui_reset.status.prefs,
|
||||
&gettext("Reset Excluded Files?"),
|
||||
&gettext("Your own patterns are removed, and the built-in ones apply again."),
|
||||
&gettext("Reset"),
|
||||
move || {
|
||||
change_patterns(&ui, &w, &rows, |list| {
|
||||
*list = default_patterns();
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
let ui_sweep = ui.clone();
|
||||
widgets.sweep_row.connect_selected_notify(move |row| {
|
||||
if ui_sweep.status.settings_suppress.get() {
|
||||
return;
|
||||
}
|
||||
let Some(mode) = SWEEP_MODES.get(row.selected() as usize).copied() else {
|
||||
return;
|
||||
};
|
||||
let stored = (mode != SweepMode::default()).then_some(mode);
|
||||
match ui_sweep
|
||||
.dirs
|
||||
.update_config(|config| config.conflict_sweep = stored)
|
||||
{
|
||||
Ok(()) => offer_restart(&ui_sweep),
|
||||
Err(e) => prefs_toast(
|
||||
&ui_sweep,
|
||||
&gettext_f(
|
||||
"{what}: {detail}",
|
||||
&[
|
||||
("what", &gettext("Couldn't save the setting")),
|
||||
("detail", &e.to_string()),
|
||||
],
|
||||
),
|
||||
),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn default_patterns() -> Vec<String> {
|
||||
DEFAULT_IGNORE_PATTERNS
|
||||
.iter()
|
||||
.map(|p| (*p).to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Apply `edit` to the patterns in effect and save them, then show them and
|
||||
/// have every synced folder sync with them. Says whether it saved.
|
||||
fn change_patterns(
|
||||
ui: &Rc<Ui>,
|
||||
widgets: &Rc<SyncPrefs>,
|
||||
rows: &Rc<RefCell<Vec<adw::PreferencesRow>>>,
|
||||
edit: impl FnOnce(&mut Vec<String>),
|
||||
) -> bool {
|
||||
match ui.dirs.change_ignore_patterns(edit) {
|
||||
Ok(config) => {
|
||||
paint_patterns(ui, widgets, rows, &config);
|
||||
// Best effort: the next pass picks the change up anyway.
|
||||
let _ = spawn_request(ui.dirs.control_socket(), Request::SyncNow { id: None });
|
||||
true
|
||||
}
|
||||
Err(e) => {
|
||||
prefs_toast(
|
||||
ui,
|
||||
&gettext_f(
|
||||
"{what}: {detail}",
|
||||
&[
|
||||
("what", &gettext("Couldn't save the patterns")),
|
||||
("detail", &e.to_string()),
|
||||
],
|
||||
),
|
||||
);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Show the patterns in effect below the entry row: the user's own one row
|
||||
/// each, then the built-in ones folded into one row, since they are many and
|
||||
/// rarely changed.
|
||||
fn paint_patterns(
|
||||
ui: &Rc<Ui>,
|
||||
widgets: &Rc<SyncPrefs>,
|
||||
rows: &Rc<RefCell<Vec<adw::PreferencesRow>>>,
|
||||
config: &pdfs_core::config::AppConfig,
|
||||
) {
|
||||
for row in rows.borrow_mut().drain(..) {
|
||||
widgets.patterns.remove(&row);
|
||||
}
|
||||
widgets
|
||||
.reset
|
||||
.set_sensitive(config.ignore_patterns.is_some());
|
||||
let list = config.resolved_ignore_patterns();
|
||||
let (builtin, own): (Vec<String>, Vec<String>) = list
|
||||
.into_iter()
|
||||
.partition(|p| DEFAULT_IGNORE_PATTERNS.contains(&p.as_str()));
|
||||
for pattern in own {
|
||||
let row = pattern_row(ui, widgets, rows, pattern);
|
||||
widgets.patterns.add(&row);
|
||||
rows.borrow_mut().push(row.upcast());
|
||||
}
|
||||
// Every built-in pattern, on or off, so one turned off can be turned on
|
||||
// again without losing the user's own.
|
||||
let on = builtin.len();
|
||||
let total = DEFAULT_IGNORE_PATTERNS.len();
|
||||
let expander = adw::ExpanderRow::builder()
|
||||
.title(gettext("Built-in patterns"))
|
||||
// Translators: {on} and {total} are numbers of patterns.
|
||||
.subtitle(gettext_f(
|
||||
"{on} of {total} on: version control, dependency and build folders, and what editors, downloads and systems leave behind",
|
||||
&[("on", &on.to_string()), ("total", &total.to_string())],
|
||||
))
|
||||
.expanded(widgets.builtin_expanded.get())
|
||||
.build();
|
||||
let w = widgets.clone();
|
||||
expander.connect_expanded_notify(move |row| w.builtin_expanded.set(row.is_expanded()));
|
||||
for pattern in DEFAULT_IGNORE_PATTERNS {
|
||||
let row = adw::SwitchRow::builder()
|
||||
.title(format!("<tt>{}</tt>", glib::markup_escape_text(pattern)))
|
||||
.use_markup(true)
|
||||
.active(builtin.iter().any(|p| p == pattern))
|
||||
.build();
|
||||
let (ui, w, r) = (ui.clone(), widgets.clone(), rows.clone());
|
||||
row.connect_active_notify(move |row| {
|
||||
let active = row.is_active();
|
||||
// Repainting replaces this row; let the switch finish first.
|
||||
let (ui, w, r) = (ui.clone(), w.clone(), r.clone());
|
||||
glib::idle_add_local_once(move || {
|
||||
change_patterns(&ui, &w, &r, move |list| {
|
||||
list.retain(|p| p != pattern);
|
||||
if active {
|
||||
list.push((*pattern).to_string());
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
expander.add_row(&row);
|
||||
}
|
||||
widgets.patterns.add(&expander);
|
||||
rows.borrow_mut().push(expander.upcast());
|
||||
}
|
||||
|
||||
/// One pattern, in monospace, with a button that removes it.
|
||||
fn pattern_row(
|
||||
ui: &Rc<Ui>,
|
||||
widgets: &Rc<SyncPrefs>,
|
||||
rows: &Rc<RefCell<Vec<adw::PreferencesRow>>>,
|
||||
pattern: String,
|
||||
) -> adw::ActionRow {
|
||||
let row = adw::ActionRow::builder()
|
||||
.title(format!("<tt>{}</tt>", glib::markup_escape_text(&pattern)))
|
||||
.use_markup(true)
|
||||
.build();
|
||||
let remove = gtk4::Button::builder()
|
||||
.icon_name("user-trash-symbolic")
|
||||
.tooltip_text(gettext("Remove"))
|
||||
.valign(gtk4::Align::Center)
|
||||
.build();
|
||||
remove.add_css_class("flat");
|
||||
let (ui, w, r) = (ui.clone(), widgets.clone(), rows.clone());
|
||||
remove.connect_clicked(move |_| {
|
||||
let pattern = pattern.clone();
|
||||
change_patterns(&ui, &w, &r, move |list| list.retain(|p| *p != pattern));
|
||||
});
|
||||
row.add_suffix(&remove);
|
||||
row
|
||||
}
|
||||
|
||||
/// The sweep mode is read when the service starts; offer that restart.
|
||||
fn offer_restart(ui: &Rc<Ui>) {
|
||||
let confirm = adw::AlertDialog::builder()
|
||||
.heading(gettext("Restart Proton Drive?"))
|
||||
.body(gettext(
|
||||
"The new setting applies after Proton Drive restarts.",
|
||||
))
|
||||
.build();
|
||||
confirm.add_response("later", &gettext("Later"));
|
||||
confirm.add_response("restart", &gettext("Restart Now"));
|
||||
confirm.set_response_appearance("restart", adw::ResponseAppearance::Suggested);
|
||||
confirm.set_default_response(Some("restart"));
|
||||
confirm.set_close_response("later");
|
||||
let ui_restart = ui.clone();
|
||||
confirm.connect_response(None, move |_, resp| {
|
||||
if resp == "restart" {
|
||||
restart_service_then(&ui_restart, |_| {});
|
||||
}
|
||||
});
|
||||
confirm.present(Some(&ui.status.prefs));
|
||||
}
|
||||
|
||||
/// A toast on the Preferences dialog, which covers the window's own toasts.
|
||||
pub(crate) fn prefs_toast(ui: &Rc<Ui>, message: &str) {
|
||||
ui.status.prefs.add_toast(
|
||||
adw::Toast::builder()
|
||||
.title(message)
|
||||
.use_markup(false)
|
||||
.timeout(6)
|
||||
.build(),
|
||||
);
|
||||
}
|
||||
@@ -169,6 +169,9 @@ pub(crate) struct MainWidgets {
|
||||
pub(crate) tray_row: adw::SwitchRow,
|
||||
pub(crate) update_row: adw::SwitchRow,
|
||||
pub(crate) language_row: adw::ComboRow,
|
||||
/// Preferences → Sync and → Apps, wired once the app's state exists.
|
||||
pub(crate) sync_prefs: SyncPrefs,
|
||||
pub(crate) apps_prefs: AppsPrefs,
|
||||
}
|
||||
|
||||
/// Build the two surfaces that replaced the old Settings page:
|
||||
@@ -267,6 +270,7 @@ pub(crate) fn build_main_page() -> MainWidgets {
|
||||
|
||||
let general = adw::PreferencesPage::builder()
|
||||
.title(gettext("General"))
|
||||
.name("general")
|
||||
.icon_name("preferences-system-symbolic")
|
||||
.build();
|
||||
general.add(&startup_group);
|
||||
@@ -335,6 +339,7 @@ pub(crate) fn build_main_page() -> MainWidgets {
|
||||
|
||||
let storage = adw::PreferencesPage::builder()
|
||||
.title(gettext("Storage"))
|
||||
.name("storage")
|
||||
.icon_name("drive-harddisk-symbolic")
|
||||
.build();
|
||||
storage.add(&storage_group);
|
||||
@@ -343,7 +348,11 @@ pub(crate) fn build_main_page() -> MainWidgets {
|
||||
let prefs = adw::PreferencesDialog::builder()
|
||||
.search_enabled(false)
|
||||
.build();
|
||||
let sync_prefs = build_sync_prefs();
|
||||
let apps_prefs = build_apps_prefs();
|
||||
prefs.add(&general);
|
||||
prefs.add(&sync_prefs.page);
|
||||
prefs.add(&apps_prefs.page);
|
||||
prefs.add(&storage);
|
||||
|
||||
// ---- Sidebar footer
|
||||
@@ -463,6 +472,8 @@ pub(crate) fn build_main_page() -> MainWidgets {
|
||||
tray_row,
|
||||
update_row,
|
||||
language_row,
|
||||
sync_prefs,
|
||||
apps_prefs,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -678,9 +689,10 @@ pub(crate) fn wire_settings(
|
||||
let rows = list.model.n_items();
|
||||
list.model.items_changed(0, rows, rows);
|
||||
}
|
||||
let mut config = ui_theme.dirs.load_config();
|
||||
config.proton_theme = Some(on);
|
||||
if let Err(e) = ui_theme.dirs.save_config(&config) {
|
||||
if let Err(e) = ui_theme
|
||||
.dirs
|
||||
.update_config(|config| config.proton_theme = Some(on))
|
||||
{
|
||||
toast_error(
|
||||
&ui_theme,
|
||||
&gettext("Couldn't save the theme"),
|
||||
@@ -700,9 +712,7 @@ pub(crate) fn wire_settings(
|
||||
.gallery
|
||||
.places_map
|
||||
.set_online(on, ui_map.dirs.cache_dir());
|
||||
let mut config = ui_map.dirs.load_config();
|
||||
config.online_map = on;
|
||||
if let Err(e) = ui_map.dirs.save_config(&config) {
|
||||
if let Err(e) = ui_map.dirs.update_config(|config| config.online_map = on) {
|
||||
toast_error(
|
||||
&ui_map,
|
||||
&gettext("Couldn't save the map setting"),
|
||||
@@ -717,9 +727,10 @@ pub(crate) fn wire_settings(
|
||||
if ui_update.status.settings_suppress.get() {
|
||||
return;
|
||||
}
|
||||
let mut config = ui_update.dirs.load_config();
|
||||
config.update_check = row.is_active();
|
||||
if let Err(e) = ui_update.dirs.save_config(&config) {
|
||||
if let Err(e) = ui_update
|
||||
.dirs
|
||||
.update_config(|config| config.update_check = row.is_active())
|
||||
{
|
||||
toast_error(
|
||||
&ui_update,
|
||||
&gettext("Couldn't save the update setting"),
|
||||
@@ -739,9 +750,10 @@ pub(crate) fn wire_settings(
|
||||
return;
|
||||
}
|
||||
let show = row.is_active();
|
||||
let mut config = ui_tray.dirs.load_config();
|
||||
config.tray_hidden = !show;
|
||||
if let Err(e) = ui_tray.dirs.save_config(&config) {
|
||||
if let Err(e) = ui_tray
|
||||
.dirs
|
||||
.update_config(|config| config.tray_hidden = !show)
|
||||
{
|
||||
toast_error(
|
||||
&ui_tray,
|
||||
&gettext("Couldn't save the tray setting"),
|
||||
@@ -763,9 +775,9 @@ pub(crate) fn wire_settings(
|
||||
if ui_language.status.settings_suppress.get() {
|
||||
return;
|
||||
}
|
||||
let mut config = ui_language.dirs.load_config();
|
||||
config.language = language_at(row.selected()).map(str::to_string);
|
||||
if let Err(e) = ui_language.dirs.save_config(&config) {
|
||||
if let Err(e) = ui_language.dirs.update_config(|config| {
|
||||
config.language = language_at(row.selected()).map(str::to_string)
|
||||
}) {
|
||||
toast_error(
|
||||
&ui_language,
|
||||
&gettext("Couldn't save the language"),
|
||||
@@ -864,9 +876,10 @@ fn use_mountpoint(ui: &Rc<Ui>, path: &std::path::Path) {
|
||||
let path_str = path.display().to_string();
|
||||
|
||||
// Persist the choice to config so the next mount uses it.
|
||||
let mut config = ui.dirs.load_config();
|
||||
config.mountpoint = Some(path_str.clone());
|
||||
if let Err(e) = ui.dirs.save_config(&config) {
|
||||
if let Err(e) = ui
|
||||
.dirs
|
||||
.update_config(|config| config.mountpoint = Some(path_str.clone()))
|
||||
{
|
||||
toast_error(ui, &gettext("Couldn't save the folder"), &e.to_string());
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,426 @@
|
||||
//! The Excluded Files group on the Sync page's Folders view: what is left out
|
||||
//! of every synced folder and of each one on its own, with how many patterns
|
||||
//! each has, and an Add Pattern dialog that asks where a pattern goes.
|
||||
//!
|
||||
//! The rows open the editors that already exist: Preferences → Sync for the
|
||||
//! patterns of all folders, the Excluded Files dialog for a folder's own
|
||||
//! `.pdfsignore`. Only folders kept on this computer are listed; an
|
||||
//! online-only folder has no local files for patterns to leave out. With none
|
||||
//! of those, the group still shows, so the patterns can be found and set up
|
||||
//! before a folder is switched to Synced, and says why they do nothing yet.
|
||||
|
||||
use crate::*;
|
||||
use pdfs_core::syncignore::{FolderRules, add_folder_pattern, check_pattern};
|
||||
|
||||
pub(crate) struct ExclusionsState {
|
||||
pub(crate) group: adw::PreferencesGroup,
|
||||
pub(crate) add: gtk4::Button,
|
||||
pub(crate) rows: RefCell<Vec<adw::ActionRow>>,
|
||||
/// The synced folders kept on this computer the rows were built for, as
|
||||
/// id and root.
|
||||
pub(crate) folders: RefCell<Vec<(i64, PathBuf)>>,
|
||||
/// Counts painted, so a slow read from an older paint does not land on
|
||||
/// newer rows.
|
||||
pub(crate) generation: Cell<u64>,
|
||||
}
|
||||
|
||||
pub(crate) fn build_exclusions_group() -> (adw::PreferencesGroup, gtk4::Button) {
|
||||
let add = gtk4::Button::builder()
|
||||
.child(
|
||||
&adw::ButtonContent::builder()
|
||||
.label(gettext("Add Pattern"))
|
||||
.icon_name("list-add-symbolic")
|
||||
.build(),
|
||||
)
|
||||
.tooltip_text(gettext(
|
||||
"Leave files matching a pattern out of all synced folders or one of them",
|
||||
))
|
||||
.valign(gtk4::Align::Center)
|
||||
.build();
|
||||
add.add_css_class("flat");
|
||||
let group = adw::PreferencesGroup::builder()
|
||||
.title(gettext("Excluded Files"))
|
||||
.description(gettext(
|
||||
"Files matching these patterns stay on this computer and are not synced. Excluding never deletes anything from Proton Drive.",
|
||||
))
|
||||
.header_suffix(&add)
|
||||
.visible(false)
|
||||
.build();
|
||||
(group, add)
|
||||
}
|
||||
|
||||
pub(crate) fn wire_exclusions(ui: &Rc<Ui>) {
|
||||
let ui_add = ui.clone();
|
||||
ui.locations
|
||||
.exclusions
|
||||
.add
|
||||
.connect_clicked(move |_| present_add_pattern_dialog(&ui_add, None));
|
||||
// Preferences change the patterns of all folders; show the new count.
|
||||
let ui_prefs = ui.clone();
|
||||
ui.status
|
||||
.prefs
|
||||
.connect_closed(move |_| refresh_exclusions(&ui_prefs));
|
||||
}
|
||||
|
||||
/// Rebuild the rows for the folders in `items` when the set of synced folders
|
||||
/// kept on this computer changed, or on the first paint. The tick repaints the folder list every few
|
||||
/// seconds; the rows and their counts stay as they are in between.
|
||||
pub(crate) fn paint_exclusions(ui: &Rc<Ui>, items: &[MountSpec]) {
|
||||
let folders: Vec<(i64, PathBuf)> = items
|
||||
.iter()
|
||||
.filter(|spec| spec.mode == MountMode::Mirror)
|
||||
.filter_map(|spec| match spec.kind {
|
||||
MountKind::Device { sync_folder_id } | MountKind::Attached { sync_folder_id } => {
|
||||
Some((sync_folder_id, PathBuf::from(&spec.local_path)))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let state = &ui.locations.exclusions;
|
||||
if *state.folders.borrow() == folders && !state.rows.borrow().is_empty() {
|
||||
return;
|
||||
}
|
||||
*state.folders.borrow_mut() = folders;
|
||||
refresh_exclusions(ui);
|
||||
}
|
||||
|
||||
/// Build the rows again from the folders last painted, and read every count
|
||||
/// anew: after a pattern was added or a list edited.
|
||||
pub(crate) fn refresh_exclusions(ui: &Rc<Ui>) {
|
||||
let state = &ui.locations.exclusions;
|
||||
for row in state.rows.borrow_mut().drain(..) {
|
||||
state.group.remove(&row);
|
||||
}
|
||||
let folders = state.folders.borrow().clone();
|
||||
state.group.set_visible(true);
|
||||
let generation = state.generation.get() + 1;
|
||||
state.generation.set(generation);
|
||||
|
||||
let config = ui.dirs.load_config();
|
||||
let all = adw::ActionRow::builder()
|
||||
.title(gettext("All Synced Folders"))
|
||||
.subtitle(glib::markup_escape_text(&all_folders_subtitle(&config)).as_str())
|
||||
.activatable(true)
|
||||
.build();
|
||||
all.add_prefix(>k4::Image::from_icon_name("view-list-symbolic"));
|
||||
all.add_suffix(>k4::Image::from_icon_name("go-next-symbolic"));
|
||||
let ui_all = ui.clone();
|
||||
all.connect_activated(move |_| {
|
||||
let prefs = &ui_all.status.prefs;
|
||||
prefs.set_visible_page_name("sync");
|
||||
prefs.present(ui_window(&ui_all).as_ref());
|
||||
});
|
||||
state.group.add(&all);
|
||||
let mut rows = vec![all];
|
||||
if folders.is_empty() {
|
||||
let none = adw::ActionRow::builder()
|
||||
.title(gettext("No folder is set to Synced"))
|
||||
.subtitle(gettext(
|
||||
"Patterns apply only to folders kept on this computer. Online-only folders upload every file saved in them.",
|
||||
))
|
||||
.build();
|
||||
none.add_prefix(>k4::Image::from_icon_name("info-outline-symbolic"));
|
||||
state.group.add(&none);
|
||||
rows.push(none);
|
||||
}
|
||||
|
||||
let mut counted = Vec::new();
|
||||
for (id, root) in folders {
|
||||
let name = root
|
||||
.file_name()
|
||||
.map(|name| name.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| root.display().to_string());
|
||||
let row = adw::ActionRow::builder()
|
||||
.title(glib::markup_escape_text(&name).as_str())
|
||||
.tooltip_text(root.display().to_string())
|
||||
.subtitle(glib::markup_escape_text(&tilde_path(&root.display().to_string())).as_str())
|
||||
.subtitle_lines(1)
|
||||
.activatable(true)
|
||||
.build();
|
||||
row.add_prefix(>k4::Image::from_icon_name("folder-symbolic"));
|
||||
row.add_suffix(>k4::Image::from_icon_name("go-next-symbolic"));
|
||||
let (ui_row, root_row) = (ui.clone(), root.clone());
|
||||
row.connect_activated(move |_| present_ignore_dialog(&ui_row, id, root_row.clone()));
|
||||
state.group.add(&row);
|
||||
counted.push((row.clone(), root));
|
||||
rows.push(row);
|
||||
}
|
||||
*state.rows.borrow_mut() = rows;
|
||||
|
||||
// A folder may sit on a slow or sleeping disk: count off the main thread.
|
||||
let ui = ui.clone();
|
||||
glib::spawn_future_local(async move {
|
||||
let roots: Vec<PathBuf> = counted.iter().map(|(_, root)| root.clone()).collect();
|
||||
let counts = gio::spawn_blocking(move || {
|
||||
roots
|
||||
.iter()
|
||||
.map(|root| {
|
||||
FolderRules::read(root)
|
||||
.ok()
|
||||
.map(|rules| rules.patterns().len())
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
if ui.locations.exclusions.generation.get() != generation {
|
||||
return;
|
||||
}
|
||||
for ((row, root), count) in counted.iter().zip(counts) {
|
||||
let state = match count {
|
||||
Some(0) => gettext("no own patterns"),
|
||||
// Translators: how many patterns a synced folder has of its own.
|
||||
Some(n) => ngettext_f("{n} own pattern", "{n} own patterns", n as u64, &[]),
|
||||
None => gettext("own patterns unreadable"),
|
||||
};
|
||||
// Translators: a synced folder's location and how many patterns of its own it has, such as "~/Projects · 2 own patterns".
|
||||
let subtitle = gettext_f(
|
||||
"{path} · {state}",
|
||||
&[
|
||||
("path", &tilde_path(&root.display().to_string())),
|
||||
("state", &state),
|
||||
],
|
||||
);
|
||||
row.set_subtitle(glib::markup_escape_text(&subtitle).as_str());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// How many patterns apply to every synced folder, and whether they are the
|
||||
/// built-in ones.
|
||||
fn all_folders_subtitle(config: &pdfs_core::config::AppConfig) -> String {
|
||||
let n = config.resolved_ignore_patterns().len() as u64;
|
||||
match (&config.ignore_patterns, n) {
|
||||
(_, 0) => gettext("No patterns: every file is synced"),
|
||||
(None, n) => ngettext_f("{n} built-in pattern", "{n} built-in patterns", n, &[]),
|
||||
(Some(_), n) => ngettext_f("{n} pattern", "{n} patterns", n, &[]),
|
||||
}
|
||||
}
|
||||
|
||||
/// Ask for a pattern and where it applies: every synced folder, or one of
|
||||
/// them (`folder`, preselected when given).
|
||||
pub(crate) fn present_add_pattern_dialog(ui: &Rc<Ui>, folder: Option<i64>) {
|
||||
let folders = ui.locations.exclusions.folders.borrow().clone();
|
||||
let pattern_row = adw::EntryRow::builder().title(gettext("Pattern")).build();
|
||||
pattern_row.add_css_class("monospace");
|
||||
let mut places = vec![gettext("All synced folders")];
|
||||
places.extend(
|
||||
folders
|
||||
.iter()
|
||||
.map(|(_, root)| tilde_path(&root.display().to_string())),
|
||||
);
|
||||
let places: Vec<&str> = places.iter().map(String::as_str).collect();
|
||||
let scope_row = adw::ComboRow::builder()
|
||||
.title(gettext("Apply To"))
|
||||
.model(>k4::StringList::new(&places))
|
||||
.build();
|
||||
if let Some(at) = folder.and_then(|id| folders.iter().position(|(f, _)| *f == id)) {
|
||||
scope_row.set_selected(at as u32 + 1);
|
||||
}
|
||||
let rows = adw::PreferencesGroup::new();
|
||||
rows.add(&pattern_row);
|
||||
rows.add(&scope_row);
|
||||
|
||||
let hint = gtk4::Label::builder()
|
||||
.label(gettext(
|
||||
"Use * for any characters, such as *.db, and end a pattern with / to match folders only, such as build/.",
|
||||
))
|
||||
.wrap(true)
|
||||
.xalign(0.0)
|
||||
.build();
|
||||
hint.add_css_class("dim-label");
|
||||
hint.add_css_class("caption");
|
||||
let problem = gtk4::Label::builder()
|
||||
.wrap(true)
|
||||
.xalign(0.0)
|
||||
.visible(false)
|
||||
.build();
|
||||
problem.add_css_class("error");
|
||||
|
||||
let body = gtk4::Box::new(gtk4::Orientation::Vertical, 12);
|
||||
body.set_margin_top(12);
|
||||
body.set_margin_bottom(18);
|
||||
body.set_margin_start(18);
|
||||
body.set_margin_end(18);
|
||||
body.append(&rows);
|
||||
body.append(&hint);
|
||||
body.append(&problem);
|
||||
|
||||
let cancel = gtk4::Button::with_label(&gettext("Cancel"));
|
||||
let add = gtk4::Button::with_label(&gettext("Add"));
|
||||
add.add_css_class("suggested-action");
|
||||
add.set_sensitive(false);
|
||||
let header = adw::HeaderBar::builder()
|
||||
.show_start_title_buttons(false)
|
||||
.show_end_title_buttons(false)
|
||||
.build();
|
||||
header.pack_start(&cancel);
|
||||
header.pack_end(&add);
|
||||
let view = adw::ToolbarView::new();
|
||||
view.add_top_bar(&header);
|
||||
view.set_content(Some(&body));
|
||||
let dialog = adw::Dialog::builder()
|
||||
.title(gettext("Add Pattern"))
|
||||
.content_width(460)
|
||||
.child(&view)
|
||||
.build();
|
||||
|
||||
let (add_check, problem_check) = (add.clone(), problem.clone());
|
||||
pattern_row.connect_changed(move |row| {
|
||||
let verdict = pattern_problem(&row.text());
|
||||
match &verdict {
|
||||
Some(message) if !row.text().trim().is_empty() => {
|
||||
row.add_css_class("error");
|
||||
problem_check.set_text(message);
|
||||
problem_check.set_visible(true);
|
||||
}
|
||||
_ => {
|
||||
row.remove_css_class("error");
|
||||
problem_check.set_visible(false);
|
||||
}
|
||||
}
|
||||
add_check.set_sensitive(verdict.is_none());
|
||||
});
|
||||
let d = dialog.clone();
|
||||
cancel.connect_clicked(move |_| {
|
||||
d.close();
|
||||
});
|
||||
|
||||
let submit = {
|
||||
let (ui, dialog, pattern_row, scope_row, add, problem) = (
|
||||
ui.clone(),
|
||||
dialog.clone(),
|
||||
pattern_row.clone(),
|
||||
scope_row.clone(),
|
||||
add.clone(),
|
||||
problem.clone(),
|
||||
);
|
||||
move || {
|
||||
if !add.is_sensitive() {
|
||||
return;
|
||||
}
|
||||
let pattern = pattern_row.text().trim().to_string();
|
||||
let target = match scope_row.selected() {
|
||||
0 => None,
|
||||
at => folders.get(at as usize - 1).cloned(),
|
||||
};
|
||||
// One click, one save: the button comes back if the save fails.
|
||||
add.set_sensitive(false);
|
||||
add_pattern(&ui, &dialog, &add, &problem, pattern, target);
|
||||
}
|
||||
};
|
||||
let submit_enter = submit.clone();
|
||||
pattern_row.connect_entry_activated(move |_| submit_enter());
|
||||
add.connect_clicked(move |_| submit());
|
||||
|
||||
dialog.present(ui_window(ui).as_ref());
|
||||
pattern_row.grab_focus();
|
||||
}
|
||||
|
||||
/// What is wrong with `text` as a pattern to add, or `None` when it is one.
|
||||
fn pattern_problem(text: &str) -> Option<String> {
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
return Some(String::new());
|
||||
}
|
||||
if text.starts_with('#') {
|
||||
return Some(gettext(
|
||||
"A line starting with # is a comment, not a pattern.",
|
||||
));
|
||||
}
|
||||
check_pattern(text).err().map(|e| {
|
||||
tracing::debug!(pattern = %text, error = %e, "not a valid ignore pattern");
|
||||
// Translators: {pattern} is what the user typed as a pattern.
|
||||
gettext_f("“{pattern}” isn't a valid pattern.", &[("pattern", text)])
|
||||
})
|
||||
}
|
||||
|
||||
/// Save `pattern` for every synced folder (`target` is `None`) or for the
|
||||
/// folder `target`, then close `dialog`, say so and sync. A failure shows in
|
||||
/// `problem`, in the dialog, which stays open.
|
||||
fn add_pattern(
|
||||
ui: &Rc<Ui>,
|
||||
dialog: &adw::Dialog,
|
||||
add: >k4::Button,
|
||||
problem: >k4::Label,
|
||||
pattern: String,
|
||||
target: Option<(i64, PathBuf)>,
|
||||
) {
|
||||
let (ui, dialog, add, problem) = (ui.clone(), dialog.clone(), add.clone(), problem.clone());
|
||||
glib::spawn_future_local(async move {
|
||||
let (id, place) = match &target {
|
||||
None => (None, gettext("all synced folders")),
|
||||
Some((id, root)) => (Some(*id), tilde_path(&root.display().to_string())),
|
||||
};
|
||||
let added: Result<bool, String> = match target {
|
||||
None => {
|
||||
let mut added = false;
|
||||
ui.dirs
|
||||
.change_ignore_patterns(|list| {
|
||||
if !list.contains(&pattern) {
|
||||
list.push(pattern.clone());
|
||||
added = true;
|
||||
}
|
||||
})
|
||||
.map(|_| added)
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
Some((_, root)) => {
|
||||
let p = pattern.clone();
|
||||
gio::spawn_blocking(move || add_folder_pattern(&root, &p))
|
||||
.await
|
||||
.unwrap_or_else(|_| Err(std::io::Error::other("the save did not finish")))
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
};
|
||||
match added {
|
||||
Ok(added) => {
|
||||
dialog.close();
|
||||
let message = if added {
|
||||
// Translators: {pattern} is an ignore pattern, {place} "all synced folders" or a folder path.
|
||||
gettext_f(
|
||||
"“{pattern}” is now excluded in {place}",
|
||||
&[("pattern", &pattern), ("place", &place)],
|
||||
)
|
||||
} else {
|
||||
gettext_f(
|
||||
"“{pattern}” was already excluded in {place}",
|
||||
&[("pattern", &pattern), ("place", &place)],
|
||||
)
|
||||
};
|
||||
toast(&ui, &message);
|
||||
refresh_exclusions(&ui);
|
||||
if added {
|
||||
// Best effort: the next pass picks the change up anyway.
|
||||
let _ = spawn_request(ui.dirs.control_socket(), Request::SyncNow { id });
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
add.set_sensitive(true);
|
||||
problem.set_text(&gettext_f(
|
||||
"{what}: {detail}",
|
||||
&[
|
||||
("what", &gettext("Couldn't save the patterns")),
|
||||
("detail", &e),
|
||||
],
|
||||
));
|
||||
problem.set_visible(true);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_real_patterns_can_be_added() {
|
||||
assert!(pattern_problem("*.db").is_none());
|
||||
assert!(pattern_problem(" build/ ").is_none());
|
||||
assert!(pattern_problem("").is_some());
|
||||
assert!(pattern_problem(" ").is_some());
|
||||
assert!(pattern_problem("# note").is_some());
|
||||
assert!(pattern_problem("*.{jpg,png").is_some());
|
||||
}
|
||||
}
|
||||
@@ -82,10 +82,10 @@ pub(crate) fn start_update_checks(ui: &Rc<Ui>) {
|
||||
match fetch_latest().await {
|
||||
Ok(latest) => {
|
||||
checked = Some(unix_now());
|
||||
let mut config = ui.dirs.load_config();
|
||||
config.update_last_checked = checked;
|
||||
config.update_latest = latest;
|
||||
if let Err(e) = ui.dirs.save_config(&config) {
|
||||
if let Err(e) = ui.dirs.update_config(|config| {
|
||||
config.update_last_checked = checked;
|
||||
config.update_latest = latest;
|
||||
}) {
|
||||
tracing::warn!("update check: cannot save the result: {e}");
|
||||
}
|
||||
show_latest(&ui);
|
||||
|
||||
@@ -0,0 +1,343 @@
|
||||
//! The Excluded Files dialog of one synced folder: its own `.pdfsignore`,
|
||||
//! edited as text, with a check of what the rules do to a path.
|
||||
//!
|
||||
//! The file sits in the synced folder and syncs like any other file, so it can
|
||||
//! change on another computer while it is open here. Saving checks for that
|
||||
//! and asks, rather than writing over the other edit.
|
||||
|
||||
use crate::*;
|
||||
use pdfs_core::syncignore::{FolderRules, IgnoreRules, RuleSource, Verdict, WriteRulesError};
|
||||
|
||||
/// Open the dialog for the synced folder `id` at `root`.
|
||||
pub(crate) fn present_ignore_dialog(ui: &Rc<Ui>, id: i64, root: PathBuf) {
|
||||
let root_display = tilde_path(&root.display().to_string());
|
||||
let intro = gtk4::Label::builder()
|
||||
// Translators: {folder} is a local folder path such as ~/Projects.
|
||||
.label(gettext_f(
|
||||
"Patterns for {folder} only, one per line, on top of the ones for all synced folders. Lines starting with # are comments.",
|
||||
&[("folder", &root_display)],
|
||||
))
|
||||
.wrap(true)
|
||||
.xalign(0.0)
|
||||
.build();
|
||||
let text = gtk4::TextView::builder()
|
||||
.monospace(true)
|
||||
.wrap_mode(gtk4::WrapMode::WordChar)
|
||||
.top_margin(8)
|
||||
.bottom_margin(8)
|
||||
.left_margin(8)
|
||||
.right_margin(8)
|
||||
.sensitive(false)
|
||||
.build();
|
||||
let scroller = gtk4::ScrolledWindow::builder()
|
||||
.child(&text)
|
||||
.min_content_height(180)
|
||||
.vexpand(true)
|
||||
.build();
|
||||
scroller.add_css_class("card");
|
||||
let problems = gtk4::Label::builder()
|
||||
.wrap(true)
|
||||
.xalign(0.0)
|
||||
.visible(false)
|
||||
.build();
|
||||
problems.add_css_class("error");
|
||||
|
||||
let check_row = adw::EntryRow::builder()
|
||||
.title(gettext("Check a path in the folder"))
|
||||
.build();
|
||||
let verdict = gtk4::Label::builder()
|
||||
.wrap(true)
|
||||
.xalign(0.0)
|
||||
.margin_top(6)
|
||||
.build();
|
||||
verdict.add_css_class("dim-label");
|
||||
let check_group = adw::PreferencesGroup::new();
|
||||
check_group.add(&check_row);
|
||||
|
||||
let all_folders = gtk4::Button::builder()
|
||||
.label(gettext("Patterns for All Folders…"))
|
||||
.halign(gtk4::Align::Start)
|
||||
.build();
|
||||
all_folders.add_css_class("flat");
|
||||
|
||||
let body = gtk4::Box::new(gtk4::Orientation::Vertical, 12);
|
||||
body.set_margin_top(12);
|
||||
body.set_margin_bottom(18);
|
||||
body.set_margin_start(18);
|
||||
body.set_margin_end(18);
|
||||
body.append(&intro);
|
||||
body.append(&scroller);
|
||||
body.append(&problems);
|
||||
body.append(&check_group);
|
||||
body.append(&verdict);
|
||||
body.append(&all_folders);
|
||||
|
||||
let cancel = gtk4::Button::with_label(&gettext("Cancel"));
|
||||
let save = gtk4::Button::with_label(&gettext("Save"));
|
||||
save.add_css_class("suggested-action");
|
||||
save.set_sensitive(false);
|
||||
let header = adw::HeaderBar::builder()
|
||||
.show_start_title_buttons(false)
|
||||
.show_end_title_buttons(false)
|
||||
.build();
|
||||
header.pack_start(&cancel);
|
||||
header.pack_end(&save);
|
||||
let toasts = adw::ToastOverlay::new();
|
||||
toasts.set_child(Some(&body));
|
||||
let view = adw::ToolbarView::new();
|
||||
view.add_top_bar(&header);
|
||||
view.set_content(Some(&toasts));
|
||||
let dialog = adw::Dialog::builder()
|
||||
.title(gettext("Excluded Files"))
|
||||
.content_width(560)
|
||||
.content_height(560)
|
||||
.child(&view)
|
||||
.build();
|
||||
|
||||
// What was read, so the save can tell whether the file changed since.
|
||||
let loaded: Rc<RefCell<Option<FolderRules>>> = Rc::default();
|
||||
let globals = Rc::new(ui.dirs.load_config().resolved_ignore_patterns());
|
||||
|
||||
let show_verdict = {
|
||||
let (text, check_row, verdict, root, globals) = (
|
||||
text.clone(),
|
||||
check_row.clone(),
|
||||
verdict.clone(),
|
||||
root.clone(),
|
||||
globals.clone(),
|
||||
);
|
||||
move || {
|
||||
let typed = check_row.text();
|
||||
let typed = typed.trim();
|
||||
if typed.is_empty() {
|
||||
verdict.set_text("");
|
||||
return;
|
||||
}
|
||||
let path = Path::new(typed);
|
||||
let rel = path.strip_prefix(&root).unwrap_or(path);
|
||||
let rel = rel.to_string_lossy();
|
||||
let rel = rel.trim_start_matches('/');
|
||||
let is_dir = typed.ends_with('/') || root.join(rel).is_dir();
|
||||
let rules = IgnoreRules::with_folder_text(&root, &globals, &buffer_text(&text));
|
||||
verdict.set_text(&verdict_text(&rules.explain(rel, is_dir)));
|
||||
}
|
||||
};
|
||||
let on_text = {
|
||||
let (problems, save, show_verdict) = (problems.clone(), save.clone(), show_verdict.clone());
|
||||
move |text: &str| {
|
||||
let bad = pdfs_core::syncignore::check_rules(text);
|
||||
problems.set_visible(!bad.is_empty());
|
||||
if let Some((line, _)) = bad.first() {
|
||||
problems.set_text(&ngettext_f(
|
||||
"Line {line} isn't a valid pattern.",
|
||||
"Line {line} and {more} more aren't valid patterns.",
|
||||
bad.len() as u64,
|
||||
&[
|
||||
("line", &line.to_string()),
|
||||
("more", &(bad.len() - 1).to_string()),
|
||||
],
|
||||
));
|
||||
}
|
||||
save.set_sensitive(bad.is_empty());
|
||||
show_verdict();
|
||||
}
|
||||
};
|
||||
let on_text_changed = on_text.clone();
|
||||
text.buffer()
|
||||
.connect_changed(move |buffer| on_text_changed(&buffer_text_of(buffer)));
|
||||
check_row.connect_changed(move |_| show_verdict());
|
||||
|
||||
let d = dialog.clone();
|
||||
cancel.connect_clicked(move |_| {
|
||||
d.close();
|
||||
});
|
||||
let (ui_all, d) = (ui.clone(), dialog.clone());
|
||||
all_folders.connect_clicked(move |_| {
|
||||
d.close();
|
||||
let prefs = &ui_all.status.prefs;
|
||||
prefs.set_visible_page_name("sync");
|
||||
prefs.present(ui_window(&ui_all).as_ref());
|
||||
});
|
||||
|
||||
// Read off the main thread: the folder may be on a slow disk.
|
||||
let reader = {
|
||||
let (text, loaded, root, toasts) =
|
||||
(text.clone(), loaded.clone(), root.clone(), toasts.clone());
|
||||
move || {
|
||||
let (text, loaded, root, toasts) =
|
||||
(text.clone(), loaded.clone(), root.clone(), toasts.clone());
|
||||
glib::spawn_future_local(async move {
|
||||
let read = gio::spawn_blocking(move || FolderRules::read(&root))
|
||||
.await
|
||||
.unwrap_or_else(|_| Err(std::io::Error::other("the read did not finish")));
|
||||
match read {
|
||||
Ok(rules) => {
|
||||
text.buffer().set_text(rules.text.as_deref().unwrap_or(""));
|
||||
text.set_sensitive(true);
|
||||
*loaded.borrow_mut() = Some(rules);
|
||||
}
|
||||
Err(e) => dialog_toast(
|
||||
&toasts,
|
||||
&gettext_f(
|
||||
"{what}: {detail}",
|
||||
&[
|
||||
("what", &gettext("Couldn't read the patterns")),
|
||||
("detail", &e.to_string()),
|
||||
],
|
||||
),
|
||||
),
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
reader();
|
||||
|
||||
let (ui_save, d) = (ui.clone(), dialog.clone());
|
||||
save.connect_clicked(move |_| {
|
||||
let Some(rules) = loaded.borrow().clone() else {
|
||||
return;
|
||||
};
|
||||
write_rules(
|
||||
&ui_save,
|
||||
&d,
|
||||
&toasts,
|
||||
id,
|
||||
rules,
|
||||
buffer_text(&text),
|
||||
reader.clone(),
|
||||
);
|
||||
});
|
||||
|
||||
dialog.present(ui_window(ui).as_ref());
|
||||
}
|
||||
|
||||
/// Save `body` over `rules`, then close and sync the folder. When the file
|
||||
/// changed since it was read, ask whether to load the other version or to
|
||||
/// replace it; `reload` reads the file into the dialog again.
|
||||
fn write_rules(
|
||||
ui: &Rc<Ui>,
|
||||
dialog: &adw::Dialog,
|
||||
toasts: &adw::ToastOverlay,
|
||||
id: i64,
|
||||
rules: FolderRules,
|
||||
body: String,
|
||||
reload: impl Fn() + Clone + 'static,
|
||||
) {
|
||||
let (ui, dialog, toasts) = (ui.clone(), dialog.clone(), toasts.clone());
|
||||
glib::spawn_future_local(async move {
|
||||
let to_write = rules.clone();
|
||||
let text = body.clone();
|
||||
let written = gio::spawn_blocking(move || to_write.write(&text))
|
||||
.await
|
||||
.unwrap_or_else(|_| {
|
||||
Err(WriteRulesError::Io(std::io::Error::other(
|
||||
"the write did not finish",
|
||||
)))
|
||||
});
|
||||
match written {
|
||||
Ok(()) => {
|
||||
dialog.close();
|
||||
toast(&ui, &gettext("Excluded files saved"));
|
||||
refresh_exclusions(&ui);
|
||||
let _ = spawn_request(ui.dirs.control_socket(), Request::SyncNow { id: Some(id) });
|
||||
}
|
||||
Err(WriteRulesError::Changed) => {
|
||||
let ask = adw::AlertDialog::builder()
|
||||
.heading(gettext("Patterns Changed Elsewhere"))
|
||||
.body(gettext(
|
||||
"The patterns of this folder changed while you edited them, for example on another computer. Load the other version, or replace it with yours?",
|
||||
))
|
||||
.build();
|
||||
ask.add_response("cancel", &gettext("Cancel"));
|
||||
ask.add_response("reload", &gettext("Load Other Version"));
|
||||
ask.add_response("replace", &gettext("Replace"));
|
||||
ask.set_response_appearance("replace", adw::ResponseAppearance::Destructive);
|
||||
ask.set_default_response(Some("cancel"));
|
||||
ask.set_close_response("cancel");
|
||||
let (ui, d, t) = (ui.clone(), dialog.clone(), toasts.clone());
|
||||
ask.connect_response(None, move |_, response| match response {
|
||||
"reload" => reload(),
|
||||
"replace" => {
|
||||
// Read the other version only as the base to check
|
||||
// against, then write over it.
|
||||
let (ui, d, t, body, reload) = (
|
||||
ui.clone(),
|
||||
d.clone(),
|
||||
t.clone(),
|
||||
body.clone(),
|
||||
reload.clone(),
|
||||
);
|
||||
let root = rules.path.parent().map(Path::to_path_buf);
|
||||
glib::spawn_future_local(async move {
|
||||
let Some(root) = root else { return };
|
||||
let read = gio::spawn_blocking(move || FolderRules::read(&root))
|
||||
.await
|
||||
.ok()
|
||||
.and_then(Result::ok);
|
||||
if let Some(current) = read {
|
||||
write_rules(&ui, &d, &t, id, current, body, reload);
|
||||
}
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
ask.present(Some(&dialog));
|
||||
}
|
||||
Err(WriteRulesError::Io(e)) => dialog_toast(
|
||||
&toasts,
|
||||
&gettext_f(
|
||||
"{what}: {detail}",
|
||||
&[
|
||||
("what", &gettext("Couldn't save the patterns")),
|
||||
("detail", &e.to_string()),
|
||||
],
|
||||
),
|
||||
),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Say what the rules do to the path being checked.
|
||||
fn verdict_text(verdict: &Verdict) -> String {
|
||||
match verdict {
|
||||
Verdict::Synced => gettext("Synced: no pattern matches it."),
|
||||
// Translators: {pattern} is an ignore pattern such as *.log.
|
||||
Verdict::Excluded {
|
||||
pattern,
|
||||
source: RuleSource::ThisFolder,
|
||||
} => gettext_f(
|
||||
"Not synced: excluded by “{pattern}” above.",
|
||||
&[("pattern", pattern)],
|
||||
),
|
||||
Verdict::Excluded {
|
||||
pattern,
|
||||
source: RuleSource::AllFolders,
|
||||
} => gettext_f(
|
||||
"Not synced: excluded by “{pattern}” in the patterns for all folders.",
|
||||
&[("pattern", pattern)],
|
||||
),
|
||||
Verdict::Included { pattern, .. } => gettext_f(
|
||||
"Synced: “{pattern}” includes it again.",
|
||||
&[("pattern", pattern)],
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn buffer_text(view: >k4::TextView) -> String {
|
||||
buffer_text_of(&view.buffer())
|
||||
}
|
||||
|
||||
fn buffer_text_of(buffer: >k4::TextBuffer) -> String {
|
||||
let (start, end) = buffer.bounds();
|
||||
buffer.text(&start, &end, false).to_string()
|
||||
}
|
||||
|
||||
fn dialog_toast(toasts: &adw::ToastOverlay, message: &str) {
|
||||
toasts.add_toast(
|
||||
adw::Toast::builder()
|
||||
.title(message)
|
||||
.use_markup(false)
|
||||
.timeout(6)
|
||||
.build(),
|
||||
);
|
||||
}
|
||||
@@ -2,6 +2,7 @@ pub(crate) mod compat;
|
||||
pub(crate) mod crumb;
|
||||
pub(crate) mod details;
|
||||
pub(crate) mod file_list;
|
||||
pub(crate) mod ignore_dialog;
|
||||
pub(crate) mod menu;
|
||||
pub(crate) mod photo_drag;
|
||||
pub(crate) mod player;
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
|
||||
use gettextrs::LocaleCategory;
|
||||
use pdfs_core::config::AppDirs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The gettext text domain, matching `po/pdfs.pot` and the installed `.mo` name.
|
||||
pub(crate) const DOMAIN: &str = "pdfs";
|
||||
@@ -53,14 +54,11 @@ pub(crate) fn init() {
|
||||
if let Some(code) = language {
|
||||
apply_language(&code);
|
||||
}
|
||||
let dir = std::env::var(LOCALEDIR_ENV)
|
||||
.ok()
|
||||
.filter(|dir| !dir.is_empty())
|
||||
.unwrap_or_else(|| {
|
||||
option_env!("PDFS_LOCALEDIR")
|
||||
.unwrap_or(DEFAULT_LOCALEDIR)
|
||||
.to_string()
|
||||
});
|
||||
let dir = locale_dir(
|
||||
std::env::var(LOCALEDIR_ENV).ok(),
|
||||
option_env!("PDFS_LOCALEDIR"),
|
||||
std::env::current_exe().ok(),
|
||||
);
|
||||
if let Err(e) = gettextrs::bindtextdomain(DOMAIN, dir) {
|
||||
tracing::warn!("bindtextdomain failed: {e}");
|
||||
}
|
||||
@@ -73,6 +71,33 @@ pub(crate) fn init() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the catalogs are: `$PDFS_LOCALEDIR`, then the directory the build
|
||||
/// named, then `share/locale` beside the `bin` directory the program runs
|
||||
/// from when that holds a catalog of ours, then [`DEFAULT_LOCALEDIR`].
|
||||
///
|
||||
/// The third is for an install outside `/usr`, such as the release tarball's
|
||||
/// `install.sh` into `~/.local`: its programs find their translations without
|
||||
/// a wrapper setting the variable.
|
||||
fn locale_dir(env: Option<String>, build: Option<&str>, exe: Option<PathBuf>) -> PathBuf {
|
||||
if let Some(dir) = env.filter(|dir| !dir.is_empty()) {
|
||||
return PathBuf::from(dir);
|
||||
}
|
||||
if let Some(dir) = build {
|
||||
return PathBuf::from(dir);
|
||||
}
|
||||
let beside = exe
|
||||
.as_deref()
|
||||
.and_then(Path::parent)
|
||||
.and_then(Path::parent)
|
||||
.map(|prefix| prefix.join("share/locale"))
|
||||
.filter(|dir| {
|
||||
LANGUAGES
|
||||
.iter()
|
||||
.any(|(code, _)| dir.join(code).join("LC_MESSAGES/pdfs.mo").is_file())
|
||||
});
|
||||
beside.unwrap_or_else(|| PathBuf::from(DEFAULT_LOCALEDIR))
|
||||
}
|
||||
|
||||
/// The iso-codes text domain that translates ISO 3166-1 country names.
|
||||
const ISO_3166_DOMAIN: &str = "iso_3166-1";
|
||||
|
||||
@@ -234,6 +259,32 @@ fn fill(template: &str, args: &[(&str, &str)]) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_catalogs_are_found_beside_an_install_outside_usr() {
|
||||
let prefix = std::env::temp_dir().join(format!("pdfs-locale-{}", std::process::id()));
|
||||
let mo = prefix.join("share/locale/de/LC_MESSAGES/pdfs.mo");
|
||||
std::fs::create_dir_all(mo.parent().unwrap()).unwrap();
|
||||
std::fs::write(&mo, b"").unwrap();
|
||||
let exe = Some(prefix.join("bin/pdfs-app"));
|
||||
|
||||
assert_eq!(
|
||||
locale_dir(None, None, exe.clone()),
|
||||
prefix.join("share/locale")
|
||||
);
|
||||
// The variable and the build's own choice still win.
|
||||
assert_eq!(
|
||||
locale_dir(Some("/x".into()), Some("/y"), exe.clone()),
|
||||
PathBuf::from("/x")
|
||||
);
|
||||
assert_eq!(locale_dir(None, Some("/y"), exe), PathBuf::from("/y"));
|
||||
// A prefix without our catalogs falls back to the system's.
|
||||
assert_eq!(
|
||||
locale_dir(None, None, Some(PathBuf::from("/nonexistent/bin/pdfs-app"))),
|
||||
PathBuf::from(DEFAULT_LOCALEDIR)
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&prefix);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_replaces_named_placeholders_in_any_order() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -398,12 +398,10 @@ fn open_manager(args: &[&str]) {
|
||||
/// Remember that the user hid the icon, so the next login's autostart and the
|
||||
/// app both leave it away, then exit.
|
||||
fn hide_tray() {
|
||||
if let Ok(dirs) = AppDirs::new() {
|
||||
let mut config = dirs.load_config();
|
||||
config.tray_hidden = true;
|
||||
if let Err(e) = dirs.save_config(&config) {
|
||||
tracing::warn!("hide tray icon: {e}");
|
||||
}
|
||||
if let Ok(dirs) = AppDirs::new()
|
||||
&& let Err(e) = dirs.update_config(|config| config.tray_hidden = true)
|
||||
{
|
||||
tracing::warn!("hide tray icon: {e}");
|
||||
}
|
||||
std::process::exit(0);
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ const STOCK: &[&str] = &[
|
||||
// GTK's built-in icons
|
||||
"info-outline-symbolic",
|
||||
// Adwaita
|
||||
"application-x-executable-symbolic",
|
||||
"audio-x-generic-symbolic",
|
||||
"checkbox-checked-symbolic",
|
||||
"checkbox-symbolic",
|
||||
|
||||
@@ -109,6 +109,7 @@ a live account since.
|
||||
|
||||
| Entry | Title |
|
||||
|---|---|
|
||||
| [B291](#b291--on-fedora-45s-oo7-every-saved-sign-in-is-lost-at-the-next-reboot) | On Fedora 45's oo7, every saved sign-in is lost at the next reboot |
|
||||
| [B289](#b289--the-takeout-import-mixes-in-other-services-and-drops-location-and-live-photos) | The Takeout import mixes in other services and drops location and live photos |
|
||||
| [B288](#b288--an-interrupted-takeout-import-reads-as-finished-and-one-error-ends-it) | An interrupted Takeout import reads as finished, and one error ends it |
|
||||
| [B287](#b287--a-photo-draft-left-by-an-interrupted-upload-blocks-that-name) | A photo draft left by an interrupted upload blocks that name |
|
||||
@@ -305,6 +306,7 @@ a live account since.
|
||||
|
||||
| Entry | Title |
|
||||
|---|---|
|
||||
| [B292](#b292--two-programs-changing-settings-at-once-lose-one-of-the-changes) | Two programs changing settings at once lose one of the changes |
|
||||
| [B290](#b290--reopening-the-database-right-after-closing-it-can-be-refused-as-another-daemon) | Reopening the database right after closing it can be refused as another daemon |
|
||||
| [B276](#b276--a-stop-can-end-with-a-panic-in-a-thread-the-stop-never-waited-for) | A stop can end with a panic in a thread the stop never waited for |
|
||||
| [B258](#b258--journalctl--p-warning-shows-nothing-whatever-the-daemon-logged) | `journalctl -p warning` shows nothing, whatever the daemon logged |
|
||||
@@ -393,6 +395,73 @@ a live account since.
|
||||
|
||||
Newest first.
|
||||
|
||||
### B292 — Two programs changing settings at once lose one of the changes
|
||||
|
||||
**Status:** Fixed
|
||||
|
||||
**Found:** 2026-11-15, reading every writer of `config.json` while adding settings to Preferences.
|
||||
|
||||
**Where:** `crates/pdfs-core/src/config.rs`, `AppDirs::save_config` and its callers in the app,
|
||||
the tray and the daemon
|
||||
|
||||
**Repro:** Change the cache size in Preferences (the daemon writes `cache_budget`) while the app
|
||||
saves the window size or the tray hides itself. Both read the file before either wrote it, and
|
||||
the one that wrote last puts the other setting back. Not seen in the field; the window is a few
|
||||
milliseconds, but more settings in the app make it more likely.
|
||||
|
||||
**Cause:** Every writer loaded the file, changed one field and wrote the whole file back, with
|
||||
nothing ordering them. The atomic rename kept the file whole, not the changes.
|
||||
|
||||
**Fix:** `AppDirs::update_config` reads, changes and writes under an `flock` on
|
||||
`config.json.lock`, and every writer goes through it. It refuses an unreadable file before
|
||||
applying the change (B223). A lock held longer than 5 seconds is reported as an error instead of
|
||||
waited on.
|
||||
|
||||
**Verified:** `cargo test -p pdfs-core config::tests` on 2026-11-15,
|
||||
`concurrent_changes_to_different_settings_are_all_kept` and
|
||||
`a_change_is_never_applied_over_an_unreadable_config`.
|
||||
|
||||
---
|
||||
|
||||
### B291 — On Fedora 45's oo7, every saved sign-in is lost at the next reboot
|
||||
|
||||
**Status:** Fixed, not verified live
|
||||
**Found:** 2026-11-15, from the reporter's package list in
|
||||
[issue #78](https://github.com/narrrl/proton-drive-linux/issues/78): `oo7-daemon-0.7.0~beta^1.e91b98a`,
|
||||
the build Fedora 45 and 46 ship as stable, from before oo7's
|
||||
[7fb11dd](https://github.com/linux-credentials/oo7/commit/7fb11dd111c4be8fec01996e3caa31c44fa962b3)
|
||||
("server: Write item changes to the keyring file"). See
|
||||
[the investigation](ISSUE-78.md#setsecret-is-kept-only-in-memory-in-fedoras-oo7).
|
||||
**Where:** `crates/pdfs-core/src/auth.rs`, `write_stored`; `crates/pdfs-core/src/secretservice.rs`
|
||||
|
||||
**Repro:** With oo7-daemon at e91b98a, save the session blob, save it again with a new refresh
|
||||
token, and restart oo7-daemon. The read after the restart returns the first blob. The keyring
|
||||
store writes an existing item with `SetSecret`, and that oo7 build applies `SetSecret` only to the
|
||||
item in memory; the keyring file keeps what `CreateItem` wrote. Within a boot every read returns
|
||||
the new tokens, so nothing looks wrong. After a reboot the daemon resumes with the refresh token
|
||||
of the last `pdfs login`, which Proton spent long ago: `InvalidRefreshToken`, and the user has to
|
||||
sign in again. Typing the password at login, or the fixes for B284 and B285, change nothing.
|
||||
|
||||
**Cause:** A bug in that oo7 build, fixed in oo7 0.7.0 but not packaged by Fedora. Every token
|
||||
refresh pdfs saved went through the one call it does not persist.
|
||||
|
||||
**Fix:** An existing entry is saved by `CreateItem` with `replace`, which that build writes to the
|
||||
file: a new item in the old one's collection, with its label and all its attributes, so the
|
||||
provider replaces the old one. A duplicate that a provider leaves behind is removed; if it cannot
|
||||
be, the new item is taken out again and the save falls back to the usual `SetSecret`. The first
|
||||
save, a locked item, two matching items, or any failure before the new item exists also fall back
|
||||
to it. The connection used for this never shows a prompt. The daemon log now has a short
|
||||
fingerprint of the refresh token at each start and each save, so a log across a reboot shows
|
||||
whether the keyring returned the last token saved.
|
||||
|
||||
**Verified:** 2026-11-15, `real_secret_service_keeps_the_last_save_across_a_provider_restart`
|
||||
(ignored; needs a throwaway Secret Service) against oo7-daemon built at e91b98a: with the
|
||||
in-place write it reads `r1` after the restart, with this change `r3` and one item. The same test
|
||||
and `real_secret_service_survives_a_provider_restart` pass against gnome-keyring. Not yet run on
|
||||
a Fedora 45 desktop with a real account.
|
||||
|
||||
---
|
||||
|
||||
### B290 — Reopening the database right after closing it can be refused as another daemon
|
||||
|
||||
**Status:** Fixed, 2026-11-15
|
||||
@@ -417,6 +486,8 @@ second later.
|
||||
**Verified:** `cargo test -p pdfs-core` on 2026-11-15, including
|
||||
`a_second_writer_is_refused_while_the_first_holds_the_database`.
|
||||
|
||||
---
|
||||
|
||||
### B289 — The Takeout import mixes in other services and drops location and live photos
|
||||
|
||||
**Status:** Fixed, not verified live
|
||||
|
||||
+43
-7
@@ -18,6 +18,39 @@ Existing folders stay device backups. Older builds cannot open the upgraded data
|
||||
|
||||
### Added
|
||||
|
||||
- **Excluded files, opening files and the search launcher in Preferences** (#99). Settings that
|
||||
could only be changed in `config.json` now have a place in the app:
|
||||
- **Sync → Excluded Files**: the patterns every synced folder leaves out. Add your own, such as
|
||||
`*.db` or `build/`, and turn each built-in pattern on or off. A change applies at once.
|
||||
- **Sync → Conflict Copies**: whether identical conflict copies are only reported, moved to the
|
||||
trash, or not looked for.
|
||||
- **Apps → Open Files With**: which program opens which kind of file, in order, optionally in a
|
||||
terminal, for example `nvim` for text files. A change applies to the next file opened.
|
||||
- **Apps → Search Launcher**: whether `pdfs-prompt` opens its own window, your dmenu-style
|
||||
launcher (rofi, wofi, fuzzel, bemenu) or fzf in a terminal.
|
||||
|
||||
The Sync page's Folders view lists **Excluded Files** under the folders: how many patterns
|
||||
apply to all of them and to each one, and **Add Pattern** to add one for all synced folders or
|
||||
for a single folder. A folder's own rules (its `.pdfsignore`) open in an editor, also from the
|
||||
folder's menu. It checks every line as you type, tells you whether a path is synced and which
|
||||
pattern decides, and asks before replacing rules that changed on another computer meanwhile.
|
||||
`pdfs sync ignore list|add|remove|reset|check` does the same from a terminal, and `--folder`
|
||||
picks a single folder.
|
||||
`pdfs-app --page preferences-sync` (or `-apps`, `-storage`, plain `preferences`) opens
|
||||
Preferences at that page.
|
||||
- **More clutter left out of synced folders by default**: `desktop.ini`, `.directory`, trash
|
||||
folders, `.fuse_hidden*` and `.nfs*` leftovers, partial downloads (`*.part`, `*.crdownload`),
|
||||
Kate swap files and office lock files. This only changes folders where you never set your own
|
||||
list. Leaving a file out never deletes its copy on Proton Drive.
|
||||
- **An install without a package, for immutable distributions** (#99). The release `.tar.gz` now
|
||||
carries everything around the programs and an `install.sh` that installs them into your home
|
||||
folder, no root needed: `~/.local` for the programs, menu entry, icon, translations and shell
|
||||
completion, `~/.config` for the service and the tray's login entry. It checks the libraries
|
||||
first and names the packages to install, refuses to install next to a package of the client,
|
||||
updates in place (restarting a running service) and removes itself with `--uninstall`, leaving
|
||||
settings and data alone. The app finds its translations and the tray beside its own program, so
|
||||
nothing has to be on the `PATH`. [Installation](INSTALL.md) also shows how to layer the COPR
|
||||
package on Fedora Atomic (Silverblue, Kinoite, Bazzite, Bluefin).
|
||||
- **Sync a local folder with a folder you already have in My files** (#67, #77).
|
||||
`pdfs sync attach ~/Work --to Work` keeps `~/Work` an ordinary local folder and syncs it both
|
||||
ways with My files/Work. The first sync uploads files that are only on this computer, downloads
|
||||
@@ -146,6 +179,9 @@ Existing folders stay device backups. Older builds cannot open the upgraded data
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Two programs changing settings at once no longer lose one of the changes** (B292). The app,
|
||||
the tray and the service now change `config.json` under a lock, so for example a new cache
|
||||
size saved by the service and the window size saved by the app both stay.
|
||||
- **Resuming a Google Photos import no longer fails at once** (#94, B286, B287). A photo upload
|
||||
that was cut short left a draft behind, and every later run stopped with
|
||||
`check for existing photos: serialization error: invalid type: null`. Such drafts are now
|
||||
@@ -162,13 +198,13 @@ Existing folders stay device backups. Older builds cannot open the upgraded data
|
||||
screen there, and with nothing to scroll no more were loaded. More now load whenever the photos
|
||||
don't fill the window, also after a zoom or a resize.
|
||||
|
||||
- **Signed out after a cold boot on Fedora 45** (issue #78, B284, B285). Fedora 45 replaced the
|
||||
GNOME keyring with oo7, and two things there could keep a refreshed sign-in from being saved:
|
||||
oo7 reports the entries of a locked keyring as missing, which the client took for a sign-out,
|
||||
and a restarted oo7 no longer knew the client's connection, which then failed every save until
|
||||
the service restarted. The refreshed sign-in lived only in memory, and the next boot found the
|
||||
spent one. The client now keeps such a sign-in and saves it once the keyring can be read, and
|
||||
reconnects to a keyring service that restarted.
|
||||
- **Signed out after every reboot on Fedora 45** (issue #78, B284, B285, B291). Fedora 45 replaced
|
||||
the GNOME keyring with oo7, and the oo7 build it ships keeps a changed keyring entry only in
|
||||
memory: every refreshed sign-in the client saved was gone after a reboot, and the next start
|
||||
found one Proton had already retired. The client now saves the sign-in as a new entry that
|
||||
replaces the old one, which that oo7 does write to disk. It also no longer drops a refreshed
|
||||
sign-in when oo7 reports the entries of a locked keyring as missing, and it reconnects to a
|
||||
keyring service that restarted.
|
||||
|
||||
- **Thumbnails appear in the folder you are looking at as soon as they are made.** During
|
||||
**Build thumbnails**, the folder on screen kept its file icons until you left it and opened it
|
||||
|
||||
@@ -119,6 +119,10 @@ commands are for scripts and for cases where the mount is not available.
|
||||
| `pdfs sync reset ID` | Forget what a synced folder synced before and compare it with Proton Drive again. A file on one side only is copied to the other, and a file that differs keeps both versions. Nothing is deleted. |
|
||||
| `pdfs sync pause [--for 1h] [--folder ID]` | Pause uploads and synced folders. Reading files keeps working. `--for` ends the pause by itself (`30m`, `1h`, `2d`). |
|
||||
| `pdfs sync resume [--folder ID]` | Resume after a pause. |
|
||||
| `pdfs sync ignore list [--folder PATH]` | Print the patterns every synced folder leaves out; built-in ones are marked. With `--folder`, the own patterns of the synced folder holding `PATH`. |
|
||||
| `pdfs sync ignore add PATTERN [--folder PATH]` / `remove PATTERN [--folder PATH]` | Leave out, or stop leaving out, files matching a gitignore-style pattern such as `*.db` or `build/`, in every synced folder or, with `--folder`, in that folder's `.pdfsignore` only. A pattern starting with `-` goes after `--`. |
|
||||
| `pdfs sync ignore reset` | Use the built-in patterns again. |
|
||||
| `pdfs sync ignore check PATH` | Say whether a file in a synced folder is synced, and which pattern decides. |
|
||||
| `pdfs sync limit [--up RATE] [--down RATE]` | Cap bandwidth, for example `500K` or `2M` per second. `0` removes a cap. Without options, prints the current caps. |
|
||||
| `pdfs sync queue` | List changes that have not reached Proton Drive yet. |
|
||||
| `pdfs sync issues` | List queued changes Proton Drive refused or that keep failing, and what to do. |
|
||||
|
||||
+15
-7
@@ -44,9 +44,13 @@ the [security model](SECURITY_MODEL.md#what-is-kept-on-this-computer).
|
||||
## `config.json`
|
||||
|
||||
The file is created with defaults on first start. Every key is optional; a missing key takes its
|
||||
default. Edit it while the app is closed, then restart the service
|
||||
default. Most keys can be changed in the app, under **Preferences** (the "In app" column below).
|
||||
To edit the file by hand, close the app first, then restart the service
|
||||
(`systemctl --user restart proton-drive.service`) for service settings to apply.
|
||||
|
||||
The app, the tray and the service each change the file under a lock (`config.json.lock` next to
|
||||
it), so two of them changing different settings at once both keep their change.
|
||||
|
||||
An unreadable file is never overwritten: the programs log an error and run with defaults until you
|
||||
fix it.
|
||||
|
||||
@@ -80,9 +84,9 @@ fix it.
|
||||
| `cache_budget` | bytes | 5 GiB | Storage → Cache | Soft limit for cached content. `0` means unlimited. Available-offline files do not count against it |
|
||||
| `upload_limit` | bytes/s | none | General → Network | Shared cap for all uploads. `0` or `null` means none |
|
||||
| `download_limit` | bytes/s | none | General → Network | Shared cap for all downloads, reads from the mount included |
|
||||
| `ignore_patterns` | list | see below | — | Global ignore rules for synced folders |
|
||||
| `ignore_patterns` | list | see below | Sync → Excluded Files | Global ignore rules for synced folders |
|
||||
| `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` | — | See [`conflict_sweep`](#conflict_sweep) |
|
||||
| `conflict_sweep` | `off` / `report` / `enforce` | `report` | Sync → Conflict Copies | See [`conflict_sweep`](#conflict_sweep) |
|
||||
| `local_first` | bool | `true` | — | See [`local_first`](#local_first) |
|
||||
| `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 |
|
||||
@@ -93,8 +97,8 @@ fix it.
|
||||
| `update_latest` | version | none | — | The latest release the update check found |
|
||||
| `files_view` | object | grid, by name | My files view menu | `list`, `sort` (`name`, `size`, `modified`), `descending`, `folders_first` |
|
||||
| `window` | object | 980 × 680 | Resizing the app window | `width`, `height` (the unmaximized size), `maximized` |
|
||||
| `open_with` | object | `xdg-open` | — | See [`open_with`](#open_with) |
|
||||
| `prompt` | object | built-in window | — | See [`prompt`](#prompt) |
|
||||
| `open_with` | object | `xdg-open` | Apps → Open Files With | See [`open_with`](#open_with) |
|
||||
| `prompt` | object | built-in window | Apps → Search Launcher | See [`prompt`](#prompt) |
|
||||
|
||||
`app_version` and `user_agent` identify the client to Proton. When the keys are absent, the
|
||||
client sends its own release (`external-drive-linux@<version>-stable`, `proton-drive-linux/<version>`).
|
||||
@@ -109,10 +113,14 @@ Gitignore-style rules applied to every synced folder, in addition to each folder
|
||||
|
||||
```json
|
||||
[".git/", ".hg/", ".svn/", "node_modules/", "target/", ".venv/", "__pycache__/",
|
||||
"*~", "*.swp", "*.tmp", ".DS_Store", "Thumbs.db"]
|
||||
"*~", "*.swp", "*.tmp", ".DS_Store", "Thumbs.db",
|
||||
"desktop.ini", ".directory", ".Trash-*/", ".Trashes/", ".Spotlight-V100/",
|
||||
".fuse_hidden*", ".nfs*", "*.part", "*.crdownload", "*.kate-swp", ".~lock.*#", "~$*"]
|
||||
```
|
||||
|
||||
Set it to `[]` to turn the defaults off. See
|
||||
Preferences → Sync → Excluded Files edits this list, **Add Pattern** on the Sync page's Folders
|
||||
view adds to it, and `pdfs sync ignore` does the same from a terminal. A list equal to the defaults is saved as absent, so it follows the defaults of later
|
||||
releases. Set it to `[]` to turn the defaults off. See
|
||||
[Synced folders](SYNCED_FOLDERS.md#excluding-files-with-pdfsignore) for how excluding behaves.
|
||||
|
||||
### `conflict_sweep`
|
||||
|
||||
+49
-8
@@ -21,7 +21,8 @@ again.
|
||||
| [Arch Linux](#arch-linux-aur) | `proton-drive-for-linux` in the AUR | With your AUR helper |
|
||||
| [Debian, Ubuntu 24.04 or newer](#debian-and-ubuntu-2404-or-newer) | `.deb` from the release page | Download each release |
|
||||
| [NixOS](#nixos-flake) | The flake in this repository | With `nix flake update` |
|
||||
| [Anything else](#other-distributions) | `.tar.gz` from the release page, or [build from source](#build-from-source) | By hand |
|
||||
| [Fedora Atomic](#fedora-atomic-silverblue-kinoite-bazzite-bluefin) (Silverblue, Kinoite, Bazzite, Bluefin) | The COPR repository, layered with `rpm-ostree` | With `rpm-ostree upgrade` |
|
||||
| [Anything else](#other-distributions), immutable ones included | `.tar.gz` from the release page, installed into your home folder by its `install.sh`, or [build from source](#build-from-source) | Run the new release's `install.sh` |
|
||||
|
||||
Release packages are for x86_64. You also need a Secret Service provider, such as GNOME
|
||||
Keyring, KWallet or KeePassXC, to keep your session. Most desktops have one already.
|
||||
@@ -139,12 +140,42 @@ the module) and a Secret Service such as GNOME Keyring or KWallet. To leave out
|
||||
it video thumbnails, override the package with `withFfmpeg = false`. The recipe is in
|
||||
[`packaging/nix/`](../packaging/nix/).
|
||||
|
||||
### Fedora Atomic (Silverblue, Kinoite, Bazzite, Bluefin)
|
||||
|
||||
The system is read-only, so layer the COPR package on top of it. It brings its libraries along:
|
||||
|
||||
```bash
|
||||
sudo curl -o /etc/yum.repos.d/proton-drive-linux.repo \
|
||||
"https://copr.fedorainfracloud.org/coprs/narl-rs/proton-drive-linux/repo/fedora-$(rpm -E %fedora)/narl-rs-proton-drive-linux-fedora-$(rpm -E %fedora).repo"
|
||||
rpm-ostree install proton-drive-linux
|
||||
systemctl reboot
|
||||
```
|
||||
|
||||
`rpm-ostree upgrade` brings new releases with the system's own updates.
|
||||
|
||||
### Other distributions
|
||||
|
||||
Unpack the `.tar.gz` from the [latest release](https://github.com/narrrl/proton-drive-linux/releases/latest)
|
||||
into a directory on your `PATH`, then install the service as shown in
|
||||
[Using a binary outside `/usr/bin`](#using-a-binary-outside-usrbin). The binaries need GTK 4.12,
|
||||
libadwaita 1.5, WebKitGTK 6.0 and FUSE 3; see [Requirements](#requirements).
|
||||
The `.tar.gz` from the [latest release](https://github.com/narrrl/proton-drive-linux/releases/latest)
|
||||
installs into your home folder, without root, so it also works where the system is read-only:
|
||||
|
||||
```bash
|
||||
tar -xzf proton-drive-linux-*-x86_64.tar.gz
|
||||
proton-drive-linux-*-x86_64/install.sh
|
||||
```
|
||||
|
||||
It puts the programs in `~/.local/bin`, the menu entry, icon, translations and shell completion in
|
||||
`~/.local/share`, the service in `~/.config/systemd/user` and the tray's login entry in
|
||||
`~/.config/autostart`, each pointing at `~/.local/bin`. Then open **Proton Drive for Linux** from
|
||||
your applications menu. `--prefix DIR` installs somewhere else.
|
||||
|
||||
The system has to provide glibc 2.39 or newer (the binaries are built on Ubuntu 24.04), GTK 4.12,
|
||||
libadwaita 1.5, WebKitGTK 6.0 and FUSE 3 with a setuid `fusermount3`; see
|
||||
[Requirements](#requirements). `install.sh` checks the libraries first and names the packages to
|
||||
install for each distribution. It refuses to install next to a package of this client, since the
|
||||
two would run different versions of the service.
|
||||
|
||||
To update, download the new release and run its `install.sh`; a running service restarts on the new
|
||||
version. Turn on **Preferences → General → Check for updates** to hear about new releases.
|
||||
|
||||
## Optional extras
|
||||
|
||||
@@ -195,7 +226,9 @@ browser, solve it, then press Enter.
|
||||
| COPR (Fedora) | `sudo dnf upgrade` |
|
||||
| AUR | `paru -Syu`, or your AUR helper's equivalent |
|
||||
| Nix flake | `nix flake update proton-drive-linux`, or change the pinned tag, then rebuild |
|
||||
| `.deb`, release `.rpm`, `.tar.gz` | Download the new release and install it over the old one |
|
||||
| Fedora Atomic | `rpm-ostree upgrade`, then reboot |
|
||||
| `.deb`, release `.rpm` | Download the new release and install it over the old one |
|
||||
| `.tar.gz` | Download the new release and run its `install.sh` |
|
||||
|
||||
The service switches to the new version the next time it starts. To switch at once:
|
||||
|
||||
@@ -245,6 +278,8 @@ open in an older release, so going back to an older version means clearing the l
|
||||
| `.deb` | `sudo apt remove proton-drive-linux` |
|
||||
| AUR | `sudo pacman -R proton-drive-for-linux` (or the `-bin` or `-git` package) |
|
||||
| NixOS | Remove the module and the flake input, then rebuild |
|
||||
| Fedora Atomic | `rpm-ostree uninstall proton-drive-linux`, remove `/etc/yum.repos.d/proton-drive-linux.repo`, then reboot |
|
||||
| `.tar.gz` | `~/.local/share/proton-drive-linux/install.sh --uninstall` |
|
||||
|
||||
Removing the package also stops the service of every logged-in user, in case step 1 was
|
||||
skipped.
|
||||
@@ -353,8 +388,10 @@ sudo dnf install packaging/out/x86_64/proton-drive-linux-*.rpm
|
||||
|
||||
### Using a binary outside `/usr/bin`
|
||||
|
||||
The service unit starts `/usr/bin/pdfs daemon`. If you installed the programs somewhere else, for
|
||||
example `~/.local/bin`, install the unit for your user and point it at your binary:
|
||||
The release tarball's `install.sh` does all of this for you (see
|
||||
[Other distributions](#other-distributions)). For programs you built yourself: the service unit
|
||||
starts `/usr/bin/pdfs daemon`. If you installed the programs somewhere else, for example
|
||||
`~/.local/bin`, install the unit for your user and point it at your binary:
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.config/systemd/user
|
||||
@@ -382,3 +419,7 @@ Every package installs the same files:
|
||||
| `/usr/lib/systemd/user/proton-drive.service` | User service that keeps the drive mounted |
|
||||
| `/etc/xdg/autostart/io.narl.proton-drive-linux-tray.desktop` | Starts the tray at login |
|
||||
| `/usr/share/locale/*/LC_MESSAGES/pdfs.mo` | Translations |
|
||||
|
||||
The release tarball's `install.sh` puts the same files under `~/.local` instead of `/usr`, the
|
||||
service in `~/.config/systemd/user` and the tray's login entry in `~/.config/autostart`. It keeps a
|
||||
list of them in `~/.local/share/proton-drive-linux/installed-files` for `--uninstall`.
|
||||
@@ -58,6 +58,52 @@ can resolve the default alias to a locked collection. Both have fixes in
|
||||
after the reporter's November 7 retest. Neither can be assigned as this report's cause without
|
||||
matching runtime evidence.
|
||||
|
||||
## SetSecret is kept only in memory in Fedora's oo7
|
||||
|
||||
Follow-up on 2026-11-15. The reporter's `rpm -qa 'oo7*'` shows
|
||||
`oo7-daemon-0.7.0~beta^1.e91b98a-1.fc45`, not the 0.7.0 release assumed above. Bodhi lists that
|
||||
build as the stable oo7 for Fedora 45 and 46; neither has 0.7.0 or 0.7.1. Commit e91b98a
|
||||
(October 24) predates
|
||||
[7fb11dd](https://github.com/linux-credentials/oo7/commit/7fb11dd111c4be8fec01996e3caa31c44fa962b3)
|
||||
(October 28): "Setting the Label or Attributes of an item, or calling SetSecret, only changed the
|
||||
item in memory, so the old values came back once the daemon restarted." 0.7.0 carries it as
|
||||
37e3334.
|
||||
|
||||
pdfs writes an existing entry with `SetSecret`, so on that build every saved token rotation was
|
||||
lost at the next reboot. This explains the reporter's log: the keyring was unlocked one second
|
||||
before pdfs started (they type their password at login) and still held a spent refresh token.
|
||||
It does not need a locked keyring or a restarted provider.
|
||||
|
||||
pdfs now saves an existing entry with `CreateItem` and `replace` instead
|
||||
(`crates/pdfs-core/src/secretservice.rs`, B291), which e91b98a writes to the keyring file.
|
||||
Reproduced and verified with oo7-daemon built at e91b98a in a throwaway session bus:
|
||||
|
||||
```sh
|
||||
git clone https://github.com/linux-credentials/oo7.git /tmp/oo7 && git -C /tmp/oo7 checkout e91b98a
|
||||
cargo build --manifest-path /tmp/oo7/Cargo.toml -p oo7-daemon --bin oo7-daemon
|
||||
OO7=/tmp/oo7/target/debug/oo7-daemon
|
||||
T=$(mktemp -d /tmp/ss.XXXX); mkdir -p $T/data $T/run; chmod 700 $T/run
|
||||
XDG_DATA_HOME=$T/data XDG_RUNTIME_DIR=$T/run OO7=$OO7 PDFS_SECRET_SERVICE_RESTART_TEST=1 \
|
||||
PDFS_RESTART_PROVIDER='pkill -x oo7-daemon; sleep 1; (printf pw | setsid "$OO7" --login >/dev/null 2>&1 &); sleep 2' \
|
||||
dbus-run-session -- sh -c 'printf pw | setsid "$OO7" --login >/dev/null 2>&1 & sleep 2;
|
||||
cargo test -p pdfs-core real_secret_service_keeps -- --ignored'
|
||||
```
|
||||
|
||||
With the in-place write, the read after the restart returns the first of three saves (`r1`);
|
||||
with the replacing write it returns the last (`r3`), and one item is left.
|
||||
|
||||
The daemon also logs a short fingerprint of the refresh token when it resumes the stored session
|
||||
and each time it saves a rotation (`refresh=1a2b3c4d`). If a start is refused, compare the
|
||||
fingerprint it resumed with against the last one saved in the boot before:
|
||||
|
||||
```sh
|
||||
journalctl --user -b -1 -u proton-drive.service | grep -E 'refresh=' | tail -2
|
||||
journalctl --user -b 0 -u proton-drive.service | grep -E 'refresh=' | head -2
|
||||
```
|
||||
|
||||
The same fingerprint means the keyring kept the last save and Proton refused it; a different one
|
||||
means the keyring lost it.
|
||||
|
||||
## A restarted Secret Service
|
||||
|
||||
A second path to the same symptom, independent of locking (B285). The keyring store pdfs used
|
||||
|
||||
@@ -69,9 +69,10 @@ windowrulev2 = center, class:^(pdfs-prompt)$
|
||||
bind = SUPER, space, exec, pdfs-prompt --fzf
|
||||
```
|
||||
|
||||
To make `--dmenu` or `--fzf` the default without changing your shortcut, set `prompt.mode` in
|
||||
`config.json` (see [Configuration → `prompt`](CONFIGURATION.md#prompt)). `--gtk` always opens the
|
||||
built-in window.
|
||||
To make `--dmenu` or `--fzf` the default without changing your shortcut, pick it in
|
||||
**Preferences → Apps → Search Launcher**, or set `prompt.mode` in `config.json` (see
|
||||
[Configuration → `prompt`](CONFIGURATION.md#prompt)). `--gtk` always opens the built-in window.
|
||||
Which program opens a file you pick is set under **Preferences → Apps → Open Files With**.
|
||||
|
||||
## Tray
|
||||
|
||||
|
||||
+33
-4
@@ -100,10 +100,39 @@ apply together:
|
||||
!important.log
|
||||
```
|
||||
|
||||
2. The `ignore_patterns` list in `config.json`, for every synced folder (see
|
||||
[Configuration](CONFIGURATION.md#ignore_patterns)). When you have not set it, it skips
|
||||
`.git/`, `.hg/`, `.svn/`, `node_modules/`, `target/`, `.venv/`, `__pycache__/`, `*~`,
|
||||
`*.swp`, `*.tmp`, `.DS_Store` and `Thumbs.db`.
|
||||
2. The patterns for every synced folder: **Preferences → Sync → Excluded Files** in the app, or
|
||||
`ignore_patterns` in `config.json` (see [Configuration](CONFIGURATION.md#ignore_patterns)).
|
||||
Built in are version control (`.git/`, `.hg/`, `.svn/`), dependency and build folders
|
||||
(`node_modules/`, `target/`, `.venv/`, `__pycache__/`), and what editors, downloads and other
|
||||
systems leave behind (`*~`, `*.swp`, `*.tmp`, `*.part`, `*.crdownload`, `*.kate-swp`, office
|
||||
lock files, `.DS_Store`, `Thumbs.db`, `desktop.ini`, `.directory`, trash folders, `.nfs*` and
|
||||
`.fuse_hidden*`). Each built-in pattern can be turned off on its own.
|
||||
|
||||
In the app, open the **Sync** page, then **Folders**. Under the folder list, **Excluded Files**
|
||||
shows how many patterns apply to all synced folders and how many each folder has of its own:
|
||||
|
||||
- **Add Pattern** asks for a pattern and where it applies: all synced folders, or one of them.
|
||||
- **All Synced Folders** opens Preferences → Sync, with every pattern and the built-in ones.
|
||||
- A folder opens the editor for its own rules, which **Excluded Files…** in the folder's menu
|
||||
opens too. It checks every line as you type, and **Check a path** tells you whether a file is
|
||||
synced and which pattern decides. If the file changed meanwhile, for example on another
|
||||
computer, it asks before replacing that version.
|
||||
|
||||
From a terminal:
|
||||
|
||||
```bash
|
||||
pdfs sync ignore list # the patterns for every synced folder
|
||||
pdfs sync ignore add '*.db' # leave out files ending in .db
|
||||
pdfs sync ignore remove '*.db'
|
||||
pdfs sync ignore reset # back to the built-in patterns
|
||||
pdfs sync ignore add 'cache/' --folder ~/Projects # only in ~/Projects/.pdfsignore
|
||||
pdfs sync ignore list --folder ~/Projects
|
||||
pdfs sync ignore check ~/Projects/app/node_modules
|
||||
```
|
||||
|
||||
The rules apply to folders kept on this computer. Files you save into `~/ProtonDrive` itself or into
|
||||
an online-only folder are always uploaded, except download and editor scratch files, which wait for
|
||||
their final name.
|
||||
|
||||
Rules are read again on every sync pass. Excluding never deletes anything: a file that becomes
|
||||
excluded is no longer synced, and its copy on Proton Drive stays.
|
||||
|
||||
@@ -53,6 +53,8 @@ The app uses these words, and so do these pages:
|
||||
| Page | Settings |
|
||||
|---|---|
|
||||
| **General** | Start on login · Proton Drive folder location · upload and download limits · Proton theme, street map for Places, tray icon · language · check for updates |
|
||||
| **Sync** | Files and folders every synced folder leaves out · what happens to identical conflict copies |
|
||||
| **Apps** | Which program opens which kind of file · how the search launcher opens |
|
||||
| **Storage** | Cache size limit · clear the cache · files kept available offline |
|
||||
|
||||
The account menu shows the storage you use and holds **Sign Out…**. Settings that are not in the
|
||||
|
||||
@@ -31,16 +31,6 @@ pkgbase = proton-drive-for-linux-bin
|
||||
options = !strip
|
||||
options = !debug
|
||||
source = proton-drive-linux-3.7.0-x86_64.tar.gz::https://github.com/narrrl/proton-drive-linux/releases/download/v3.7.0/proton-drive-linux-3.7.0-x86_64.tar.gz
|
||||
source = io.narl.proton-drive-linux-3.7.0.desktop::https://raw.githubusercontent.com/narrrl/proton-drive-linux/v3.7.0/packaging/io.narl.proton-drive-linux.desktop
|
||||
source = io.narl.proton-drive-linux-tray-3.7.0.desktop::https://raw.githubusercontent.com/narrrl/proton-drive-linux/v3.7.0/packaging/io.narl.proton-drive-linux-tray.desktop
|
||||
source = io.narl.proton-drive-linux-3.7.0.svg::https://raw.githubusercontent.com/narrrl/proton-drive-linux/v3.7.0/packaging/io.narl.proton-drive-linux.svg
|
||||
source = proton-drive-3.7.0.service::https://raw.githubusercontent.com/narrrl/proton-drive-linux/v3.7.0/packaging/proton-drive.service
|
||||
source = LICENSE-3.7.0::https://raw.githubusercontent.com/narrrl/proton-drive-linux/v3.7.0/LICENSE
|
||||
sha256sums = 3f0d16c19b10b30e3f181e3c7fb439f0a8c38980e8ab7a4a96ae6596b349787c
|
||||
sha256sums = d190d6771fff0b975271fb62fd3fb0fa8bbf17d7278c10853c18557855b0c123
|
||||
sha256sums = 1d95e250370220e3bb6aead6ce34d1d6cc759f42c4803b75f1667e78ff47c6c0
|
||||
sha256sums = e598a93c2715c3a9fdc7fb937902083d4a1135e8fbdfe6fe7e37f0383ebbd828
|
||||
sha256sums = 44c25dca6e759c46fca50b58099aa6194abe78293dee07d971bbbce0ff3ca58f
|
||||
sha256sums = 02c419e7f9af08dda720e4f852f3e57cf5a69e192605440f750e9d244fa2817c
|
||||
sha256sums = SKIP
|
||||
|
||||
pkgname = proton-drive-for-linux-bin
|
||||
@@ -25,54 +25,37 @@ options=('!strip' '!debug')
|
||||
# Stops the running daemon before removal, so the mount stops mirroring deletes.
|
||||
install=proton-drive.install
|
||||
_tag="v$pkgver"
|
||||
_raw="https://raw.githubusercontent.com/narrrl/proton-drive-linux/$_tag"
|
||||
# The release tarball holds the four binaries only, so the desktop integration
|
||||
# files come straight from the tagged tree. Every one carries $pkgver in its
|
||||
# name: makepkg reuses a cached file of the same name, so an unversioned name
|
||||
# keeps the old copy after upstream changes it and fails the checksum.
|
||||
source=("proton-drive-linux-$pkgver-x86_64.tar.gz::$_repo/releases/download/$_tag/proton-drive-linux-$pkgver-x86_64.tar.gz"
|
||||
"io.narl.proton-drive-linux-$pkgver.desktop::$_raw/packaging/io.narl.proton-drive-linux.desktop"
|
||||
"io.narl.proton-drive-linux-tray-$pkgver.desktop::$_raw/packaging/io.narl.proton-drive-linux-tray.desktop"
|
||||
"io.narl.proton-drive-linux-$pkgver.svg::$_raw/packaging/io.narl.proton-drive-linux.svg"
|
||||
"proton-drive-$pkgver.service::$_raw/packaging/proton-drive.service"
|
||||
"LICENSE-$pkgver::$_raw/LICENSE")
|
||||
sha256sums=('3f0d16c19b10b30e3f181e3c7fb439f0a8c38980e8ab7a4a96ae6596b349787c'
|
||||
'd190d6771fff0b975271fb62fd3fb0fa8bbf17d7278c10853c18557855b0c123'
|
||||
'1d95e250370220e3bb6aead6ce34d1d6cc759f42c4803b75f1667e78ff47c6c0'
|
||||
'e598a93c2715c3a9fdc7fb937902083d4a1135e8fbdfe6fe7e37f0383ebbd828'
|
||||
'44c25dca6e759c46fca50b58099aa6194abe78293dee07d971bbbce0ff3ca58f'
|
||||
'02c419e7f9af08dda720e4f852f3e57cf5a69e192605440f750e9d244fa2817c')
|
||||
# The release tarball holds the binaries and everything installed around them
|
||||
# (desktop files, icon, user service, translations, completions) in a /usr-like
|
||||
# tree under one directory.
|
||||
source=("proton-drive-linux-$pkgver-x86_64.tar.gz::$_repo/releases/download/$_tag/proton-drive-linux-$pkgver-x86_64.tar.gz")
|
||||
sha256sums=('SKIP')
|
||||
|
||||
package() {
|
||||
install -Dm755 "$srcdir/pdfs" "$pkgdir/usr/bin/pdfs"
|
||||
install -Dm755 "$srcdir/pdfs-tray" "$pkgdir/usr/bin/pdfs-tray"
|
||||
install -Dm755 "$srcdir/pdfs-app" "$pkgdir/usr/bin/pdfs-app"
|
||||
install -Dm755 "$srcdir/pdfs-prompt" "$pkgdir/usr/bin/pdfs-prompt"
|
||||
cd "$srcdir/proton-drive-linux-$pkgver-x86_64"
|
||||
local exe
|
||||
for exe in pdfs pdfs-tray pdfs-app pdfs-prompt; do
|
||||
install -Dm755 "bin/$exe" "$pkgdir/usr/bin/$exe"
|
||||
done
|
||||
|
||||
install -Dm644 "$srcdir/io.narl.proton-drive-linux-$pkgver.desktop" \
|
||||
install -Dm644 share/applications/io.narl.proton-drive-linux.desktop \
|
||||
"$pkgdir/usr/share/applications/io.narl.proton-drive-linux.desktop"
|
||||
install -Dm644 "$srcdir/io.narl.proton-drive-linux-tray-$pkgver.desktop" \
|
||||
install -Dm644 etc/xdg/autostart/io.narl.proton-drive-linux-tray.desktop \
|
||||
"$pkgdir/etc/xdg/autostart/io.narl.proton-drive-linux-tray.desktop"
|
||||
install -Dm644 "$srcdir/io.narl.proton-drive-linux-$pkgver.svg" \
|
||||
install -Dm644 share/icons/hicolor/scalable/apps/io.narl.proton-drive-linux.svg \
|
||||
"$pkgdir/usr/share/icons/hicolor/scalable/apps/io.narl.proton-drive-linux.svg"
|
||||
|
||||
# systemd user unit for the auto-mount daemon; enabled per user, not by pacman.
|
||||
install -Dm644 "$srcdir/proton-drive-$pkgver.service" \
|
||||
install -Dm644 lib/systemd/user/proton-drive.service \
|
||||
"$pkgdir/usr/lib/systemd/user/proton-drive.service"
|
||||
|
||||
# Translations ship precompiled in the release tarball.
|
||||
# Translations and shell completion for bash, zsh and fish.
|
||||
install -dm755 "$pkgdir/usr/share"
|
||||
cp -r --no-preserve=ownership "$srcdir/locale" "$pkgdir/usr/share/locale"
|
||||
cp -r --no-preserve=ownership share/locale share/bash-completion share/zsh share/fish \
|
||||
"$pkgdir/usr/share/"
|
||||
|
||||
# Shell completion for bash, zsh and fish, written by the binary itself.
|
||||
local share="$pkgdir/usr/share"
|
||||
install -d "$share/bash-completion/completions" "$share/zsh/site-functions" \
|
||||
"$share/fish/vendor_completions.d"
|
||||
"$srcdir/pdfs" completions bash > "$share/bash-completion/completions/pdfs"
|
||||
"$srcdir/pdfs" completions zsh > "$share/zsh/site-functions/_pdfs"
|
||||
"$srcdir/pdfs" completions fish > "$share/fish/vendor_completions.d/pdfs.fish"
|
||||
|
||||
install -Dm644 "$srcdir/LICENSE-$pkgver" "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
|
||||
install -Dm644 share/licenses/proton-drive-linux/LICENSE \
|
||||
"$pkgdir/usr/share/licenses/$pkgname/LICENSE"
|
||||
|
||||
# pacman brings new releases, so the app never checks for them itself.
|
||||
install -Dm644 /dev/null "$pkgdir/usr/share/proton-drive-linux/managed-updates"
|
||||
|
||||
Executable
+45
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env bash
|
||||
# Lay out the release tarball: built binaries, desktop files, icon, user
|
||||
# service, translations, shell completions and install.sh, under one top-level
|
||||
# directory with a /usr-like tree, then pack it.
|
||||
#
|
||||
# usage: packaging/tarball/build.sh <binary dir> <version> <output dir>
|
||||
# e.g. packaging/tarball/build.sh target/release 3.8.0 dist
|
||||
# Writes <output dir>/proton-drive-linux-<version>-x86_64.tar.gz and prints
|
||||
# its path.
|
||||
set -euo pipefail
|
||||
|
||||
if [ $# -ne 3 ]; then
|
||||
echo "usage: $0 <binary dir> <version> <output dir>" >&2
|
||||
exit 2
|
||||
fi
|
||||
bin_dir="$1"
|
||||
version="$2"
|
||||
out="$3"
|
||||
repo="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
|
||||
name="proton-drive-linux-$version-x86_64"
|
||||
stage="$(mktemp -d)"
|
||||
trap 'rm -rf "$stage"' EXIT
|
||||
root="$stage/$name"
|
||||
|
||||
for exe in pdfs pdfs-app pdfs-tray pdfs-prompt; do
|
||||
install -Dm755 "$bin_dir/$exe" "$root/bin/$exe"
|
||||
done
|
||||
install -Dm644 "$repo/packaging/io.narl.proton-drive-linux.desktop" \
|
||||
"$root/share/applications/io.narl.proton-drive-linux.desktop"
|
||||
install -Dm644 "$repo/packaging/io.narl.proton-drive-linux-tray.desktop" \
|
||||
"$root/etc/xdg/autostart/io.narl.proton-drive-linux-tray.desktop"
|
||||
install -Dm644 "$repo/packaging/io.narl.proton-drive-linux.svg" \
|
||||
"$root/share/icons/hicolor/scalable/apps/io.narl.proton-drive-linux.svg"
|
||||
install -Dm644 "$repo/packaging/proton-drive.service" \
|
||||
"$root/lib/systemd/user/proton-drive.service"
|
||||
install -Dm644 "$repo/LICENSE" "$root/share/licenses/proton-drive-linux/LICENSE"
|
||||
"$repo/po/build.sh" "$root/share/locale"
|
||||
"$repo/packaging/completions.sh" "$root/bin/pdfs" "$root/share"
|
||||
install -Dm755 "$repo/packaging/tarball/install.sh" "$root/install.sh"
|
||||
|
||||
mkdir -p "$out"
|
||||
tarball="$(cd "$out" && pwd)/$name.tar.gz"
|
||||
tar -czf "$tarball" -C "$stage" --owner=0 --group=0 "$name"
|
||||
echo "$tarball"
|
||||
Executable
+194
@@ -0,0 +1,194 @@
|
||||
#!/usr/bin/env bash
|
||||
# Install Proton Drive for Linux from this release tarball into your home
|
||||
# directory, or remove it again. Needs no root, so it works on distributions
|
||||
# where the system is read-only, as long as GTK 4, libadwaita, WebKitGTK 6 and
|
||||
# FUSE 3 are on the system.
|
||||
set -Eeuo pipefail
|
||||
|
||||
usage() {
|
||||
cat >&2 <<'EOF'
|
||||
usage: ./install.sh [--prefix DIR] [--no-service] [--force]
|
||||
./install.sh --uninstall [--prefix DIR] [--no-service]
|
||||
|
||||
Installs the app, the tray, the search launcher and the `pdfs` command into
|
||||
~/.local (bin/, share/), the background service into ~/.config/systemd/user and
|
||||
the tray's login entry into ~/.config/autostart. Run it again from a newer
|
||||
tarball to update; the running service restarts on the new version.
|
||||
|
||||
--prefix DIR install under DIR instead of ~/.local
|
||||
--uninstall remove what an earlier run installed; your settings, cache
|
||||
and the files in Proton Drive stay
|
||||
--no-service leave systemd alone (no reload, restart or stop)
|
||||
--force install although libraries are missing or a package
|
||||
already installs Proton Drive for Linux
|
||||
EOF
|
||||
exit 2
|
||||
}
|
||||
|
||||
prefix=""
|
||||
uninstall=0
|
||||
service=1
|
||||
force=0
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--prefix) [[ $# -ge 2 ]] || usage; prefix="$2"; shift ;;
|
||||
--prefix=*) prefix="${1#*=}" ;;
|
||||
--uninstall) uninstall=1 ;;
|
||||
--no-service) service=0 ;;
|
||||
--force) force=1 ;;
|
||||
-h | --help) usage ;;
|
||||
*) echo "unknown option: $1" >&2; usage ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
# The copy kept for --uninstall knows where it was installed.
|
||||
if [[ -z "$prefix" && -f "$here/installed-files" ]]; then
|
||||
prefix="$(dirname "$(dirname "$here")")"
|
||||
fi
|
||||
prefix="${prefix:-$HOME/.local}"
|
||||
[[ "$prefix" == /* ]] || prefix="$PWD/$prefix"
|
||||
prefix="${prefix%/}"
|
||||
|
||||
config_home="${XDG_CONFIG_HOME:-$HOME/.config}"
|
||||
unit_dir="$config_home/systemd/user"
|
||||
autostart_dir="$config_home/autostart"
|
||||
data_dir="$prefix/share/proton-drive-linux"
|
||||
manifest="$data_dir/installed-files"
|
||||
unit=proton-drive.service
|
||||
|
||||
say() { printf '%s\n' "$*"; }
|
||||
warn() { printf 'warning: %s\n' "$*" >&2; }
|
||||
die() { printf 'error: %s\n' "$*" >&2; exit 1; }
|
||||
|
||||
systemctl_user() {
|
||||
[[ $service -eq 1 ]] || return 0
|
||||
command -v systemctl >/dev/null || return 0
|
||||
systemctl --user "$@" 2>/dev/null || true
|
||||
}
|
||||
|
||||
# Remove every file listed in the manifest `$1` that is not in the list `$2`
|
||||
# (one path per line), then the directories that leaves empty.
|
||||
remove_listed() {
|
||||
local list="$1" keep="${2:-}" path
|
||||
[[ -f "$list" ]] || return 0
|
||||
while IFS= read -r path; do
|
||||
[[ -n "$path" ]] || continue
|
||||
if [[ -n "$keep" ]] && grep -Fxq -- "$path" <<<"$keep"; then
|
||||
continue
|
||||
fi
|
||||
rm -f -- "$path"
|
||||
rmdir -p --ignore-fail-on-non-empty -- "$(dirname -- "$path")" 2>/dev/null || true
|
||||
done <"$list"
|
||||
}
|
||||
|
||||
if [[ $uninstall -eq 1 ]]; then
|
||||
[[ -f "$manifest" ]] || die "nothing installed under $prefix (no $manifest)"
|
||||
# Stopping unmounts My files; queued changes stay and upload on the next start.
|
||||
systemctl_user disable --now "$unit"
|
||||
remove_listed "$manifest"
|
||||
rm -f -- "$manifest" "$data_dir/install.sh"
|
||||
rmdir --ignore-fail-on-non-empty -- "$data_dir" 2>/dev/null || true
|
||||
systemctl_user daemon-reload
|
||||
say "Removed Proton Drive for Linux from $prefix."
|
||||
say "Your settings, cache and sign-in stay; see the uninstall section of docs/INSTALL.md to remove them too."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
[[ -x "$here/bin/pdfs" ]] || die "run install.sh from the unpacked tarball (no bin/pdfs next to it)"
|
||||
|
||||
# A package and this install would each bring a service unit, and the one in
|
||||
# ~/.config wins: the two would run different versions against one database.
|
||||
if [[ $force -eq 0 && ( -e /usr/bin/pdfs || -e /usr/lib/systemd/user/$unit ) ]]; then
|
||||
die "a package already installs Proton Drive for Linux (/usr/bin/pdfs). Remove it first, or keep using it."
|
||||
fi
|
||||
|
||||
# Missing libraries would only show when the app does not start.
|
||||
missing="$(for exe in pdfs pdfs-app pdfs-tray pdfs-prompt; do
|
||||
ldd "$here/bin/$exe" 2>&1 | grep -E 'not found' || true
|
||||
done | sort -u)"
|
||||
if [[ -n "$missing" ]]; then
|
||||
printf '%s\n' "$missing" | sed 's/^[[:space:]]*/ /' >&2
|
||||
if grep -q 'GLIBC_' <<<"$missing"; then
|
||||
warn "these binaries need glibc 2.39 or newer (Ubuntu 24.04, Debian 13, Fedora 40)"
|
||||
fi
|
||||
cat >&2 <<'EOF'
|
||||
Install the missing libraries, then run this again:
|
||||
Fedora, Fedora Atomic gtk4 libadwaita webkitgtk6.0 fuse3
|
||||
(on Silverblue and its siblings, layer the COPR package
|
||||
instead: see docs/INSTALL.md)
|
||||
Debian, Ubuntu libgtk-4-1 libadwaita-1-0 libwebkitgtk-6.0-4 fuse3
|
||||
Arch Linux gtk4 libadwaita webkitgtk-6.0 fuse3
|
||||
openSUSE libgtk-4-1 libadwaita-1-0 libwebkitgtk-6_0-4 fuse3
|
||||
EOF
|
||||
[[ $force -eq 1 ]] || die "missing libraries (--force installs anyway)"
|
||||
fi
|
||||
|
||||
fusermount="$(command -v fusermount3 || true)"
|
||||
if [[ -z "$fusermount" ]]; then
|
||||
warn "fusermount3 is missing; install fuse3, or My files cannot be mounted"
|
||||
elif [[ ! -u "$fusermount" ]]; then
|
||||
warn "$fusermount is not setuid root; My files may not mount"
|
||||
fi
|
||||
|
||||
# Where each file of the tarball goes, as "source<TAB>target" lines.
|
||||
targets() {
|
||||
local file rel
|
||||
while IFS= read -r -d '' file; do
|
||||
rel="${file#"$here"/}"
|
||||
case "$rel" in
|
||||
bin/* | share/*) printf '%s\t%s\n' "$rel" "$prefix/$rel" ;;
|
||||
lib/systemd/user/*) printf '%s\t%s\n' "$rel" "$unit_dir/${rel##*/}" ;;
|
||||
etc/xdg/autostart/*) printf '%s\t%s\n' "$rel" "$autostart_dir/${rel##*/}" ;;
|
||||
esac
|
||||
done < <(find "$here/bin" "$here/share" "$here/lib" "$here/etc" -type f -print0 | sort -z)
|
||||
}
|
||||
|
||||
# A desktop entry and a unit file take a quoted path; double quotes and
|
||||
# backslashes inside it are escaped.
|
||||
quoted() {
|
||||
local path="${1//\\/\\\\}"
|
||||
printf '"%s"' "${path//\"/\\\"}"
|
||||
}
|
||||
|
||||
new_files=""
|
||||
while IFS=$'\t' read -r rel target; do
|
||||
mode=644
|
||||
[[ "$rel" == bin/* ]] && mode=755
|
||||
install -Dm"$mode" -- "$here/$rel" "$target"
|
||||
case "$rel" in
|
||||
share/applications/*.desktop | etc/xdg/autostart/*.desktop)
|
||||
exe="$(sed -n 's/^Exec=\([^ ]*\).*/\1/p' "$target" | head -n1)"
|
||||
sed -i "s|^Exec=$exe|Exec=$(quoted "$prefix/bin/$exe" | sed 's/[&|]/\\&/g')|" "$target"
|
||||
;;
|
||||
lib/systemd/user/*)
|
||||
sed -i "s|^ExecStart=/usr/bin/pdfs|ExecStart=$(quoted "$prefix/bin/pdfs" | sed 's/[&|]/\\&/g')|" "$target"
|
||||
;;
|
||||
esac
|
||||
new_files+="$target"$'\n'
|
||||
done < <(targets)
|
||||
|
||||
# Drop what an older version installed and this one does not.
|
||||
remove_listed "$manifest" "$new_files"
|
||||
mkdir -p -- "$data_dir"
|
||||
printf '%s' "$new_files" >"$manifest"
|
||||
install -m755 -- "$here/install.sh" "$data_dir/install.sh"
|
||||
|
||||
if command -v gtk-update-icon-cache >/dev/null &&
|
||||
[[ -f "$prefix/share/icons/hicolor/index.theme" ]]; then
|
||||
gtk-update-icon-cache -q -t "$prefix/share/icons/hicolor" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
systemctl_user daemon-reload
|
||||
if [[ $service -eq 1 ]] && command -v systemctl >/dev/null &&
|
||||
systemctl --user is-active -q "$unit" 2>/dev/null; then
|
||||
systemctl --user restart "$unit" && say "Restarted the running service on the new version."
|
||||
fi
|
||||
|
||||
say "Installed Proton Drive for Linux $("$prefix/bin/pdfs" --version 2>/dev/null | awk '{print $NF}') into $prefix."
|
||||
say "Open \"Proton Drive for Linux\" from your applications menu and sign in; the app starts the service."
|
||||
case ":$PATH:" in
|
||||
*":$prefix/bin:"*) ;;
|
||||
*) say "To use \`pdfs\` in a terminal, add $prefix/bin to your PATH." ;;
|
||||
esac
|
||||
say "To update, run install.sh from a newer tarball. To remove: $data_dir/install.sh --uninstall"
|
||||
Executable
+69
@@ -0,0 +1,69 @@
|
||||
#!/usr/bin/env bash
|
||||
# Check a release tarball: install it into a throwaway home, check that every
|
||||
# file landed with its paths rewritten and that the programs run, update it in
|
||||
# place, then uninstall and check nothing is left. Touches no real home and no
|
||||
# systemd (--no-service).
|
||||
#
|
||||
# usage: packaging/tarball/test.sh <tarball>
|
||||
set -euo pipefail
|
||||
|
||||
if [ $# -ne 1 ]; then
|
||||
echo "usage: $0 <tarball>" >&2
|
||||
exit 2
|
||||
fi
|
||||
tarball="$(cd "$(dirname "$1")" && pwd)/$(basename "$1")"
|
||||
work="$(mktemp -d)"
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
|
||||
fail() { echo "FAIL: $*" >&2; exit 1; }
|
||||
|
||||
tar -xzf "$tarball" -C "$work"
|
||||
src="$(find "$work" -mindepth 1 -maxdepth 1 -type d -name 'proton-drive-linux-*')"
|
||||
[ -x "$src/install.sh" ] || fail "no install.sh in the tarball"
|
||||
|
||||
export HOME="$work/home" XDG_CONFIG_HOME="$work/home/.config"
|
||||
mkdir -p "$HOME"
|
||||
prefix="$HOME/.local"
|
||||
"$src/install.sh" --no-service --force >"$work/install.log" 2>&1 ||
|
||||
{ cat "$work/install.log" >&2; fail "install.sh failed"; }
|
||||
|
||||
for exe in pdfs pdfs-app pdfs-tray pdfs-prompt; do
|
||||
[ -x "$prefix/bin/$exe" ] || fail "$exe was not installed"
|
||||
done
|
||||
"$prefix/bin/pdfs" --version >/dev/null || fail "pdfs does not run"
|
||||
app="$prefix/share/applications/io.narl.proton-drive-linux.desktop"
|
||||
tray="$XDG_CONFIG_HOME/autostart/io.narl.proton-drive-linux-tray.desktop"
|
||||
unit="$XDG_CONFIG_HOME/systemd/user/proton-drive.service"
|
||||
grep -qx "Exec=\"$prefix/bin/pdfs-app\"" "$app" || fail "the app's Exec= was not rewritten: $(grep ^Exec= "$app")"
|
||||
grep -qx "Exec=\"$prefix/bin/pdfs-tray\"" "$tray" || fail "the tray's Exec= was not rewritten: $(grep ^Exec= "$tray")"
|
||||
grep -qx "ExecStart=\"$prefix/bin/pdfs\" daemon" "$unit" || fail "ExecStart= was not rewritten: $(grep ^ExecStart= "$unit")"
|
||||
[ -f "$prefix/share/locale/de/LC_MESSAGES/pdfs.mo" ] || fail "no translations"
|
||||
[ -f "$prefix/share/icons/hicolor/scalable/apps/io.narl.proton-drive-linux.svg" ] || fail "no icon"
|
||||
[ -f "$prefix/share/bash-completion/completions/pdfs" ] || fail "no bash completion"
|
||||
[ ! -e "$prefix/share/proton-drive-linux/managed-updates" ] || fail "the update check must stay on offer"
|
||||
uninstaller="$prefix/share/proton-drive-linux/install.sh"
|
||||
[ -x "$uninstaller" ] || fail "install.sh was not kept for --uninstall"
|
||||
|
||||
# An update from the same tarball leaves the same files.
|
||||
before="$(cd "$work/home" && find . -type f | sort)"
|
||||
"$src/install.sh" --no-service --force >"$work/update.log" 2>&1 ||
|
||||
{ cat "$work/update.log" >&2; fail "updating failed"; }
|
||||
after="$(cd "$work/home" && find . -type f | sort)"
|
||||
[ "$before" = "$after" ] || fail "an update changed the set of files: $(diff <(echo "$before") <(echo "$after"))"
|
||||
|
||||
# A file an older version installed and this one does not is removed.
|
||||
stale="$prefix/share/locale/xx/LC_MESSAGES/pdfs.mo"
|
||||
mkdir -p "$(dirname "$stale")" && : >"$stale"
|
||||
echo "$stale" >>"$prefix/share/proton-drive-linux/installed-files"
|
||||
"$src/install.sh" --no-service --force >/dev/null 2>&1
|
||||
[ ! -e "$stale" ] || fail "a file the new version does not ship was left behind"
|
||||
|
||||
# Settings are not the installer's: uninstalling keeps them.
|
||||
mkdir -p "$XDG_CONFIG_HOME/proton-drive-linux"
|
||||
echo '{}' >"$XDG_CONFIG_HOME/proton-drive-linux/config.json"
|
||||
"$uninstaller" --uninstall --no-service >"$work/uninstall.log" 2>&1 ||
|
||||
{ cat "$work/uninstall.log" >&2; fail "uninstall failed"; }
|
||||
left="$(cd "$work/home" && find . -type f | sort)"
|
||||
[ "$left" = "./.config/proton-drive-linux/config.json" ] || fail "uninstall left files behind: $left"
|
||||
|
||||
echo "tarball OK: $(basename "$tarball")"
|
||||
@@ -13,9 +13,12 @@ crates/pdfs-gui/src/app/pages/photo_viewer.rs
|
||||
crates/pdfs-gui/src/app/pages/photos.rs
|
||||
crates/pdfs-gui/src/app/pages/places.rs
|
||||
crates/pdfs-gui/src/app/pages/places_map.rs
|
||||
crates/pdfs-gui/src/app/pages/preferences_apps.rs
|
||||
crates/pdfs-gui/src/app/pages/preferences_sync.rs
|
||||
crates/pdfs-gui/src/app/pages/shared.rs
|
||||
crates/pdfs-gui/src/app/pages/shared_by_me.rs
|
||||
crates/pdfs-gui/src/app/pages/status.rs
|
||||
crates/pdfs-gui/src/app/pages/sync_exclusions.rs
|
||||
crates/pdfs-gui/src/app/pages/takeout.rs
|
||||
crates/pdfs-gui/src/app/pages/trash.rs
|
||||
crates/pdfs-gui/src/app/pages/verify.rs
|
||||
@@ -23,6 +26,7 @@ crates/pdfs-gui/src/app/update.rs
|
||||
crates/pdfs-gui/src/app/widgets/compat.rs
|
||||
crates/pdfs-gui/src/app/widgets/details.rs
|
||||
crates/pdfs-gui/src/app/widgets/file_list.rs
|
||||
crates/pdfs-gui/src/app/widgets/ignore_dialog.rs
|
||||
crates/pdfs-gui/src/app/widgets/menu.rs
|
||||
crates/pdfs-gui/src/app/widgets/player.rs
|
||||
crates/pdfs-gui/src/app/widgets/share_dialog.rs
|
||||
|
||||
+981
-517
File diff suppressed because it is too large.
Load diff
+912
-469
File diff suppressed because it is too large.
Load diff
+944
-476
File diff suppressed because it is too large.
Load diff
+16
-4
@@ -16,7 +16,8 @@ Options:
|
||||
--out DIR where the PNGs go (default: images/)
|
||||
--only LIST capture only these, comma-separated (default: all of
|
||||
login,files,photos,photos_map,computers,sync,conflicts,
|
||||
prompt_gtk,prompt_fzf)
|
||||
prompt_gtk,prompt_fzf). preferences_sync and
|
||||
preferences_apps exist too, for pull requests only
|
||||
--website DIR afterwards, copy them into the website checkout at DIR
|
||||
with its scripts/sync-screenshots.sh
|
||||
--settle SECS how long a page gets to load before its capture (default 3)
|
||||
@@ -34,6 +35,8 @@ EOF
|
||||
|
||||
repo="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
all=login,files,photos,photos_map,computers,sync,conflicts,prompt_gtk,prompt_fzf
|
||||
# Not in the README, so not taken by default.
|
||||
extra=preferences_sync,preferences_apps
|
||||
|
||||
# The capture itself, run by cage inside the throwaway session (see below).
|
||||
if [[ "${1:-}" == --capture ]]; then
|
||||
@@ -66,7 +69,8 @@ if [[ "${1:-}" == --capture ]]; then
|
||||
app=$!
|
||||
sleep "$SETTLE"
|
||||
for shot in files:browser photos:gallery photos_map:places-map computers:devices \
|
||||
sync:sync-folders conflicts:activity; do
|
||||
sync:sync-folders conflicts:activity \
|
||||
preferences_sync:preferences-sync preferences_apps:preferences-apps; do
|
||||
name=${shot%%:*}
|
||||
wants "$name" || continue
|
||||
"$BIN/pdfs-app" --page "${shot#*:}"
|
||||
@@ -138,7 +142,7 @@ while (($#)); do
|
||||
shift
|
||||
done
|
||||
for shot in ${shots//,/ }; do
|
||||
[[ ",$all," == *",$shot,"* ]] || { echo "no screenshot called $shot" >&2; exit 2; }
|
||||
[[ ",$all,$extra," == *",$shot,"* ]] || { echo "no screenshot called $shot" >&2; exit 2; }
|
||||
done
|
||||
for tool in cage grim wlr-randr magick dbus-run-session gnome-keyring-daemon cargo curl; do
|
||||
command -v "$tool" >/dev/null || { echo "$tool is required" >&2; exit 2; }
|
||||
@@ -185,7 +189,15 @@ cat >"$root/config/proton-drive-linux/config.json" <<'EOF'
|
||||
"tray_hidden": true,
|
||||
"update_check": false,
|
||||
"online_map": false,
|
||||
"files_view": { "list": false }
|
||||
"files_view": { "list": false },
|
||||
"ignore_patterns": [".git/", "node_modules/", "target/", "*~", "*.swp", ".DS_Store",
|
||||
"*.iso", "build/", "*.sqlite-wal"],
|
||||
"open_with": {
|
||||
"rules": [
|
||||
{ "match": ["@text", "*.md"], "command": ["nvim"], "terminal": true },
|
||||
{ "match": ["@image"], "command": ["loupe"] }
|
||||
]
|
||||
}
|
||||
}
|
||||
EOF
|
||||
|
||||
|
||||
Reference in new issue
Block a user