diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index f8bb794..cfe001f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1,5 +1,5 @@
-# Pull requests and branch pushes: formatting, lints, tests, Nautilus extension.
-# Jobs: Nautilus extension and packaging checks; native libraries (.NET NativeAOT + Rust, cached
+# Pull requests and branch pushes: formatting, lints, tests, Nautilus extension, Dolphin plugins.
+# Jobs: Nautilus extension and packaging checks; Dolphin plugins; native libraries (.NET NativeAOT + Rust, cached
# on the revisions pinned in scripts/build-native.sh); Rust formatting, lints and tests.
name: ci
on:
@@ -19,6 +19,21 @@ jobs:
- run: for f in po/*.po; do msgfmt --check -o /dev/null "$f"; done
- run: scripts/check-version.sh
+ # The Dolphin plugins need KDE Frameworks 6, which Ubuntu 24.04 does not have: Debian 13 container
+ # (6.13, the target of the DEB package; it provides KOverlayIconPlugin in KIOCore).
+ dolphin-plugin:
+ runs-on: ubuntu-24.04
+ container: docker.io/library/debian:trixie
+ steps:
+ - run: |
+ apt-get update
+ apt-get install -y --no-install-recommends ca-certificates git g++ make cmake extra-cmake-modules \
+ libkf6kio-dev libkf6coreaddons-dev libkf6i18n-dev qt6-base-dev
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ - run: cmake -S integrations/dolphin -B build-dolphin -DCMAKE_BUILD_TYPE=Release
+ - run: cmake --build build-dolphin
+ - run: ls -l build-dolphin/bin/kf6/overlayicon/pdriveoverlay.so build-dolphin/bin/kf6/kfileitemaction/pdriveactions.so
+
# The two native libraries the Rust crates link against. A cache hit (same pinned revisions,
# runner image and .NET major version) skips the .NET build, which takes several minutes.
native:
diff --git a/.gitignore b/.gitignore
index c4df25f..516fd00 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,5 +2,6 @@
/third_party/
/native/linux-x64/
/extension/*.so
+/integrations/dolphin/build/
/dist/
/.superset/config.local.json
diff --git a/Cargo.lock b/Cargo.lock
index 24272ea..cf1bae4 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2758,7 +2758,10 @@ name = "pdrive"
version = "0.3.0"
dependencies = [
"anyhow",
+ "gio",
+ "glib",
"pdcore",
+ "pdi18n",
"pdsdk",
"tokio",
]
@@ -2776,6 +2779,7 @@ dependencies = [
"pdi18n",
"reqwest",
"serde",
+ "tempfile",
"tokio",
"toml_edit",
]
diff --git a/PLAN.md b/PLAN.md
index da09e5f..ed81642 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -171,6 +171,17 @@ Choix techniques (tranchés le 28/10/2026) :
- **Connexion :** sans session, l'application ne lance pas le daemon et sa fenêtre propose « Se connecter », qui exécute `pdrive login` (mention « application tierce non officielle » affichée dans la fenêtre), puis lance le daemon. « Se déconnecter » arrête le daemon puis exécute `pdrive logout`.
- **Icône :** dossier violet, à dessiner en SVG sans reprendre le logo Proton. Variantes : synchronisé, en cours de synchronisation, erreur, déconnecté. Elles sont installées dans le thème `hicolor` et transmises par nom (`IconName`) ; pas de repli en pixmap pour l'instant.
+### Intégration à Dolphin et à COSMIC Files (13/11/2026)
+
+Plan : ajouter Dolphin (KDE) et COSMIC Files à Nautilus, sans changer le daemon (l'API D-Bus `io.github.bpresles.PDrive1` suffisait) ni le bouton « Ouvrir le dossier » (il suit `mimeapps.list` via GIO). Un seul paquet contient l'extension Nautilus et les plugins Dolphin, sans dépendance vers KF6, Qt6 ni `libnautilus-extension` (une machine peut avoir plusieurs environnements) ; `Recommends: nautilus` est retiré, `Suggests: nautilus, dolphin` ajouté.
+
+- [x] CLI `pdrive keep-offline PATH...` et `pdrive free-up-space PATH...` (`crates/pdrive/src/offline.rs`) : chemins hors du montage ignorés, notification de bureau et code 1 si aucun n'est dans le drive ou si le daemon est absent ; page de manuel mise à jour.
+- [x] `crates/pdrive-app/src/integrations.rs`, appelé au démarrage et au changement de point de montage, selon les gestionnaires **installés** (jamais selon la session) : signet « Proton Drive » dans `user-places.xbel` (fichier existant seulement, marqueur `pdrive-for-linux `), favori et actions `context_actions` de COSMIC Files (RON édité comme du texte, entrées reconnues par leur commande `pdrive`). Écriture atomique, idempotente, limitée à nos entrées. Réglage `file_manager_integration` (actif par défaut, interrupteur dans les réglages, clé acceptée par le parseur strict du daemon), option `pdrive-app --remove-integrations` (appelée par `scripts/uninstall.sh`). Tests unitaires sur des chaînes et des dossiers temporaires.
+- [x] Plugins Dolphin C++ / KF6 (`integrations/dolphin/`) : `pdriveoverlay` (`KOverlayIconPlugin`, emblèmes, cache borné, appels D-Bus asynchrones) et `pdriveactions` (`KAbstractFileItemActionPlugin`, menus limités aux fichiers du drive). Textes du domaine gettext `pdrive` par `i18nd` ; `scripts/update-po.sh` extrait `i18nd`.
+- [x] Paquets : spec RPM (`__requires_exclude_from`), `debian/` (`dh_shlibdeps -X`, plus de `libnautilus-extension4` en `Depends`), PKGBUILD (`optdepends` `nautilus` et `dolphin`), `scripts/install-system.sh` (construit ce qui est détecté) et `uninstall.sh`, scripts de conteneur, job CI `dolphin-plugin` (Debian 13), README, `packaging/README.md`, pages de manuel.
+- Limites : pas d'emblèmes dans COSMIC Files (aucune API d'extension) et ses deux actions apparaissent sur tous les fichiers ; Nemo, Thunar et Caja non traités ; les paquets ne nettoient pas les fichiers de configuration de l'utilisateur à la désinstallation.
+- [ ] À tester à la main : COSMIC (favori, actions, notification hors drive, interrupteur), session KDE réelle (emblèmes, menus, entrée dans Emplacements, pas de second volume dans « Périphériques », icônes `emblem-pdrive-*` avec le thème Breeze), changement d'environnement sans réinstaller, installation du paquet sur une machine GNOME seule (ni KF6 ni Qt6 tirés).
+
## 3. Autres pistes (backlog)
- [ ] Fichiers « Partagés avec moi » (SDK : `EnumerateSharedWithMeNodeUids`), sous un sous-dossier dédié.
diff --git a/README.md b/README.md
index 14ffe0a..4796ad1 100644
--- a/README.md
+++ b/README.md
@@ -6,8 +6,9 @@
> Drive SDK and does not reuse any Proton logo.
PDrive for Linux gives Proton Drive a place in the Linux desktop: your "My files" folder is
-mounted at `~/ProtonDrive`, files are downloaded when you open them, and Nautilus (GNOME Files)
-shows their sync state, with a sidebar entry and a context menu.
+mounted at `~/ProtonDrive`, files are downloaded when you open them, and the file managers show
+it: Nautilus (GNOME Files) and Dolphin (KDE) show the sync state with a context menu, Dolphin and
+COSMIC Files list the drive in their sidebar (see [File managers](#file-managers)).
Status: early alpha (the application identifies itself to Proton with the `-alpha` channel).
@@ -32,6 +33,10 @@ Status: early alpha (the application identifies itself to Proton with the `-alph
files are dropped first, pinned files are kept).
- **Nautilus extension**: sync state emblems, and the context menu entries "Keep Available
Offline" and "Free Up Space". Open windows are reloaded when the drive is mounted.
+- **Dolphin plugins** (KDE Frameworks 6): the same emblems and context menu entries, plus a
+ "Proton Drive" entry in the places panel.
+- **COSMIC Files**: a favorite and two context menu actions ("PDrive: Keep Available Offline",
+ "PDrive: Free Up Space"). No emblems: COSMIC Files has no extension API.
- **Sidebar entry** through libcloudproviders, with a menu (show status, open in the browser,
mount / unmount).
- **Desktop application** (`pdrive-app`): tray icon, status window (account, used space,
@@ -45,7 +50,8 @@ Status: early alpha (the application identifies itself to Proton with the `-alph
on Fedora, already installed on Ubuntu); otherwise the status window is shown with an
explanation.
- **Translations** with gettext (French first, see `po/`).
-- **Command-line tool** `pdrive`: `login`, `logout`, `status`, `ls [PATH]`, `selftest`.
+- **Command-line tool** `pdrive`: `login`, `logout`, `status`, `ls [PATH]`, `keep-offline PATH...`,
+ `free-up-space PATH...`, `selftest`.
The session is kept in the Secret Service keyring (oo7, GNOME Keyring, KWallet, ...). The
sign-in goes through your browser: PDrive never sees your password. When Proton no longer
@@ -109,8 +115,12 @@ flowchart LR
`packaging/io.github.bpresles.PDrive.ini`.
- **`pdrive-app`** (GTK4 / libadwaita, application id `io.github.bpresles.PDrive.App`) runs and
watches the daemon and shows its state. The daemon stops when the application dies.
-- **The Nautilus extension** (`extension/`) asks the daemon over D-Bus for the state of the
- files it displays.
+- **The Nautilus extension** (`extension/`, C) and **the Dolphin plugins**
+ (`integrations/dolphin/`, C++ / KDE Frameworks 6) ask the daemon over D-Bus for the state of
+ the files they display. Nothing in the daemon is specific to a file manager.
+- **`pdrive-app`** also writes the sidebar entries and menu actions of Dolphin and COSMIC Files in
+ the configuration of the user (`crates/pdrive-app/src/integrations.rs`); COSMIC Files runs
+ `pdrive keep-offline` / `pdrive free-up-space`.
## Installation
@@ -130,8 +140,13 @@ flowchart LR
KDE Frameworks 6.14 (Fedora 44 has 6.31). Debian 13 has `kwallet6` 6.13, whose `kwalletd6`
only offers it as an option: enable it in the KDE Wallet settings ("Use KWallet for the
Secret Service interface") or use another provider.
-- For the Nautilus extension: the development files of `libnautilus-extension-4`
- (`nautilus-devel` on Fedora) and GTK 4.
+- Optional, one per file manager you want the plugins of: for the Nautilus extension, the
+ development files of `libnautilus-extension-4` (`nautilus-devel` on Fedora) and GTK 4; for the
+ Dolphin plugins, CMake, `extra-cmake-modules` and the development files of KDE Frameworks 6
+ KIO, KCoreAddons, KI18n and Qt 6 (`kf6-kio-devel kf6-kcoreaddons-devel kf6-ki18n-devel
+ qt6-qtbase-devel` on Fedora; `libkf6kio-dev libkf6coreaddons-dev libkf6i18n-dev qt6-base-dev`
+ on Debian 13). `scripts/install-system.sh` builds the ones it finds. COSMIC Files needs
+ nothing to build.
- On GNOME: the AppIndicator extension, for the tray icon (see above).
### From source
@@ -141,8 +156,8 @@ git clone https://github.com/bpresles/PDrive-for-Linux.git
cd PDrive-for-Linux
scripts/install.sh # as your user
-scripts/install-system.sh # Nautilus extension and sidebar, needs sudo
-nautilus -q # restart Nautilus to load the extension
+scripts/install-system.sh # Nautilus extension, Dolphin plugins and sidebar, needs sudo
+nautilus -q # restart Nautilus to load the extension (Dolphin: close it)
```
`scripts/install.sh` builds the native libraries if needed (`scripts/build-native.sh`, which
@@ -157,20 +172,60 @@ in release mode and installs, under your home directory:
- `~/.local/share/man/man1/`: manual pages `pdrive(1)`, `pdrived(1)` and `pdrive-app(1)`.
`~/.local/bin` must be in your `PATH` to run the commands from a terminal. `scripts/install-system.sh`
-builds the Nautilus extension and installs it in the extension directory of Nautilus, the
-sidebar declaration in `/usr/local/share/cloud-providers/` and the translations of the
-extension in `/usr/local/share/locale/`. It needs `sudo` because Nautilus and libcloudproviders
-only read system directories.
+builds the Nautilus extension (if `libnautilus-extension-4` is found) and installs it in the
+extension directory of Nautilus, builds the Dolphin plugins (if CMake finds KDE Frameworks 6 KIO)
+and installs them in the Qt 6 plugin directory of the system, and installs the sidebar declaration
+in `/usr/local/share/cloud-providers/` and the translations in `/usr/local/share/locale/`. It
+needs `sudo` because Nautilus, Dolphin and libcloudproviders only read system directories.
### First start
1. Start **PDrive** from the applications menu (or run `pdrive-app`).
2. Click "Sign in": your browser opens for the Proton sign-in (the window mentions that this
is an unofficial client). `pdrive login` does the same from a terminal.
-3. The daemon mounts the drive at `~/ProtonDrive`; it is also in the Nautilus sidebar.
+3. The daemon mounts the drive at `~/ProtonDrive`; it is also in the sidebar of the file managers
+ (see below).
4. After the first sign-in, the application offers to start at login. You can change it in the
settings (it creates `~/.config/autostart/io.github.bpresles.PDrive.App.desktop`).
+### File managers
+
+One installation serves every desktop of the machine: a package (or `install-system.sh`) installs
+the plugin of each file manager, and each plugin is only loaded by its own file manager, so
+switching between GNOME, KDE and COSMIC sessions needs nothing more. The packages require none of
+them (`Suggests: nautilus, dolphin`) and pull no KDE or GNOME library.
+
+| | Nautilus (GNOME) | Dolphin (KDE Plasma) | COSMIC Files |
+|---|---|---|---|
+| Sync state emblems | yes (extension) | yes (`KOverlayIconPlugin`) | no: no extension API |
+| "Keep Available Offline" / "Free Up Space" | file menu | file menu, only on drive files | file menu, on **every** file (see below) |
+| Sidebar entry | libcloudproviders (system-wide) | "Proton Drive" in Places (`user-places.xbel`) | favorite |
+
+`pdrive-app` sets up the Dolphin places entry and the COSMIC Files favorite and actions in your
+own configuration (a package cannot write it), at every start, according to the file managers
+**installed**, not to the session you are running: with COSMIC and Dolphin both installed, the
+Dolphin entry is added from a COSMIC session too. A file manager installed later is taken into
+account at the next start of `pdrive-app`.
+
+- Dolphin: `$XDG_DATA_HOME/user-places.xbel` is only changed if it exists (Dolphin creates it at
+ its first start), with a marker so that only our entry is touched.
+- COSMIC Files (when `com.system76.CosmicFiles.desktop` is installed):
+ `~/.config/cosmic/com.system76.CosmicFiles/v1/favorites` and `.../context_actions`. COSMIC Files
+ cannot limit an action to a folder: "PDrive: Keep Available Offline" and "PDrive: Free Up Space"
+ appear on every file, and run `pdrive keep-offline` / `pdrive free-up-space`, which ignore paths
+ outside the drive and say so in a notification. If `pdrive` is not in the `PATH` of the session
+ (for example `~/.local/bin`), the actions use its full path. The favorite is recognised by the
+ mount point: turning the integration off removes it, even if you had added it by hand.
+- The switch "Add PDrive to the file managers (sidebar, menus)" in the settings
+ (`file_manager_integration`, on by default) removes these entries when turned off.
+ `pdrive-app --remove-integrations` removes them and exits (`scripts/uninstall.sh` runs it).
+ Removing a package does not touch your configuration files: run it first.
+- Nautilus is unchanged: no bookmark is added, its sidebar entry comes from libcloudproviders.
+- The "Open folder" button opens the folder with the default application of your system, as
+ before.
+- Not available: emblems in COSMIC Files (no API), Nemo, Thunar, Caja. The AppImage contains
+ none of the plugins (they live in system directories), like the Nautilus extension.
+
### Packages
RPM and DEB packages are meant to be published with the releases of the repository:
@@ -190,6 +245,8 @@ mountpoint = "~/ProtonDrive"
cache_size_gib = 10
# Whether launching pdrive-app opens its status window (read by pdrive-app only).
show_window_at_startup = true
+# Whether pdrive-app adds the drive to the file managers (Dolphin, COSMIC Files).
+file_manager_integration = true
```
| Key | Default | Meaning |
@@ -197,6 +254,7 @@ show_window_at_startup = true
| `mountpoint` | `"~/ProtonDrive"` | Folder where the drive appears (a symbolic link to the hidden real mount). |
| `cache_size_gib` | `10` | Size limit of the cache of downloaded files, in GiB. |
| `show_window_at_startup` | `true` | Open the status window when `pdrive-app` is started by hand. It is never opened with `--background` (start at login). |
+| `file_manager_integration` | `true` | Add the drive to the sidebar and menus of Dolphin and COSMIC Files (switch in the settings; see [File managers](#file-managers)). |
Other locations: the content cache and the pending uploads are under `~/.cache/pdrive/`; the
hidden mount and the list of pinned files (`pinned.json`) are under `~/.local/share/pdrive/`. Setting `PDRIVE_VERBOSE=1`
@@ -220,7 +278,9 @@ Without a journal, the log is `$XDG_STATE_HOME/pdrive/pdrive.log` (by default
- Files "Shared with me" and Photos are not handled.
- `O_NOATIME` is refused on files that are not in the cache.
- Deleting a file moves it directly to the Proton trash, not to the Nautilus trash.
-- Rendering on KDE and GNOME, and the translated Nautilus menus, still need more real-world testing.
+- Rendering on KDE and GNOME, and the translated Nautilus and Dolphin menus, still need more real-world testing.
+- COSMIC Files shows no state emblems (no extension API), and its two PDrive actions appear on every
+ file (they do nothing outside the drive).
- Keep a single Secret Service on the desktop. With two of them installed (for example GNOME
Keyring and oo7), whichever starts first at login answers, each with its own copy of the
session; Proton renews the session regularly and refuses the outdated copy, which then asks
@@ -236,7 +296,8 @@ the files of an RPM or DEB package. The equivalent by hand, after quitting PDriv
menu (it unmounts the drive):
```sh
-# User files
+# User files (first remove the entries added to Dolphin and COSMIC Files)
+pdrive-app --remove-integrations
rm -f ~/.local/bin/{pdrive-app,pdrived,pdrive}
rm -rf ~/.local/lib/pdrive
rm -f ~/.local/share/applications/io.github.bpresles.PDrive.App.desktop
@@ -247,11 +308,15 @@ rm -f ~/.local/share/man/man1/{pdrive,pdrived,pdrive-app}.1
# System files
sudo rm -f "$(pkg-config --variable=extensiondir libnautilus-extension-4)/libpdrive-nautilus.so"
+sudo rm -f "$(qtpaths6 --query QT_INSTALL_PLUGINS)"/kf6/{overlayicon/pdriveoverlay,kfileitemaction/pdriveactions}.so
sudo rm -f /usr/local/share/cloud-providers/io.github.bpresles.PDrive.ini
sudo rm -f /usr/local/share/locale/*/LC_MESSAGES/pdrive.mo
-nautilus -q
+nautilus -q # and close Dolphin
```
+With a package installation, run `pdrive-app --remove-integrations` before removing the package:
+the package does not touch your configuration files.
+
Your data: `pdrive logout` first removes the session from the keyring and revokes it. Then,
if you want, delete `~/.config/pdrive/`, `~/.cache/pdrive/` (note: this loses uploads still
pending) and `~/.local/share/pdrive/`. Files stored in Proton Drive are not affected.
diff --git a/crates/pdrive-app/Cargo.toml b/crates/pdrive-app/Cargo.toml
index df61a80..cdf59e1 100644
--- a/crates/pdrive-app/Cargo.toml
+++ b/crates/pdrive-app/Cargo.toml
@@ -17,3 +17,6 @@ toml_edit = "0.25"
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "json"] }
serde = { version = "1", features = ["derive"] }
libc = "0.2"
+
+[dev-dependencies]
+tempfile = "3.27.0"
diff --git a/crates/pdrive-app/src/config.rs b/crates/pdrive-app/src/config.rs
index e4c17e1..8e90fdb 100644
--- a/crates/pdrive-app/src/config.rs
+++ b/crates/pdrive-app/src/config.rs
@@ -26,13 +26,21 @@ fn home() -> PathBuf {
std::env::var_os("HOME").map(PathBuf::from).unwrap_or_default()
}
-fn config_home() -> PathBuf {
+pub fn config_home() -> PathBuf {
match std::env::var_os("XDG_CONFIG_HOME") {
Some(dir) if !dir.is_empty() && Path::new(&dir).is_absolute() => PathBuf::from(dir),
_ => home().join(".config"),
}
}
+/// `$XDG_DATA_HOME`, `~/.local/share` by default.
+pub fn data_home() -> PathBuf {
+ match std::env::var_os("XDG_DATA_HOME") {
+ Some(dir) if !dir.is_empty() && Path::new(&dir).is_absolute() => PathBuf::from(dir),
+ _ => home().join(".local/share"),
+ }
+}
+
fn settings_path() -> PathBuf {
config_home().join("pdrive").join("config.toml")
}
@@ -101,6 +109,21 @@ pub fn set_show_window_at_startup(show: bool) -> Result<()> {
write_document(&document)
}
+/// Whether the drive is added to the file managers (see `integrations.rs`); on by default.
+pub fn file_manager_integration() -> bool {
+ integration_of(&read_document())
+}
+
+fn integration_of(document: &DocumentMut) -> bool {
+ document.get("file_manager_integration").and_then(|v| v.as_bool()).unwrap_or(true)
+}
+
+pub fn set_file_manager_integration(enabled: bool) -> Result<()> {
+ let mut document = read_document();
+ set(&mut document, "file_manager_integration", Value::from(enabled));
+ write_document(&document)
+}
+
/// Expands a leading "~" to the home folder.
pub fn expand_home(path: &str) -> PathBuf {
match path.strip_prefix('~') {
@@ -179,6 +202,17 @@ mod tests {
assert!(show_window_of(&parse("show_window_at_startup = \"no\"\n")));
}
+ #[test]
+ fn file_manager_integration_defaults_to_true_and_reads_false() {
+ assert!(integration_of(&parse("")));
+ assert!(!integration_of(&parse("file_manager_integration = false\n")));
+ assert!(integration_of(&parse("file_manager_integration = \"no\"\n")));
+ let mut document = parse(COMMENTED);
+ set(&mut document, "file_manager_integration", Value::from(false));
+ assert!(document.to_string().starts_with(COMMENTED));
+ assert!(!integration_of(&parse(&document.to_string())));
+ }
+
#[test]
fn reads_integer_and_float_sizes() {
assert_eq!(settings_of(&parse("cache_size_gib = 4\n")).cache_size_gib, 4.0);
diff --git a/crates/pdrive-app/src/integrations.rs b/crates/pdrive-app/src/integrations.rs
new file mode 100644
index 0000000..c604817
--- /dev/null
+++ b/crates/pdrive-app/src/integrations.rs
@@ -0,0 +1,761 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 Bertrand Presles
+//! Integration of the drive in the file managers, through the user's own configuration files
+//! (a package cannot write them):
+//!
+//! - Dolphin (and the KDE file dialogs): an "Proton Drive" entry in `user-places.xbel`, marked
+//! with `pdrive-for-linux `. Only an existing file is changed: KDE would stop adding
+//! its default places to a file made by someone else.
+//! - COSMIC Files: a favorite (`Path("…")`) and two context-menu actions running
+//! `pdrive keep-offline` / `pdrive free-up-space` (see `crates/pdrive/src/offline.rs`), only
+//! when `com.system76.CosmicFiles.desktop` is installed. The RON files are edited as text:
+//! a round trip through a RON value would lose the enum variants such as `Path("…")`.
+//!
+//! What is installed decides, never the current session: both are set up on a machine that
+//! has both file managers, whatever desktop runs now. Everything is idempotent, only touches
+//! the entries recognised as ours (the XBEL marker, the `pdrive` command of an action, the
+//! mount point of a favorite), keeps the rest of the files as they are and writes only when
+//! the content changes, atomically.
+//! Nautilus needs nothing here: its sidebar entry comes from libcloudproviders.
+
+use std::ops::Range;
+use std::path::{Path, PathBuf};
+
+use anyhow::{Context, Result, anyhow};
+use pdi18n::tr;
+
+use crate::config;
+use crate::supervisor::program;
+
+const XBEL_MARKER: &str = "pdrive-for-linux ";
+const XBEL_TITLE: &str = "Proton Drive";
+const XBEL_ICON: &str = config::APP_ID;
+const COSMIC_FILES_DESKTOP: &str = "com.system76.CosmicFiles.desktop";
+const COSMIC_CONFIG: &str = "cosmic/com.system76.CosmicFiles/v1";
+const COSMIC_DEFAULT_FAVORITES: [&str; 6] = ["Home", "Documents", "Downloads", "Music", "Pictures", "Videos"];
+
+/// Where things are: the XDG directories of the user and the system.
+#[derive(Clone, Debug)]
+pub struct Env {
+ pub data_home: PathBuf,
+ pub data_dirs: Vec,
+ pub config_home: PathBuf,
+}
+
+impl Env {
+ pub fn from_process() -> Self {
+ let data_dirs = match std::env::var("XDG_DATA_DIRS") {
+ Ok(dirs) if !dirs.is_empty() => dirs.split(':').map(PathBuf::from).collect(),
+ _ => vec![PathBuf::from("/usr/local/share"), PathBuf::from("/usr/share")],
+ };
+ Self { data_home: config::data_home(), data_dirs, config_home: config::config_home() }
+ }
+
+ fn desktop_file_installed(&self, id: &str) -> bool {
+ std::iter::once(&self.data_home).chain(&self.data_dirs).any(|dir| dir.join("applications").join(id).is_file())
+ }
+
+ fn xbel(&self) -> PathBuf {
+ self.data_home.join("user-places.xbel")
+ }
+
+ fn cosmic_dir(&self) -> PathBuf {
+ self.config_home.join(COSMIC_CONFIG)
+ }
+}
+
+/// The two context-menu actions, with their names in the language of the user.
+pub struct Actions {
+ pub keep_name: String,
+ pub free_name: String,
+ /// The `pdrive` command: `pdrive` when the PATH of the session finds it, else its full path.
+ pub command: String,
+}
+
+impl Actions {
+ pub fn current() -> Self {
+ Self { keep_name: tr("PDrive: Keep Available Offline"), free_name: tr("PDrive: Free Up Space"), command: pdrive_command() }
+ }
+
+ fn entries(&self) -> [(Subcommand, String); 2] {
+ [(Subcommand::KeepOffline, self.entry(Subcommand::KeepOffline)), (Subcommand::FreeUpSpace, self.entry(Subcommand::FreeUpSpace))]
+ }
+
+ fn entry(&self, subcommand: Subcommand) -> String {
+ let (name, word) = match subcommand {
+ Subcommand::KeepOffline => (&self.keep_name, "keep-offline"),
+ Subcommand::FreeUpSpace => (&self.free_name, "free-up-space"),
+ };
+ let line = format!("{} {word} %F", quote_word(&self.command));
+ format!("(name: {}, confirm: false, selection: Any, steps: [{}])", ron_string(name), ron_string(&line))
+ }
+}
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+enum Subcommand {
+ KeepOffline,
+ FreeUpSpace,
+}
+
+/// `pdrive` when the PATH finds an executable of that name, else the one installed next to
+/// this program (`~/.local/bin` is not always in the PATH of a graphical session).
+fn pdrive_command() -> String {
+ let in_path = std::env::var_os("PATH").is_some_and(|path| std::env::split_paths(&path).any(|dir| is_executable(&dir.join("pdrive"))));
+ let next_to_us = program("pdrive");
+ if in_path || !next_to_us.is_absolute() { "pdrive".to_owned() } else { next_to_us.to_string_lossy().into_owned() }
+}
+
+fn is_executable(path: &Path) -> bool {
+ use std::os::unix::fs::PermissionsExt;
+ path.metadata().is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
+}
+
+/// Sets the integrations up (`enabled`) or removes them. `old_mount` is the previous mount
+/// point, when it changed: its favorite is removed. Returns the errors, one per file manager:
+/// a failure of one does not prevent the others.
+pub fn apply(env: &Env, enabled: bool, old_mount: Option<&Path>, mount: &Path, actions: &Actions) -> Vec {
+ let mut errors = Vec::new();
+ if let Err(e) = apply_dolphin(env, enabled, mount) {
+ errors.push(e.context("Dolphin places"));
+ }
+ if let Err(e) = apply_cosmic(env, enabled, old_mount, mount, actions) {
+ errors.push(e.context("COSMIC Files"));
+ }
+ errors
+}
+
+/// Applies the setting `file_manager_integration` for the current mount point (used at startup
+/// and when the setting changes).
+pub fn apply_from_settings() -> Vec {
+ let (env, mount) = (Env::from_process(), config::expand_home(&config::load().mountpoint));
+ apply(&env, config::file_manager_integration(), None, &mount, &Actions::current())
+}
+
+/// The mount point setting changed (`old` and `new` as written in the settings): the entries
+/// follow it, when enabled.
+pub fn mount_point_changed(old: &str, new: &str) -> Vec {
+ if !config::file_manager_integration() {
+ return Vec::new();
+ }
+ let (old, new) = (config::expand_home(old), config::expand_home(new));
+ apply(&Env::from_process(), true, Some(&old), &new, &Actions::current())
+}
+
+/// `pdrive-app --remove-integrations`: removes the entries whatever the setting is.
+pub fn remove_all() -> bool {
+ let (env, mount) = (Env::from_process(), config::expand_home(&config::load().mountpoint));
+ let errors = apply(&env, false, None, &mount, &Actions::current());
+ let ok = errors.is_empty();
+ report(errors);
+ ok
+}
+
+pub fn report(errors: Vec) {
+ for error in errors {
+ eprintln!("file manager integration: {error:#}");
+ }
+}
+
+fn apply_dolphin(env: &Env, enabled: bool, mount: &Path) -> Result<()> {
+ // No file, nothing to do (and nothing to remove): retried at the next start.
+ update_file(&env.xbel(), false, |text| {
+ let text = text.expect("the file exists");
+ Ok(if enabled { xbel_add(text, mount) } else { xbel_remove(text) })
+ })
+}
+
+fn apply_cosmic(env: &Env, enabled: bool, old_mount: Option<&Path>, mount: &Path, actions: &Actions) -> Result<()> {
+ // Disabling cleans what may have been written even if the application was removed since.
+ if enabled && !env.desktop_file_installed(COSMIC_FILES_DESKTOP) {
+ return Ok(());
+ }
+ let dir = env.cosmic_dir();
+ let favorites = update_file(&dir.join("favorites"), enabled, |text| favorites_sync(text, enabled, old_mount, mount));
+ let context = update_file(&dir.join("context_actions"), enabled, |text| context_actions_sync(text, enabled, actions));
+ favorites.and(context)
+}
+
+/// Reads `path`, lets `change` compute the new content (`None`: unchanged) and writes it
+/// atomically. A missing file is passed as `None` when `create` is set, else it is skipped.
+fn update_file(path: &Path, create: bool, change: impl FnOnce(Option<&str>) -> Result>) -> Result<()> {
+ // Dotfile managers link these files: the link is kept, its target is replaced.
+ let real = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_owned());
+ let text = match std::fs::read_to_string(&real) {
+ Ok(text) => Some(text),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
+ Err(e) => return Err(anyhow!(e).context(format!("cannot read {}", path.display()))),
+ };
+ if text.is_none() && !create {
+ return Ok(());
+ }
+ let Some(new) = change(text.as_deref()).with_context(|| format!("cannot update {}", path.display()))? else { return Ok(()) };
+ if text.as_deref() == Some(new.as_str()) {
+ return Ok(());
+ }
+ write_atomically(&real, &new).with_context(|| format!("cannot write {}", path.display()))
+}
+
+fn write_atomically(path: &Path, content: &str) -> Result<()> {
+ let parent = path.parent().context("no parent directory")?;
+ std::fs::create_dir_all(parent)?;
+ let name = path.file_name().context("no file name")?.to_string_lossy();
+ let temporary = parent.join(format!(".{name}.pdrive-{}.tmp", std::process::id()));
+ let written = std::fs::write(&temporary, content).and_then(|()| {
+ if let Ok(metadata) = std::fs::metadata(path) {
+ let _ = std::fs::set_permissions(&temporary, metadata.permissions());
+ }
+ std::fs::rename(&temporary, path)
+ });
+ if written.is_err() {
+ let _ = std::fs::remove_file(&temporary);
+ }
+ Ok(written?)
+}
+
+// ---------------------------------------------------------------------------------------------
+// XBEL (KDE places)
+// ---------------------------------------------------------------------------------------------
+
+/// `file://` URI with the bytes other than unreserved characters and `/` percent-encoded.
+fn file_uri(path: &Path) -> String {
+ use std::os::unix::ffi::OsStrExt;
+ let mut uri = String::from("file://");
+ for &byte in path.as_os_str().as_bytes() {
+ if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~' | b'/') {
+ uri.push(byte as char);
+ } else {
+ uri.push_str(&format!("%{byte:02X}"));
+ }
+ }
+ uri
+}
+
+fn xbel_bookmark(href: &str) -> String {
+ format!(
+ " \n {XBEL_TITLE} \n \n \n \n \n \n {XBEL_MARKER}\n false \n \n \n \n"
+ )
+}
+
+/// The `` element (whole lines) that holds our marker.
+fn xbel_element(text: &str) -> Option> {
+ let marker = text.find(XBEL_MARKER)?;
+ // "")? + " ".len();
+ let start = text[..open].rfind('\n').map_or(0, |i| i + 1);
+ let end = text[close..].find('\n').map_or(text.len(), |i| close + i + 1);
+ Some(start..end)
+}
+
+/// Adds the entry, or only follows a new mount point in the existing one (so that what the user
+/// changed in Dolphin, such as hiding it, stays). `None` when nothing changes or the text is
+/// not an XBEL file.
+fn xbel_add(text: &str, mount: &Path) -> Option {
+ let href = file_uri(mount);
+ if let Some(range) = xbel_element(text) {
+ let element = &text[range.clone()];
+ let marker = element.find("href=\"")? + "href=\"".len();
+ let end = marker + element[marker..].find('"')?;
+ if element[marker..end] == href {
+ return None;
+ }
+ return Some(format!("{}{}{}{}{}", &text[..range.start], &element[..marker], href, &element[end..], &text[range.end..]));
+ }
+ let close = text.rfind("")?;
+ let separator = if close == 0 || text[..close].ends_with('\n') { "" } else { "\n" };
+ Some(format!("{}{separator}{}{}", &text[..close], xbel_bookmark(&href), &text[close..]))
+}
+
+fn xbel_remove(text: &str) -> Option {
+ let range = xbel_element(text)?;
+ Some(format!("{}{}", &text[..range.start], &text[range.end..]))
+}
+
+// ---------------------------------------------------------------------------------------------
+// COSMIC Files (RON, edited as text)
+// ---------------------------------------------------------------------------------------------
+
+fn ron_string(text: &str) -> String {
+ format!("\"{}\"", text.replace('\\', "\\\\").replace('"', "\\\""))
+}
+
+/// The word as a shell-like command line wants it: quoted when it holds a space or a quote.
+fn quote_word(word: &str) -> String {
+ if word.chars().any(|c| c.is_whitespace() || c == '"' || c == '\\' || c == '\'') {
+ format!("\"{}\"", word.replace('\\', "\\\\").replace('"', "\\\""))
+ } else {
+ word.to_owned()
+ }
+}
+
+/// Splits a command line on spaces, `"…"` grouping words (with `\` escapes inside).
+fn split_command(line: &str) -> Vec {
+ let (mut words, mut word, mut quoted, mut started) = (Vec::new(), String::new(), false, false);
+ let mut chars = line.chars();
+ while let Some(c) = chars.next() {
+ match c {
+ '"' => {
+ quoted = !quoted;
+ started = true;
+ }
+ '\\' if quoted => word.extend(chars.next()),
+ c if c.is_whitespace() && !quoted => {
+ if started {
+ words.push(std::mem::take(&mut word));
+ started = false;
+ }
+ }
+ c => {
+ word.push(c);
+ started = true;
+ }
+ }
+ }
+ if started {
+ words.push(word);
+ }
+ words
+}
+
+/// The string literals of a RON fragment, unescaped.
+fn ron_strings(fragment: &str) -> Vec {
+ let (mut strings, mut current, mut inside) = (Vec::new(), String::new(), false);
+ let mut chars = fragment.chars();
+ while let Some(c) = chars.next() {
+ match (inside, c) {
+ (false, '"') => inside = true,
+ (true, '"') => {
+ inside = false;
+ strings.push(std::mem::take(&mut current));
+ }
+ (true, '\\') => current.extend(chars.next()),
+ (true, c) => current.push(c),
+ _ => {}
+ }
+ }
+ strings
+}
+
+/// The action of one `context_actions` element when it runs our `pdrive` command.
+fn recognise(group: &str) -> Option {
+ // Only the command lines (`steps`), not the name.
+ let steps = &group[group.find("steps:")?..];
+ ron_strings(steps).iter().find_map(|line| {
+ let words = split_command(line);
+ let program = Path::new(words.first()?).file_name()?;
+ if program != "pdrive" {
+ return None;
+ }
+ match words.get(1)?.as_str() {
+ "keep-offline" => Some(Subcommand::KeepOffline),
+ "free-up-space" => Some(Subcommand::FreeUpSpace),
+ _ => None,
+ }
+ })
+}
+
+/// Positions of the `[` and the `]` that delimit the list of a RON file (the `]` is the last
+/// character that is not whitespace), skipping strings and comments.
+fn list_bounds(text: &str) -> Option<(usize, usize)> {
+ let open = scan(text, 0..text.len(), |_, c, _| c == '[').first().map(|(i, _)| *i)?;
+ let close = text.trim_end().len().checked_sub(1).filter(|&i| text.as_bytes()[i] == b']' && i > open)?;
+ Some((open, close))
+}
+
+/// Calls `visit(index, char, depth)` for each character outside strings and `//` comments, with
+/// the nesting depth of `([{` before it; returns those for which `visit` is true.
+fn scan(text: &str, range: Range, mut visit: impl FnMut(usize, char, usize) -> bool) -> Vec<(usize, char)> {
+ let (mut found, mut depth, mut in_string, mut escaped, mut comment) = (Vec::new(), 0usize, false, false, false);
+ let mut previous_slash = false;
+ for (offset, c) in text[range.clone()].char_indices() {
+ let index = range.start + offset;
+ if comment {
+ comment = c != '\n';
+ continue;
+ }
+ if in_string {
+ match (escaped, c) {
+ (true, _) => escaped = false,
+ (false, '\\') => escaped = true,
+ (false, '"') => in_string = false,
+ _ => {}
+ }
+ continue;
+ }
+ if c == '/' && previous_slash {
+ comment = true;
+ previous_slash = false;
+ continue;
+ }
+ previous_slash = c == '/';
+ if c == '"' {
+ in_string = true;
+ continue;
+ }
+ if visit(index, c, depth) {
+ found.push((index, c));
+ }
+ match c {
+ '(' | '[' | '{' => depth += 1,
+ ')' | ']' | '}' => depth = depth.saturating_sub(1),
+ _ => {}
+ }
+ }
+ found
+}
+
+/// The bare `( … )` elements of the list, as byte ranges.
+fn list_groups(text: &str, open: usize, close: usize) -> Vec> {
+ let starts = scan(text, open + 1..close, |_, c, depth| c == '(' && depth == 0);
+ let ends = scan(text, open + 1..close, |_, c, depth| c == ')' && depth == 1);
+ starts.iter().zip(&ends).map(|((start, _), (end, _))| *start..*end + 1).collect()
+}
+
+/// Appends an element at the end of the list.
+fn list_append(text: &str, item: &str) -> Result {
+ let (_, close) = list_bounds(text).context("not a list")?;
+ let head = text[..close].trim_end();
+ let comma = if head.ends_with(',') || head.ends_with('[') { "" } else { "," };
+ Ok(format!("{head}{comma}\n {item},\n{}", &text[close..]))
+}
+
+/// Removes the range with the whole line(s) it takes, its comma included.
+fn remove_element(text: &mut String, range: Range) {
+ let start = text[..range.start].rfind('\n').map_or(0, |i| i + 1);
+ let alone_before = text[start..range.start].trim().is_empty();
+ let mut end = range.end;
+ if text[end..].starts_with(',') {
+ end += 1;
+ }
+ let rest = &text[end..];
+ let line_rest = rest.find('\n').unwrap_or(rest.len());
+ if alone_before && rest[..line_rest].trim().is_empty() {
+ end += (line_rest + 1).min(rest.len());
+ text.replace_range(start..end, "");
+ } else {
+ text.replace_range(range.start..end, "");
+ }
+}
+
+fn favorite_entry(path: &Path) -> String {
+ format!("Path({})", ron_string(&path.to_string_lossy()))
+}
+
+fn favorites_sync(text: Option<&str>, enabled: bool, old_mount: Option<&Path>, mount: &Path) -> Result> {
+ let entry = favorite_entry(mount);
+ let Some(text) = text else {
+ if !enabled {
+ return Ok(None);
+ }
+ let defaults: String = COSMIC_DEFAULT_FAVORITES.iter().map(|name| format!(" {name},\n")).collect();
+ return Ok(Some(format!("[\n{defaults} {entry},\n]")));
+ };
+ list_bounds(text).context("not a list")?;
+ let mut text = text.to_owned();
+ for old in old_mount.into_iter().filter(|old| *old != mount) {
+ text = without_lines(&text, &favorite_entry(old));
+ }
+ if !enabled {
+ return Ok(Some(without_lines(&text, &entry)));
+ }
+ if !text.contains(&entry) {
+ text = list_append(&text, &entry)?;
+ }
+ Ok(Some(text))
+}
+
+/// The text without the lines that only hold `entry` (with or without its comma).
+fn without_lines(text: &str, entry: &str) -> String {
+ text.split_inclusive('\n').filter(|line| line.trim().trim_end_matches(',') != entry).collect()
+}
+
+fn context_actions_sync(text: Option<&str>, enabled: bool, actions: &Actions) -> Result > {
+ let wanted = actions.entries();
+ let Some(text) = text else {
+ if !enabled {
+ return Ok(None);
+ }
+ let items: String = wanted.iter().map(|(_, entry)| format!(" {entry},\n")).collect();
+ return Ok(Some(format!("[\n{items}]")));
+ };
+ let (open, close) = list_bounds(text).context("not a list")?;
+ let mut text = text.to_owned();
+ // Existing elements of ours, from the end so that the ranges stay valid.
+ let mut present = Vec::new();
+ for range in list_groups(&text, open, close).into_iter().rev() {
+ let Some(subcommand) = recognise(&text[range.clone()]) else { continue };
+ let entry = &wanted.iter().find(|(s, _)| *s == subcommand).expect("both subcommands").1;
+ // Kept (and updated) once per action; the extra copies and all of them when disabled go.
+ if enabled && !present.contains(&subcommand) {
+ present.push(subcommand);
+ if &text[range.clone()] != entry {
+ text.replace_range(range, entry);
+ }
+ } else {
+ remove_element(&mut text, range);
+ }
+ }
+ if enabled {
+ for (subcommand, entry) in &wanted {
+ if !present.contains(subcommand) {
+ text = list_append(&text, entry)?;
+ }
+ }
+ }
+ Ok(Some(text))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn mount() -> PathBuf {
+ PathBuf::from("/home/u/ProtonDrive")
+ }
+
+ fn actions() -> Actions {
+ Actions { keep_name: "PDrive: Keep Available Offline".into(), free_name: "PDrive: Free Up Space".into(), command: "pdrive".into() }
+ }
+
+ const XBEL: &str = "\n\n\n \n \n 4 \n \n \n \n Home \n \n \n \n \n \n 1/0 \n true \n \n \n \n \n";
+
+ // XBEL
+
+ #[test]
+ fn xbel_entry_is_added_before_the_end_and_keeps_the_rest() {
+ let added = xbel_add(XBEL, &mount()).unwrap();
+ assert!(added.starts_with(&XBEL[..XBEL.len() - "\n".len()]));
+ assert!(added.ends_with(" \n\n"));
+ assert!(added.contains(""));
+ assert!(added.contains("Proton Drive "));
+ assert!(added.contains(""));
+ assert_eq!(added.matches(XBEL_MARKER).count(), 1);
+ assert_eq!(added.matches("false", "true \n false");
+ let moved = xbel_add(&added, Path::new("/mnt/Mon Drive")).unwrap();
+ assert!(moved.contains(""));
+ assert!(moved.contains("true "));
+ assert_eq!(moved.matches(XBEL_MARKER).count(), 1);
+ assert_eq!(moved.replace("Mon%20Drive", "ProtonDrive").replace("/mnt/", "/home/u/"), added);
+ }
+
+ #[test]
+ fn xbel_without_end_tag_is_left_alone() {
+ assert_eq!(xbel_add("not xml", &mount()), None);
+ }
+
+ #[test]
+ fn file_uri_encodes_unusual_bytes() {
+ assert_eq!(file_uri(Path::new("/home/é u/a&b")), "file:///home/%C3%A9%20u/a%26b");
+ }
+
+ // RON helpers
+
+ #[test]
+ fn command_lines_round_trip() {
+ assert_eq!(quote_word("pdrive"), "pdrive");
+ assert_eq!(quote_word("/home/a b/pdrive"), "\"/home/a b/pdrive\"");
+ assert_eq!(split_command("\"/home/a b/pdrive\" keep-offline %F"), ["/home/a b/pdrive", "keep-offline", "%F"]);
+ assert_eq!(ron_strings(r#"(name: "a \"b\"", steps: ["x y"])"#), ["a \"b\"", "x y"]);
+ }
+
+ #[test]
+ fn our_actions_are_recognised_by_their_command() {
+ assert_eq!(recognise(r#"(name: "x", steps: ["pdrive keep-offline %F"])"#), Some(Subcommand::KeepOffline));
+ assert_eq!(recognise(r#"(name: "x", steps: ["/opt/b/pdrive free-up-space %F"])"#), Some(Subcommand::FreeUpSpace));
+ assert_eq!(recognise(r#"(name: "pdrive keep-offline", steps: ["echo %F"])"#), None);
+ assert_eq!(recognise(r#"(name: "x", steps: ["other keep-offline %F"])"#), None);
+ }
+
+ // favorites
+
+ const FAVORITES: &str = "[\n Home,\n Documents,\n Path(\"/mnt/data\"),\n Path(\"/a]b\"),\n]";
+
+ #[test]
+ fn favorite_is_appended_once_and_removed() {
+ let added = favorites_sync(Some(FAVORITES), true, None, &mount()).unwrap().unwrap();
+ assert_eq!(added, "[\n Home,\n Documents,\n Path(\"/mnt/data\"),\n Path(\"/a]b\"),\n Path(\"/home/u/ProtonDrive\"),\n]");
+ assert_eq!(favorites_sync(Some(&added), true, None, &mount()).unwrap().unwrap(), added);
+ assert_eq!(favorites_sync(Some(&added), false, None, &mount()).unwrap().unwrap(), FAVORITES);
+ }
+
+ #[test]
+ fn favorite_without_trailing_comma_or_newline_and_empty_list() {
+ let added = favorites_sync(Some("[Home]"), true, None, &mount()).unwrap().unwrap();
+ assert_eq!(added, "[Home,\n Path(\"/home/u/ProtonDrive\"),\n]");
+ let added = favorites_sync(Some("[\n]\n"), true, None, &mount()).unwrap().unwrap();
+ assert_eq!(added, "[\n Path(\"/home/u/ProtonDrive\"),\n]\n");
+ assert!(favorites_sync(Some("garbage"), true, None, &mount()).is_err());
+ }
+
+ #[test]
+ fn favorite_follows_a_new_mount_point() {
+ let added = favorites_sync(Some(FAVORITES), true, None, &mount()).unwrap().unwrap();
+ let moved = favorites_sync(Some(&added), true, Some(&mount()), Path::new("/mnt/pd")).unwrap().unwrap();
+ assert!(!moved.contains("ProtonDrive"));
+ assert!(moved.contains("Path(\"/mnt/pd\"),\n]"));
+ assert!(moved.contains("Path(\"/mnt/data\")"));
+ }
+
+ #[test]
+ fn missing_favorites_file_gets_the_defaults() {
+ let text = favorites_sync(None, true, None, &mount()).unwrap().unwrap();
+ assert_eq!(text, "[\n Home,\n Documents,\n Downloads,\n Music,\n Pictures,\n Videos,\n Path(\"/home/u/ProtonDrive\"),\n]");
+ assert_eq!(favorites_sync(None, false, None, &mount()).unwrap(), None);
+ }
+
+ // context actions
+
+ const MINE: &str = "[\n (name: \"Mine\", confirm: false, selection: Files, steps: [\"mytool %F\"]),\n]";
+
+ #[test]
+ fn actions_are_appended_after_the_users_own() {
+ let added = context_actions_sync(Some(MINE), true, &actions()).unwrap().unwrap();
+ assert!(added.starts_with(&MINE[..MINE.len() - 2]));
+ assert!(added.contains(" (name: \"PDrive: Keep Available Offline\", confirm: false, selection: Any, steps: [\"pdrive keep-offline %F\"]),\n"));
+ assert!(added.contains(" (name: \"PDrive: Free Up Space\", confirm: false, selection: Any, steps: [\"pdrive free-up-space %F\"]),\n]"));
+ assert_eq!(context_actions_sync(Some(&added), true, &actions()).unwrap().unwrap(), added);
+ assert_eq!(context_actions_sync(Some(&added), false, &actions()).unwrap().unwrap(), MINE);
+ }
+
+ #[test]
+ fn actions_follow_a_language_or_binary_change() {
+ let added = context_actions_sync(Some(MINE), true, &actions()).unwrap().unwrap();
+ let french = Actions {
+ keep_name: "PDrive : garder disponible hors ligne".into(),
+ free_name: "PDrive : libérer de l'espace".into(),
+ command: "/home/u/my bin/pdrive".into(),
+ };
+ let changed = context_actions_sync(Some(&added), true, &french).unwrap().unwrap();
+ assert!(changed.contains("name: \"PDrive : garder disponible hors ligne\""));
+ assert!(changed.contains("steps: [\"\\\"/home/u/my bin/pdrive\\\" free-up-space %F\"]"));
+ assert!(changed.contains("\"mytool %F\""));
+ assert_eq!(changed.matches("pdrive").count(), 2);
+ // Still recognised, so removable.
+ assert_eq!(context_actions_sync(Some(&changed), false, &french).unwrap().unwrap(), MINE);
+ }
+
+ #[test]
+ fn duplicates_are_merged_and_missing_files_created() {
+ let entry = actions().entry(Subcommand::KeepOffline);
+ let doubled = format!("[\n {entry},\n {entry},\n]");
+ let fixed = context_actions_sync(Some(&doubled), true, &actions()).unwrap().unwrap();
+ assert_eq!(fixed.matches("keep-offline").count(), 1);
+ assert_eq!(fixed.matches("free-up-space").count(), 1);
+ let created = context_actions_sync(None, true, &actions()).unwrap().unwrap();
+ assert_eq!(created.matches("(name:").count(), 2);
+ assert_eq!(context_actions_sync(Some(&created), false, &actions()).unwrap().unwrap(), "[\n]");
+ assert_eq!(context_actions_sync(None, false, &actions()).unwrap(), None);
+ }
+
+ #[test]
+ fn comments_and_nested_parentheses_do_not_confuse_the_scan() {
+ let text = "[\n // (not an element)\n (name: \"a)b\", confirm: true, selection: Any, steps: [\"x (y\"]),\n]";
+ let added = context_actions_sync(Some(text), true, &actions()).unwrap().unwrap();
+ assert!(added.starts_with(&text[..text.len() - 2]));
+ assert_eq!(context_actions_sync(Some(&added), false, &actions()).unwrap().unwrap(), text);
+ }
+
+ // Files
+
+ struct Fixture {
+ _dir: tempfile::TempDir,
+ env: Env,
+ }
+
+ fn fixture(cosmic_installed: bool) -> Fixture {
+ let dir = tempfile::tempdir().unwrap();
+ let (data_home, system, config_home) = (dir.path().join("data"), dir.path().join("system"), dir.path().join("config"));
+ std::fs::create_dir_all(system.join("applications")).unwrap();
+ std::fs::create_dir_all(&data_home).unwrap();
+ if cosmic_installed {
+ std::fs::write(system.join("applications").join(COSMIC_FILES_DESKTOP), "[Desktop Entry]\n").unwrap();
+ }
+ Fixture { env: Env { data_home, data_dirs: vec![system], config_home }, _dir: dir }
+ }
+
+ #[test]
+ fn nothing_is_created_for_file_managers_that_are_not_there() {
+ let f = fixture(false);
+ assert!(apply(&f.env, true, None, &mount(), &actions()).is_empty());
+ assert!(!f.env.xbel().exists());
+ assert!(!f.env.cosmic_dir().exists());
+ assert!(apply(&f.env, false, None, &mount(), &actions()).is_empty());
+ }
+
+ #[test]
+ fn both_managers_are_set_up_and_removed_whatever_the_session() {
+ let f = fixture(true);
+ std::fs::write(f.env.xbel(), XBEL).unwrap();
+ // The session is irrelevant: it is not even read.
+ assert!(apply(&f.env, true, None, &mount(), &actions()).is_empty());
+ assert!(std::fs::read_to_string(f.env.xbel()).unwrap().contains(XBEL_MARKER));
+ let favorites = std::fs::read_to_string(f.env.cosmic_dir().join("favorites")).unwrap();
+ assert!(favorites.contains("Videos,\n Path(\"/home/u/ProtonDrive\"),\n]"));
+ let context = std::fs::read_to_string(f.env.cosmic_dir().join("context_actions")).unwrap();
+ assert_eq!(context.matches("selection: Any").count(), 2);
+
+ // A second pass writes nothing.
+ let before = std::fs::metadata(f.env.xbel()).unwrap().modified().unwrap();
+ assert!(apply(&f.env, true, None, &mount(), &actions()).is_empty());
+ assert_eq!(std::fs::metadata(f.env.xbel()).unwrap().modified().unwrap(), before);
+
+ assert!(apply(&f.env, false, None, &mount(), &actions()).is_empty());
+ assert_eq!(std::fs::read_to_string(f.env.xbel()).unwrap(), XBEL);
+ assert!(!std::fs::read_to_string(f.env.cosmic_dir().join("favorites")).unwrap().contains("ProtonDrive"));
+ assert!(!std::fs::read_to_string(f.env.cosmic_dir().join("context_actions")).unwrap().contains("pdrive"));
+ }
+
+ #[test]
+ fn existing_cosmic_files_are_edited_in_place_and_links_are_kept() {
+ let f = fixture(true);
+ std::fs::create_dir_all(f.env.cosmic_dir()).unwrap();
+ let real = f.env.config_home.join("dotfiles-favorites");
+ std::fs::write(&real, FAVORITES).unwrap();
+ let link = f.env.cosmic_dir().join("favorites");
+ std::os::unix::fs::symlink(&real, &link).unwrap();
+ assert!(apply(&f.env, true, None, &mount(), &actions()).is_empty());
+ assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
+ assert!(std::fs::read_to_string(&real).unwrap().contains("Path(\"/home/u/ProtonDrive\")"));
+ assert!(std::fs::read_to_string(&real).unwrap().contains("Path(\"/mnt/data\")"));
+ // No leftover temporary file.
+ assert_eq!(std::fs::read_dir(f.env.config_home.as_path()).unwrap().count(), 2);
+ }
+
+ #[test]
+ fn an_unreadable_file_does_not_stop_the_other_manager() {
+ let f = fixture(true);
+ std::fs::create_dir_all(f.env.cosmic_dir()).unwrap();
+ std::fs::write(f.env.cosmic_dir().join("favorites"), "garbage").unwrap();
+ std::fs::write(f.env.xbel(), XBEL).unwrap();
+ let errors = apply(&f.env, true, None, &mount(), &actions());
+ assert_eq!(errors.len(), 1);
+ assert_eq!(std::fs::read_to_string(f.env.cosmic_dir().join("favorites")).unwrap(), "garbage");
+ assert!(std::fs::read_to_string(f.env.xbel()).unwrap().contains(XBEL_MARKER));
+ }
+
+ #[test]
+ fn a_changed_mount_point_moves_both_entries() {
+ let f = fixture(true);
+ std::fs::write(f.env.xbel(), XBEL).unwrap();
+ apply(&f.env, true, None, &mount(), &actions());
+ let new = PathBuf::from("/mnt/pd");
+ assert!(apply(&f.env, true, Some(&mount()), &new, &actions()).is_empty());
+ let xbel = std::fs::read_to_string(f.env.xbel()).unwrap();
+ assert!(xbel.contains("href=\"file:///mnt/pd\"") && !xbel.contains("ProtonDrive"));
+ let favorites = std::fs::read_to_string(f.env.cosmic_dir().join("favorites")).unwrap();
+ assert!(favorites.contains("Path(\"/mnt/pd\")") && !favorites.contains("ProtonDrive"));
+ }
+}
diff --git a/crates/pdrive-app/src/main.rs b/crates/pdrive-app/src/main.rs
index 3496ec2..131e4e5 100644
--- a/crates/pdrive-app/src/main.rs
+++ b/crates/pdrive-app/src/main.rs
@@ -3,6 +3,7 @@
//! PDrive for Linux desktop application.
//!
//! pdrive-app [--background]
+//! pdrive-app --remove-integrations
//!
//! Single instance (`io.github.bpresles.PDrive.App`) that stays alive without a window:
//! it runs and supervises `pdrived`, shows the tray icon (StatusNotifierItem) and the status
@@ -10,10 +11,14 @@
//! `--background` (autostart) no window is opened. Only "Quit" in the tray menu (or SIGTERM)
//! ends it, after stopping the daemon. The logs of the daemon go to this program's standard
//! error output, which `logs.rs` sends to the journal when it would be lost.
+//!
+//! `--remove-integrations` removes the entries added to the file managers (`integrations.rs`)
+//! and exits; the uninstall script runs it.
mod about;
mod config;
mod daemon;
+mod integrations;
mod logs;
mod settings;
mod supervisor;
@@ -82,6 +87,10 @@ fn terminate_signals() -> async_channel::Receiver<()> {
}
fn main() -> glib::ExitCode {
+ if std::env::args().any(|a| a == "--remove-integrations") {
+ pdi18n::init();
+ return if integrations::remove_all() { glib::ExitCode::SUCCESS } else { glib::ExitCode::FAILURE };
+ }
logs::init();
let terminate = terminate_signals();
pdi18n::init();
@@ -184,6 +193,13 @@ impl App {
me.add_actions();
me.watch_names();
me.supervisor.ensure_running();
+ // Decided by what is installed, at every start: a file manager installed since is
+ // taken into account.
+ glib::spawn_future_local(async {
+ if let Ok(errors) = gio::spawn_blocking(integrations::apply_from_settings).await {
+ integrations::report(errors);
+ }
+ });
let weak = Rc::downgrade(&me);
glib::spawn_future_local(async move {
diff --git a/crates/pdrive-app/src/settings.rs b/crates/pdrive-app/src/settings.rs
index 0716a1c..cb18005 100644
--- a/crates/pdrive-app/src/settings.rs
+++ b/crates/pdrive-app/src/settings.rs
@@ -7,6 +7,7 @@ use std::rc::Rc;
use adw::prelude::*;
use crate::config::{self, Settings};
+use crate::integrations;
use crate::update::RELEASES_URL;
use crate::window::open_uri;
use pdi18n::{tr, tr_fmt};
@@ -59,6 +60,21 @@ pub fn show(
}
});
startup.add(&show_window);
+ let file_managers =
+ adw::SwitchRow::builder().title(tr("Add PDrive to the file managers (sidebar, menus)")).active(config::file_manager_integration()).build();
+ let toaster = dialog.clone();
+ file_managers.connect_active_notify(move |row| {
+ if let Err(e) = config::set_file_manager_integration(row.is_active()) {
+ toaster.add_toast(adw::Toast::new(&format!("{}: {e}", tr("Cannot change the file manager setting"))));
+ return;
+ }
+ let errors = integrations::apply_from_settings();
+ if !errors.is_empty() {
+ toaster.add_toast(adw::Toast::new(&tr("Some file managers could not be updated. See the logs of the application.")));
+ }
+ integrations::report(errors);
+ });
+ startup.add(&file_managers);
page.add(&startup);
let updates = adw::PreferencesGroup::new();
@@ -128,8 +144,12 @@ pub fn show(
if mountpoint.is_empty() || (mountpoint == current.mountpoint && size == current.cache_size_gib) {
return;
}
+ let saved_mountpoint = mountpoint.clone();
match config::save(&Settings { mountpoint, cache_size_gib: size }) {
- Ok(()) => restart_daemon(),
+ Ok(()) => {
+ integrations::report(integrations::mount_point_changed(¤t.mountpoint, &saved_mountpoint));
+ restart_daemon();
+ }
Err(e) => eprintln!("cannot save the settings: {e:#}"),
}
});
diff --git a/crates/pdrive/Cargo.toml b/crates/pdrive/Cargo.toml
index 05e35d9..df799ff 100644
--- a/crates/pdrive/Cargo.toml
+++ b/crates/pdrive/Cargo.toml
@@ -9,4 +9,7 @@ version.workspace = true
pdcore = { path = "../pdcore" }
pdsdk = { path = "../pdsdk" }
tokio.workspace = true
+pdi18n = { path = "../pdi18n" }
anyhow.workspace = true
+glib = "0.22"
+gio = "0.22"
diff --git a/crates/pdrive/src/main.rs b/crates/pdrive/src/main.rs
index 53e2718..97960f4 100644
--- a/crates/pdrive/src/main.rs
+++ b/crates/pdrive/src/main.rs
@@ -7,10 +7,15 @@
//! pdrive logout revoke the session and remove it from the keyring
//! pdrive status exit status 0 if a session is stored in the keyring, 1 otherwise
//!
+//! pdrive keep-offline PATH... keep files or folders of the drive available offline
+//! pdrive free-up-space PATH... free the local space used by files or folders of the drive
+//!
//! Set PDRIVE_VERBOSE=1 to log HTTP requests and SDK debug messages.
use std::sync::Arc;
+mod offline;
+
use anyhow::{Result, bail};
use pdcore::config;
use pdsdk::proto::{Node, node::Kind};
@@ -29,8 +34,13 @@ async fn main() -> Result<()> {
std::process::exit(if signed_in { 0 } else { 1 });
}
Some("selftest") => selftest().await,
+ Some(command @ ("keep-offline" | "free-up-space")) => {
+ pdi18n::init();
+ let action = if command == "keep-offline" { offline::Action::KeepOffline } else { offline::Action::FreeUpSpace };
+ std::process::exit(offline::run(action, &args[1..]));
+ }
_ => {
- eprintln!("usage: pdrive login | ls [PATH] | logout | status | selftest");
+ eprintln!("usage: pdrive login | ls [PATH] | logout | status | keep-offline PATH... | free-up-space PATH... | selftest");
std::process::exit(2);
}
}
diff --git a/crates/pdrive/src/offline.rs b/crates/pdrive/src/offline.rs
new file mode 100644
index 0000000..10ea90b
--- /dev/null
+++ b/crates/pdrive/src/offline.rs
@@ -0,0 +1,204 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 Bertrand Presles
+//! `pdrive keep-offline PATH...` and `pdrive free-up-space PATH...`: the same actions as the
+//! Nautilus menu, through the D-Bus API of the daemon (`io.github.bpresles.PDrive1`). Meant for
+//! file managers that can only run a command line (COSMIC Files) and for scripts.
+//!
+//! Such menus can be shown on every file, so paths outside the drive are ignored; when none is
+//! inside it, a desktop notification says so and the exit status is non-zero.
+
+use std::collections::HashMap;
+use std::path::{Path, PathBuf};
+
+use glib::variant::{ToVariant, Variant};
+use pdi18n::tr;
+
+const BUS_NAME: &str = "io.github.bpresles.PDrive";
+const OBJECT_PATH: &str = "/io/github/bpresles/PDrive";
+const INTERFACE: &str = "io.github.bpresles.PDrive1";
+const APP_ICON: &str = "io.github.bpresles.PDrive.App";
+const CALL_TIMEOUT_MS: i32 = 10_000;
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum Action {
+ KeepOffline,
+ FreeUpSpace,
+}
+
+impl Action {
+ fn method(self) -> &'static str {
+ match self {
+ Action::KeepOffline => "KeepOffline",
+ Action::FreeUpSpace => "FreeUpSpace",
+ }
+ }
+
+ fn command(self) -> &'static str {
+ match self {
+ Action::KeepOffline => "keep-offline",
+ Action::FreeUpSpace => "free-up-space",
+ }
+ }
+}
+
+/// Runs the action and returns the process exit status.
+pub fn run(action: Action, args: &[String]) -> i32 {
+ if args.is_empty() {
+ eprintln!("usage: pdrive {} PATH...", action.command());
+ return 2;
+ }
+ let connection = match gio::bus_get_sync(gio::BusType::Session, None::<&gio::Cancellable>) {
+ Ok(connection) => connection,
+ Err(e) => return fail(None, &format!("{}: {e}", tr("Cannot reach the session bus"))),
+ };
+ let (mount_point, mount_target) = match (property(&connection, "MountPoint"), property(&connection, "MountTarget")) {
+ (Ok(point), Ok(target)) => (point, target),
+ (Err(e), _) | (_, Err(e)) => {
+ let message = if is_daemon_missing(&e) { tr("PDrive is not running. Start it first.") } else { e.message().to_owned() };
+ return fail(Some(&connection), &message);
+ }
+ };
+ let prefixes = [PathBuf::from(mount_point), PathBuf::from(mount_target)];
+
+ let (inside, ignored) = partition(args, &prefixes);
+ for path in &ignored {
+ eprintln!("{}: {}", tr("Ignored, not in Proton Drive"), path.display());
+ }
+ if inside.is_empty() {
+ return fail(Some(&connection), &tr("These files are not in Proton Drive"));
+ }
+ let paths: Vec = inside.iter().map(|p| p.to_string_lossy().into_owned()).collect();
+ let call = connection.call_sync(
+ Some(BUS_NAME),
+ OBJECT_PATH,
+ INTERFACE,
+ action.method(),
+ Some(&(paths,).to_variant()),
+ None,
+ gio::DBusCallFlags::NO_AUTO_START,
+ CALL_TIMEOUT_MS,
+ None::<&gio::Cancellable>,
+ );
+ match call {
+ Ok(_) => 0,
+ Err(e) => fail(Some(&connection), e.message()),
+ }
+}
+
+fn is_daemon_missing(e: &glib::Error) -> bool {
+ e.matches(gio::DBusError::ServiceUnknown) || e.matches(gio::DBusError::NameHasNoOwner)
+}
+
+fn property(connection: &gio::DBusConnection, name: &str) -> Result {
+ let reply = connection.call_sync(
+ Some(BUS_NAME),
+ OBJECT_PATH,
+ "org.freedesktop.DBus.Properties",
+ "Get",
+ Some(&(INTERFACE, name).to_variant()),
+ None,
+ gio::DBusCallFlags::NO_AUTO_START,
+ CALL_TIMEOUT_MS,
+ None::<&gio::Cancellable>,
+ )?;
+ let value = reply.try_child_value(0).and_then(|v| v.as_variant());
+ Ok(value.and_then(|v| v.get::()).unwrap_or_default())
+}
+
+/// Prints the message, shows it as a notification when a bus is available, and returns 1.
+fn fail(connection: Option<&gio::DBusConnection>, message: &str) -> i32 {
+ eprintln!("pdrive: {message}");
+ if let Some(connection) = connection {
+ notify(connection, message);
+ }
+ 1
+}
+
+/// `org.freedesktop.Notifications.Notify`; `gio::Notification` needs an application. A missing
+/// notification service is not an error.
+fn notify(connection: &gio::DBusConnection, body: &str) {
+ let hints: HashMap = HashMap::new();
+ let parameters = ("PDrive", 0u32, APP_ICON, "PDrive", body, Vec::::new(), hints, -1i32).to_variant();
+ let _ = connection.call_sync(
+ Some("org.freedesktop.Notifications"),
+ "/org/freedesktop/Notifications",
+ "org.freedesktop.Notifications",
+ "Notify",
+ Some(¶meters),
+ None,
+ gio::DBusCallFlags::NONE,
+ CALL_TIMEOUT_MS,
+ None::<&gio::Cancellable>,
+ );
+}
+
+/// Splits the arguments into the absolute paths inside one of the prefixes (as given, then with
+/// symbolic links resolved) and the ones outside.
+fn partition(args: &[String], prefixes: &[PathBuf]) -> (Vec, Vec) {
+ let mut inside = Vec::new();
+ let mut ignored = Vec::new();
+ for arg in args {
+ let Ok(absolute) = std::path::absolute(arg) else {
+ ignored.push(PathBuf::from(arg));
+ continue;
+ };
+ let resolved = std::fs::canonicalize(&absolute).ok();
+ match [Some(absolute.clone()), resolved].into_iter().flatten().find(|p| is_in(p, prefixes)) {
+ Some(path) => inside.push(path),
+ None => ignored.push(absolute),
+ }
+ }
+ (inside, ignored)
+}
+
+fn is_in(path: &Path, prefixes: &[PathBuf]) -> bool {
+ prefixes.iter().any(|prefix| !prefix.as_os_str().is_empty() && path.starts_with(prefix))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn strings(items: &[&str]) -> Vec {
+ items.iter().map(|s| s.to_string()).collect()
+ }
+
+ #[test]
+ fn splits_paths_by_mount_prefix() {
+ let prefixes = [PathBuf::from("/home/u/ProtonDrive"), PathBuf::from("/run/user/1000/pdrive")];
+ let (inside, ignored) = partition(
+ &strings(&["/home/u/ProtonDrive/a.txt", "/home/u/ProtonDrive", "/home/u/ProtonDriveX/b", "/tmp/c", "/run/user/1000/pdrive/d/e"]),
+ &prefixes,
+ );
+ assert_eq!(inside, ["/home/u/ProtonDrive/a.txt", "/home/u/ProtonDrive", "/run/user/1000/pdrive/d/e"].map(PathBuf::from));
+ assert_eq!(ignored, ["/home/u/ProtonDriveX/b", "/tmp/c"].map(PathBuf::from));
+ }
+
+ #[test]
+ fn empty_prefixes_match_nothing() {
+ let (inside, ignored) = partition(&strings(&["/a"]), &[PathBuf::new()]);
+ assert!(inside.is_empty());
+ assert_eq!(ignored, [PathBuf::from("/a")]);
+ }
+
+ #[test]
+ fn relative_paths_are_made_absolute() {
+ let cwd = std::env::current_dir().unwrap();
+ let (inside, _) = partition(&strings(&["x.txt"]), std::slice::from_ref(&cwd));
+ assert_eq!(inside, [cwd.join("x.txt")]);
+ }
+
+ #[test]
+ fn symbolic_links_into_the_drive_count() {
+ let dir = std::env::temp_dir().join(format!("pdrive-offline-test-{}", std::process::id()));
+ let real = dir.join("drive");
+ std::fs::create_dir_all(&real).unwrap();
+ std::fs::write(real.join("f"), "x").unwrap();
+ std::os::unix::fs::symlink(&real, dir.join("link")).unwrap();
+ let real = std::fs::canonicalize(&real).unwrap();
+ let (inside, ignored) = partition(&[dir.join("link/f").to_string_lossy().into_owned()], std::slice::from_ref(&real));
+ std::fs::remove_dir_all(&dir).unwrap();
+ assert!(ignored.is_empty());
+ assert_eq!(inside, [real.join("f")]);
+ }
+}
diff --git a/crates/pdrived/src/config.rs b/crates/pdrived/src/config.rs
index 3c7d491..91fd9de 100644
--- a/crates/pdrived/src/config.rs
+++ b/crates/pdrived/src/config.rs
@@ -9,6 +9,9 @@
//! cache_size_gib = 10
//! # Whether launching pdrive-app opens its status window (read by pdrive-app only).
//! show_window_at_startup = true
+//! # Whether pdrive-app adds the drive to the file managers: Dolphin places, COSMIC Files
+//! # favorite and actions (read by pdrive-app only).
+//! file_manager_integration = true
//! ```
use std::path::{Path, PathBuf};
@@ -39,11 +42,14 @@ pub struct Settings {
/// Setting of pdrive-app, accepted here as the file is shared.
#[allow(dead_code)]
pub show_window_at_startup: bool,
+ /// Setting of pdrive-app, accepted here as the file is shared.
+ #[allow(dead_code)]
+ pub file_manager_integration: bool,
}
impl Default for Settings {
fn default() -> Self {
- Self { mountpoint: "~/ProtonDrive".into(), cache_size_gib: 10.0, show_window_at_startup: true }
+ Self { mountpoint: "~/ProtonDrive".into(), cache_size_gib: 10.0, show_window_at_startup: true, file_manager_integration: true }
}
}
@@ -92,15 +98,17 @@ mod tests {
assert_eq!(settings.mountpoint, "~/ProtonDrive");
assert_eq!(settings.cache_size_gib, 10.0);
assert!(settings.show_window_at_startup);
+ assert!(settings.file_manager_integration);
}
#[test]
fn documented_example_parses() {
- let text = "# comment\nmountpoint = \"/mnt/drive\"\ncache_size_gib = 2.5\nshow_window_at_startup = false\n";
+ let text = "# comment\nmountpoint = \"/mnt/drive\"\ncache_size_gib = 2.5\nshow_window_at_startup = false\nfile_manager_integration = false\n";
let settings: Settings = toml::from_str(text).unwrap();
assert_eq!(settings.mountpoint, "/mnt/drive");
assert_eq!(settings.cache_size_gib, 2.5);
assert!(!settings.show_window_at_startup);
+ assert!(!settings.file_manager_integration);
// An integer is accepted for the size, as written by the application.
assert_eq!(toml::from_str::("cache_size_gib = 10").unwrap().cache_size_gib, 10.0);
}
diff --git a/debian/control b/debian/control
index c983e09..791878e 100644
--- a/debian/control
+++ b/debian/control
@@ -6,11 +6,18 @@ Build-Depends: debhelper-compat (= 13),
cargo (>= 1.92),
rustc (>= 1.92),
gcc,
+ g++,
make,
+ cmake,
+ extra-cmake-modules,
gettext,
desktop-file-utils,
pkg-config,
libnautilus-extension-dev,
+ libkf6kio-dev,
+ libkf6coreaddons-dev,
+ libkf6i18n-dev,
+ qt6-base-dev,
libgtk-4-dev (>= 4.12),
libadwaita-1-dev (>= 1.6),
libglib2.0-dev
@@ -21,15 +28,19 @@ Rules-Requires-Root: no
Package: pdrive-for-linux
Architecture: amd64 arm64
Depends: ${shlibs:Depends}, ${misc:Depends},
- fuse3,
- libnautilus-extension4
-Recommends: gnome-shell-extension-appindicator, nautilus
-Description: Unofficial Proton Drive client (FUSE mount, Nautilus integration)
+ fuse3
+Recommends: gnome-shell-extension-appindicator
+Suggests: nautilus, dolphin
+Description: Unofficial Proton Drive client (FUSE mount, file manager integration)
PDrive for Linux mounts Proton Drive as a FUSE file system, with on-demand
- download, offline pinning, sync state emblems and menu entries in Nautilus, a
+ download, offline pinning, sync state emblems and menu entries in Nautilus and
+ Dolphin, entries in the sidebar and menus of Dolphin and COSMIC Files, a
desktop application (tray icon, status window) that runs the daemon, and a
command-line tool.
.
+ The plugins of a file manager are only loaded by it, so none is required and
+ several desktops can be installed side by side.
+ .
The session is stored through the Secret Service API: the desktop must provide
a Secret Service (oo7, GNOME Keyring, KWallet, KeePassXC...). None is pulled in
as a dependency, so that the one already chosen by the desktop is kept.
diff --git a/debian/rules b/debian/rules
index dfedc2e..ff365d0 100755
--- a/debian/rules
+++ b/debian/rules
@@ -10,7 +10,10 @@ PKG := pdrive-for-linux
APP_ID := io.github.bpresles.PDrive.App
CLOUD_INI := io.github.bpresles.PDrive.ini
LIBDIR := /usr/lib/$(DEB_HOST_MULTIARCH)/pdrive
-EXTDIR := $(shell pkg-config --variable=extensiondir libnautilus-extension-4)
+# File manager plugins (Nautilus extension, Dolphin plugins). dh_shlibdeps ignores them: they must
+# not make the package depend on the libraries of their file manager (KF6 for a GNOME user,
+# libnautilus-extension for a KDE user); the file manager brings them.
+PLUGINS := libpdrive-nautilus.so pdriveoverlay.so pdriveactions.so
export CARGO_HOME := $(CURDIR)/debian/cargo-home
# Native libraries of the build architecture (build.rs picks the same directory by target arch).
NATIVE_RID := linux-$(if $(filter arm64,$(DEB_HOST_ARCH)),arm64,x64)
@@ -32,6 +35,9 @@ override_dh_auto_configure:
override_dh_auto_build:
cargo build --release --frozen --offline -p pdrived -p pdrive -p pdrive-app
CFLAGS="$(CFLAGS) $(CPPFLAGS)" $(MAKE) -C extension LOCALEDIR=/usr/share/locale
+ CXXFLAGS="$(CXXFLAGS) $(CPPFLAGS)" LDFLAGS="$(LDFLAGS)" cmake -S integrations/dolphin -B debian/build-dolphin \
+ -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr -DKDE_INSTALL_LIBDIR=lib/$(DEB_HOST_MULTIARCH)
+ cmake --build debian/build-dolphin --parallel
while read -r lang; do \
case "$$lang" in ''|\#*) continue;; esac; \
mkdir -p debian/locale/$$lang/LC_MESSAGES; \
@@ -40,6 +46,11 @@ override_dh_auto_build:
override_dh_auto_test:
desktop-file-validate packaging/$(APP_ID).desktop
+ # The Dolphin plugins: no /usr/local, no build directory.
+ for p in $$(find debian/build-dolphin/bin -name '*.so'); do \
+ ! grep -q /usr/local $$p || { echo "$$p refers to /usr/local" >&2; exit 1; }; \
+ ! grep -q "$(CURDIR)" $$p || { echo "$$p refers to the build tree" >&2; exit 1; }; \
+ done
# The binaries must not refer to the build tree (the SDK loads libproton_crypto.so from that path).
for b in pdrive pdrived; do \
! grep -q "$(CURDIR)/native" target/release/$$b || { echo "$$b refers to the build tree" >&2; exit 1; }; \
@@ -50,6 +61,7 @@ override_dh_auto_install:
install -Dpm0755 target/release/pdrive target/release/pdrived target/release/pdrive-app -t debian/$(PKG)/usr/bin
install -Dpm0644 native/$(NATIVE_RID)/libproton_drive_sdk.so native/$(NATIVE_RID)/libproton_crypto.so -t debian/$(PKG)$(LIBDIR)
$(MAKE) -C extension install DESTDIR=$(CURDIR)/debian/$(PKG) LOCALEDIR=/usr/share/locale
+ DESTDIR=$(CURDIR)/debian/$(PKG) cmake --install debian/build-dolphin
install -Dpm0644 packaging/$(CLOUD_INI) -t debian/$(PKG)/usr/share/cloud-providers
install -Dpm0644 packaging/$(APP_ID).desktop -t debian/$(PKG)/usr/share/applications
cd packaging/icons/hicolor && find . -name '*.svg' -exec install -Dpm0644 '{}' $(CURDIR)/debian/$(PKG)/usr/share/icons/hicolor/'{}' ';'
@@ -60,9 +72,9 @@ override_dh_makeshlibs:
dh_makeshlibs -n
override_dh_shlibdeps:
- dh_shlibdeps -- -l$(CURDIR)/debian/$(PKG)$(LIBDIR)
+ dh_shlibdeps $(addprefix -X,$(PLUGINS)) -- -l$(CURDIR)/debian/$(PKG)$(LIBDIR)
# dh_clean would delete vendor/*/Cargo.toml.orig, which the vendored checksums reference.
override_dh_clean:
dh_clean -X.orig
- rm -rf debian/locale debian/cargo-home
+ rm -rf debian/locale debian/cargo-home debian/build-dolphin
diff --git a/integrations/dolphin/CMakeLists.txt b/integrations/dolphin/CMakeLists.txt
new file mode 100644
index 0000000..785b29b
--- /dev/null
+++ b/integrations/dolphin/CMakeLists.txt
@@ -0,0 +1,38 @@
+# SPDX-License-Identifier: GPL-3.0-or-later
+# Copyright (C) 2026 Bertrand Presles
+#
+# Dolphin (KDE Frameworks 6) plugins of PDrive for Linux:
+# - pdriveoverlay: emblems for the sync state of the files (KOverlayIconPlugin);
+# - pdriveactions: "Keep Available Offline" / "Free Up Space" in the context menu
+# (KAbstractFileItemActionPlugin).
+# Both only talk to the pdrived daemon over D-Bus (io.github.bpresles.PDrive1).
+cmake_minimum_required(VERSION 3.16)
+project(pdrive-dolphin VERSION 0.3.0 LANGUAGES CXX)
+
+find_package(ECM 6.0.0 REQUIRED NO_MODULE)
+set(CMAKE_MODULE_PATH ${ECM_MODULE_PATH})
+
+include(KDEInstallDirs6)
+include(KDECMakeSettings)
+include(KDECompilerSettings NO_POLICY_SCOPE)
+include(FeatureSummary)
+
+find_package(Qt6 REQUIRED COMPONENTS Core DBus Widgets)
+find_package(KF6 REQUIRED COMPONENTS CoreAddons I18n KIO)
+
+set(CMAKE_AUTOMOC ON)
+
+# Shared by both plugins, linked into each of them.
+add_library(pdriveclient OBJECT pdriveclient.cpp pdriveclient.h)
+set_property(TARGET pdriveclient PROPERTY POSITION_INDEPENDENT_CODE ON)
+target_link_libraries(pdriveclient PUBLIC Qt6::Core Qt6::DBus)
+
+kcoreaddons_add_plugin(pdriveoverlay INSTALL_NAMESPACE "kf6/overlayicon")
+target_sources(pdriveoverlay PRIVATE pdriveoverlay.cpp pdriveoverlay.h $)
+target_link_libraries(pdriveoverlay PRIVATE Qt6::DBus KF6::CoreAddons KF6::KIOCore)
+
+kcoreaddons_add_plugin(pdriveactions INSTALL_NAMESPACE "kf6/kfileitemaction")
+target_sources(pdriveactions PRIVATE pdriveactions.cpp pdriveactions.h $)
+target_link_libraries(pdriveactions PRIVATE Qt6::DBus Qt6::Widgets KF6::CoreAddons KF6::I18n KF6::KIOWidgets)
+
+feature_summary(WHAT ALL INCLUDE_QUIET_PACKAGES FATAL_ON_MISSING_REQUIRED_PACKAGES)
diff --git a/integrations/dolphin/pdriveactions.cpp b/integrations/dolphin/pdriveactions.cpp
new file mode 100644
index 0000000..803f7e1
--- /dev/null
+++ b/integrations/dolphin/pdriveactions.cpp
@@ -0,0 +1,55 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 Bertrand Presles
+
+#include "pdriveactions.h"
+
+#include
+#include
+#include
+
+#include
+#include
+#include
+
+// Texts of the "pdrive" gettext domain, as in the Nautilus extension. i18nd names the domain
+// each time: setting the application domain would change the one of Dolphin.
+
+PDriveActionsPlugin::PDriveActionsPlugin(QObject *parent)
+ : KAbstractFileItemActionPlugin(parent)
+ , m_client(new PDriveClient(this))
+{
+}
+
+QList PDriveActionsPlugin::actions(const KFileItemListProperties &fileItemInfos, QWidget *parentWidget)
+{
+ const QList urls = fileItemInfos.urlList();
+ if (urls.isEmpty()) {
+ return {};
+ }
+ QStringList paths;
+ for (const QUrl &url : urls) {
+ // One file outside the drive and there is nothing to offer.
+ if (!m_client->isInMount(url)) {
+ return {};
+ }
+ paths.append(url.toLocalFile());
+ }
+
+ auto *keep = new QAction(QIcon::fromTheme(QStringLiteral("emblem-pdrive-pinned")), i18nd("pdrive", "Keep Available Offline"), parentWidget);
+ keep->setToolTip(i18nd("pdrive", "Download and keep available without network"));
+ connect(keep, &QAction::triggered, m_client, [client = m_client, paths]() {
+ client->keepOffline(paths);
+ });
+
+ auto *release = new QAction(QIcon::fromTheme(QStringLiteral("emblem-pdrive-online")), i18nd("pdrive", "Free Up Space"), parentWidget);
+ release->setToolTip(i18nd("pdrive", "Remove the downloaded copy, keeping it in the cloud"));
+ connect(release, &QAction::triggered, m_client, [client = m_client, paths]() {
+ client->freeUpSpace(paths);
+ });
+
+ return {keep, release};
+}
+
+K_PLUGIN_CLASS_WITH_JSON(PDriveActionsPlugin, "pdriveactions.json")
+
+#include "pdriveactions.moc"
diff --git a/integrations/dolphin/pdriveactions.h b/integrations/dolphin/pdriveactions.h
new file mode 100644
index 0000000..a8f7f7b
--- /dev/null
+++ b/integrations/dolphin/pdriveactions.h
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 Bertrand Presles
+//
+// "Keep Available Offline" and "Free Up Space" in the context menu of Dolphin, for the files
+// of the PDrive mount only (a service menu cannot be limited to a folder, a plugin can).
+#pragma once
+
+#include
+
+#include "pdriveclient.h"
+
+class PDriveActionsPlugin : public KAbstractFileItemActionPlugin
+{
+ Q_OBJECT
+public:
+ explicit PDriveActionsPlugin(QObject *parent = nullptr);
+
+ QList actions(const KFileItemListProperties &fileItemInfos, QWidget *parentWidget) override;
+
+private:
+ PDriveClient *m_client;
+};
diff --git a/integrations/dolphin/pdriveactions.json b/integrations/dolphin/pdriveactions.json
new file mode 100644
index 0000000..803f374
--- /dev/null
+++ b/integrations/dolphin/pdriveactions.json
@@ -0,0 +1,12 @@
+{
+ "KPlugin": {
+ "Description": "Keep Available Offline and Free Up Space for PDrive for Linux (unofficial Proton Drive client)",
+ "Icon": "emblem-pdrive-pinned",
+ "Id": "pdriveactions",
+ "MimeTypes": [
+ "application/octet-stream",
+ "inode/directory"
+ ],
+ "Name": "PDrive for Linux actions"
+ }
+}
diff --git a/integrations/dolphin/pdriveclient.cpp b/integrations/dolphin/pdriveclient.cpp
new file mode 100644
index 0000000..cff9ca3
--- /dev/null
+++ b/integrations/dolphin/pdriveclient.cpp
@@ -0,0 +1,173 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 Bertrand Presles
+
+#include "pdriveclient.h"
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+namespace
+{
+const auto BusName = QStringLiteral("io.github.bpresles.PDrive");
+const auto ObjectPath = QStringLiteral("/io/github/bpresles/PDrive");
+const auto Interface = QStringLiteral("io.github.bpresles.PDrive1");
+constexpr int CallTimeoutMs = 2000;
+
+QString folderPrefix(const QString &path)
+{
+ if (path.isEmpty()) {
+ return QString();
+ }
+ return QDir::cleanPath(path) + QLatin1Char('/');
+}
+}
+
+PDriveClient::PDriveClient(QObject *parent)
+ : QObject(parent)
+{
+ QDBusConnection bus = QDBusConnection::sessionBus();
+ if (!bus.isConnected()) {
+ return;
+ }
+ m_watcher = new QDBusServiceWatcher(BusName, bus, QDBusServiceWatcher::WatchForOwnerChange, this);
+ connect(m_watcher, &QDBusServiceWatcher::serviceOwnerChanged, this, [this](const QString &, const QString &, const QString &newOwner) {
+ onOwnerChanged(newOwner);
+ });
+ bus.connect(BusName, ObjectPath, Interface, QStringLiteral("FileStatusChanged"), this, SLOT(onFileStatusChanged(QString)));
+ bus.connect(BusName, ObjectPath, Interface, QStringLiteral("MountStateChanged"), this, SLOT(onMountStateChanged(bool)));
+
+ // The daemon may already run: NameHasOwner, asynchronously.
+ auto call = QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.DBus"),
+ QStringLiteral("/org/freedesktop/DBus"),
+ QStringLiteral("org.freedesktop.DBus"),
+ QStringLiteral("NameHasOwner"));
+ call << BusName;
+ auto *watcher = new QDBusPendingCallWatcher(bus.asyncCall(call, CallTimeoutMs), this);
+ connect(watcher, &QDBusPendingCallWatcher::finished, this, [this](QDBusPendingCallWatcher *w) {
+ w->deleteLater();
+ const QDBusPendingReply reply = *w;
+ if (reply.isValid() && reply.value() && !m_connected) {
+ onOwnerChanged(QStringLiteral("running"));
+ }
+ });
+}
+
+bool PDriveClient::isReady() const
+{
+ return m_connected && !m_mountPrefix.isEmpty();
+}
+
+QString PDriveClient::mountPoint() const
+{
+ return m_mountPrefix.isEmpty() ? QString() : m_mountPrefix.chopped(1);
+}
+
+bool PDriveClient::isInMount(const QUrl &url) const
+{
+ return url.isLocalFile() && isInMount(url.toLocalFile());
+}
+
+bool PDriveClient::isInMount(const QString &path) const
+{
+ if (!m_connected) {
+ return false;
+ }
+ return (!m_mountPrefix.isEmpty() && path.startsWith(m_mountPrefix)) || (!m_targetPrefix.isEmpty() && path.startsWith(m_targetPrefix));
+}
+
+void PDriveClient::clear()
+{
+ ++m_generation;
+ m_connected = false;
+ m_mountPrefix.clear();
+ m_targetPrefix.clear();
+}
+
+void PDriveClient::onOwnerChanged(const QString &newOwner)
+{
+ clear();
+ if (newOwner.isEmpty()) {
+ Q_EMIT unmounted();
+ return;
+ }
+ m_connected = true;
+ loadMountPoints();
+}
+
+void PDriveClient::loadMountPoints()
+{
+ const int generation = m_generation;
+ const struct {
+ const char *property;
+ bool isPoint;
+ } properties[] = {{"MountPoint", true}, {"MountTarget", false}};
+ for (const auto &entry : properties) {
+ auto call = QDBusMessage::createMethodCall(BusName, ObjectPath, QStringLiteral("org.freedesktop.DBus.Properties"), QStringLiteral("Get"));
+ call << Interface << QString::fromLatin1(entry.property);
+ const bool isPoint = entry.isPoint;
+ auto *watcher = new QDBusPendingCallWatcher(QDBusConnection::sessionBus().asyncCall(call, CallTimeoutMs), this);
+ connect(watcher, &QDBusPendingCallWatcher::finished, this, [this, generation, isPoint](QDBusPendingCallWatcher *w) {
+ w->deleteLater();
+ const QDBusPendingReply reply = *w;
+ // The daemon changed (or vanished) meanwhile: this answer is stale.
+ if (generation != m_generation || !reply.isValid()) {
+ return;
+ }
+ const QString prefix = folderPrefix(reply.value().variant().toString());
+ (isPoint ? m_mountPrefix : m_targetPrefix) = prefix;
+ if (isPoint && !prefix.isEmpty()) {
+ Q_EMIT mounted();
+ }
+ });
+ }
+}
+
+void PDriveClient::fileStatus(const QString &path, std::function done)
+{
+ auto call = QDBusMessage::createMethodCall(BusName, ObjectPath, Interface, QStringLiteral("GetFileStatus"));
+ call << path;
+ auto *watcher = new QDBusPendingCallWatcher(QDBusConnection::sessionBus().asyncCall(call, CallTimeoutMs), this);
+ connect(watcher, &QDBusPendingCallWatcher::finished, this, [done = std::move(done)](QDBusPendingCallWatcher *w) {
+ w->deleteLater();
+ const QDBusPendingReply reply = *w;
+ done(reply.isValid() ? reply.value() : QString());
+ });
+}
+
+void PDriveClient::keepOffline(const QStringList &paths)
+{
+ callWithPaths(QStringLiteral("KeepOffline"), paths);
+}
+
+void PDriveClient::freeUpSpace(const QStringList &paths)
+{
+ callWithPaths(QStringLiteral("FreeUpSpace"), paths);
+}
+
+void PDriveClient::callWithPaths(const QString &method, const QStringList &paths)
+{
+ auto call = QDBusMessage::createMethodCall(BusName, ObjectPath, Interface, method);
+ call << paths;
+ // The daemon does the work in the background: nothing to wait for.
+ QDBusConnection::sessionBus().asyncCall(call, CallTimeoutMs);
+}
+
+void PDriveClient::onFileStatusChanged(const QString &path)
+{
+ Q_EMIT fileStatusChanged(path);
+}
+
+void PDriveClient::onMountStateChanged(bool mounted)
+{
+ if (mounted) {
+ // The mount points may differ in a new run of the daemon.
+ loadMountPoints();
+ } else {
+ Q_EMIT unmounted();
+ }
+}
diff --git a/integrations/dolphin/pdriveclient.h b/integrations/dolphin/pdriveclient.h
new file mode 100644
index 0000000..5ae4233
--- /dev/null
+++ b/integrations/dolphin/pdriveclient.h
@@ -0,0 +1,62 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 Bertrand Presles
+//
+// Client of the pdrived daemon (D-Bus io.github.bpresles.PDrive1) for the Dolphin plugins.
+// Nothing here blocks: the plugins run inside Dolphin. Without the daemon, every question
+// is answered "not in the drive".
+#pragma once
+
+#include
+#include
+#include
+#include
+
+#include
+
+class QDBusServiceWatcher;
+
+class PDriveClient : public QObject
+{
+ Q_OBJECT
+public:
+ explicit PDriveClient(QObject *parent = nullptr);
+
+ /// Whether the daemon runs and its mount point is known.
+ bool isReady() const;
+ /// The mount point (the folder shown to the user), empty when unknown.
+ QString mountPoint() const;
+ /// Whether the URL is a local file strictly inside the mount point or the real mount folder.
+ bool isInMount(const QUrl &url) const;
+ bool isInMount(const QString &path) const;
+
+ /// Asks the daemon for the state of a file ("online", "available", "pinned", "uploading", ...).
+ /// `done` is called later, with an empty string when the daemon cannot answer.
+ void fileStatus(const QString &path, std::function done);
+ void keepOffline(const QStringList &paths);
+ void freeUpSpace(const QStringList &paths);
+
+Q_SIGNALS:
+ /// The daemon appeared or the drive was mounted, and the mount point is known.
+ void mounted();
+ /// The daemon vanished or the drive was unmounted.
+ void unmounted();
+ void fileStatusChanged(const QString &path);
+
+private Q_SLOTS:
+ void onFileStatusChanged(const QString &path);
+ void onMountStateChanged(bool mounted);
+
+private:
+ void onOwnerChanged(const QString &newOwner);
+ void loadMountPoints();
+ void callWithPaths(const QString &method, const QStringList &paths);
+ void clear();
+
+ QDBusServiceWatcher *m_watcher = nullptr;
+ bool m_connected = false;
+ /// "/path/to/folder/" with the trailing slash, so that the folder itself is not inside.
+ QString m_mountPrefix;
+ QString m_targetPrefix;
+ /// Incremented when the daemon changes: answers of an earlier one are ignored.
+ int m_generation = 0;
+};
diff --git a/integrations/dolphin/pdriveoverlay.cpp b/integrations/dolphin/pdriveoverlay.cpp
new file mode 100644
index 0000000..0c3b887
--- /dev/null
+++ b/integrations/dolphin/pdriveoverlay.cpp
@@ -0,0 +1,124 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 Bertrand Presles
+
+#include "pdriveoverlay.h"
+
+#include
+#include
+
+namespace
+{
+/// Bounds the memory: the cache is simply dropped when it is full, and fills up again with
+/// what is shown.
+constexpr int MaxCacheEntries = 10000;
+/// Questions to the daemon in flight at the same time (a folder can hold thousands of files).
+constexpr int MaxInflight = 16;
+}
+
+PDriveOverlayPlugin::PDriveOverlayPlugin(QObject *parent)
+ : KOverlayIconPlugin(parent)
+ , m_client(new PDriveClient(this))
+{
+ // The drive was just mounted: Dolphin does not see the content appear over the mount
+ // point, so it is told to list the folder again.
+ connect(m_client, &PDriveClient::mounted, this, [this]() {
+ forgetEverything();
+ // What Dolphin asked for before the mount point was known.
+ const QSet waiting = std::exchange(m_waiting, {});
+ for (const QString &path : waiting) {
+ if (m_client->isInMount(path)) {
+ request(path);
+ }
+ }
+ org::kde::KDirNotify::emitFilesAdded(QUrl::fromLocalFile(m_client->mountPoint()));
+ });
+ connect(m_client, &PDriveClient::unmounted, this, &PDriveOverlayPlugin::forgetEverything);
+ connect(m_client, &PDriveClient::fileStatusChanged, this, [this](const QString &path) {
+ // Only what was asked for before is shown somewhere.
+ if (m_cache.contains(path)) {
+ request(path);
+ }
+ });
+}
+
+QStringList PDriveOverlayPlugin::overlaysForStatus(const QString &status)
+{
+ // The emblems of the Nautilus extension; "emblem-synchronizing" is in every icon theme,
+ // the others are installed by the package (hicolor).
+ if (status == QLatin1String("uploading")) {
+ return {QStringLiteral("emblem-synchronizing")};
+ }
+ if (status == QLatin1String("pinned")) {
+ return {QStringLiteral("emblem-pdrive-pinned")};
+ }
+ if (status == QLatin1String("available")) {
+ return {QStringLiteral("emblem-pdrive-available")};
+ }
+ if (status == QLatin1String("online")) {
+ return {QStringLiteral("emblem-pdrive-online")};
+ }
+ return {};
+}
+
+QStringList PDriveOverlayPlugin::getOverlays(const QUrl &url)
+{
+ if (!m_client->isReady()) {
+ // Not known yet whether the file is in the drive: remembered until it is.
+ if (url.isLocalFile() && m_waiting.size() < MaxCacheEntries) {
+ m_waiting.insert(url.toLocalFile());
+ }
+ return {};
+ }
+ if (!m_client->isInMount(url)) {
+ return {};
+ }
+ const QString path = url.toLocalFile();
+ const auto it = m_cache.constFind(path);
+ if (it != m_cache.constEnd()) {
+ return *it;
+ }
+ request(path);
+ return {};
+}
+
+void PDriveOverlayPlugin::request(const QString &path)
+{
+ if (m_pending.contains(path)) {
+ return;
+ }
+ m_pending.insert(path);
+ m_queue.enqueue(path);
+ pump();
+}
+
+void PDriveOverlayPlugin::pump()
+{
+ while (m_inflight < MaxInflight && !m_queue.isEmpty()) {
+ const QString path = m_queue.dequeue();
+ ++m_inflight;
+ m_client->fileStatus(path, [this, path, generation = m_generation](const QString &status) {
+ --m_inflight;
+ if (generation == m_generation) {
+ m_pending.remove(path);
+ const QStringList overlays = overlaysForStatus(status);
+ const QStringList shown = m_cache.value(path);
+ if (m_cache.size() >= MaxCacheEntries) {
+ m_cache.clear();
+ }
+ m_cache.insert(path, overlays);
+ if (overlays != shown) {
+ Q_EMIT overlaysChanged(QUrl::fromLocalFile(path), overlays);
+ }
+ }
+ pump();
+ });
+ }
+}
+
+void PDriveOverlayPlugin::forgetEverything()
+{
+ ++m_generation;
+ m_cache.clear();
+ m_queue.clear();
+ m_pending.clear();
+}
diff --git a/integrations/dolphin/pdriveoverlay.h b/integrations/dolphin/pdriveoverlay.h
new file mode 100644
index 0000000..dad0c81
--- /dev/null
+++ b/integrations/dolphin/pdriveoverlay.h
@@ -0,0 +1,47 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 Bertrand Presles
+//
+// Emblems for the sync state of the files of the PDrive mount, in Dolphin.
+#pragma once
+
+#include
+
+#include
+#include
+#include
+#include
+
+#include "pdriveclient.h"
+
+/// Dolphin loads overlay plugins with QPluginLoader::instance() and qobject_cast to
+/// KOverlayIconPlugin (KFileItemModelRolesUpdater), so the plugin object itself must be the
+/// root object of the library: Q_PLUGIN_METADATA, not a KPluginFactory (K_PLUGIN_CLASS_WITH_JSON),
+/// which Dolphin silently drops.
+class PDriveOverlayPlugin : public KOverlayIconPlugin
+{
+ Q_OBJECT
+ Q_PLUGIN_METADATA(IID "io.github.bpresles.PDrive.OverlayIconPlugin" FILE "pdriveoverlay.json")
+public:
+ explicit PDriveOverlayPlugin(QObject *parent = nullptr);
+
+ /// Never blocks: answers from the cache, or with no emblem while the daemon is asked
+ /// (`overlaysChanged` follows with the answer).
+ QStringList getOverlays(const QUrl &url) override;
+
+private:
+ void request(const QString &path);
+ void pump();
+ void forgetEverything();
+ static QStringList overlaysForStatus(const QString &status);
+
+ PDriveClient *m_client;
+ QHash m_cache;
+ QQueue m_queue;
+ QSet m_pending;
+ /// Paths asked for before the mount point was known (the daemon answers asynchronously
+ /// when Dolphin starts): asked again once it is.
+ QSet m_waiting;
+ int m_inflight = 0;
+ /// Incremented when the cache is dropped: answers of an earlier generation are ignored.
+ int m_generation = 0;
+};
diff --git a/integrations/dolphin/pdriveoverlay.json b/integrations/dolphin/pdriveoverlay.json
new file mode 100644
index 0000000..b87dec2
--- /dev/null
+++ b/integrations/dolphin/pdriveoverlay.json
@@ -0,0 +1,7 @@
+{
+ "KPlugin": {
+ "Description": "Sync state emblems of the PDrive for Linux files (unofficial Proton Drive client)",
+ "Id": "pdriveoverlay",
+ "Name": "PDrive for Linux emblems"
+ }
+}
diff --git a/packaging/README.md b/packaging/README.md
index 5311d1b..85e37ae 100644
--- a/packaging/README.md
+++ b/packaging/README.md
@@ -2,7 +2,8 @@
Layout of the packages: `/usr/bin/{pdrive,pdrived,pdrive-app}`, private libraries in
`/usr/lib64/pdrive` (Fedora) or `/usr/lib//pdrive` (Debian, rpath set at build time with `PDSDK_RUNTIME_LIB_DIR`),
-the Nautilus extension in the Nautilus extensions directory, `.ini` in
+the Nautilus extension in the Nautilus extensions directory, the Dolphin plugins in the Qt 6 plugin directory
+(`/kf6/overlayicon/pdriveoverlay.so` and `/kf6/kfileitemaction/pdriveactions.so`), `.ini` in
`/usr/share/cloud-providers`, icons, `.desktop`, `.mo` in `/usr/share/locale`, manual pages (`packaging/man/*.1`, plain troff) in `/usr/share/man/man1`.
Third-party licence inventories (`licenses/*.tsv`, generated by `scripts/audit-licenses.sh`) go to the documentation directory.
@@ -11,6 +12,32 @@ GNOME Keyring, KWallet, KeePassXC...), there is no virtual package or capability
and installing a second one makes two Secret Services compete for the session (README, "Known
limitations"). The requirement is stated in the package descriptions.
+## One package for every file manager
+
+A single package holds the Nautilus extension **and** the Dolphin plugins (built from
+`extension/` and `integrations/dolphin/`), so that everything works on a machine with several
+desktops installed. Each plugin is only loaded by its own file manager, which brings its libraries:
+the package must therefore not depend on them, or a GNOME user would get KF6 and Qt 6, and a KDE user
+`libnautilus-extension`.
+
+- RPM: `%global __requires_exclude_from` drops the automatic dependencies of both plugin
+ directories. Check with `rpm -qpR`: no `libKF6*`, `libQt6*` or `libnautilus-extension`.
+- DEB: `libnautilus-extension4` is no longer in `Depends`, and `dh_shlibdeps -X` ignores the three
+ plugins (`PLUGINS` in `debian/rules`). Check with `dpkg -I`.
+- Arch: `depends` is unchanged (makepkg does not compute library dependencies); `nautilus` and
+ `dolphin` are `optdepends`.
+- No `Recommends: nautilus` any more: no file manager is favored. `Suggests: nautilus, dolphin`
+ (RPM and DEB); `gnome-shell-extension-appindicator` stays in `Recommends`.
+- Build dependencies: `cmake extra-cmake-modules` and the KF6 KIO, KCoreAddons, KI18n and Qt 6
+ development files (`kf6-kio-devel`..., `libkf6kio-dev`..., `kio` on Arch), in the spec,
+ `debian/control` and `scripts/container/build-*.sh`. KDE Frameworks 6 is older in Debian 13 (6.13)
+ than in Fedora: both build the plugins (`KOverlayIconPlugin` is in `KIOCore` since KF 6.0).
+- COSMIC Files has no plugin: `pdrive-app` writes its favorite and its context-menu actions in the
+ user configuration (`pdrive-app --remove-integrations` undoes it). The same goes for the places
+ of Dolphin. A package never changes these user files, so removing it leaves them (they are
+ harmless and `pdrive-app --remove-integrations` cleans them).
+- CI: the `dolphin-plugin` job builds the plugins in a Debian 13 container (Ubuntu 24.04 has no KF6).
+
## Build inputs (no .NET, no network when building the packages)
1. Native archive `pdrive-native-linux---.tar.xz`: the two prebuilt libraries
@@ -53,8 +80,8 @@ an AUR submission: the sources are release assets, not downloaded by the PKGBUIL
`scripts/container/build-appimage.sh`, in a Debian 13 container (libadwaita >= 1.6). `linuxdeploy`
and its GTK plugin bundle GTK 4, libadwaita and the other libraries; the tools are pinned by version
and SHA-256. The AppImage holds `pdrive-app` (the default command), `pdrived` and `pdrive`. Not
-included, because they live in system directories: the Nautilus extension (no emblems or menu
-entries) and the libcloudproviders declaration (no account in the file manager sidebar).
+included, because they live in system directories: the Nautilus extension and the Dolphin plugins (no emblems or menu
+entries; the Dolphin places entry and the COSMIC Files favorite and actions are written by `pdrive-app` and still work) and the libcloudproviders declaration (no account in the file manager sidebar).
`libproton_crypto.so` is loaded by path: the AppRun hook sets `PDRIVE_LIB_DIR` to the mount point
(`pdsdk::runtime_lib_dir`). The host must provide `fusermount3` (the daemon calls it), a Secret
Service provider, and a glibc at least as recent as Debian 13's (2.41).
@@ -74,4 +101,5 @@ built on Ubuntu 24.04 (glibc 2.34+ required, satisfied by current Fedora).
Files under `/usr/local` belong to the administrator: the package scripts never delete them, they
only print a warning telling to remove that file (the account would be listed twice). The extension
is written by that script to the same system directory as the package; the package takes it over.
-Per-user files (`~/.local/...`, `pdrive.service`) are not touched either.
+Per-user files (`~/.local/...`, `pdrive.service`) are not touched either. The Dolphin plugins
+installed by `install-system.sh` go to the Qt 6 plugin directory of the system, like the package ones.
diff --git a/packaging/arch/PKGBUILD b/packaging/arch/PKGBUILD
index ce6c436..cff4cd4 100644
--- a/packaging/arch/PKGBUILD
+++ b/packaging/arch/PKGBUILD
@@ -19,7 +19,7 @@ _cloud_ini=io.github.bpresles.PDrive.ini
pkgname=pdrive-for-linux
pkgver=0.3.0
pkgrel=1
-pkgdesc='Unofficial Proton Drive client for Linux (FUSE mount, Nautilus integration)'
+pkgdesc='Unofficial Proton Drive client for Linux (FUSE mount, file manager integration)'
arch=(x86_64 aarch64)
url='https://github.com/bpresles/PDrive-for-Linux'
# GPL-3.0-or-later: this project. Bundled components: see THIRD_PARTY_NOTICES and licenses/*.tsv.
@@ -29,8 +29,17 @@ license=(GPL-3.0-or-later)
# desktop brings its own (oo7, gnome-keyring, kwallet, keepassxc...), and pulling in a second
# one makes two Secret Services compete for the session.
depends=(fuse3 gtk4 libadwaita glib2 hicolor-icon-theme)
-makedepends=(cargo gcc make gettext desktop-file-utils pkgconf nautilus xz)
-optdepends=('nautilus: file manager integration (emblems, menu entries)'
+# The plugins of a file manager are loaded by it, which brings its libraries (makepkg does not compute
+# library dependencies): nautilus and dolphin are optional, whichever desktops are installed.
+makedepends=(cargo gcc make cmake extra-cmake-modules gettext desktop-file-utils pkgconf nautilus kio xz)
+optdepends=('nautilus: sync state emblems and menu entries in Nautilus'
+ 'dolphin: sync state emblems and menu entries in Dolphin'
+ # Libraries of the Dolphin plugins, brought by dolphin: listed so that namcap knows
+ # they are optional on purpose (one package for every desktop).
+ 'qt6-base: Dolphin plugins'
+ 'kio: Dolphin plugins'
+ 'kcoreaddons: Dolphin plugins'
+ 'ki18n: Dolphin plugins'
'gnome-shell-extension-appindicator: tray icon on GNOME')
options=(!lto !debug)
source=("pdrive-for-linux-$pkgver.tar.xz"
@@ -55,6 +64,8 @@ build() {
export PDSDK_RUNTIME_LIB_DIR=/usr/lib/pdrive
cargo build --release --frozen --offline -p pdrived -p pdrive -p pdrive-app
make -C extension LOCALEDIR=/usr/share/locale
+ cmake -S integrations/dolphin -B build-dolphin -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr -DKDE_INSTALL_LIBDIR=lib
+ cmake --build build-dolphin
}
check() {
@@ -66,6 +77,12 @@ check() {
! grep -q "$PWD/native" "target/release/$b" || { echo "$b refers to the build tree" >&2; return 1; }
grep -q /usr/lib/pdrive "target/release/$b"
done
+ # The Dolphin plugins: no /usr/local, no build directory.
+ local plugin
+ for plugin in build-dolphin/bin/kf6/*/*.so; do
+ ! grep -q /usr/local "$plugin" || { echo "$plugin refers to /usr/local" >&2; return 1; }
+ ! grep -q "$PWD" "$plugin" || { echo "$plugin refers to the build tree" >&2; return 1; }
+ done
}
package() {
@@ -74,6 +91,7 @@ package() {
install -Dpm0755 native/$_rid/libproton_drive_sdk.so native/$_rid/libproton_crypto.so -t "$pkgdir/usr/lib/pdrive"
make -C extension install DESTDIR="$pkgdir" LOCALEDIR=/usr/share/locale
+ DESTDIR="$pkgdir" cmake --install build-dolphin
install -Dpm0644 packaging/man/*.1 -t "$pkgdir/usr/share/man/man1"
install -Dpm0644 "packaging/$_cloud_ini" -t "$pkgdir/usr/share/cloud-providers"
diff --git a/packaging/man/pdrive-app.1 b/packaging/man/pdrive-app.1
index f34c355..40e4ee6 100644
--- a/packaging/man/pdrive-app.1
+++ b/packaging/man/pdrive-app.1
@@ -1,11 +1,13 @@
.\" SPDX-License-Identifier: GPL-3.0-or-later
.\" Copyright (C) 2026 Bertrand Presles
-.TH PDRIVE-APP 1 "October 2026" "PDrive for Linux" "User Commands"
+.TH PDRIVE-APP 1 "November 2026" "PDrive for Linux" "User Commands"
.SH NAME
pdrive-app \- desktop application of PDrive for Linux (tray icon, status window)
.SH SYNOPSIS
.B pdrive-app
.RB [ \-\-background ]
+.br
+.B pdrive-app \-\-remove\-integrations
.SH DESCRIPTION
.B pdrive-app
is the desktop application of PDrive for Linux, an unofficial Proton Drive
@@ -33,6 +35,42 @@ extension. PDrive for Linux is not affiliated with, or endorsed by, Proton AG.
Start without opening the status window. Used by the autostart entry, which
the settings window creates in
.IR ~/.config/autostart .
+.TP
+.B \-\-remove\-integrations
+Remove the entries added to the file managers (see
+.BR "FILE MANAGERS" )
+and exit. The uninstall script runs it.
+.SH FILE MANAGERS
+At every start, when the setting
+.B file_manager_integration
+is on (the default; the settings window has a switch), the application adds the
+drive to the file managers that are installed, whatever the current desktop
+session is. Nautilus needs nothing: its sidebar entry comes from the
+CloudProviders interface.
+.TP
+.B Dolphin
+An entry "Proton Drive" in
+.IR $XDG_DATA_HOME/user-places.xbel ,
+only when that file already exists.
+.TP
+.B COSMIC Files
+Only if
+.I com.system76.CosmicFiles.desktop
+is installed: a favorite in
+.I ~/.config/cosmic/com.system76.CosmicFiles/v1/favorites
+and two context-menu actions in
+.I .../v1/context_actions
+that run
+.BR "pdrive keep\-offline" " and " "pdrive free\-up\-space"
+(see
+.BR pdrive (1)).
+COSMIC Files cannot limit them to the drive, so they appear on every file and
+do nothing, with a notification, outside it.
+.PP
+Only the entries recognised as ours are changed or removed; the rest of the
+files is left as it is. Packages never touch these user files: run
+.B pdrive\-app \-\-remove\-integrations
+before removing the package to clean them up.
.SH ENVIRONMENT
.TP
.B PDRIVE_VERBOSE
diff --git a/packaging/man/pdrive.1 b/packaging/man/pdrive.1
index 226d2a4..637a918 100644
--- a/packaging/man/pdrive.1
+++ b/packaging/man/pdrive.1
@@ -1,6 +1,6 @@
.\" SPDX-License-Identifier: GPL-3.0-or-later
.\" Copyright (C) 2026 Bertrand Presles
-.TH PDRIVE 1 "October 2026" "PDrive for Linux" "User Commands"
+.TH PDRIVE 1 "November 2026" "PDrive for Linux" "User Commands"
.SH NAME
pdrive \- command-line tool of PDrive for Linux, an unofficial Proton Drive client
.SH SYNOPSIS
@@ -9,6 +9,9 @@ pdrive \- command-line tool of PDrive for Linux, an unofficial Proton Drive clie
.br
.B pdrive ls
.RI [ PATH ]
+.br
+.BR pdrive " " keep\-offline " | " free\-up\-space
+.IR PATH ...
.SH DESCRIPTION
.B pdrive
signs in to and out of a Proton account and lists folders of
@@ -44,6 +47,22 @@ Print
or
.BR "not signed in" .
.TP
+.BI "keep\-offline " PATH ...
+Keep the files or folders available offline (same action as the Nautilus and Dolphin
+menus). Each
+.I PATH
+must be inside the mounted drive: the others are ignored with a message.
+.TP
+.BI "free\-up\-space " PATH ...
+Free the local space used by the files or folders (they stay in the drive).
+.PP
+.RS
+Both commands talk to the running daemon. When it is not running, or when no
+.I PATH
+is in the drive, they print the reason, show a desktop notification, and exit with status 1.
+They are what the COSMIC Files context-menu actions run.
+.RE
+.TP
.B selftest
Check the bridge with the SDK library without network access.
.SH EXIT STATUS
diff --git a/packaging/man/pdrived.1 b/packaging/man/pdrived.1
index 33dece7..bef6201 100644
--- a/packaging/man/pdrived.1
+++ b/packaging/man/pdrived.1
@@ -63,8 +63,9 @@ Optional settings (under
.B $XDG_CONFIG_HOME
if set). Keys:
.BR mountpoint " (default " ~/ProtonDrive ),
-.BR cache_size_gib " (default 10) and"
-.BR show_window_at_startup " (default true, read by " pdrive-app ).
+.BR cache_size_gib " (default 10),"
+.BR show_window_at_startup " and"
+.BR file_manager_integration " (both default true, read by " pdrive-app ).
Unknown keys are rejected.
.TP
.I ~/.cache/pdrive/
diff --git a/packaging/rpm/pdrive-for-linux.spec b/packaging/rpm/pdrive-for-linux.spec
index 85bbe59..9744178 100644
--- a/packaging/rpm/pdrive-for-linux.spec
+++ b/packaging/rpm/pdrive-for-linux.spec
@@ -23,10 +23,17 @@
%global __provides_exclude_from ^%{_libdir}/pdrive/.*$
%global __requires_exclude ^libproton_(drive_sdk|crypto)\\.so.*$
+# Plugins of the file managers: Qt plugin directory of the Dolphin plugins (KDE Frameworks 6).
+%global qt6_plugins %{_libdir}/qt6/plugins
+# One package serves every desktop installed on the machine: the plugins are loaded by their own
+# file manager, which brings its libraries (libnautilus-extension, KF6, Qt6). They must not
+# require them, or a GNOME user would get KDE libraries and the other way round.
+%global __requires_exclude_from ^(%{_libdir}/nautilus/extensions-4|%{qt6_plugins}/kf6)/.*$
+
Name: pdrive-for-linux
Version: 0.3.0
Release: 1%{?dist}
-Summary: Unofficial Proton Drive client for Linux (FUSE mount, Nautilus integration)
+Summary: Unofficial Proton Drive client for Linux (FUSE mount, file manager integration)
# GPL-3.0-or-later: this project. Bundled components, audited 29/10/2026 (THIRD_PARTY_NOTICES,
# licenses/*.tsv): MIT (Proton SDK and cryptography, .NET runtime and Microsoft NuGet packages,
# most Rust crates), Apache-2.0, BSD-3-Clause, ISC, Zlib, Unicode-3.0, Unlicense, CDLA-Permissive-2.0
@@ -40,6 +47,9 @@ Source1: %{url}/releases/download/v%{version}/pdrive-native-%{native_rid}
ExclusiveArch: x86_64 aarch64
BuildRequires: gcc
+BuildRequires: gcc-c++
+BuildRequires: cmake
+BuildRequires: extra-cmake-modules
BuildRequires: make
BuildRequires: cargo >= 1.92
BuildRequires: rust >= 1.92
@@ -47,6 +57,11 @@ BuildRequires: binutils
BuildRequires: gettext
BuildRequires: desktop-file-utils
BuildRequires: pkgconfig(libnautilus-extension-4)
+BuildRequires: cmake(KF6KIO)
+BuildRequires: cmake(KF6CoreAddons)
+BuildRequires: cmake(KF6I18n)
+BuildRequires: cmake(Qt6DBus)
+BuildRequires: cmake(Qt6Widgets)
BuildRequires: pkgconfig(gtk4) >= 4.12
BuildRequires: pkgconfig(libadwaita-1) >= 1.6
BuildRequires: pkgconfig(glib-2.0)
@@ -60,13 +75,17 @@ Requires: fuse3
# one makes two Secret Services compete for the session.
Requires: hicolor-icon-theme
Recommends: gnome-shell-extension-appindicator
-Recommends: nautilus
+# No file manager is favored: each one gets its plugin, and none is required.
+Suggests: nautilus
+Suggests: dolphin
%description
PDrive for Linux mounts Proton Drive as a FUSE file system, with on-demand
-download, offline pinning, sync state emblems and menu entries in Nautilus, a
+download, offline pinning, sync state emblems and menu entries in Nautilus and
+Dolphin, entries in the sidebar and menus of Dolphin and COSMIC Files, a
desktop application (tray icon, status window) that runs the daemon, and a
-command-line tool.
+command-line tool. The plugins of a file manager are only loaded by it: none
+is required, and several desktops can be installed side by side.
The session is stored through the Secret Service API: the desktop must provide
a Secret Service (oo7, GNOME Keyring, KWallet, KeePassXC...).
@@ -97,11 +116,16 @@ cargo build --release --frozen --offline -p pdrived -p pdrive -p pdrive-app
%set_build_flags
make -C extension LOCALEDIR=%{_datadir}/locale
+# Dolphin plugins (CXXFLAGS and LDFLAGS come from the environment set above).
+cmake -S integrations/dolphin -B build-dolphin -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=%{_prefix} -DKDE_INSTALL_LIBDIR=%{_lib}
+cmake --build build-dolphin %{?_smp_mflags}
+
%install
install -Dpm0755 target/release/pdrive target/release/pdrived target/release/pdrive-app -t %{buildroot}%{_bindir}
install -Dpm0755 native/%{native_rid}/libproton_drive_sdk.so native/%{native_rid}/libproton_crypto.so -t %{buildroot}%{_libdir}/pdrive
make -C extension install DESTDIR=%{buildroot} LOCALEDIR=%{_datadir}/locale EXTENSION_DIR=%{_libdir}/nautilus/extensions-4
+DESTDIR=%{buildroot} cmake --install build-dolphin
install -Dpm0644 packaging/man/*.1 -t %{buildroot}%{_mandir}/man1
install -Dpm0644 packaging/%{cloud_ini} %{buildroot}%{_datadir}/cloud-providers/%{cloud_ini}
@@ -123,6 +147,12 @@ desktop-file-validate %{buildroot}%{_datadir}/applications/%{app_id}.desktop
grep -q '^BusName=' %{buildroot}%{_datadir}/cloud-providers/%{cloud_ini}
# The extension must carry the system locale directory, not /usr/local.
! grep -q /usr/local %{buildroot}%{_libdir}/nautilus/extensions-4/libpdrive-nautilus.so
+# The Dolphin plugins: no /usr/local, no build directory.
+for plugin in %{buildroot}%{qt6_plugins}/kf6/overlayicon/pdriveoverlay.so %{buildroot}%{qt6_plugins}/kf6/kfileitemaction/pdriveactions.so; do
+ test -f "$plugin"
+ ! grep -q /usr/local "$plugin"
+ ! grep -q "$PWD" "$plugin"
+done
# The binaries must find the private libraries through the installed rpath only.
# and must not refer to the build tree (the SDK loads libproton_crypto.so from that path).
for b in pdrive pdrived; do
@@ -160,6 +190,11 @@ done
%{_libdir}/pdrive/libproton_drive_sdk.so
%{_libdir}/pdrive/libproton_crypto.so
%{_libdir}/nautilus/extensions-4/libpdrive-nautilus.so
+%dir %{qt6_plugins}/kf6
+%dir %{qt6_plugins}/kf6/overlayicon
+%dir %{qt6_plugins}/kf6/kfileitemaction
+%{qt6_plugins}/kf6/overlayicon/pdriveoverlay.so
+%{qt6_plugins}/kf6/kfileitemaction/pdriveactions.so
%{_datadir}/cloud-providers/%{cloud_ini}
%{_datadir}/applications/%{app_id}.desktop
%{_datadir}/icons/hicolor/*/*/*.svg
diff --git a/po/POTFILES b/po/POTFILES
index 07199c4..48e1170 100644
--- a/po/POTFILES
+++ b/po/POTFILES
@@ -1,7 +1,10 @@
+crates/pdrive/src/offline.rs
crates/pdrive-app/src/about.rs
+crates/pdrive-app/src/integrations.rs
crates/pdrive-app/src/main.rs
crates/pdrive-app/src/settings.rs
crates/pdrive-app/src/tray.rs
crates/pdrive-app/src/window.rs
crates/pdrived/src/dbus.rs
extension/pdrive-nautilus.c
+integrations/dolphin/pdriveactions.cpp
diff --git a/po/fr.po b/po/fr.po
index f304d72..f9e2620 100644
--- a/po/fr.po
+++ b/po/fr.po
@@ -7,7 +7,7 @@ msgid ""
msgstr ""
"Project-Id-Version: pdrive\n"
"Report-Msgid-Bugs-To: https://github.com/bpresles/PDrive-for-Linux/issues\n"
-"POT-Creation-Date: 2026-11-04 21:35+0100\n"
+"POT-Creation-Date: 2026-11-13 19:36+0100\n"
"PO-Revision-Date: 2026-10-28 22:02+0100\n"
"Last-Translator: PDrive for Linux authors\n"
"Language-Team: French\n"
@@ -30,29 +30,37 @@ msgstr "Version {}"
msgid "About"
msgstr "À propos"
-#: crates/pdrive-app/src/main.rs:466
+#: crates/pdrive-app/src/integrations.rs:77
+msgid "PDrive: Free Up Space"
+msgstr "PDrive : libérer de l’espace"
+
+#: crates/pdrive-app/src/integrations.rs:77
+msgid "PDrive: Keep Available Offline"
+msgstr "PDrive : garder disponible hors ligne"
+
+#: crates/pdrive-app/src/main.rs:482
msgid "Sign-in failed"
msgstr "Échec de la connexion"
-#: crates/pdrive-app/src/main.rs:466
+#: crates/pdrive-app/src/main.rs:482
msgid "The sign-in did not complete. Try again."
msgstr "La connexion n’a pas abouti. Réessayez."
-#: crates/pdrive-app/src/main.rs:480
+#: crates/pdrive-app/src/main.rs:496
msgid "Sign-out failed"
msgstr "Échec de la déconnexion"
-#: crates/pdrive-app/src/main.rs:480
+#: crates/pdrive-app/src/main.rs:496
msgid "The session could not be removed. See the logs of the application."
msgstr ""
"La session n’a pas pu être supprimée. Consultez les journaux de "
"l’application."
-#: crates/pdrive-app/src/main.rs:494
+#: crates/pdrive-app/src/main.rs:510
msgid "Start PDrive when you log in?"
msgstr "Lancer PDrive à l’ouverture de session ?"
-#: crates/pdrive-app/src/main.rs:495
+#: crates/pdrive-app/src/main.rs:511
msgid ""
"The Proton Drive folder is then mounted automatically. You can change this "
"in the settings."
@@ -60,105 +68,120 @@ msgstr ""
"Le dossier Proton Drive est alors monté automatiquement. Vous pouvez "
"modifier ce choix dans les réglages."
-#: crates/pdrive-app/src/main.rs:497
+#: crates/pdrive-app/src/main.rs:513
msgid "Not now"
msgstr "Pas maintenant"
-#: crates/pdrive-app/src/main.rs:497
+#: crates/pdrive-app/src/main.rs:513
msgid "Start at login"
msgstr "Lancer à l’ouverture de session"
-#: crates/pdrive-app/src/main.rs:526
+#: crates/pdrive-app/src/main.rs:542
msgid "You already have the latest version"
msgstr "Vous avez déjà la dernière version"
-#: crates/pdrive-app/src/main.rs:531
+#: crates/pdrive-app/src/main.rs:547
msgid "Cannot check for updates"
msgstr "Impossible de rechercher les mises à jour"
-#: crates/pdrive-app/src/main.rs:541
+#: crates/pdrive-app/src/main.rs:557
#, rust-format
msgid "New version is available: v{}"
msgstr "Une nouvelle version est disponible : v{}"
-#: crates/pdrive-app/src/main.rs:542
+#: crates/pdrive-app/src/main.rs:558
msgid "Ignore"
msgstr "Ignorer"
-#: crates/pdrive-app/src/main.rs:542
+#: crates/pdrive-app/src/main.rs:558
msgid "Update"
msgstr "Mettre à jour"
-#: crates/pdrive-app/src/main.rs:555 crates/pdrive-app/src/main.rs:561
+#: crates/pdrive-app/src/main.rs:571 crates/pdrive-app/src/main.rs:577
msgid "OK"
msgstr "OK"
-#: crates/pdrive-app/src/settings.rs:29 crates/pdrive-app/src/tray.rs:111
+#: crates/pdrive-app/src/settings.rs:30 crates/pdrive-app/src/tray.rs:111
#: crates/pdrive-app/src/window.rs:72
msgid "Settings"
msgstr "Réglages"
-#: crates/pdrive-app/src/settings.rs:33
+#: crates/pdrive-app/src/settings.rs:34
msgid "Synchronization"
msgstr "Synchronisation"
-#: crates/pdrive-app/src/settings.rs:34
+#: crates/pdrive-app/src/settings.rs:35
msgid "Changes apply when the dialog is closed, restarting the service."
msgstr ""
"Les modifications s’appliquent à la fermeture de la fenêtre, avec un "
"redémarrage du service."
-#: crates/pdrive-app/src/settings.rs:36
+#: crates/pdrive-app/src/settings.rs:37
msgid "Mount point"
msgstr "Point de montage"
-#: crates/pdrive-app/src/settings.rs:38
+#: crates/pdrive-app/src/settings.rs:39
msgid "Cache size (GiB)"
msgstr "Taille du cache (Gio)"
-#: crates/pdrive-app/src/settings.rs:46
+#: crates/pdrive-app/src/settings.rs:47
msgid "Start when I log in"
msgstr "Lancer à l’ouverture de session"
-#: crates/pdrive-app/src/settings.rs:50 crates/pdrive-app/src/settings.rs:58
+#: crates/pdrive-app/src/settings.rs:51 crates/pdrive-app/src/settings.rs:59
msgid "Cannot change the startup setting"
msgstr "Impossible de modifier le réglage de démarrage"
-#: crates/pdrive-app/src/settings.rs:54
+#: crates/pdrive-app/src/settings.rs:55
msgid "Show the status window at startup"
msgstr "Ouvrir la fenêtre d’état au démarrage"
-#: crates/pdrive-app/src/settings.rs:65
+#: crates/pdrive-app/src/settings.rs:64
+msgid "Add PDrive to the file managers (sidebar, menus)"
+msgstr "Ajouter PDrive aux gestionnaires de fichiers (barre latérale, menus)"
+
+#: crates/pdrive-app/src/settings.rs:68
+msgid "Cannot change the file manager setting"
+msgstr "Impossible de modifier le réglage des gestionnaires de fichiers"
+
+#: crates/pdrive-app/src/settings.rs:73
+msgid ""
+"Some file managers could not be updated. See the logs of the application."
+msgstr ""
+"Certains gestionnaires de fichiers n’ont pas pu être mis à jour. Consultez "
+"les journaux de l’application."
+
+#: crates/pdrive-app/src/settings.rs:81
#, rust-format
msgid "Installed version: {}"
msgstr "Version installée : {}"
-#: crates/pdrive-app/src/settings.rs:65
+#: crates/pdrive-app/src/settings.rs:81
msgid "Updates"
msgstr "Mises à jour"
-#: crates/pdrive-app/src/settings.rs:69
+#: crates/pdrive-app/src/settings.rs:85
#, rust-format
msgid "New version available: v{}"
msgstr "Nouvelle version disponible : v{}"
-#: crates/pdrive-app/src/settings.rs:74 crates/pdrive-app/src/tray.rs:104
+#: crates/pdrive-app/src/settings.rs:90 crates/pdrive-app/src/tray.rs:104
msgid "Check for update…"
msgstr "Rechercher une mise à jour…"
-#: crates/pdrive-app/src/settings.rs:82
+#: crates/pdrive-app/src/settings.rs:98
msgid "Account"
msgstr "Compte"
-#: crates/pdrive-app/src/settings.rs:84 crates/pdrive-app/src/settings.rs:92
+#: crates/pdrive-app/src/settings.rs:100 crates/pdrive-app/src/settings.rs:108
msgid "Sign out"
msgstr "Se déconnecter"
-#: crates/pdrive-app/src/settings.rs:89
+#: crates/pdrive-app/src/settings.rs:105
msgid "Sign out?"
msgstr "Se déconnecter ?"
-#: crates/pdrive-app/src/settings.rs:90
+#: crates/pdrive-app/src/settings.rs:106
msgid ""
"The service is stopped and the session is removed from this computer. "
"Pending uploads are resumed after the next sign-in."
@@ -166,7 +189,7 @@ msgstr ""
"Le service est arrêté et la session est supprimée de cet ordinateur. Les "
"envois en attente reprendront après la prochaine connexion."
-#: crates/pdrive-app/src/settings.rs:92
+#: crates/pdrive-app/src/settings.rs:108
msgid "Cancel"
msgstr "Annuler"
@@ -348,6 +371,22 @@ msgid_plural "{} days ago"
msgstr[0] "Il y a {} jour"
msgstr[1] "Il y a {} jours"
+#: crates/pdrive/src/offline.rs:52
+msgid "Cannot reach the session bus"
+msgstr "Bus de session inaccessible"
+
+#: crates/pdrive/src/offline.rs:57
+msgid "PDrive is not running. Start it first."
+msgstr "PDrive n’est pas lancé. Démarrez-le d’abord."
+
+#: crates/pdrive/src/offline.rs:65
+msgid "Ignored, not in Proton Drive"
+msgstr "Ignoré, hors de Proton Drive"
+
+#: crates/pdrive/src/offline.rs:68
+msgid "These files are not in Proton Drive"
+msgstr "Ces fichiers ne sont pas dans Proton Drive"
+
#: crates/pdrived/src/dbus.rs:259
#, rust-format
msgid "{} (unofficial client) · {}"
@@ -379,18 +418,18 @@ msgstr "Afficher l’état"
msgid "Open in the browser"
msgstr "Ouvrir dans le navigateur"
-#: extension/pdrive-nautilus.c:333
+#: extension/pdrive-nautilus.c:333 integrations/dolphin/pdriveactions.cpp:38
msgid "Keep Available Offline"
msgstr "Garder disponible hors ligne"
-#: extension/pdrive-nautilus.c:334
+#: extension/pdrive-nautilus.c:334 integrations/dolphin/pdriveactions.cpp:39
msgid "Download and keep available without network"
msgstr "Télécharger et garder disponible sans réseau"
-#: extension/pdrive-nautilus.c:336
+#: extension/pdrive-nautilus.c:336 integrations/dolphin/pdriveactions.cpp:44
msgid "Free Up Space"
msgstr "Libérer de l’espace"
-#: extension/pdrive-nautilus.c:337
+#: extension/pdrive-nautilus.c:337 integrations/dolphin/pdriveactions.cpp:45
msgid "Remove the downloaded copy, keeping it in the cloud"
msgstr "Supprimer la copie téléchargée, en la conservant dans le cloud"
diff --git a/po/pdrive.pot b/po/pdrive.pot
index a379f9a..e9bcfa0 100644
--- a/po/pdrive.pot
+++ b/po/pdrive.pot
@@ -8,7 +8,7 @@ msgid ""
msgstr ""
"Project-Id-Version: pdrive\n"
"Report-Msgid-Bugs-To: https://github.com/bpresles/PDrive-for-Linux/issues\n"
-"POT-Creation-Date: 2026-11-04 21:35+0100\n"
+"POT-Creation-Date: 2026-11-13 19:36+0100\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME \n"
"Language-Team: LANGUAGE \n"
@@ -31,135 +31,156 @@ msgstr ""
msgid "About"
msgstr ""
-#: crates/pdrive-app/src/main.rs:466
+#: crates/pdrive-app/src/integrations.rs:77
+msgid "PDrive: Free Up Space"
+msgstr ""
+
+#: crates/pdrive-app/src/integrations.rs:77
+msgid "PDrive: Keep Available Offline"
+msgstr ""
+
+#: crates/pdrive-app/src/main.rs:482
msgid "Sign-in failed"
msgstr ""
-#: crates/pdrive-app/src/main.rs:466
+#: crates/pdrive-app/src/main.rs:482
msgid "The sign-in did not complete. Try again."
msgstr ""
-#: crates/pdrive-app/src/main.rs:480
+#: crates/pdrive-app/src/main.rs:496
msgid "Sign-out failed"
msgstr ""
-#: crates/pdrive-app/src/main.rs:480
+#: crates/pdrive-app/src/main.rs:496
msgid "The session could not be removed. See the logs of the application."
msgstr ""
-#: crates/pdrive-app/src/main.rs:494
+#: crates/pdrive-app/src/main.rs:510
msgid "Start PDrive when you log in?"
msgstr ""
-#: crates/pdrive-app/src/main.rs:495
+#: crates/pdrive-app/src/main.rs:511
msgid ""
"The Proton Drive folder is then mounted automatically. You can change this "
"in the settings."
msgstr ""
-#: crates/pdrive-app/src/main.rs:497
+#: crates/pdrive-app/src/main.rs:513
msgid "Not now"
msgstr ""
-#: crates/pdrive-app/src/main.rs:497
+#: crates/pdrive-app/src/main.rs:513
msgid "Start at login"
msgstr ""
-#: crates/pdrive-app/src/main.rs:526
+#: crates/pdrive-app/src/main.rs:542
msgid "You already have the latest version"
msgstr ""
-#: crates/pdrive-app/src/main.rs:531
+#: crates/pdrive-app/src/main.rs:547
msgid "Cannot check for updates"
msgstr ""
-#: crates/pdrive-app/src/main.rs:541
+#: crates/pdrive-app/src/main.rs:557
#, rust-format
msgid "New version is available: v{}"
msgstr ""
-#: crates/pdrive-app/src/main.rs:542
+#: crates/pdrive-app/src/main.rs:558
msgid "Ignore"
msgstr ""
-#: crates/pdrive-app/src/main.rs:542
+#: crates/pdrive-app/src/main.rs:558
msgid "Update"
msgstr ""
-#: crates/pdrive-app/src/main.rs:555 crates/pdrive-app/src/main.rs:561
+#: crates/pdrive-app/src/main.rs:571 crates/pdrive-app/src/main.rs:577
msgid "OK"
msgstr ""
-#: crates/pdrive-app/src/settings.rs:29 crates/pdrive-app/src/tray.rs:111
+#: crates/pdrive-app/src/settings.rs:30 crates/pdrive-app/src/tray.rs:111
#: crates/pdrive-app/src/window.rs:72
msgid "Settings"
msgstr ""
-#: crates/pdrive-app/src/settings.rs:33
+#: crates/pdrive-app/src/settings.rs:34
msgid "Synchronization"
msgstr ""
-#: crates/pdrive-app/src/settings.rs:34
+#: crates/pdrive-app/src/settings.rs:35
msgid "Changes apply when the dialog is closed, restarting the service."
msgstr ""
-#: crates/pdrive-app/src/settings.rs:36
+#: crates/pdrive-app/src/settings.rs:37
msgid "Mount point"
msgstr ""
-#: crates/pdrive-app/src/settings.rs:38
+#: crates/pdrive-app/src/settings.rs:39
msgid "Cache size (GiB)"
msgstr ""
-#: crates/pdrive-app/src/settings.rs:46
+#: crates/pdrive-app/src/settings.rs:47
msgid "Start when I log in"
msgstr ""
-#: crates/pdrive-app/src/settings.rs:50 crates/pdrive-app/src/settings.rs:58
+#: crates/pdrive-app/src/settings.rs:51 crates/pdrive-app/src/settings.rs:59
msgid "Cannot change the startup setting"
msgstr ""
-#: crates/pdrive-app/src/settings.rs:54
+#: crates/pdrive-app/src/settings.rs:55
msgid "Show the status window at startup"
msgstr ""
-#: crates/pdrive-app/src/settings.rs:65
+#: crates/pdrive-app/src/settings.rs:64
+msgid "Add PDrive to the file managers (sidebar, menus)"
+msgstr ""
+
+#: crates/pdrive-app/src/settings.rs:68
+msgid "Cannot change the file manager setting"
+msgstr ""
+
+#: crates/pdrive-app/src/settings.rs:73
+msgid ""
+"Some file managers could not be updated. See the logs of the application."
+msgstr ""
+
+#: crates/pdrive-app/src/settings.rs:81
#, rust-format
msgid "Installed version: {}"
msgstr ""
-#: crates/pdrive-app/src/settings.rs:65
+#: crates/pdrive-app/src/settings.rs:81
msgid "Updates"
msgstr ""
-#: crates/pdrive-app/src/settings.rs:69
+#: crates/pdrive-app/src/settings.rs:85
#, rust-format
msgid "New version available: v{}"
msgstr ""
-#: crates/pdrive-app/src/settings.rs:74 crates/pdrive-app/src/tray.rs:104
+#: crates/pdrive-app/src/settings.rs:90 crates/pdrive-app/src/tray.rs:104
msgid "Check for update…"
msgstr ""
-#: crates/pdrive-app/src/settings.rs:82
+#: crates/pdrive-app/src/settings.rs:98
msgid "Account"
msgstr ""
-#: crates/pdrive-app/src/settings.rs:84 crates/pdrive-app/src/settings.rs:92
+#: crates/pdrive-app/src/settings.rs:100 crates/pdrive-app/src/settings.rs:108
msgid "Sign out"
msgstr ""
-#: crates/pdrive-app/src/settings.rs:89
+#: crates/pdrive-app/src/settings.rs:105
msgid "Sign out?"
msgstr ""
-#: crates/pdrive-app/src/settings.rs:90
+#: crates/pdrive-app/src/settings.rs:106
msgid ""
"The service is stopped and the session is removed from this computer. "
"Pending uploads are resumed after the next sign-in."
msgstr ""
-#: crates/pdrive-app/src/settings.rs:92
+#: crates/pdrive-app/src/settings.rs:108
msgid "Cancel"
msgstr ""
@@ -338,6 +359,22 @@ msgid_plural "{} days ago"
msgstr[0] ""
msgstr[1] ""
+#: crates/pdrive/src/offline.rs:52
+msgid "Cannot reach the session bus"
+msgstr ""
+
+#: crates/pdrive/src/offline.rs:57
+msgid "PDrive is not running. Start it first."
+msgstr ""
+
+#: crates/pdrive/src/offline.rs:65
+msgid "Ignored, not in Proton Drive"
+msgstr ""
+
+#: crates/pdrive/src/offline.rs:68
+msgid "These files are not in Proton Drive"
+msgstr ""
+
#: crates/pdrived/src/dbus.rs:259
#, rust-format
msgid "{} (unofficial client) · {}"
@@ -369,18 +406,18 @@ msgstr ""
msgid "Open in the browser"
msgstr ""
-#: extension/pdrive-nautilus.c:333
+#: extension/pdrive-nautilus.c:333 integrations/dolphin/pdriveactions.cpp:38
msgid "Keep Available Offline"
msgstr ""
-#: extension/pdrive-nautilus.c:334
+#: extension/pdrive-nautilus.c:334 integrations/dolphin/pdriveactions.cpp:39
msgid "Download and keep available without network"
msgstr ""
-#: extension/pdrive-nautilus.c:336
+#: extension/pdrive-nautilus.c:336 integrations/dolphin/pdriveactions.cpp:44
msgid "Free Up Space"
msgstr ""
-#: extension/pdrive-nautilus.c:337
+#: extension/pdrive-nautilus.c:337 integrations/dolphin/pdriveactions.cpp:45
msgid "Remove the downloaded copy, keeping it in the cloud"
msgstr ""
diff --git a/scripts/container/build-arch.sh b/scripts/container/build-arch.sh
index 12d5258..a316a14 100755
--- a/scripts/container/build-arch.sh
+++ b/scripts/container/build-arch.sh
@@ -4,6 +4,7 @@
# an unprivileged user.
set -euo pipefail
pacman -Syu --noconfirm --needed base-devel cargo gettext desktop-file-utils pkgconf nautilus gtk4 libadwaita \
+ cmake extra-cmake-modules kio \
glib2 fuse3 xz tar namcap git zstd
useradd --create-home builder
B=/home/builder/build; mkdir -p "$B"
diff --git a/scripts/container/build-deb.sh b/scripts/container/build-deb.sh
index fe5d7e4..96408bc 100755
--- a/scripts/container/build-deb.sh
+++ b/scripts/container/build-deb.sh
@@ -6,6 +6,7 @@ set -euo pipefail
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install -y --no-install-recommends build-essential debhelper dpkg-dev fakeroot gettext \
+ cmake extra-cmake-modules libkf6kio-dev libkf6coreaddons-dev libkf6i18n-dev qt6-base-dev \
desktop-file-utils pkg-config libnautilus-extension-dev libgtk-4-dev libadwaita-1-dev libglib2.0-dev \
xz-utils lintian ca-certificates curl cargo rustc
DPKG_FLAGS=()
diff --git a/scripts/container/build-rpm.sh b/scripts/container/build-rpm.sh
index c1b173a..0e021c8 100755
--- a/scripts/container/build-rpm.sh
+++ b/scripts/container/build-rpm.sh
@@ -2,7 +2,8 @@
# Runs inside a Fedora container (local script and GitHub workflow). /dist holds the two
# sources and receives the RPM and SRPM. Spec taken from the source tarball.
set -euo pipefail
-dnf -y install rpm-build rpmlint cargo rust gcc make binutils gettext desktop-file-utils \
+dnf -y install rpm-build rpmlint cargo rust gcc gcc-c++ make cmake extra-cmake-modules binutils gettext desktop-file-utils \
+ 'cmake(KF6KIO)' 'cmake(KF6CoreAddons)' 'cmake(KF6I18n)' 'cmake(Qt6DBus)' 'cmake(Qt6Widgets)' \
'pkgconfig(libnautilus-extension-4)' 'pkgconfig(gtk4)' 'pkgconfig(libadwaita-1)' \
'pkgconfig(glib-2.0)' 'pkgconfig(gio-2.0)' 'pkgconfig(gmodule-2.0)' xz tar
TOP=/tmp/rpmbuild; mkdir -p "$TOP"/{SOURCES,SPECS}
diff --git a/scripts/install-system.sh b/scripts/install-system.sh
index 1222563..97657a6 100755
--- a/scripts/install-system.sh
+++ b/scripts/install-system.sh
@@ -2,18 +2,46 @@
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (C) 2026 Bertrand Presles
# Installs the parts of PDrive for Linux that must live in system directories (needs sudo):
-# the Nautilus extension (Nautilus only loads extensions from its system directory), and
+# the Nautilus extension (Nautilus only loads extensions from its system directory),
+# the Dolphin plugins (KDE Frameworks 6: sync state emblems and menu entries, loaded from the
+# Qt plugin directory of the system),
# the libcloudproviders declaration (only read from system data directories),
-# and the translations of the extension, in the LOCALEDIR it is built with.
-# Requires nautilus-devel to build the extension.
+# and the translations of the plugins, in the LOCALEDIR the extension is built with.
+# Each file manager is handled if its development files are found, and skipped otherwise:
+# Nautilus needs nautilus-devel (pkg-config libnautilus-extension-4),
+# Dolphin needs cmake, extra-cmake-modules, kf6-kio-devel, kf6-kcoreaddons-devel,
+# kf6-ki18n-devel and qt6-qtbase-devel (Debian: libkf6kio-dev, libkf6coreaddons-dev,
+# libkf6i18n-dev, qt6-base-dev).
+# COSMIC Files needs nothing here: pdrive-app sets it up in the configuration of the user.
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
CLOUD_PROVIDERS_DIR=/usr/local/share/cloud-providers
LOCALEDIR=/usr/local/share/locale
+restart_hints=()
+
+if pkg-config --exists libnautilus-extension-4; then
+ make -C "$ROOT/extension" LOCALEDIR="$LOCALEDIR"
+ sudo make -C "$ROOT/extension" LOCALEDIR="$LOCALEDIR" install
+ restart_hints+=("Nautilus: nautilus -q")
+else
+ echo "Nautilus extension skipped: libnautilus-extension-4 not found (install nautilus-devel)."
+fi
+
+dolphin_build="$ROOT/integrations/dolphin/build"
+qt_plugins="$( (qtpaths6 --query QT_INSTALL_PLUGINS || qmake6 -query QT_INSTALL_PLUGINS) 2>/dev/null | head -n1 || true)"
+if [[ -z "$qt_plugins" ]]; then
+ echo "Dolphin plugins skipped: qtpaths6 not found (install qt6-qtbase-devel)."
+elif cmake -S "$ROOT/integrations/dolphin" -B "$dolphin_build" -DCMAKE_BUILD_TYPE=Release >/dev/null 2>&1; then
+ cmake --build "$dolphin_build"
+ sudo install -Dm0755 "$dolphin_build/bin/kf6/overlayicon/pdriveoverlay.so" "$qt_plugins/kf6/overlayicon/pdriveoverlay.so"
+ sudo install -Dm0755 "$dolphin_build/bin/kf6/kfileitemaction/pdriveactions.so" "$qt_plugins/kf6/kfileitemaction/pdriveactions.so"
+ restart_hints+=("Dolphin: close all its windows, then start it again")
+else
+ echo "Dolphin plugins skipped: CMake did not find KF6 KIO (see the requirements above)."
+fi
+rm -rf "$dolphin_build"
-make -C "$ROOT/extension" LOCALEDIR="$LOCALEDIR"
-sudo make -C "$ROOT/extension" LOCALEDIR="$LOCALEDIR" install
# Migrate from the former D-Bus name (io.github.pdrive.PDrive).
sudo rm -f "$CLOUD_PROVIDERS_DIR/io.github.pdrive.PDrive.ini"
sudo install -Dm0644 "$ROOT/packaging/io.github.bpresles.PDrive.ini" "$CLOUD_PROVIDERS_DIR/io.github.bpresles.PDrive.ini"
@@ -25,4 +53,9 @@ while read -r lang; do
rm -f "$ROOT/po/$lang.mo"
done < "$ROOT/po/LINGUAS"
-echo "Installed. Restart Nautilus to load the extension: nautilus -q"
+if (( ${#restart_hints[@]} )); then
+ echo "Installed. Restart the file managers to load the plugins:"
+ printf ' %s\n' "${restart_hints[@]}"
+else
+ echo "Installed (no file manager plugin: none of the development packages above was found)."
+fi
diff --git a/scripts/uninstall.sh b/scripts/uninstall.sh
index 4ede41c..9b2247a 100755
--- a/scripts/uninstall.sh
+++ b/scripts/uninstall.sh
@@ -8,6 +8,8 @@
# Kept: the session in the keyring, the settings (~/.config/pdrive), the cache and pending
# uploads (~/.cache/pdrive), the offline choices (~/.local/share/pdrive) and the ~/ProtonDrive
# link, which a package installation reuses; see the end of this script to remove them.
+# The entries that pdrive-app added to the file managers of the user (Dolphin places, COSMIC
+# Files favorite and actions) are removed with pdrive-app --remove-integrations.
# Files installed by an RPM or DEB package are left alone.
set -euo pipefail
@@ -54,6 +56,11 @@ for unit in pdrive.service nautilus-drive-poc.service; do
done
[[ -n "${UNITS_REMOVED:-}" ]] && systemctl --user daemon-reload
+# Entries added to the file managers: with the binary of this installation, before it goes.
+if [[ -x "$BIN_DIR/pdrive-app" ]]; then
+ "$BIN_DIR/pdrive-app" --remove-integrations || echo "Could not remove all the file manager entries." >&2
+fi
+
# User installation (install.sh).
rm -f "$BIN_DIR"/{pdrive-app,pdrived,pdrive,pdfs,pdpoc}
rm -rf "$HOME/.local/lib/pdrive" "$HOME/.local/lib/nautilus-drive-poc"
@@ -68,13 +75,20 @@ rm -f "$DATA_HOME"/locale/*/LC_MESSAGES/pdrive.mo
rm -f "$DATA_HOME"/man/man1/{pdrive,pdrived,pdrive-app}.1
update-desktop-database -q "$DATA_HOME/applications" 2>/dev/null || true
-# System installation (install-system.sh): the Nautilus extension, unless a package owns it.
-extension_dirs=("$(pkg-config --variable=extensiondir libnautilus-extension-4 2>/dev/null || true)" /usr/lib64/nautilus/extensions-4 /usr/lib/*/nautilus/extensions-4)
+# System installation (install-system.sh): the Nautilus extension and the Dolphin plugins, unless
+# a package owns them.
+qt_plugins="$( (qtpaths6 --query QT_INSTALL_PLUGINS || qmake6 -query QT_INSTALL_PLUGINS) 2>/dev/null | head -n1 || true)"
+candidates=()
+for dir in "$(pkg-config --variable=extensiondir libnautilus-extension-4 2>/dev/null || true)" /usr/lib64/nautilus/extensions-4 /usr/lib/*/nautilus/extensions-4; do
+ [[ -n "$dir" ]] && candidates+=("$dir/libpdrive-nautilus.so")
+done
+for dir in "$qt_plugins" /usr/lib64/qt6/plugins /usr/lib/qt6/plugins /usr/lib/*/qt6/plugins; do
+ [[ -n "$dir" ]] && candidates+=("$dir/kf6/overlayicon/pdriveoverlay.so" "$dir/kf6/kfileitemaction/pdriveactions.so")
+done
system_files=()
-for dir in "${extension_dirs[@]}"; do
- file="$dir/libpdrive-nautilus.so"
- [[ -n "$dir" && -f "$file" ]] || continue
- if rpm -qf "$file" >/dev/null 2>&1 || dpkg -S "$file" >/dev/null 2>&1; then
+for file in "${candidates[@]}"; do
+ [[ -f "$file" ]] || continue
+ if rpm -qf "$file" >/dev/null 2>&1 || dpkg -S "$file" >/dev/null 2>&1 || pacman -Qo "$file" >/dev/null 2>&1; then
echo "Kept $file: it belongs to an installed package."
continue
fi
@@ -90,7 +104,7 @@ fi
cat <